use dioxus::prelude::*;
use crate::class::compose;
#[cfg(feature = "brand-icons")]
#[rustfmt::skip]
#[allow(missing_docs)]
#[cfg_attr(not(feature = "icon-names"), allow(dead_code))]
pub mod brand;
#[rustfmt::skip]
#[allow(missing_docs)]
#[cfg_attr(not(feature = "icon-names"), allow(dead_code))]
pub mod lucide;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconSource {
Lucide,
Brand,
}
impl IconSource {
pub fn as_str(self) -> &'static str {
match self {
Self::Lucide => "lucide",
Self::Brand => "brand",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconStyle {
Stroke,
Fill,
}
#[derive(Debug, PartialEq, Eq)]
pub struct IconNode {
pub tag: &'static str,
pub attributes: &'static [(&'static str, &'static str)],
pub children: &'static [IconNode],
}
#[derive(Debug, PartialEq, Eq)]
pub struct IconData {
pub name: &'static str,
pub source: IconSource,
pub width: u32,
pub height: u32,
pub style: IconStyle,
pub nodes: &'static [IconNode],
}
#[cfg(feature = "icon-names")]
fn to_kebab_case(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 4);
let mut previous: Option<char> = None;
for character in value.trim().chars() {
if character.is_ascii_uppercase()
&& previous.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
{
out.push('-');
}
if character.is_whitespace() || character == '_' {
if !out.ends_with('-') {
out.push('-');
}
} else {
out.push(character.to_ascii_lowercase());
}
previous = Some(character);
}
out
}
#[cfg(feature = "icon-names")]
fn find(
index: &'static [(&'static str, &'static IconData)],
name: &str,
) -> Option<&'static IconData> {
index
.binary_search_by(|(entry, _)| (*entry).cmp(name))
.ok()
.map(|position| index[position].1)
}
#[cfg(feature = "icon-names")]
pub fn icon(name: &str) -> Option<&'static IconData> {
match name.split_once(':') {
None => find(lucide::INDEX, &to_kebab_case(name)),
Some((prefix, rest)) if to_kebab_case(prefix) == "brand" => {
brand_icon(&to_kebab_case(rest))
}
Some(_) => None,
}
}
#[cfg(all(feature = "icon-names", feature = "brand-icons"))]
fn brand_icon(name: &str) -> Option<&'static IconData> {
find(brand::INDEX, name)
}
#[cfg(all(feature = "icon-names", not(feature = "brand-icons")))]
fn brand_icon(_name: &str) -> Option<&'static IconData> {
None
}
#[cfg(feature = "icon-names")]
pub fn icon_names() -> impl Iterator<Item = &'static str> {
lucide::INDEX.iter().map(|(name, _)| *name)
}
fn render_node(node: &'static IconNode) -> Element {
let attributes: Vec<Attribute> = node
.attributes
.iter()
.map(|(name, value)| Attribute::new(name, *value, None, false))
.collect();
let children = node.children.iter().map(render_node);
match node.tag {
"circle" => rsx! { circle { ..attributes, {children} } },
"ellipse" => rsx! { ellipse { ..attributes, {children} } },
"g" => rsx! { g { ..attributes, {children} } },
"line" => rsx! { line { ..attributes, {children} } },
"polygon" => rsx! { polygon { ..attributes, {children} } },
"polyline" => rsx! { polyline { ..attributes, {children} } },
"rect" => rsx! { rect { ..attributes, {children} } },
_ => rsx! { path { ..attributes, {children} } },
}
}
pub fn icon_svg(icon: &'static IconData, class: &str) -> Element {
let filled = icon.style == IconStyle::Fill;
let view_box = format!("0 0 {} {}", icon.width, icon.height);
rsx! {
svg {
"aria-hidden": "true",
class,
fill: if filled { "currentColor" } else { "none" },
"focusable": "false",
height: "1em",
stroke: if filled { "none" } else { "currentColor" },
stroke_linecap: "round",
stroke_linejoin: "round",
stroke_width: if filled { "0" } else { "2" },
view_box,
width: "1em",
xmlns: "http://www.w3.org/2000/svg",
for node in icon.nodes {
{render_node(node)}
}
}
}
}
pub(crate) fn icon_svg_class(icon: &IconData) -> String {
format!("ui-icon__svg {}-{}", icon.source.as_str(), icon.name)
}
#[cfg(feature = "icon-names")]
pub(crate) fn resolve_name(name: Option<&str>) -> Option<&'static IconData> {
name.and_then(icon)
}
#[cfg(not(feature = "icon-names"))]
pub(crate) fn resolve_name(_name: Option<&str>) -> Option<&'static IconData> {
None
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconSize {
#[default]
Default,
Sm,
Lg,
Xl,
}
impl IconSize {
fn class(self) -> Option<&'static str> {
match self {
Self::Default => None,
Self::Sm => Some("ui-icon--sm"),
Self::Lg => Some("ui-icon--lg"),
Self::Xl => Some("ui-icon--xl"),
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct IconProps {
pub icon: Option<&'static IconData>,
#[props(into)]
pub name: Option<String>,
#[props(into)]
pub label: Option<String>,
#[props(into)]
pub aria_label: Option<String>,
pub decorative: Option<bool>,
pub aria_hidden: Option<bool>,
#[props(into)]
pub role: Option<String>,
#[props(default)]
pub size: IconSize,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = span)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Icon(props: IconProps) -> Element {
let artwork = props.icon.or_else(|| resolve_name(props.name.as_deref()));
let label = props.label.or(props.aria_label);
let decorative = props
.decorative
.unwrap_or_else(|| label.as_deref().is_none_or(str::is_empty));
let (aria_hidden, aria_label, role) = if decorative {
(Some(props.aria_hidden.unwrap_or(true)), None, props.role)
} else {
(
props.aria_hidden,
label,
Some(props.role.unwrap_or_else(|| "img".to_string())),
)
};
let class = compose([Some("ui-icon"), props.size.class(), props.class.as_deref()]);
rsx! {
span {
aria_hidden: aria_hidden.map(|hidden| hidden.to_string()),
aria_label,
class,
role,
..props.attributes,
if let Some(artwork) = artwork {
{icon_svg(artwork, &icon_svg_class(artwork))}
} else {
{props.children}
}
}
}
}
#[cfg(all(test, feature = "icon-names"))]
mod tests {
use super::{icon, lucide, to_kebab_case};
#[test]
fn kebab_case_matches_lumen_core() {
assert_eq!(to_kebab_case("ArrowDown"), "arrow-down");
assert_eq!(to_kebab_case("arrow_down"), "arrow-down");
assert_eq!(to_kebab_case(" Trash2 "), "trash2");
}
#[test]
fn resolves_canonical_and_export_names() {
assert_eq!(icon("trash"), Some(&lucide::TRASH));
assert_eq!(icon("Trash"), Some(&lucide::TRASH));
assert_eq!(
icon("arrow-down-0-1").map(|data| data.name),
Some("arrow-down-0-1")
);
assert_eq!(icon("not-an-icon"), None);
assert_eq!(icon("unknown:trash"), None);
}
#[test]
fn index_is_sorted_for_binary_search() {
assert!(lucide::INDEX.windows(2).all(|pair| pair[0].0 < pair[1].0));
}
}