lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Small helpers shared by the content components: JavaScript number text, optional text, and
//! citation URL checks.
// cspell:words IDNA rsplit

use std::fmt::Write as _;

use super::number_format::{
    FORMATTED_NUMBER_FALLBACK, FormattedNumberValue, NumberFormatOptions, format_lumen_number,
};

/// `String(value)` in JavaScript, so inline styles and attributes match lumen-react.
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();
    }

    format_lumen_number(
        &FormattedNumberValue::Number(value),
        &NumberFormatOptions::default(),
        FORMATTED_NUMBER_FALLBACK,
    )
    .value
    .unwrap_or_default()
}

/// Trimmed text, or `None` when it is missing or 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)
}

const MAX_URL_LENGTH: usize = 2048;

fn is_unsafe_url_character(character: char) -> bool {
    character <= ' ' || character == '\u{7f}' || character == '\\'
}

fn push_percent_encoded(out: &mut String, character: char, encode: impl Fn(char) -> bool) {
    if character.is_ascii() && !encode(character) {
        out.push(character);
        return;
    }

    let mut buffer = [0_u8; 4];

    for byte in character.encode_utf8(&mut buffer).bytes() {
        let _ = write!(out, "%{byte:02X}");
    }
}

fn is_dot_segment(segment: &str, dots: usize) -> bool {
    let lower = segment.to_ascii_lowercase();
    let mut rest = lower.as_str();
    let mut count = 0;

    while !rest.is_empty() {
        if let Some(next) = rest.strip_prefix('.') {
            rest = next;
        } else if let Some(next) = rest.strip_prefix("%2e") {
            rest = next;
        } else {
            return false;
        }

        count += 1;
    }

    count == dots
}

/// Serializes a URL path the way the WHATWG URL parser does for `http` and `https`: dot segments
/// are resolved and unsafe characters are percent-encoded.
fn normalize_path(path: &str) -> String {
    let mut segments: Vec<String> = Vec::new();
    let parts: Vec<&str> = path.split('/').skip(1).collect();
    let last = parts.len().saturating_sub(1);

    for (index, part) in parts.iter().enumerate() {
        if is_dot_segment(part, 2) {
            segments.pop();

            if index == last {
                segments.push(String::new());
            }
        } else if is_dot_segment(part, 1) {
            if index == last {
                segments.push(String::new());
            }
        } else {
            let mut encoded = String::new();

            for character in part.chars() {
                push_percent_encoded(&mut encoded, character, |c| {
                    matches!(c, '"' | '#' | '<' | '>' | '?' | '`' | '{' | '}')
                });
            }

            segments.push(encoded);
        }
    }

    if segments.is_empty() {
        return "/".to_string();
    }

    let mut out = String::new();

    for segment in segments {
        out.push('/');
        out.push_str(&segment);
    }

    out
}

fn normalize_ipv4(host: &str) -> Option<String> {
    let parts: Vec<&str> = host.split('.').collect();

    if parts.len() != 4 {
        return None;
    }

    let mut octets = Vec::with_capacity(4);

    for part in parts {
        if part.is_empty()
            || part.len() > 3
            || !part.bytes().all(|byte| byte.is_ascii_digit())
            || (part.len() > 1 && part.starts_with('0'))
        {
            return None;
        }

        let octet: u16 = part.parse().ok()?;

        if octet > 255 {
            return None;
        }

        octets.push(octet.to_string());
    }

    Some(octets.join("."))
}

/// Lowercases a domain and rejects anything that needs IDNA, IPv6, or numeric host rewriting.
fn normalize_host(host: &str) -> Option<String> {
    if host.is_empty() || !host.is_ascii() {
        return None;
    }

    let host = host.to_ascii_lowercase();
    let forbidden = |c: char| {
        matches!(
            c,
            '#' | '%' | '/' | ':' | '<' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '|'
        ) || c.is_ascii_control()
    };

    if host.chars().any(forbidden) {
        return None;
    }

    let last_label = host.trim_end_matches('.').rsplit('.').next().unwrap_or("");
    let numeric = !last_label.is_empty()
        && (last_label.bytes().all(|byte| byte.is_ascii_digit()) || last_label.starts_with("0x"));

    if numeric {
        return normalize_ipv4(&host);
    }

    Some(host)
}

/// Splits `rest` at the first `?` and `#` and serializes the path, query, and fragment.
fn serialize_tail(rest: &str) -> String {
    let (before_fragment, fragment) = match rest.split_once('#') {
        Some((before, fragment)) => (before, Some(fragment)),
        None => (rest, None),
    };
    let (path, query) = match before_fragment.split_once('?') {
        Some((path, query)) => (path, Some(query)),
        None => (before_fragment, None),
    };
    let mut out = normalize_path(if path.is_empty() { "/" } else { path });

    if let Some(query) = query {
        out.push('?');

        for character in query.chars() {
            push_percent_encoded(&mut out, character, |c| {
                matches!(c, '"' | '#' | '<' | '>' | '\'')
            });
        }
    }

    if let Some(fragment) = fragment {
        out.push('#');

        for character in fragment.chars() {
            push_percent_encoded(&mut out, character, |c| matches!(c, '"' | '<' | '>' | '`'));
        }
    }

    out
}

