gpui_material_components/
icon.rs1use 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 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
15 pub enum IconName { $($variant),+ }
16
17 impl IconName {
18 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
20
21 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#[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 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 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(crate) fn inherit_color(mut self) -> Self {
131 self.color = None;
132 self
133 }
134
135 pub fn mirror_in_rtl(mut self, mirror: bool) -> Self {
136 self.mirror = mirror;
137 self
138 }
139
140 pub fn rotate(mut self, angle: Radians) -> Self {
142 self.rotation = angle;
143 self
144 }
145}
146
147impl RenderOnce for Icon {
148 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
149 let theme = window_material_theme(window, cx);
150 let tint = self.color.map_or_else(
151 || window.text_style().color,
152 |role| color(theme.colors.color(role)),
153 );
154 let side = self
155 .side
156 .unwrap_or_else(|| window.text_style().font_size.to_pixels(window.rem_size()));
157 let rtl = self.mirror && theme.layout.direction == Direction::Rtl;
158 let transform = Transformation::rotate(self.rotation)
159 .with_scaling(size(if rtl { -1. } else { 1. }, 1.));
160 let icon = match self.content {
161 IconContent::Symbol(symbol) => svg()
162 .data(symbol.svg_data(self.filled))
163 .size_full()
164 .text_color(tint)
165 .with_transformation(transform)
166 .into_any_element(),
167 IconContent::Svg(path) => svg()
168 .path(path)
169 .size_full()
170 .text_color(tint)
171 .with_transformation(transform)
172 .into_any_element(),
173 IconContent::Element(element) => element,
174 };
175 let icon = div()
176 .size(side)
177 .flex_none()
178 .flex()
179 .items_center()
180 .justify_center()
181 .text_color(tint)
182 .child(icon);
183 match self.name {
184 Some((id, label)) => icon
185 .id(id)
186 .test_support()
187 .role(Role::Image)
188 .aria_label(label)
189 .into_any_element(),
190 None => icon.into_any_element(),
191 }
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198 use std::sync::Arc;
199
200 #[test]
201 fn every_bundled_symbol_rasterizes_without_fonts_or_application_assets() {
202 let renderer = gpui::SvgRenderer::new(Arc::new(()));
203 for name in IconName::ALL {
204 for filled in [false, true] {
205 let data = name.svg_data(filled);
206 let source = std::str::from_utf8(data).unwrap();
208 assert!(!source.contains("<text") && !source.contains("<image"));
209 assert!(!source.contains("href="));
210 for scale in [1., 2.] {
211 let image = renderer
212 .render_single_frame(data, scale)
213 .unwrap_or_else(|error| panic!("{name:?} fill={filled}: {error}"));
214 assert!(
215 image
216 .as_bytes(0)
217 .unwrap()
218 .as_chunks::<4>()
219 .0
220 .iter()
221 .any(|pixel| pixel[3] != 0),
222 "{name:?} fill={filled} must paint visible pixels"
223 );
224 }
225 }
226 }
227 assert_ne!(
228 IconName::Favorite.svg_data(false),
229 IconName::Favorite.svg_data(true)
230 );
231 }
232}