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