gpui_material_components/
icon.rs1use 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 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
17 pub enum IconName { $($variant),+ }
18
19 impl IconName {
20 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
22
23 pub fn svg_data(self, filled: bool) -> &'static [u8] {
25 match (self, filled) {
26 $((Self::$variant, false) => include_bytes!(concat!("../assets/material-symbols/", $name, "_24px.svg")),
27 (Self::$variant, true) => include_bytes!(concat!("../assets/material-symbols/", $name, "_fill1_24px.svg"))),+
28 }
29 }
30 }
31 };
32}
33
34symbols! {
35 Add => "add",
36 Remove => "remove",
37 Check => "check",
38 Close => "close",
39 ChevronRight => "chevron_right",
40 ArrowForward => "arrow_forward",
41 ArrowDropDown => "arrow_drop_down",
42 Favorite => "favorite",
43 Archive => "archive",
44 Inbox => "inbox",
45 Description => "description",
46 Notifications => "notifications",
47 MotionPhotosOn => "motion_photos_on",
48 Contrast => "contrast",
49 DarkMode => "dark_mode",
50 LightMode => "light_mode",
51 LeftPanelOpen => "left_panel_open",
52 LeftPanelClose => "left_panel_close",
53 Search => "search",
54 Error => "error",
55 Info => "info",
56 Edit => "edit",
57 Exposure => "exposure",
58 Visibility => "visibility",
59 VisibilityOff => "visibility_off",
60}
61
62#[derive(IntoElement)]
67pub struct Icon {
68 content: IconContent,
69 name: Option<(ElementId, SharedString)>,
70 side: Option<Pixels>,
71 color: Option<ColorRole>,
72 color_override: Option<Hsla>,
73 mirror: bool,
74 rotation: Radians,
75 filled: bool,
76}
77
78enum IconContent {
79 Symbol(IconName),
80 Svg(SharedString),
81 SvgData(Arc<[u8]>),
82 Element(AnyElement),
83}
84
85impl Icon {
86 pub fn new(symbol: IconName) -> Self {
87 Self {
88 content: IconContent::Symbol(symbol),
89 name: None,
90 side: None,
91 color: None,
92 color_override: None,
93 mirror: false,
94 rotation: radians(0.),
95 filled: false,
96 }
97 }
98
99 pub fn svg(path: impl Into<SharedString>) -> Self {
101 Self {
102 content: IconContent::Svg(path.into()),
103 side: Some(px(24.)),
104 color: Some(ColorRole::OnSurfaceVariant),
105 ..Self::new(IconName::Info)
106 }
107 }
108
109 pub fn svg_data(data: impl Into<Arc<[u8]>>) -> Self {
111 Self {
112 content: IconContent::SvgData(data.into()),
113 ..Self::new(IconName::Info)
114 }
115 }
116
117 pub fn custom(element: impl IntoElement) -> Self {
118 Self {
119 content: IconContent::Element(element.into_any_element()),
120 ..Self::svg("")
121 }
122 }
123
124 pub fn filled(mut self, filled: bool) -> Self {
126 self.filled = filled;
127 self
128 }
129
130 pub fn label(mut self, id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
131 self.name = Some((id.into(), name.into()));
132 self
133 }
134
135 pub fn size(mut self, side: Pixels) -> Self {
136 self.side = Some(side.max(px(0.)));
137 self
138 }
139
140 pub fn color(mut self, color: ColorRole) -> Self {
141 self.color = Some(color);
142 self.color_override = None;
143 self
144 }
145
146 pub fn color_override(mut self, color: impl Into<Hsla>) -> Self {
149 self.color_override = Some(color.into());
150 self
151 }
152
153 pub fn inherit_color(mut self) -> Self {
156 self.color = None;
157 self.color_override = None;
158 self
159 }
160
161 pub fn mirror_in_rtl(mut self, mirror: bool) -> Self {
162 self.mirror = mirror;
163 self
164 }
165
166 pub fn rotate(mut self, angle: Radians) -> Self {
168 self.rotation = angle;
169 self
170 }
171}
172
173impl RenderOnce for Icon {
174 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
175 let theme = current_material_theme(window, cx);
176 let tint = self.color_override.unwrap_or_else(|| {
177 self.color.map_or_else(
178 || window.text_style().color,
179 |role| color(theme.colors.color(role)),
180 )
181 });
182 let side = self
183 .side
184 .unwrap_or_else(|| window.text_style().font_size.to_pixels(window.rem_size()));
185 let rtl = self.mirror && theme.layout.direction == Direction::Rtl;
186 let transform = Transformation::rotate(self.rotation)
187 .with_scaling(size(if rtl { -1. } else { 1. }, 1.));
188 let icon_svg = || {
189 svg()
190 .size_full()
191 .text_color(tint)
192 .with_transformation(transform)
193 };
194 let icon = match self.content {
195 IconContent::Symbol(symbol) => icon_svg()
196 .data(symbol.svg_data(self.filled))
197 .into_any_element(),
198 IconContent::Svg(path) => icon_svg().path(path).into_any_element(),
199 IconContent::SvgData(data) => icon_svg().data(&data).into_any_element(),
200 IconContent::Element(element) => element,
201 };
202 let icon = div()
203 .size(side)
204 .flex_none()
205 .flex()
206 .items_center()
207 .justify_center()
208 .text_color(tint)
209 .child(icon);
210 match self.name {
211 Some((id, label)) => icon
212 .id(id)
213 .test_support()
214 .role(Role::Image)
215 .aria_label(label)
216 .into_any_element(),
217 None => icon.into_any_element(),
218 }
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 #[test]
227 fn every_bundled_symbol_rasterizes_without_fonts_or_application_assets() {
228 let renderer = gpui::SvgRenderer::new(Arc::new(()));
229 for name in IconName::ALL {
230 for filled in [false, true] {
231 let data = name.svg_data(filled);
232 let source = std::str::from_utf8(data).unwrap();
234 assert!(!source.contains("<text") && !source.contains("<image"));
235 assert!(!source.contains("href="));
236 for scale in [1., 2.] {
237 let image = renderer
238 .render_single_frame(data, scale)
239 .unwrap_or_else(|error| panic!("{name:?} fill={filled}: {error}"));
240 assert!(
241 image
242 .as_bytes(0)
243 .unwrap()
244 .as_chunks::<4>()
245 .0
246 .iter()
247 .any(|pixel| pixel[3] != 0),
248 "{name:?} fill={filled} must paint visible pixels"
249 );
250 }
251 }
252 }
253 assert_ne!(
254 IconName::Favorite.svg_data(false),
255 IconName::Favorite.svg_data(true)
256 );
257 }
258}