lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Private helpers shared by the navigation components: slot checks, text extraction, URL and
//! template utilities ported from `@santi020k/lumen-core`.
// cspell:words vnode rsplit mple hrefs

use dioxus::dioxus_core::{AttributeValue, DynamicNode, TemplateNode};
use dioxus::prelude::*;

/// Whether an element renders anything, like `hasSlotContent` in lumen-react.
pub(crate) fn has_content(element: &Element) -> bool {
    match element {
        Ok(node) => *node != VNode::placeholder(),
        Err(_) => true,
    }
}

/// Whether an optional slot renders anything.
pub(crate) fn has_slot(element: Option<&Element>) -> bool {
    element.is_some_and(has_content)
}

fn push_template_text(node: &TemplateNode, vnode: &VNode, out: &mut String) {
    match node {
        TemplateNode::Text { text } => out.push_str(text),
        TemplateNode::Element { children, .. } => {
            for child in *children {
                push_template_text(child, vnode, out);
            }
        }
        TemplateNode::Dynamic { id } => {
            if let Some(dynamic) = vnode.dynamic_nodes.get(*id) {
                push_dynamic_text(dynamic, out);
            }
        }
    }
}

fn push_dynamic_text(node: &DynamicNode, out: &mut String) {
    match node {
        DynamicNode::Text(text) => out.push_str(&text.value),
        DynamicNode::Fragment(nodes) => {
            for vnode in nodes {
                push_vnode_text(vnode, out);
            }
        }
        DynamicNode::Component(_) | DynamicNode::Placeholder(_) => {}
    }
}

fn push_vnode_text(vnode: &VNode, out: &mut String) {
    for root in vnode.template.roots {
        push_template_text(root, vnode, out);
    }
}

/// Plain text of an element's static and dynamic text nodes, like `textOf` in lumen-react.
///
/// Text rendered by nested components is not visible here, the same as React reading
/// `props.children`; pass an explicit label in that case.
pub(crate) fn element_text(element: &Element) -> String {
    let mut out = String::new();

    if let Ok(vnode) = element {
        push_vnode_text(vnode, &mut out);
    }

    out
}

