gpui_material_components/
icon.rs1use std::sync::Arc;
2
3use gpui::{
4 AnyElement, App, ElementId, InteractiveElement, IntoElement, ParentElement, Pixels, Radians,
5 RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Transformation, Window,
6 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}
59
60#[derive(IntoElement)]
65pub struct Icon {
66 content: IconContent,
67 name: Option<(ElementId, SharedString)>,
68 side: Option<Pixels>,
69 color: Option<ColorRole>,
70 mirror: bool,
71 rotation: Radians,
72 filled: bool,
73}
74
75enum IconContent {
76 Symbol(IconName),
77 Svg(SharedString),
78 SvgData(Arc<[u8]>),
79 Element(AnyElement),
80}
81
82impl Icon {
83 pub fn new(symbol: IconName) -> Self {
84 Self {
85 content: IconContent::Symbol(symbol),
86 name: None,
87 side: None,
88 color: None,
89 mirror: false,
90 rotation: radians(0.),
91 filled: false,
92 }
93 }
94
95 pub fn svg(path: impl Into<SharedString>) -> Self {
97 Self {
98 content: IconContent::Svg(path.into()),
99 side: Some(px(24.)),
100 color: Some(ColorRole::OnSurfaceVariant),
101 ..Self::new(IconName::Info)
102 }
103 }
104
105 pub fn svg_data(data: impl Into<Arc<[u8]>>) -> Self {
107 Self {
108 content: IconContent::SvgData(data.into()),
109 ..Self::new(IconName::Info)
110 }
111 }
112
113 pub fn custom(element: impl IntoElement) -> Self {
114 Self {
115 content: IconContent::Element(element.into_any_element()),
116 ..Self::svg("")
117 }
118 }
119
120 pub fn filled(mut self, filled: bool) -> Self {
122 self.filled = filled;
123 self
124 }
125
126 pub fn label(mut self, id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
127 self.name = Some((id.into(), name.into()));
128 self
129 }
130
131 pub fn size(mut self, side: Pixels) -> Self {
132 self.side = Some(side.max(px(0.)));
133 self
134 }
135
136 pub fn color(mut self, color: ColorRole) -> Self {
137 self.color = Some(color);
138 self
139 }
140
141 #[cfg_attr(not(feature = "full"), allow(dead_code))]
142 pub(crate) fn inherit_color(mut self) -> Self {
143 self.color = None;
144 self
145 }
146
147 pub fn mirror_in_rtl(mut self, mirror: bool) -> Self {
148 self.mirror = mirror;
149 self
150 }
151
152 pub fn rotate(mut self, angle: Radians) -> Self {
154 self.rotation = angle;
155 self
156 }
157}
158
159impl RenderOnce for Icon {
160 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
161 let theme = current_material_theme(window, cx);
162 let tint = self.color.map_or_else(
163 || window.text_style().color,
164 |role| color(theme.colors.color(role)),
165 );
166 let side = self
167 .side
168 .unwrap_or_else(|| window.text_style().font_size.to_pixels(window.rem_size()));
169 let rtl = self.mirror && theme.layout.direction == Direction::Rtl;
170 let transform = Transformation::rotate(self.rotation)
171 .with_scaling(size(if rtl { -1. } else { 1. }, 1.));
172 let icon_svg = || {
173 svg()
174 .size_full()
175 .text_color(tint)
176 .with_transformation(transform)
177 };
178 let icon = match self.content {
179 IconContent::Symbol(symbol) => icon_svg()
180 .data(symbol.svg_data(self.filled))
181 .into_any_element(),
182 IconContent::Svg(path) => icon_svg().path(path).into_any_element(),
183 IconContent::SvgData(data) => icon_svg().data(&data).into_any_element(),
184 IconContent::Element(element) => element,
185 };
186 let icon = div()
187 .size(side)
188 .flex_none()
189 .flex()
190 .items_center()
191 .justify_center()
192 .text_color(tint)
193 .child(icon);
194 match self.name {
195 Some((id, label)) => icon
196 .id(id)
197 .test_support()
198 .role(Role::Image)
199 .aria_label(label)
200 .into_any_element(),
201 None => icon.into_any_element(),
202 }
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn every_bundled_symbol_rasterizes_without_fonts_or_application_assets() {
212 let renderer = gpui::SvgRenderer::new(Arc::new(()));
213 for name in IconName::ALL {
214 for filled in [false, true] {
215 let data = name.svg_data(filled);
216 let source = std::str::from_utf8(data).unwrap();
218 assert!(!source.contains("<text") && !source.contains("<image"));
219 assert!(!source.contains("href="));
220 for scale in [1., 2.] {
221 let image = renderer
222 .render_single_frame(data, scale)
223 .unwrap_or_else(|error| panic!("{name:?} fill={filled}: {error}"));
224 assert!(
225 image
226 .as_bytes(0)
227 .unwrap()
228 .as_chunks::<4>()
229 .0
230 .iter()
231 .any(|pixel| pixel[3] != 0),
232 "{name:?} fill={filled} must paint visible pixels"
233 );
234 }
235 }
236 }
237 assert_ne!(
238 IconName::Favorite.svg_data(false),
239 IconName::Favorite.svg_data(true)
240 );
241 }
242}