Skip to main content

gpui_material_components/
icon.rs

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