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 {
18 $(
19 #[doc = concat!("Material Symbols Outlined `", $name, "` glyph.")]
20 $variant
21 ),+
22 }
23
24 impl IconName {
25 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
27
28 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#[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 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 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 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 pub fn custom(element: impl IntoElement) -> Self {
125 Self {
126 content: IconContent::Element(element.into_any_element()),
127 ..Self::svg("")
128 }
129 }
130
131 pub fn filled(mut self, filled: bool) -> Self {
133 self.filled = filled;
134 self
135 }
136
137 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 pub fn size(mut self, side: Pixels) -> Self {
146 if f32::from(side).is_finite() {
147 self.side = Some(side.max(px(0.)));
148 }
149 self
150 }
151
152 pub fn color(mut self, color: ColorRole) -> Self {
154 self.color = Some(color);
155 self.color_override = None;
156 self
157 }
158
159 pub fn color_override(mut self, color: impl Into<Hsla>) -> Self {
162 self.color_override = Some(color.into());
163 self
164 }
165
166 pub fn inherit_color(mut self) -> Self {
169 self.color = None;
170 self.color_override = None;
171 self
172 }
173
174 pub fn mirror_in_rtl(mut self, mirror: bool) -> Self {
176 self.mirror = mirror;
177 self
178 }
179
180 pub fn rotate(mut self, angle: Radians) -> Self {
183 if angle.0.is_finite() {
184 self.rotation = angle;
185 }
186 self
187 }
188}
189
190impl RenderOnce for Icon {
191 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
192 let theme = current_material_theme(window, cx);
193 let tint = self.color_override.unwrap_or_else(|| {
194 self.color.map_or_else(
195 || window.text_style().color,
196 |role| color(theme.colors.color(role)),
197 )
198 });
199 let side = self
200 .side
201 .unwrap_or_else(|| window.text_style().font_size.to_pixels(window.rem_size()));
202 let rtl = self.mirror && theme.layout.direction == Direction::Rtl;
203 let transform = Transformation::rotate(self.rotation)
204 .with_scaling(size(if rtl { -1. } else { 1. }, 1.));
205 let icon_svg = || {
206 svg()
207 .size_full()
208 .text_color(tint)
209 .with_transformation(transform)
210 };
211 let icon = match self.content {
212 IconContent::Symbol(symbol) => icon_svg()
213 .data(symbol.svg_data(self.filled))
214 .into_any_element(),
215 IconContent::Svg(path) => icon_svg().path(path).into_any_element(),
216 IconContent::SvgData(data) => icon_svg().data(&data).into_any_element(),
217 IconContent::Element(element) => {
218 if rtl {
221 div()
222 .size_full()
223 .flex()
224 .flex_row_reverse()
225 .items_center()
226 .justify_center()
227 .child(element)
228 .into_any_element()
229 } else {
230 element
231 }
232 }
233 };
234 let icon = div()
235 .size(side)
236 .flex_none()
237 .flex()
238 .items_center()
239 .justify_center()
240 .text_color(tint)
241 .child(icon);
242 match self.name {
243 Some((id, label)) => icon
244 .id(id)
245 .test_support()
246 .role(Role::Image)
247 .aria_label(label)
248 .into_any_element(),
249 None => icon.into_any_element(),
250 }
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
259 fn every_bundled_symbol_rasterizes_without_fonts_or_application_assets() {
260 let renderer = gpui::SvgRenderer::new(Arc::new(()));
261 for name in IconName::ALL {
262 for filled in [false, true] {
263 let data = name.svg_data(filled);
264 let source = std::str::from_utf8(data).unwrap();
266 assert!(!source.contains("<text") && !source.contains("<image"));
267 assert!(!source.contains("href="));
268 for scale in [1., 2.] {
269 let image = renderer
270 .render_single_frame(data, scale)
271 .unwrap_or_else(|error| panic!("{name:?} fill={filled}: {error}"));
272 assert!(
273 image
274 .as_bytes(0)
275 .unwrap()
276 .as_chunks::<4>()
277 .0
278 .iter()
279 .any(|pixel| pixel[3] != 0),
280 "{name:?} fill={filled} must paint visible pixels"
281 );
282 }
283 }
284 }
285 assert_ne!(
286 IconName::Favorite.svg_data(false),
287 IconName::Favorite.svg_data(true)
288 );
289 }
290}