Skip to main content

gpui_material_components/
icon.rs

1use std::sync::Arc;
2
3use gpui::{
4    AnyElement, App, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
5    Radians, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Transformation,
6    Window, div, px, radians, size, svg,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{color, current_material_theme};
10use gpui_material_theme::{ColorRole, Direction};
11
12macro_rules! symbols {
13    ($($variant:ident => $name:literal),+ $(,)?) => {
14        /// Bundled official Material Symbols Outlined, weight 400, grade 0, optical size 24.
15        /// Both fill variants are embedded unchanged, without an application AssetSource.
16        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
17        pub enum IconName {
18            $(
19                #[doc = concat!("Material Symbols Outlined `", $name, "` glyph.")]
20                $variant
21            ),+
22        }
23
24        impl IconName {
25            /// All bundled symbols, useful for icon pickers and asset validation.
26            pub const ALL: &'static [Self] = &[$(Self::$variant),+];
27
28            /// Unchanged upstream SVG bytes for FILL=0 or FILL=1.
29            pub fn svg_data(self, filled: bool) -> &'static [u8] {
30                match (self, filled) {
31                    $((Self::$variant, false) => include_bytes!(concat!("../assets/material-symbols/", $name, "_24px.svg")),
32                      (Self::$variant, true) => include_bytes!(concat!("../assets/material-symbols/", $name, "_fill1_24px.svg"))),+
33                }
34            }
35        }
36    };
37}
38
39symbols! {
40    Add => "add",
41    Remove => "remove",
42    Check => "check",
43    Close => "close",
44    ChevronRight => "chevron_right",
45    ArrowForward => "arrow_forward",
46    ArrowDropDown => "arrow_drop_down",
47    Favorite => "favorite",
48    Archive => "archive",
49    Inbox => "inbox",
50    Description => "description",
51    Notifications => "notifications",
52    MotionPhotosOn => "motion_photos_on",
53    Contrast => "contrast",
54    DarkMode => "dark_mode",
55    LightMode => "light_mode",
56    LeftPanelOpen => "left_panel_open",
57    LeftPanelClose => "left_panel_close",
58    Search => "search",
59    Error => "error",
60    Info => "info",
61    Edit => "edit",
62    Exposure => "exposure",
63    Visibility => "visibility",
64    VisibilityOff => "visibility_off",
65}
66
67/// A decorative icon by default; `.label` exposes an independently meaningful image.
68/// Named symbols and raw SVG data inherit text size and foreground, including disabled colors, from
69/// their control's icon slot. Outside a slot, use `.size(px(24.))` for a 24dp icon.
70/// Custom SVG paths use the application's AssetSource. Mirroring is opt-in.
71#[derive(IntoElement)]
72pub struct Icon {
73    content: IconContent,
74    name: Option<(ElementId, SharedString)>,
75    side: Option<Pixels>,
76    color: Option<ColorRole>,
77    color_override: Option<Hsla>,
78    mirror: bool,
79    rotation: Radians,
80    filled: bool,
81}
82
83enum IconContent {
84    Symbol(IconName),
85    Svg(SharedString),
86    SvgData(Arc<[u8]>),
87    Element(AnyElement),
88}
89
90impl Icon {
91    /// Creates an icon from a bundled Material Symbols Outlined glyph.
92    pub fn new(symbol: IconName) -> Self {
93        Self {
94            content: IconContent::Symbol(symbol),
95            name: None,
96            side: None,
97            color: None,
98            color_override: None,
99            mirror: false,
100            rotation: radians(0.),
101            filled: false,
102        }
103    }
104
105    /// Caller-provided SVG; retains the existing 24dp/OnSurfaceVariant defaults.
106    pub fn svg(path: impl Into<SharedString>) -> Self {
107        Self {
108            content: IconContent::Svg(path.into()),
109            side: Some(px(24.)),
110            color: Some(ColorRole::OnSurfaceVariant),
111            ..Self::new(IconName::Info)
112        }
113    }
114
115    /// An in-memory SVG that inherits size and color from its icon slot.
116    pub fn svg_data(data: impl Into<Arc<[u8]>>) -> Self {
117        Self {
118            content: IconContent::SvgData(data.into()),
119            ..Self::new(IconName::Info)
120        }
121    }
122
123    /// Wraps an arbitrary caller-supplied element in a 24 dp icon container tinted to `OnSurfaceVariant` by default.
124    pub fn custom(element: impl IntoElement) -> Self {
125        Self {
126            content: IconContent::Element(element.into_any_element()),
127            ..Self::svg("")
128        }
129    }
130
131    /// Select FILL=1 for a named symbol; does not alter caller-provided content.
132    pub fn filled(mut self, filled: bool) -> Self {
133        self.filled = filled;
134        self
135    }
136
137    /// Exposes the icon as an independently meaningful `Role::Image` with the given accessible name.
138    pub fn label(mut self, id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
139        self.name = Some((id.into(), name.into()));
140        self
141    }
142
143    /// Sets an explicit square side length in logical pixels (clamped to non-negative values).
144    pub fn size(mut self, side: Pixels) -> Self {
145        self.side = Some(side.max(px(0.)));
146        self
147    }
148
149    /// Resolves the icon tint from the window theme's semantic color role.
150    pub fn color(mut self, color: ColorRole) -> Self {
151        self.color = Some(color);
152        self.color_override = None;
153        self
154    }
155
156    /// Sets a literal icon tint. A later call to [`Self::color`] or [`Self::inherit_color`]
157    /// replaces this override.
158    pub fn color_override(mut self, color: impl Into<Hsla>) -> Self {
159        self.color_override = Some(color.into());
160        self
161    }
162
163    /// Clears any explicit color role or override so the icon inherits its parent text color
164    /// (for example, inside buttons, navigation items, or surfaces).
165    pub fn inherit_color(mut self) -> Self {
166        self.color = None;
167        self.color_override = None;
168        self
169    }
170
171    /// Horizontally mirrors SVG icons when the window layout direction is right-to-left.
172    pub fn mirror_in_rtl(mut self, mirror: bool) -> Self {
173        self.mirror = mirror;
174        self
175    }
176
177    /// Paint-time rotation composed with RTL mirroring; layout is unchanged.
178    pub fn rotate(mut self, angle: Radians) -> Self {
179        self.rotation = angle;
180        self
181    }
182}
183
184impl RenderOnce for Icon {
185    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
186        let theme = current_material_theme(window, cx);
187        let tint = self.color_override.unwrap_or_else(|| {
188            self.color.map_or_else(
189                || window.text_style().color,
190                |role| color(theme.colors.color(role)),
191            )
192        });
193        let side = self
194            .side
195            .unwrap_or_else(|| window.text_style().font_size.to_pixels(window.rem_size()));
196        let rtl = self.mirror && theme.layout.direction == Direction::Rtl;
197        let transform = Transformation::rotate(self.rotation)
198            .with_scaling(size(if rtl { -1. } else { 1. }, 1.));
199        let icon_svg = || {
200            svg()
201                .size_full()
202                .text_color(tint)
203                .with_transformation(transform)
204        };
205        let icon = match self.content {
206            IconContent::Symbol(symbol) => icon_svg()
207                .data(symbol.svg_data(self.filled))
208                .into_any_element(),
209            IconContent::Svg(path) => icon_svg().path(path).into_any_element(),
210            IconContent::SvgData(data) => icon_svg().data(&data).into_any_element(),
211            IconContent::Element(element) => element,
212        };
213        let icon = div()
214            .size(side)
215            .flex_none()
216            .flex()
217            .items_center()
218            .justify_center()
219            .text_color(tint)
220            .child(icon);
221        match self.name {
222            Some((id, label)) => icon
223                .id(id)
224                .test_support()
225                .role(Role::Image)
226                .aria_label(label)
227                .into_any_element(),
228            None => icon.into_any_element(),
229        }
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn every_bundled_symbol_rasterizes_without_fonts_or_application_assets() {
239        let renderer = gpui::SvgRenderer::new(Arc::new(()));
240        for name in IconName::ALL {
241            for filled in [false, true] {
242                let data = name.svg_data(filled);
243                // Symbols must stay vector-only: no fonts, images or linked resources.
244                let source = std::str::from_utf8(data).unwrap();
245                assert!(!source.contains("<text") && !source.contains("<image"));
246                assert!(!source.contains("href="));
247                for scale in [1., 2.] {
248                    let image = renderer
249                        .render_single_frame(data, scale)
250                        .unwrap_or_else(|error| panic!("{name:?} fill={filled}: {error}"));
251                    assert!(
252                        image
253                            .as_bytes(0)
254                            .unwrap()
255                            .as_chunks::<4>()
256                            .0
257                            .iter()
258                            .any(|pixel| pixel[3] != 0),
259                        "{name:?} fill={filled} must paint visible pixels"
260                    );
261                }
262            }
263        }
264        assert_ne!(
265            IconName::Favorite.svg_data(false),
266            IconName::Favorite.svg_data(true)
267        );
268    }
269}