lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Icons: the complete Lucide interface catalog, optional Font Awesome brand icons, and [`Icon`].
//!
//! Every Lucide icon is a constant in [`lucide`], named after its canonical kebab-case name in
//! upper snake case (`trash` is [`lucide::TRASH`], `arrow-down-0-1` is `ARROW_DOWN_0_1`; names that
//! start with a digit get an `ICON_` prefix, such as `brand::ICON_500PX`). Pass a constant to
//! `Icon { icon: ... }`, or resolve a name at runtime with `icon()` / `Icon { name: ... }`.
//!
//! Runtime names need the default `icon-names` feature, which links the whole catalog (about
//! 360 KB) into any binary that renders an `Icon`. Apps that only pass constants can turn default
//! features off so only the icons they use reach the binary. Brand icons (`brand:github`) need the
//! `brand-icons` feature.

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;

/// Where an icon's artwork comes from. It becomes part of the SVG class, like `lucide-trash`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconSource {
    /// Lucide interface icons (ISC license).
    Lucide,
    /// Font Awesome Free brand icons (CC BY 4.0).
    Brand,
}

impl IconSource {
    /// The class prefix: `lucide` or `brand`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Lucide => "lucide",
            Self::Brand => "brand",
        }
    }
}

/// Whether an icon is drawn with strokes or fills.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconStyle {
    /// Stroked outlines that follow `currentColor`.
    Stroke,
    /// Filled shapes that follow `currentColor`.
    Fill,
}

/// One SVG element of an icon.
#[derive(Debug, PartialEq, Eq)]
pub struct IconNode {
    /// SVG tag name, such as `path` or `circle`.
    pub tag: &'static str,
    /// Attribute name and value pairs.
    pub attributes: &'static [(&'static str, &'static str)],
    /// Nested elements.
    pub children: &'static [IconNode],
}

/// The artwork of one icon.
#[derive(Debug, PartialEq, Eq)]
pub struct IconData {
    /// Canonical kebab-case name, such as `trash`.
    pub name: &'static str,
    /// The icon family.
    pub source: IconSource,
    /// View box width.
    pub width: u32,
    /// View box height.
    pub height: u32,
    /// Stroke or fill drawing.
    pub style: IconStyle,
    /// The SVG elements.
    pub nodes: &'static [IconNode],
}

/// Same rule as `toKebabCase` in `lumen-core`: `ArrowDown` and `arrow_down` become `arrow-down`.
#[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)
}

/// Resolves an icon name the way `getLumenIcon` does in `lumen-core`.
///
/// Plain names (`trash`, `ArrowDown`) resolve to Lucide icons. `brand:` names resolve to brand
/// icons when the `brand-icons` feature is enabled. Needs the default `icon-names` feature.
#[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
}

/// Every resolvable interface icon name, sorted. Needs the default `icon-names` feature.
#[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} } },
    }
}

/// Renders icon artwork as an inline, decorative `<svg>` sized to `1em`, like `renderIconSvg` in
/// `@santi020k/lumen-react`. Components use it for chevrons, close buttons, and status glyphs.
///
/// # Errors
///
/// Never fails on its own; the `Result` is Dioxus's [`Element`], so it can be returned from a
/// component or embedded in `rsx!`.
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)}
            }
        }
    }
}

/// The SVG class `Icon` gives its artwork: `ui-icon__svg {source}-{name}`.
pub(crate) fn icon_svg_class(icon: &IconData) -> String {
    format!("ui-icon__svg {}-{}", icon.source.as_str(), icon.name)
}

/// Resolves an optional icon name for components that accept names, like `lumen-react`.
#[cfg(feature = "icon-names")]
pub(crate) fn resolve_name(name: Option<&str>) -> Option<&'static IconData> {
    name.and_then(icon)
}

/// Without the `icon-names` feature, names do not resolve and components render no artwork.
#[cfg(not(feature = "icon-names"))]
pub(crate) fn resolve_name(_name: Option<&str>) -> Option<&'static IconData> {
    None
}

/// Size of an [`Icon`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconSize {
    /// Follows the surrounding font size.
    #[default]
    Default,
    /// Smaller than the text.
    Sm,
    /// Larger than the text.
    Lg,
    /// Display size.
    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"),
        }
    }
}

/// Props for [`Icon`].
#[derive(Props, Clone, PartialEq)]
pub struct IconProps {
    /// The artwork, such as `lucide::TRASH`. Takes precedence over `name`.
    pub icon: Option<&'static IconData>,
    /// An icon name resolved at runtime, such as `"trash"` or `"brand:github"`. Needs the default
    /// `icon-names` feature; without it, the children render instead.
    #[props(into)]
    pub name: Option<String>,
    /// Accessible name. A named icon gets `role="img"`; an unnamed one is decorative.
    #[props(into)]
    pub label: Option<String>,
    /// Same as `label`, for parity with the `aria-label` attribute.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Forces decorative (`true`) or meaningful (`false`) semantics.
    pub decorative: Option<bool>,
    /// Overrides the computed `aria-hidden`.
    pub aria_hidden: Option<bool>,
    /// Overrides the computed role.
    #[props(into)]
    pub role: Option<String>,
    /// Icon size.
    #[props(default)]
    pub size: IconSize,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
    /// Custom artwork, rendered when neither `icon` nor `name` resolves.
    pub children: Element,
}

/// An inline icon that follows the text color.
///
/// Unnamed icons are hidden from assistive technology. Give a meaningful icon a `label`.
#[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));
    }
}