use dioxus::prelude::*;
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}")
}
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
}
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("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
other => out.push(other),
}
}
out
}
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)
})
}
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} } },
}
}
pub(crate) fn attr(name: &'static str, value: impl Into<String>) -> Attribute {
Attribute::new(name, value.into(), None, false)
}
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)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContainerElement {
#[default]
Div,
Section,
Main,
Article,
Aside,
Header,
Footer,
Nav,
Ul,
Ol,
Li,
Form,
Span,
}
pub type StackElement = ContainerElement;
pub type GridElement = ContainerElement;
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} } },
}
}
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>"#),
"<a href="x">'&'</a>"
);
}
#[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);
}
}