lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Private helpers shared by the layout components: number and URI formatting that matches
//! JavaScript, heading levels, element choice for `as`-style props, and style merging.

// cspell:words apos

use dioxus::prelude::*;

/// Formats a number the way JavaScript's `String(number)` does for the values Lumen renders.
///
/// Rust and JavaScript both print the shortest round-trip digits, so only the special values,
/// negative zero, and the exponent ranges need translating.
pub(crate) fn js_number(value: f64) -> String {
    if value.is_nan() {
        return "NaN".to_string();
    }

    if value.is_infinite() {
        return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
    }

    if value == 0.0 {
        return "0".to_string();
    }

    let magnitude = value.abs();

    if !(1e-6..1e21).contains(&magnitude) {
        let formatted = format!("{value:e}");

        return match formatted.split_once('e') {
            Some((mantissa, exponent)) if !exponent.starts_with('-') => {
                format!("{mantissa}e+{exponent}")
            }
            _ => formatted,
        };
    }

    format!("{value}")
}

/// Percent-encodes text like JavaScript's `encodeURIComponent`, with a single linear pass.
pub(crate) fn encode_uri_component(text: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut out = String::with_capacity(text.len());

    for byte in text.bytes() {
        let unreserved = byte.is_ascii_alphanumeric()
            || matches!(
                byte,
                b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
            );

        if unreserved {
            out.push(char::from(byte));
        } else {
            out.push('%');
            out.push(char::from(HEX[usize::from(byte >> 4)]));
            out.push(char::from(HEX[usize::from(byte & 0x0f)]));
        }
    }

    out
}

/// Escapes the five XML special characters with one linear scan.
pub(crate) fn escape_xml(text: &str) -> String {
    let mut out = String::with_capacity(text.len());

    for character in text.chars() {
        match character {
            '&' => out.push_str("&"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            other => out.push(other),
        }
    }

    out
}

/// Clamps a heading level to 1-6, like `resolveLumenHeadingLevel` in `lumen-core`.
pub(crate) fn heading_level(value: Option<i64>, fallback: u8) -> u8 {
    value.map_or(fallback, |level| {
        u8::try_from(level.clamp(1, 6)).unwrap_or(fallback)
    })
}

/// Renders `h1`-`h6` with the given attributes and content.
pub(crate) fn heading(level: u8, attributes: Vec<Attribute>, children: Element) -> Element {
    match level {
        1 => rsx! { h1 { ..attributes, {children} } },
        2 => rsx! { h2 { ..attributes, {children} } },
        3 => rsx! { h3 { ..attributes, {children} } },
        4 => rsx! { h4 { ..attributes, {children} } },
        5 => rsx! { h5 { ..attributes, {children} } },
        _ => rsx! { h6 { ..attributes, {children} } },
    }
}

/// A text attribute.
pub(crate) fn attr(name: &'static str, value: impl Into<String>) -> Attribute {
    Attribute::new(name, value.into(), None, false)
}

/// Joins inline style declarations, skipping empty parts.
pub(crate) fn join_style<'a>(parts: impl IntoIterator<Item = Option<&'a str>>) -> Option<String> {
    let mut out = String::new();

    for part in parts.into_iter().flatten() {
        let part = part.trim().trim_end_matches(';').trim();

        if part.is_empty() {
            continue;
        }

        if !out.is_empty() {
            out.push_str("; ");
        }

        out.push_str(part);
    }

    (!out.is_empty()).then_some(out)
}

/// The element rendered by [`Container`](super::Container), [`Grid`](super::Grid),
/// [`Stack`](super::Stack), and [`ResizablePanel`](super::ResizablePanel), like the `as` prop of
/// `@santi020k/lumen-react`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContainerElement {
    /// `<div>`.
    #[default]
    Div,
    /// `<section>`.
    Section,
    /// `<main>`.
    Main,
    /// `<article>`.
    Article,
    /// `<aside>`.
    Aside,
    /// `<header>`.
    Header,
    /// `<footer>`.
    Footer,
    /// `<nav>`.
    Nav,
    /// `<ul>`.
    Ul,
    /// `<ol>`.
    Ol,
    /// `<li>`.
    Li,
    /// `<form>`.
    Form,
    /// `<span>`.
    Span,
}

