Skip to main content

next_rust_icons/
lib.rs

1//! Every [Lucide](https://lucide.dev) icon as a Next Rust component.
2//!
3//! ```
4//! use next_rust_icons as icons;
5//! use next_rust_view::*;
6//!
7//! let html = render_static(div![
8//!     icons::House(),
9//!     icons::ArrowRight().size(16).color("#e11d48").stroke_width(1.5),
10//!     icons::Search().class("text-zinc-500").title("Search"),
11//! ]);
12//! assert!(html.contains(r##"<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#e11d48" stroke-width="1.5""##));
13//! ```
14//!
15//! Each icon is a function named like on lucide.dev in PascalCase
16//! (`arrow-right` → [`ArrowRight`]) returning an [`Icon`](struct@Icon). Everything about
17//! it can be changed:
18//!
19//! | method | default | |
20//! |---|---|---|
21//! | [`size`](Icon::size) | `24` | width and height: a number of pixels or any CSS length (`"1.25em"`) |
22//! | [`color`](Icon::color) | `currentColor` | the stroke color: follows the text color unless set |
23//! | [`stroke_width`](Icon::stroke_width) | `2` | line thickness |
24//! | [`absolute_stroke_width`](Icon::absolute_stroke_width) | `false` | keep the thickness in pixels when resizing |
25//! | [`fill`](Icon::fill) | `none` | fill color |
26//! | [`title`](Icon::title) | none | accessible name; without one the icon is hidden from screen readers |
27//! | [`class`](Icon::class) | none | classes (Tailwind works) |
28//! | [`with`](Icon::with) | | any attribute: `aria(..)`, `data(..)`, `style(..)`, ... |
29//!
30//! Icons render as inline `<svg>` and add nothing to pages that don't use
31//! them; unused icons are left out of the binary. [`by_name`] finds an icon
32//! from a string (that one keeps every icon in the binary).
33//!
34//! The artwork is Lucide's, under the ISC license (`LICENSE-LUCIDE`).
35
36#![forbid(unsafe_code)]
37
38use next_rust_view::{Attr, Element, Node, Part, View, raw_html};
39
40#[allow(non_snake_case)]
41mod generated;
42
43pub use generated::*;
44
45/// The Lucide release the icons come from.
46pub const LUCIDE_VERSION: &str = generated::LUCIDE_VERSION;
47
48/// The drawing of one icon.
49#[derive(Debug, PartialEq, Eq)]
50pub struct IconData {
51    /// Lucide name: `arrow-right`.
52    pub name: &'static str,
53    /// SVG elements inside the 24×24 view box.
54    pub body: &'static str,
55}
56
57/// An icon to render. Created by the icon functions ([`House`], ...) or
58/// [`by_name`]; every method is optional.
59#[derive(Debug)]
60pub struct Icon {
61    data: &'static IconData,
62    size: Option<String>,
63    color: Option<String>,
64    stroke_width: Option<f32>,
65    absolute_stroke_width: bool,
66    fill: Option<String>,
67    title: Option<String>,
68    extra: Element,
69}
70
71impl Icon {
72    pub fn new(data: &'static IconData) -> Self {
73        Icon {
74            data,
75            size: None,
76            color: None,
77            stroke_width: None,
78            absolute_stroke_width: false,
79            fill: None,
80            title: None,
81            extra: Element::new("svg"),
82        }
83    }
84
85    /// Width and height: pixels (`20`, `1.5`) or a CSS length (`"1.25em"`, `"100%"`).
86    pub fn size(mut self, v: impl ToString) -> Self {
87        self.size = Some(v.to_string());
88        self
89    }
90
91    /// Stroke color (`"#e11d48"`, `"var(--brand)"`). Defaults to `currentColor`,
92    /// so the icon takes the text color and CSS classes like `text-red-500` work.
93    pub fn color(mut self, v: impl Into<String>) -> Self {
94        self.color = Some(v.into());
95        self
96    }
97
98    /// Line thickness, in units of the 24×24 drawing (default 2).
99    pub fn stroke_width(mut self, v: f32) -> Self {
100        self.stroke_width = Some(v);
101        self
102    }
103
104    /// Keep the line thickness constant in pixels when the icon is resized.
105    pub fn absolute_stroke_width(mut self, v: bool) -> Self {
106        self.absolute_stroke_width = v;
107        self
108    }
109
110    /// Fill color (default `none`).
111    pub fn fill(mut self, v: impl Into<String>) -> Self {
112        self.fill = Some(v.into());
113        self
114    }
115
116    /// Accessible name, also shown as a tooltip. Icons without one are
117    /// decorative and hidden from screen readers.
118    pub fn title(mut self, v: impl Into<String>) -> Self {
119        self.title = Some(v.into());
120        self
121    }
122
123    /// Classes for the `<svg>` (none by default, to keep pages small).
124    pub fn class(self, v: impl Into<String>) -> Self {
125        self.with(next_rust_view::attrs::class(v.into()))
126    }
127
128    /// Any attribute (`aria(..)`, `data(..)`, `style(..)`, `id(..)`, ...);
129    /// it replaces the default of the same name. Children are added after
130    /// the drawing (`<animate>`, ...).
131    pub fn with(mut self, part: impl Part) -> Self {
132        self.extra = self.extra.with(part);
133        self
134    }
135
136    /// The Lucide name of the icon.
137    pub fn name(&self) -> &'static str {
138        self.data.name
139    }
140
141    fn stroke(&self) -> String {
142        let width = self.stroke_width.unwrap_or(2.0);
143        let px = self.size.as_deref().map(|s| s.trim_end_matches("px")).and_then(|s| s.parse::<f32>().ok());
144        match (self.absolute_stroke_width, px) {
145            (true, Some(px)) if px > 0.0 => number(width * 24.0 / px),
146            _ => number(width),
147        }
148    }
149}
150
151/// `2` rather than `2.0`, at most three decimals.
152fn number(v: f32) -> String {
153    let s = format!("{v:.3}");
154    s.trim_end_matches('0').trim_end_matches('.').to_owned()
155}
156
157impl View for Icon {
158    fn into_node(self) -> Node {
159        let size = self.size.clone().unwrap_or_else(|| "24".into());
160        let mut svg = Element::new("svg");
161        for (name, value) in [
162            ("width", size.clone()),
163            ("height", size),
164            ("viewBox", "0 0 24 24".into()),
165            ("fill", self.fill.clone().unwrap_or_else(|| "none".into())),
166            ("stroke", self.color.clone().unwrap_or_else(|| "currentColor".into())),
167            ("stroke-width", self.stroke()),
168            ("stroke-linecap", "round".into()),
169            ("stroke-linejoin", "round".into()),
170        ] {
171            svg.set_attr(Attr::new(name, value));
172        }
173        match &self.title {
174            Some(title) => {
175                svg.set_attr(Attr::new("role", "img"));
176                svg.set_attr(Attr::new("aria-label", title.clone()));
177                svg.children.push(Element::new("title").with(title.clone()).into_node());
178            }
179            None => svg.set_attr(Attr::new("aria-hidden", "true")),
180        }
181        for a in self.extra.attrs {
182            svg.set_attr(a);
183        }
184        // Trusted: generated from Lucide's drawings.
185        svg.children.push(raw_html(self.data.body));
186        svg.children.extend(self.extra.children);
187        svg.into_node()
188    }
189}
190
191/// Every icon, sorted by name.
192pub fn all() -> &'static [&'static IconData] {
193    generated::ALL
194}
195
196/// The icon with a Lucide name (`"arrow-right"`), for names that come from
197/// data. Using it keeps every icon in the binary; call the icon functions
198/// directly when the name is known.
199/// Former Lucide names (`"home"`, `"trash-2"`) work too.
200pub fn by_name(name: &str) -> Option<Icon> {
201    if let Ok(i) = generated::ALL.binary_search_by(|d| d.name.cmp(name)) {
202        return Some(Icon::new(generated::ALL[i]));
203    }
204    let i = generated::ALIASES.binary_search_by(|(alias, _)| (*alias).cmp(name)).ok()?;
205    Some(Icon::new(generated::ALIASES[i].1))
206}
207
208/// An icon with properties set, in the style of the element macros:
209/// `Icon![House, size = 20, class("text-zinc-500")]`.
210#[macro_export]
211macro_rules! Icon {
212    ($icon:ident $(, $($body:tt)*)?) => { $crate::__icon_munch!([$crate::$icon()] $($($body)*)?) };
213}
214
215#[doc(hidden)]
216#[macro_export]
217macro_rules! __icon_munch {
218    ([$($acc:tt)*]) => { $($acc)* };
219    ([$($acc:tt)*] $key:ident = $val:expr $(, $($rest:tt)*)?) => {
220        $crate::__icon_munch!([$($acc)*.$key($val)] $($($rest)*)?)
221    };
222    ([$($acc:tt)*] $part:expr $(, $($rest:tt)*)?) => {
223        $crate::__icon_munch!([$($acc)*.with($part)] $($($rest)*)?)
224    };
225}