/// Collapses whitespace runs to single spaces and trims the ends.
pub(crate) fn collapse_whitespace(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Trimmed text, or `None` when it is blank, like `resolveLumenOptionalText`.
pub(crate) fn optional_text(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .map(str::to_string)
}

/// The value when it has non-whitespace text, otherwise the fallback.
pub(crate) fn non_empty_or(value: Option<&str>, fallback: &str) -> String {
    match value {
        Some(text) if !text.trim().is_empty() => text.to_string(),
        _ => fallback.to_string(),
    }
}

/// True when a URL candidate contains a C0 control, space, DEL, or backslash, like
/// `hasUnsafeUrlCharacter` in lumen-core.
pub(crate) fn has_unsafe_url_character(value: &str) -> bool {
    value
        .chars()
        .any(|character| character <= ' ' || character == '\u{7f}' || character == '\\')
}

/// `encodeURIComponent`: percent-encodes everything except `A-Z a-z 0-9 - _ . ! ~ * ' ( )`.
pub(crate) fn encode_uri_component(value: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut out = String::with_capacity(value.len());

    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric()
            || matches!(
                byte,
                b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
            )
        {
            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
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// `decodeURIComponent` that returns the input unchanged when it is malformed, like
/// `decodeLumenAnchorFragment`.
pub(crate) fn decode_uri_component(value: &str) -> String {
    let bytes = value.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut index = 0;

    while index < bytes.len() {
        if bytes[index] == b'%' {
            let high = bytes.get(index + 1).copied().and_then(hex_value);
            let low = bytes.get(index + 2).copied().and_then(hex_value);

            match (high, low) {
                (Some(high), Some(low)) => {
                    out.push(high << 4 | low);
                    index += 3;
                }
                _ => return value.to_string(),
            }
        } else {
            out.push(bytes[index]);
            index += 1;
        }
    }

    String::from_utf8(out).unwrap_or_else(|_| value.to_string())
}

/// Replaces `{name}` placeholders (`name` is ASCII letters, digits, or `_`) with values in one
/// linear pass, like `formatLumenMessageTemplate`. Unknown or malformed placeholders stay as
/// written, and inserted values are never scanned again.
pub(crate) fn format_template(template: &str, values: &[(&str, &str)]) -> String {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;

    while let Some(open) = rest.find('{') {
        let after = &rest[open + 1..];
        let name_len = after
            .bytes()
            .take_while(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
            .count();
        let name = &after[..name_len];
        let closed = after.as_bytes().get(name_len) == Some(&b'}');
        let value = values
            .iter()
            .find(|(key, _)| closed && !name.is_empty() && *key == name)
            .map(|(_, value)| *value);

        if let Some(value) = value {
            out.push_str(&rest[..open]);
            out.push_str(value);
            rest = &after[name_len + 1..];
        } else {
            out.push_str(&rest[..=open]);
            rest = after;
        }
    }

    out.push_str(rest);
    out
}

/// Normalizes an absolute `http` or `https` URL the way `new URL(value).href` does for the
/// common cases: the scheme and host are lowercased, a default port is dropped, and an empty path
/// becomes `/`. Returns `None` for other schemes, credentials, missing hosts, or unsafe
/// characters, like `resolveLumenShareUrl` without a base.
pub(crate) fn normalize_web_url(value: &str) -> Option<String> {
    if value.is_empty() || value.len() > 8192 || has_unsafe_url_character(value) {
        return None;
    }

    let (scheme, rest) = value.split_once(':')?;
    let scheme = scheme.to_ascii_lowercase();

    if scheme != "http" && scheme != "https" {
        return None;
    }

    let rest = rest.strip_prefix("//")?;
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, tail) = rest.split_at(authority_end);

    if authority.is_empty() || authority.contains('@') {
        return None;
    }

    let mut host = authority.to_ascii_lowercase();
    let default_port = if scheme == "https" { ":443" } else { ":80" };

    if host.ends_with(default_port) && !host.ends_with(']') {
        host.truncate(host.len() - default_port.len());
    }

    let host_name = host
        .rsplit_once(':')
        .map_or(host.as_str(), |(name, _)| name);

    if host_name.is_empty() || host_name == "[" {
        return None;
    }

    let tail = if tail.starts_with('/') {
        tail.to_string()
    } else {
        format!("/{tail}")
    };

    Some(format!("{scheme}://{host}{tail}"))
}

/// Accepts destinations the way `resolveLumenPaginationHref` does: scheme-less relative
/// references (`?page=2`, `2/`, `/blog/2/`) and credential-free `http(s)` URLs. Protocol-relative
/// and executable schemes are rejected.
pub(crate) fn resolve_safe_href(value: &str) -> Option<String> {
    if value.is_empty()
        || value.len() > 2048
        || has_unsafe_url_character(value)
        || value.starts_with("//")
    {
        return None;
    }

    let has_scheme = value
        .chars()
        .take_while(|character| !matches!(character, '/' | '?' | '#'))
        .any(|character| character == ':');

    if has_scheme {
        normalize_web_url(value)
    } else {
        Some(value.to_string())
    }
}

/// The value of a `dir` attribute in a spread attribute list, when it is `rtl`.
pub(crate) fn is_rtl(attributes: &[Attribute]) -> bool {
    attributes.iter().any(|attribute| {
        attribute.name == "dir"
            && matches!(&attribute.value, AttributeValue::Text(text) if text.eq_ignore_ascii_case("rtl"))
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn templates_fill_known_placeholders_only() {
        assert_eq!(
            format_template("Page {page} of {total}", &[("page", "2")]),
            "Page 2 of {total}"
        );
        assert_eq!(format_template("{{a}", &[("a", "x")]), "{x");
        assert_eq!(format_template("open {", &[]), "open {");
        let long = "{".repeat(50_000);
        assert_eq!(format_template(&long, &[]), long);
    }

    #[test]
    fn uri_components_round_trip() {
        assert_eq!(encode_uri_component("a b/ñ?"), "a%20b%2F%C3%B1%3F");
        assert_eq!(encode_uri_component("-_.!~*'()"), "-_.!~*'()");
        assert_eq!(decode_uri_component("a%20b%2F%C3%B1"), "a b/ñ");
        assert_eq!(decode_uri_component("100%"), "100%");
        assert_eq!(decode_uri_component("%E0%A4%A"), "%E0%A4%A");
    }

    #[test]
    fn web_urls_normalize_like_the_url_parser() {
        assert_eq!(
            normalize_web_url("HTTPS://Example.COM").as_deref(),
            Some("https://example.com/")
        );
        assert_eq!(
            normalize_web_url("http://example.com:80/a?b#c").as_deref(),
            Some("http://example.com/a?b#c")
        );
        assert_eq!(
            normalize_web_url("https://example.com?x=1").as_deref(),
            Some("https://example.com/?x=1")
        );
        assert_eq!(normalize_web_url("https://user:pw@example.com"), None);
        assert_eq!(normalize_web_url("javascript:alert(1)"), None);
        assert_eq!(normalize_web_url("https://"), None);
        assert_eq!(normalize_web_url("https://exa mple.com"), None);
        assert_eq!(normalize_web_url(&"a".repeat(100_000)), None);
    }

    #[test]
    fn safe_hrefs_follow_the_pagination_rules() {
        assert_eq!(resolve_safe_href("?page=2").as_deref(), Some("?page=2"));
        assert_eq!(resolve_safe_href("/blog/2/").as_deref(), Some("/blog/2/"));
        assert_eq!(resolve_safe_href("2/?a=b:c").as_deref(), Some("2/?a=b:c"));
        assert_eq!(resolve_safe_href("//evil.test"), None);
        assert_eq!(resolve_safe_href("javascript:void(0)"), None);
        assert_eq!(resolve_safe_href("data:text/html,x"), None);
        assert_eq!(resolve_safe_href(""), None);
        assert_eq!(resolve_safe_href("/a\\b"), None);
        assert_eq!(resolve_safe_href(&"/a".repeat(2000)), None);
    }

    #[test]
    fn optional_text_trims_blank_values() {
        assert_eq!(optional_text(Some("  x ")).as_deref(), Some("x"));
        assert_eq!(optional_text(Some("   ")), None);
        assert_eq!(non_empty_or(Some(" "), "fallback"), "fallback");
        assert_eq!(collapse_whitespace("  a \n b  "), "a b");
    }
}