/// The element rendered by [`Stack`](super::Stack).
pub type StackElement = ContainerElement;

/// The element rendered by [`Grid`](super::Grid).
pub type GridElement = ContainerElement;

/// Renders the chosen element with the given attributes and content.
pub(crate) fn element(
    tag: ContainerElement,
    attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    match tag {
        ContainerElement::Div => rsx! { div { ..attributes, {children} } },
        ContainerElement::Section => rsx! { section { ..attributes, {children} } },
        ContainerElement::Main => rsx! { main { ..attributes, {children} } },
        ContainerElement::Article => rsx! { article { ..attributes, {children} } },
        ContainerElement::Aside => rsx! { aside { ..attributes, {children} } },
        ContainerElement::Header => rsx! { header { ..attributes, {children} } },
        ContainerElement::Footer => rsx! { footer { ..attributes, {children} } },
        ContainerElement::Nav => rsx! { nav { ..attributes, {children} } },
        ContainerElement::Ul => rsx! { ul { ..attributes, {children} } },
        ContainerElement::Ol => rsx! { ol { ..attributes, {children} } },
        ContainerElement::Li => rsx! { li { ..attributes, {children} } },
        ContainerElement::Form => rsx! { form { ..attributes, {children} } },
        ContainerElement::Span => rsx! { span { ..attributes, {children} } },
    }
}

/// The visual arrow key: swaps Left and Right in a right-to-left direction, like
/// `getLumenDirectionalKey` in `lumen-core`.
pub(crate) fn directional_key(key: &Key, right_to_left: bool) -> Key {
    match key {
        Key::ArrowLeft if right_to_left => Key::ArrowRight,
        Key::ArrowRight if right_to_left => Key::ArrowLeft,
        other => other.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::{encode_uri_component, escape_xml, heading_level, join_style, js_number};

    #[test]
    fn numbers_match_javascript_strings() {
        assert_eq!(js_number(16.0), "16");
        assert_eq!(js_number(-22.0), "-22");
        assert_eq!(js_number(12.5), "12.5");
        assert_eq!(js_number(28.000_000_000_000_004), "28.000000000000004");
        assert_eq!(js_number(-0.0), "0");
        assert_eq!(js_number(f64::NAN), "NaN");
        assert_eq!(js_number(f64::INFINITY), "Infinity");
        assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
        assert_eq!(js_number(1e21), "1e+21");
        assert_eq!(js_number(1.5e-8), "1.5e-8");
        assert_eq!(js_number(1e-7), "1e-7");
        assert_eq!(js_number(0.000_001), "0.000001");
    }

    #[test]
    fn uri_components_match_javascript() {
        assert_eq!(encode_uri_component("a b/c"), "a%20b%2Fc");
        assert_eq!(encode_uri_component("-_.!~*'()"), "-_.!~*'()");
        assert_eq!(encode_uri_component("é"), "%C3%A9");
        assert_eq!(encode_uri_component("<&>\""), "%3C%26%3E%22");
    }

    #[test]
    fn long_input_encodes_linearly() {
        let input = "<&".repeat(50_000);
        let encoded = encode_uri_component(&escape_xml(&input));

        assert_eq!(
            encoded.len(),
            50_000 * ("%26lt%3B".len() + "%26amp%3B".len())
        );
    }

    #[test]
    fn xml_escapes_every_special_character() {
        assert_eq!(
            escape_xml(r#"<a href="x">'&'</a>"#),
            "&lt;a href=&quot;x&quot;&gt;&apos;&amp;&apos;&lt;/a&gt;"
        );
    }

    #[test]
    fn heading_levels_clamp() {
        assert_eq!(heading_level(None, 2), 2);
        assert_eq!(heading_level(Some(9), 1), 6);
        assert_eq!(heading_level(Some(0), 3), 1);
        assert_eq!(heading_level(Some(-4), 3), 1);
        assert_eq!(heading_level(Some(4), 1), 4);
    }

    #[test]
    fn styles_join_without_empty_parts() {
        assert_eq!(
            join_style([Some("a: 1;"), None, Some(" "), Some("b: 2")]).as_deref(),
            Some("a: 1; b: 2")
        );
        assert_eq!(join_style([None, Some("")]), None);
    }
}