BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / icon.rs

icon.rs

icon.rs 9.3 KiB Download Raw
1use std::sync::Arc;
2
3use crate::{ActiveTheme, Sizable, Size};
4use gpui::{
5 AnyElement, App, AppContext, Context, Entity, Hsla, IntoElement, Pixels, Radians, Render,
6 RenderOnce, SharedString, StyleRefinement, Styled, Svg, Transformation, Window,
7 prelude::FluentBuilder as _, svg,
8};
9pub use gpui_kit_assets::IconNamed;
10
11// Preserve the original enum (including exhaustive matches and inherent view)
12// while the complete, shared catalog is owned by gpui-kit-assets.
13macro_rules! component_icon_names {
14 ($($name:ident => $path:literal,)*) => {
15 /// Default component icon names, retained for source compatibility.
16 /// For the complete Lucide catalog, use `gpui_kit_assets::IconName`.
17 #[derive(Clone, IntoElement)]
18 pub enum IconName {
19 $($name,)*
20 }
21
22 impl From<IconName> for gpui_kit_assets::IconName {
23 fn from(name: IconName) -> Self {
24 match name {
25 $(IconName::$name => Self::$name,)*
26 }
27 }
28 }
29
30 impl IconNamed for IconName {
31 fn path(self) -> SharedString {
32 match self { $(Self::$name => $path,)* }.into()
33 }
34 }
35 };
36}
37
38gpui_kit_assets::__component_icon_names!(component_icon_names);
39
40impl IconName {
41 /// Return the icon as an Entity<Icon>.
42 pub fn view(self, cx: &mut App) -> Entity<Icon> {
43 Icon::build(self).view(cx)
44 }
45}
46
47impl From<IconName> for AnyElement {
48 fn from(name: IconName) -> Self {
49 Icon::build(name).into_any_element()
50 }
51}
52
53impl RenderOnce for IconName {
54 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
55 Icon::build(self)
56 }
57}
58
59impl<T: IconNamed> From<T> for Icon {
60 fn from(value: T) -> Self {
61 Icon::build(value)
62 }
63}
64
65/// Component view construction for the shared `gpui_kit_assets::IconName`.
66/// The legacy component `IconName` retains its inherent `view` method.
67pub trait IconNameExt {
68 fn view(self, cx: &mut App) -> Entity<Icon>;
69}
70
71impl IconNameExt for gpui_kit_assets::IconName {
72 fn view(self, cx: &mut App) -> Entity<Icon> {
73 Icon::build(self).view(cx)
74 }
75}
76
77#[derive(Clone)]
78pub(crate) enum IconSource {
79 Path(SharedString),
80 Data(Arc<[u8]>),
81}
82
83#[derive(Clone, IntoElement)]
84pub struct Icon {
85 style: StyleRefinement,
86 source: IconSource,
87 text_color: Option<Hsla>,
88 size: Option<Size>,
89 transformation: Option<Transformation>,
90}
91
92impl Default for Icon {
93 fn default() -> Self {
94 Self {
95 style: StyleRefinement::default(),
96 source: IconSource::Path("".into()),
97 text_color: None,
98 size: None,
99 transformation: None,
100 }
101 }
102}
103
104impl Icon {
105 pub fn new(icon: impl Into<Icon>) -> Self {
106 icon.into()
107 }
108
109 fn build(name: impl IconNamed) -> Self {
110 Self::default().path(name.path())
111 }
112
113 /// Set the icon path of the Assets bundle
114 ///
115 /// For example: `icons/foo.svg`
116 /// Replaces any previously set path or SVG data.
117 pub fn path(mut self, path: impl Into<SharedString>) -> Self {
118 self.source = IconSource::Path(path.into());
119 self
120 }
121
122 /// Set raw SVG bytes without registering an asset path.
123 ///
124 /// Copies the bytes into shared storage; the input need not be static.
125 /// Cloning the icon shares those bytes. Replaces any previously set path or data.
126 /// Parsing and rendering follow GPUI's SVG behavior.
127 ///
128 /// ```
129 /// use gpui_component::Icon;
130 ///
131 /// let bytes = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
132 /// <path d="M4 12h16" stroke="currentColor"/>
133 /// </svg>"#;
134 /// let icon = Icon::default().data(bytes);
135 /// ```
136 pub fn data(mut self, data: &[u8]) -> Self {
137 self.source = IconSource::Data(Arc::from(data));
138 self
139 }
140
141 #[cfg(any(target_os = "macos", target_os = "windows", test))]
142 pub(crate) fn source_ref(&self) -> &IconSource {
143 &self.source
144 }
145
146 /// Whether `other` takes up exactly the same space as this icon. The
147 /// source, color and transformation change only what it paints.
148 pub(crate) fn same_layout(&self, other: &Self) -> bool {
149 self.style == other.style && self.size == other.size
150 }
151
152 /// Create a new view for the icon
153 pub fn view(self, cx: &mut App) -> Entity<Icon> {
154 cx.new(|_| self)
155 }
156
157 /// Set the SVG transformation, replacing any previous transformation or rotation.
158 pub fn transform(mut self, transformation: gpui::Transformation) -> Self {
159 self.transformation = Some(transformation);
160 self
161 }
162
163 pub fn empty() -> Self {
164 Self::default()
165 }
166
167 pub(crate) fn has_explicit_size(&self) -> bool {
168 self.size.is_some() || self.style.size.width.is_some() || self.style.size.height.is_some()
169 }
170
171 /// Rotate the icon by the given angle
172 ///
173 /// Replaces any previous transformation or rotation.
174 pub fn rotate(mut self, radians: impl Into<Radians>) -> Self {
175 self.transformation = Some(Transformation::rotate(radians));
176 self
177 }
178
179 fn into_svg(self, text_size: Pixels, fallback_color: Hsla) -> Svg {
180 let text_color = self.text_color.unwrap_or(fallback_color);
181 let has_base_size = self.style.size.width.is_some() || self.style.size.height.is_some();
182
183 svg()
184 .map(|mut this| {
185 *this.style() = self.style;
186 this
187 })
188 .flex_shrink_0()
189 .text_color(text_color)
190 .when(!has_base_size, |this| this.size(text_size))
191 .when_some(self.size, |this, size| match size {
192 Size::Size(px) => this.size(px),
193 Size::XSmall => this.size_3(),
194 Size::Small => this.size_3p5(),
195 Size::Medium => this.size_4(),
196 Size::Large => this.size_6(),
197 })
198 .map(|this| match self.source {
199 IconSource::Path(path) => this.path(path),
200 IconSource::Data(data) => this.data(&data),
201 })
202 .when_some(self.transformation, |this, transformation| {
203 this.with_transformation(transformation)
204 })
205 }
206}
207
208impl Styled for Icon {
209 fn style(&mut self) -> &mut StyleRefinement {
210 &mut self.style
211 }
212
213 fn text_color(mut self, color: impl Into<Hsla>) -> Self {
214 self.text_color = Some(color.into());
215 self
216 }
217}
218
219impl Sizable for Icon {
220 fn with_size(mut self, size: impl Into<Size>) -> Self {
221 self.size = Some(size.into());
222 self
223 }
224}
225
226impl RenderOnce for Icon {
227 fn render(self, window: &mut Window, _cx: &mut App) -> impl IntoElement {
228 let text_size = window.text_style().font_size.to_pixels(window.rem_size());
229 self.into_svg(text_size, window.text_style().color)
230 }
231}
232
233impl From<Icon> for AnyElement {
234 fn from(val: Icon) -> Self {
235 val.into_any_element()
236 }
237}
238
239impl Render for Icon {
240 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
241 let text_size = window.text_style().font_size.to_pixels(window.rem_size());
242 self.clone().into_svg(text_size, cx.theme().foreground)
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249 use gpui::{px, size};
250
251 const SVG: &[u8] = include_bytes!("../../assets/assets/icons/arrow-up.svg");
252
253 #[test]
254 fn test_icon_builder_preserves_owned_data_and_transform_on_clone() {
255 let transformation = Transformation::scale(size(0.5, 0.5))
256 .with_rotation(gpui::radians(std::f32::consts::FRAC_PI_2));
257 let icon = {
258 let bytes = SVG.to_vec();
259 Icon::default()
260 .data(&bytes)
261 .large()
262 .text_color(gpui::red())
263 .transform(transformation)
264 };
265 let cloned = icon.clone();
266 let (IconSource::Data(original), IconSource::Data(copy)) = (&icon.source, &cloned.source)
267 else {
268 panic!("cloning must preserve the data source");
269 };
270 assert_eq!(copy.as_ref(), SVG);
271 assert!(Arc::ptr_eq(original, copy));
272 assert_eq!(cloned.transformation, Some(transformation));
273 assert_eq!(cloned.size, icon.size);
274 assert_eq!(cloned.text_color, icon.text_color);
275
276 let mut svg = cloned.into_svg(px(12.), gpui::blue());
277 assert_eq!(svg.style().text.color, Some(gpui::red()));
278 assert_eq!(svg.style().size.width, Some(gpui::rems(1.5).into()));
279
280 let rotated = icon.rotate(gpui::radians(std::f32::consts::PI)).clone();
281 assert_eq!(
282 rotated.transformation,
283 Some(Transformation::rotate(gpui::radians(std::f32::consts::PI)))
284 );
285 }
286
287 #[test]
288 fn test_icon_source_builders_replace_previous_source() {
289 let icon = Icon::new(IconName::Search).data(SVG);
290 assert!(matches!(icon.source_ref(), IconSource::Data(bytes) if bytes.as_ref() == SVG));
291
292 let icon = icon.path("icons/replacement.svg");
293 assert!(
294 matches!(icon.source_ref(), IconSource::Path(path) if path == "icons/replacement.svg")
295 );
296
297 let icon = icon.data(SVG).data(b"replacement");
298 assert!(
299 matches!(icon.source_ref(), IconSource::Data(bytes) if bytes.as_ref() == b"replacement")
300 );
301
302 let icon = icon.path("");
303 assert!(matches!(icon.source_ref(), IconSource::Path(path) if path.is_empty()));
304 }
305}