/// A safe `cite` URL, like `resolveLumenCitationHref` in `lumen-core`: root-relative paths, or
/// absolute `http` and `https` URLs without credentials, serialized like `URL.href`.
///
/// Hosts that need IDNA conversion or IPv6 parsing are dropped instead of being normalized.
pub(crate) fn resolve_citation_href(value: &str) -> Option<String> {
    if value.len() > MAX_URL_LENGTH || value.chars().any(is_unsafe_url_character) {
        return None;
    }

    if value.starts_with('/') && !value.starts_with("//") {
        return Some(value.to_string());
    }

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

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

    let rest = rest.trim_start_matches('/');
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, tail) = rest.split_at(authority_end);
    let host_and_port = match authority.rsplit_once('@') {
        Some((credentials, host)) => {
            if !credentials.is_empty() && credentials != ":" {
                return None;
            }

            host
        }
        None => authority,
    };
    let (host, port) = match host_and_port.rsplit_once(':') {
        Some((host, port)) => (host, Some(port)),
        None => (host_and_port, None),
    };
    let host = normalize_host(host)?;
    let mut href = format!("{scheme}://{host}");

    if let Some(port) = port.filter(|port| !port.is_empty()) {
        if port.len() > 5 || !port.bytes().all(|byte| byte.is_ascii_digit()) {
            return None;
        }

        let number: u32 = port.parse().ok()?;
        let default = if scheme == "http" { 80 } else { 443 };

        if number > 65_535 {
            return None;
        }

        if number != default {
            let _ = write!(href, ":{number}");
        }
    }

    href.push_str(&serialize_tail(tail));

    Some(href)
}

#[cfg(test)]
mod tests {
    use super::{js_number, optional_text, resolve_citation_href};

    #[test]
    fn numbers_print_like_javascript() {
        assert_eq!(js_number(16.0 / 9.0), "1.7777777777777777");
        assert_eq!(js_number(-0.0), "0");
        assert_eq!(js_number(25.0), "25");
        assert_eq!(js_number(1e21), "1e+21");
        assert_eq!(js_number(f64::NAN), "NaN");
        assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
    }

    #[test]
    fn optional_text_trims_blank_values() {
        assert_eq!(optional_text(Some("  npm  ")).as_deref(), Some("npm"));
        assert_eq!(optional_text(Some("   ")), None);
        assert_eq!(optional_text(None), None);
    }

    #[test]
    fn citations_match_url_href() {
        // Expected values come from `new URL(value).href` in Node.
        let cases = [
            ("https://Example.com", Some("https://example.com/")),
            ("HTTP://example.com:80/a/./b/../c?q=a b#x", None),
            (
                "http://example.com:80/a/./b/../c?q=1#top",
                Some("http://example.com/a/c?q=1#top"),
            ),
            (
                "https://example.com:8443/quote",
                Some("https://example.com:8443/quote"),
            ),
            (
                "https://example.com/caf\u{e9}?q=\u{e9}",
                Some("https://example.com/caf%C3%A9?q=%C3%A9"),
            ),
            ("https://example.com/a/..", Some("https://example.com/")),
            ("https://example.com/%2E/x", Some("https://example.com/x")),
            ("https:example.com/path", Some("https://example.com/path")),
            ("https://@example.com", Some("https://example.com/")),
            ("https://user:pass@example.com", None),
            ("https://user@example.com", None),
            ("javascript:alert(1)", None),
            ("ftp://example.com", None),
            ("//example.com/x", None),
            ("/quotes/1", Some("/quotes/1")),
            ("https://192.168.0.1/", Some("https://192.168.0.1/")),
            (
                "https://example.com/a^b|c{d}`e\"f<g>?q='\"`^|{}#f\"`<>^|{}",
                Some(
                    "https://example.com/a^b|c%7Bd%7D%60e%22f%3Cg%3E?q=%27%22`^|{}#f%22%60%3C%3E^|{}",
                ),
            ),
            (
                "https://example.com/a/b/.",
                Some("https://example.com/a/b/"),
            ),
            (
                "https://EXAMPLE.com.:0443/x",
                Some("https://example.com./x"),
            ),
            ("https://:@example.com", Some("https://example.com/")),
            ("https://example.com:99999", None),
            ("https://ex\\ample.com", None),
            ("https://", None),
        ];

        for (input, expected) in cases {
            assert_eq!(resolve_citation_href(input).as_deref(), expected, "{input}");
        }
    }

    #[test]
    fn citations_reject_long_input() {
        let long = format!("https://example.com/{}", "a".repeat(100_000));
        assert_eq!(resolve_citation_href(&long), None);
    }
}