gpui_component/
icon.rs

1use crate::{ActiveTheme, Sizable, Size};
2use gpui::{
3    prelude::FluentBuilder as _, svg, AnyElement, App, AppContext, Context, Entity, Hsla,
4    IntoElement, Radians, Render, RenderOnce, SharedString, StyleRefinement, Styled, Svg,
5    Transformation, Window,
6};
7
8/// Types implementing this trait can automatically be converted to [`Icon`].
9///
10/// This allows you to implement a custom version of [`IconName`] that functions as a drop-in
11/// replacement for other UI components.
12pub trait IconNamed {
13    /// Returns the embedded path of the icon.
14    fn path(self) -> SharedString;
15}
16
17impl<T: IconNamed> From<T> for Icon {
18    fn from(value: T) -> Self {
19        Icon::build(value)
20    }
21}
22
23/// The name of an icon in the asset bundle.
24#[derive(IntoElement, Clone)]
25pub enum IconName {
26    ALargeSmall,
27    ArrowDown,
28    ArrowLeft,
29    ArrowRight,
30    ArrowUp,
31    Asterisk,
32    Bell,
33    BookOpen,
34    Bot,
35    Building2,
36    Calendar,
37    CaseSensitive,
38    ChartPie,
39    Check,
40    ChevronDown,
41    ChevronLeft,
42    ChevronRight,
43    ChevronsUpDown,
44    ChevronUp,
45    CircleCheck,
46    CircleUser,
47    CircleX,
48    Close,
49    Copy,
50    Dash,
51    Delete,
52    Ellipsis,
53    EllipsisVertical,
54    ExternalLink,
55    Eye,
56    EyeOff,
57    File,
58    Folder,
59    FolderClosed,
60    FolderOpen,
61    Frame,
62    GalleryVerticalEnd,
63    GitHub,
64    Globe,
65    Heart,
66    HeartOff,
67    Inbox,
68    Info,
69    Inspector,
70    LayoutDashboard,
71    Loader,
72    LoaderCircle,
73    Map,
74    Maximize,
75    Menu,
76    Minimize,
77    Minus,
78    Moon,
79    Palette,
80    PanelBottom,
81    PanelBottomOpen,
82    PanelLeft,
83    PanelLeftClose,
84    PanelLeftOpen,
85    PanelRight,
86    PanelRightClose,
87    PanelRightOpen,
88    Plus,
89    Replace,
90    ResizeCorner,
91    Search,
92    Settings,
93    Settings2,
94    SortAscending,
95    SortDescending,
96    SquareTerminal,
97    Star,
98    StarOff,
99    Sun,
100    ThumbsDown,
101    ThumbsUp,
102    TriangleAlert,
103    User,
104    WindowClose,
105    WindowMaximize,
106    WindowMinimize,
107    WindowRestore,
108}
109
110impl IconName {
111    /// Return the icon as a Entity<Icon>
112    pub fn view(self, cx: &mut App) -> Entity<Icon> {
113        Icon::build(self).view(cx)
114    }
115}
116
117impl IconNamed for IconName {
118    fn path(self) -> SharedString {
119        match self {
120            Self::ALargeSmall => "icons/a-large-small.svg",
121            Self::ArrowDown => "icons/arrow-down.svg",
122            Self::ArrowLeft => "icons/arrow-left.svg",
123            Self::ArrowRight => "icons/arrow-right.svg",
124            Self::ArrowUp => "icons/arrow-up.svg",
125            Self::Asterisk => "icons/asterisk.svg",
126            Self::Bell => "icons/bell.svg",
127            Self::BookOpen => "icons/book-open.svg",
128            Self::Bot => "icons/bot.svg",
129            Self::Building2 => "icons/building-2.svg",
130            Self::Calendar => "icons/calendar.svg",
131            Self::CaseSensitive => "icons/case-sensitive.svg",
132            Self::ChartPie => "icons/chart-pie.svg",
133            Self::Check => "icons/check.svg",
134            Self::ChevronDown => "icons/chevron-down.svg",
135            Self::ChevronLeft => "icons/chevron-left.svg",
136            Self::ChevronRight => "icons/chevron-right.svg",
137            Self::ChevronsUpDown => "icons/chevrons-up-down.svg",
138            Self::ChevronUp => "icons/chevron-up.svg",
139            Self::CircleCheck => "icons/circle-check.svg",
140            Self::CircleUser => "icons/circle-user.svg",
141            Self::CircleX => "icons/circle-x.svg",
142            Self::Close => "icons/close.svg",
143            Self::Copy => "icons/copy.svg",
144            Self::Dash => "icons/dash.svg",
145            Self::Delete => "icons/delete.svg",
146            Self::Ellipsis => "icons/ellipsis.svg",
147            Self::EllipsisVertical => "icons/ellipsis-vertical.svg",
148            Self::ExternalLink => "icons/external-link.svg",
149            Self::Eye => "icons/eye.svg",
150            Self::EyeOff => "icons/eye-off.svg",
151            Self::File => "icons/file.svg",
152            Self::Folder => "icons/folder.svg",
153            Self::FolderClosed => "icons/folder-closed.svg",
154            Self::FolderOpen => "icons/folder-open.svg",
155            Self::Frame => "icons/frame.svg",
156            Self::GalleryVerticalEnd => "icons/gallery-vertical-end.svg",
157            Self::GitHub => "icons/github.svg",
158            Self::Globe => "icons/globe.svg",
159            Self::Heart => "icons/heart.svg",
160            Self::HeartOff => "icons/heart-off.svg",
161            Self::Inbox => "icons/inbox.svg",
162            Self::Info => "icons/info.svg",
163            Self::Inspector => "icons/inspector.svg",
164            Self::LayoutDashboard => "icons/layout-dashboard.svg",
165            Self::Loader => "icons/loader.svg",
166            Self::LoaderCircle => "icons/loader-circle.svg",
167            Self::Map => "icons/map.svg",
168            Self::Maximize => "icons/maximize.svg",
169            Self::Menu => "icons/menu.svg",
170            Self::Minimize => "icons/minimize.svg",
171            Self::Minus => "icons/minus.svg",
172            Self::Moon => "icons/moon.svg",
173            Self::Palette => "icons/palette.svg",
174            Self::PanelBottom => "icons/panel-bottom.svg",
175            Self::PanelBottomOpen => "icons/panel-bottom-open.svg",
176            Self::PanelLeft => "icons/panel-left.svg",
177            Self::PanelLeftClose => "icons/panel-left-close.svg",
178            Self::PanelLeftOpen => "icons/panel-left-open.svg",
179            Self::PanelRight => "icons/panel-right.svg",
180            Self::PanelRightClose => "icons/panel-right-close.svg",
181            Self::PanelRightOpen => "icons/panel-right-open.svg",
182            Self::Plus => "icons/plus.svg",
183            Self::Replace => "icons/replace.svg",
184            Self::ResizeCorner => "icons/resize-corner.svg",
185            Self::Search => "icons/search.svg",
186            Self::Settings => "icons/settings.svg",
187            Self::Settings2 => "icons/settings-2.svg",
188            Self::SortAscending => "icons/sort-ascending.svg",
189            Self::SortDescending => "icons/sort-descending.svg",
190            Self::SquareTerminal => "icons/square-terminal.svg",
191            Self::Star => "icons/star.svg",
192            Self::StarOff => "icons/star-off.svg",
193            Self::Sun => "icons/sun.svg",
194            Self::ThumbsDown => "icons/thumbs-down.svg",
195            Self::ThumbsUp => "icons/thumbs-up.svg",
196            Self::TriangleAlert => "icons/triangle-alert.svg",
197            Self::User => "icons/user.svg",
198            Self::WindowClose => "icons/window-close.svg",
199            Self::WindowMaximize => "icons/window-maximize.svg",
200            Self::WindowMinimize => "icons/window-minimize.svg",
201            Self::WindowRestore => "icons/window-restore.svg",
202        }
203        .into()
204    }
205}
206
207impl From<IconName> for AnyElement {
208    fn from(val: IconName) -> Self {
209        Icon::build(val).into_any_element()
210    }
211}
212
213impl RenderOnce for IconName {
214    fn render(self, _: &mut Window, _cx: &mut App) -> impl IntoElement {
215        Icon::build(self)
216    }
217}
218
219#[derive(IntoElement)]
220pub struct Icon {
221    base: Svg,
222    style: StyleRefinement,
223    path: SharedString,
224    text_color: Option<Hsla>,
225    size: Option<Size>,
226    rotation: Option<Radians>,
227}
228
229impl Default for Icon {
230    fn default() -> Self {
231        Self {
232            base: svg().flex_none().size_4(),
233            style: StyleRefinement::default(),
234            path: "".into(),
235            text_color: None,
236            size: None,
237            rotation: None,
238        }
239    }
240}
241
242impl Clone for Icon {
243    fn clone(&self) -> Self {
244        let mut this = Self::default().path(self.path.clone());
245        this.style = self.style.clone();
246        this.rotation = self.rotation;
247        this.size = self.size;
248        this.text_color = self.text_color;
249        this
250    }
251}
252
253impl Icon {
254    pub fn new(icon: impl Into<Icon>) -> Self {
255        icon.into()
256    }
257
258    fn build(name: impl IconNamed) -> Self {
259        Self::default().path(name.path())
260    }
261
262    /// Set the icon path of the Assets bundle
263    ///
264    /// For example: `icons/foo.svg`
265    pub fn path(mut self, path: impl Into<SharedString>) -> Self {
266        self.path = path.into();
267        self
268    }
269
270    /// Create a new view for the icon
271    pub fn view(self, cx: &mut App) -> Entity<Icon> {
272        cx.new(|_| self)
273    }
274
275    pub fn transform(mut self, transformation: gpui::Transformation) -> Self {
276        self.base = self.base.with_transformation(transformation);
277        self
278    }
279
280    pub fn empty() -> Self {
281        Self::default()
282    }
283
284    /// Rotate the icon by the given angle
285    pub fn rotate(mut self, radians: impl Into<Radians>) -> Self {
286        self.base = self
287            .base
288            .with_transformation(Transformation::rotate(radians));
289        self
290    }
291}
292
293impl Styled for Icon {
294    fn style(&mut self) -> &mut StyleRefinement {
295        &mut self.style
296    }
297
298    fn text_color(mut self, color: impl Into<Hsla>) -> Self {
299        self.text_color = Some(color.into());
300        self
301    }
302}
303
304impl Sizable for Icon {
305    fn with_size(mut self, size: impl Into<Size>) -> Self {
306        self.size = Some(size.into());
307        self
308    }
309}
310
311impl RenderOnce for Icon {
312    fn render(self, window: &mut Window, _cx: &mut App) -> impl IntoElement {
313        let text_color = self.text_color.unwrap_or_else(|| window.text_style().color);
314        let text_size = window.text_style().font_size.to_pixels(window.rem_size());
315        let has_base_size = self.style.size.width.is_some() || self.style.size.height.is_some();
316
317        let mut base = self.base;
318        *base.style() = self.style;
319
320        base.flex_shrink_0()
321            .text_color(text_color)
322            .when(!has_base_size, |this| this.size(text_size))
323            .when_some(self.size, |this, size| match size {
324                Size::Size(px) => this.size(px),
325                Size::XSmall => this.size_3(),
326                Size::Small => this.size_3p5(),
327                Size::Medium => this.size_4(),
328                Size::Large => this.size_6(),
329            })
330            .path(self.path)
331    }
332}
333
334impl From<Icon> for AnyElement {
335    fn from(val: Icon) -> Self {
336        val.into_any_element()
337    }
338}
339
340impl Render for Icon {
341    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
342        let text_color = self.text_color.unwrap_or_else(|| cx.theme().foreground);
343        let text_size = window.text_style().font_size.to_pixels(window.rem_size());
344        let has_base_size = self.style.size.width.is_some() || self.style.size.height.is_some();
345
346        let mut base = svg().flex_none();
347        *base.style() = self.style.clone();
348
349        base.flex_shrink_0()
350            .text_color(text_color)
351            .when(!has_base_size, |this| this.size(text_size))
352            .when_some(self.size, |this, size| match size {
353                Size::Size(px) => this.size(px),
354                Size::XSmall => this.size_3(),
355                Size::Small => this.size_3p5(),
356                Size::Medium => this.size_4(),
357                Size::Large => this.size_6(),
358            })
359            .path(self.path.clone())
360            .when_some(self.rotation, |this, rotation| {
361                this.with_transformation(Transformation::rotate(rotation))
362            })
363    }
364}