forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

icons.rs275 lines, 8.8 KiBHistoryRawDownload
1//! REDESIGN §1.4 -- the icon set. Lucide (ISC; licence in
2//! `assets/icons/LICENSE-lucide.txt`), vendored as SVG under `assets/icons/`
3//! by `scripts/prep_icons.py` (stroke baked white, 24 grid) and compiled into
4//! the binary: [`Assets`] is the `gpui::AssetSource` handed to
5//! `Application::with_assets`, so `svg().path("icons/play.svg")` resolves
6//! with nothing installed beside the executable.
7//!
8//! gpui rasterises the SVG through resvg to an alpha mask and tints it with the
9//! element's `text_color`, which is why the files are white and why every icon
10//! takes its colour from the theme at the call site:
11//!
12//! ```ignore
13//! Icon::Play.el(IconSize::Toolbar, ink2()) // rest
14//! Icon::Play.el(IconSize::Toolbar, tokens().accent) // a toggle that is on
15//! ```
16//!
17//! Colour policy (§1.4): `ink2` at rest, `ink1` on hover, `accent` when a
18//! toggle is on, `ink4` disabled; [`Icon::tint`] applies it from an [`IconState`].
19//! The lane glyphs (a record dot, a note, a square) stay typographic and are not here.
20
21use crate::ui::theme::tokens;
22use gpui::{AssetSource, Pixels, Result, SharedString, Svg, px, rgb, svg, Styled};
23use std::borrow::Cow;
24
25/// The three sizes §1.4 allows (stroke is baked for the 16 and 20 px renders).
26#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27pub enum IconSize {
28 /// Lane heads, menus, inspector, dock rows, buttons that also carry a label.
29 Inline,
30 /// Transport and icon-only toolbar buttons.
31 Toolbar,
32 /// The empty-state hero only.
33 Hero,
34}
35
36impl IconSize {
37 pub const fn px(self) -> f32 {
38 match self {
39 IconSize::Inline => 16.,
40 IconSize::Toolbar => 20.,
41 IconSize::Hero => 40.,
42 }
43 }
44}
45
46/// Where an icon is in its life, which decides its tint (§1.4 colour rule).
47#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub enum IconState {
49 Rest,
50 Hover,
51 /// A toggle or tool that is on.
52 On,
53 Disabled,
54}
55
56macro_rules! icons {
57 ($($variant:ident = $file:literal,)+) => {
58 /// One variant per vendored SVG. A variant without its file fails to build.
59 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
60 pub enum Icon { $($variant,)+ }
61
62 impl Icon {
63 /// Every icon, for the gallery and the "every file is used" test.
64 pub const ALL: &'static [Icon] = &[$(Icon::$variant,)+ ];
65
66
67 /// The icon's file stem, e.g. `"skip-back"`.
68 pub const fn name(self) -> &'static str {
69 match self { $(Icon::$variant => $file,)+ }
70 }
71
72 const fn bytes(self) -> &'static [u8] {
73 match self {
74 $(Icon::$variant => include_bytes!(concat!(
75 env!("CARGO_MANIFEST_DIR"), "/../../assets/icons/", $file, ".svg"
76 )),)+
77 }
78 }
79 }
80
81 /// (asset path, bytes) for every icon.
82 const TABLE: &[(&str, &[u8])] = &[
83 $((concat!("icons/", $file, ".svg"), Icon::$variant.bytes()),)+
84 ];
85 };
86}
87
88icons! {
89 ArrowLeftToLine = "arrow-left-to-line",
90 // The same file turned half a revolution in `Icon::el_px`: no second SVG.
91 ArrowRightToLine = "arrow-left-to-line",
92 AudioWaveform = "audio-waveform",
93 Brackets = "brackets",
94 Captions = "captions",
95 Check = "check",
96 ChevronDown = "chevron-down",
97 ChevronLeft = "chevron-left",
98 ChevronRight = "chevron-right",
99 ChevronUp = "chevron-up",
100 CircleCheck = "circle-check",
101 CircleHelp = "circle-help",
102 CircleX = "circle-x",
103 Clapperboard = "clapperboard",
104 Clipboard = "clipboard",
105 Copy = "copy",
106 Download = "download",
107 Ellipsis = "ellipsis",
108 Eraser = "eraser",
109 Eye = "eye",
110 EyeOff = "eye-off",
111 Film = "film",
112 Flag = "flag",
113 FlagTriangleRight = "flag-triangle-right",
114 Folder = "folder",
115 FolderOpen = "folder-open",
116 Gauge = "gauge",
117 Activity = "activity",
118 Diamond = "diamond",
119 FastForward = "fast-forward",
120 KeyRound = "key-round",
121 Signal = "signal",
122 Spline = "spline",
123 Timer = "timer",
124 TrendingDown = "trending-down",
125 TrendingUp = "trending-up",
126 Zap = "zap",
127 Grid3x3 = "grid-3x3",
128 GripVertical = "grip-vertical",
129 Image = "image",
130 Info = "info",
131 Keyboard = "keyboard",
132 Layers = "layers",
133 Link = "link",
134 LoaderCircle = "loader-circle",
135 Lock = "lock",
136 LockOpen = "lock-open",
137 Magnet = "magnet",
138 Mic = "mic",
139 Minus = "minus",
140 Move = "move",
141 Palette = "palette",
142 Pause = "pause",
143 Play = "play",
144 Plus = "plus",
145 Redo2 = "redo-2",
146 RefreshCw = "refresh-cw",
147 Repeat = "repeat",
148 RotateCcw = "rotate-ccw",
149 Save = "save",
150 Scaling = "scaling",
151 Scan = "scan",
152 Scissors = "scissors",
153 Search = "search",
154 Settings = "settings",
155 SkipBack = "skip-back",
156 SkipForward = "skip-forward",
157 SlidersHorizontal = "sliders-horizontal",
158 Sparkles = "sparkles",
159 SquareArrowDownLeft = "square-arrow-down-left",
160 SquareArrowDownRight = "square-arrow-down-right",
161 Star = "star",
162 StarFilled = "star-filled",
163 StepBack = "step-back",
164 StepForward = "step-forward",
165 Trash2 = "trash-2",
166 TriangleAlert = "triangle-alert",
167 Type = "type",
168 Undo2 = "undo-2",
169 Unlink = "unlink",
170 Upload = "upload",
171 Volume2 = "volume-2",
172 VolumeX = "volume-x",
173 WandSparkles = "wand-sparkles",
174 Wrench = "wrench",
175 X = "x",
176 ZoomIn = "zoom-in",
177 ZoomOut = "zoom-out",
178 ArrowRight = "arrow-right",
179 // The same file turned a quarter revolution in `Icon::el_px`: no second SVG.
180 ArrowUp = "arrow-right",
181 ArrowDown = "arrow-right",
182 Circle = "circle",
183 Square = "square",
184}
185
186impl Icon {
187 /// The path `svg().path(..)` resolves through [`Assets`].
188 pub fn path(self) -> SharedString {
189 format!("icons/{}.svg", self.name()).into()
190 }
191
192 /// The icon as an element, `size` square, tinted `color` (a theme `0xRRGGBB`).
193 /// Further `Styled` calls (margins, `flex_none`) chain on the result.
194 pub fn el(self, size: IconSize, color: u32) -> Svg {
195 self.el_px(px(size.px()), color)
196 }
197
198 /// [`Icon::el`] at an exact size, for the rare in-between slot.
199 pub fn el_px(self, size: Pixels, color: u32) -> Svg {
200 let el = svg().path(self.path()).size(size).flex_none().text_color(rgb(color));
201 let turn = match self {
202 Icon::ArrowRightToLine => std::f32::consts::PI,
203 Icon::ArrowUp => -std::f32::consts::FRAC_PI_2,
204 Icon::ArrowDown => std::f32::consts::FRAC_PI_2,
205 _ => return el,
206 };
207 el.with_transformation(gpui::Transformation::rotate(gpui::radians(turn)))
208 }
209
210 /// The tint the colour rule gives an icon in `state`.
211 pub fn tint(state: IconState) -> u32 {
212 let t = tokens();
213 match state {
214 IconState::Rest => t.ink2,
215 IconState::Hover => t.ink1,
216 IconState::On => t.accent,
217 IconState::Disabled => t.ink4,
218 }
219 }
220
221 /// [`Icon::el`] tinted for `state`.
222 pub fn stated(self, size: IconSize, state: IconState) -> Svg {
223 self.el(size, Self::tint(state))
224 }
225}
226
227/// The app's `AssetSource`: the embedded icon table and nothing else.
228pub struct Assets;
229
230impl AssetSource for Assets {
231 fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
232 Ok(TABLE.iter().find(|(p, _)| *p == path).map(|(_, b)| Cow::Borrowed(*b)))
233 }
234
235 fn list(&self, path: &str) -> Result<Vec<SharedString>> {
236 Ok(TABLE
237 .iter()
238 .filter(|(p, _)| p.starts_with(path))
239 .map(|(p, _)| SharedString::from(*p))
240 .collect())
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 /// Every vendored file is a white-stroked 24 grid SVG gpui can tint, and
249 /// every file in `assets/icons/` has a variant (no orphans).
250 #[test]
251 fn every_icon_is_baked_and_every_file_has_a_variant() {
252 for icon in Icon::ALL {
253 let s = std::str::from_utf8(icon.bytes()).unwrap();
254 assert!(s.contains("viewBox=\"0 0 24 24\""), "{}", icon.name());
255 assert!(!s.contains("currentColor"), "{} is not baked", icon.name());
256 assert!(Assets.load(&icon.path()).unwrap().is_some());
257 }
258 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/icons");
259 let files = std::fs::read_dir(dir)
260 .unwrap()
261 .filter_map(|e| e.ok()?.path().file_stem().map(|s| s.to_string_lossy().into_owned()))
262 .filter(|n| n != "LICENSE-lucide")
263 .count();
264 let named: std::collections::HashSet<_> = Icon::ALL.iter().map(|i| i.name()).collect();
265 assert_eq!(files, named.len(), "an svg without a variant");
266 }
267
268 #[test]
269 fn sizes_are_the_three_the_spec_allows() {
270 assert_eq!(
271 [IconSize::Inline, IconSize::Toolbar, IconSize::Hero].map(IconSize::px),
272 [16., 20., 40.]
273 );
274 }
275}