Skip to main content

lumen_dioxus/layout/
util.rs

1//! Private helpers shared by the layout components: number and URI formatting that matches
2//! JavaScript, heading levels, element choice for `as`-style props, and style merging.
3
4// cspell:words apos
5
6use dioxus::prelude::*;
7
8/// Formats a number the way JavaScript's `String(number)` does for the values Lumen renders.
9///
10/// Rust and JavaScript both print the shortest round-trip digits, so only the special values,
11/// negative zero, and the exponent ranges need translating.
12pub(crate) fn js_number(value: f64) -> String {
13    if value.is_nan() {
14        return "NaN".to_string();
15    }
16
17    if value.is_infinite() {
18        return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
19    }
20
21    if value == 0.0 {
22        return "0".to_string();
23    }
24
25    let magnitude = value.abs();
26
27    if !(1e-6..1e21).contains(&magnitude) {
28        let formatted = format!("{value:e}");
29
30        return match formatted.split_once('e') {
31            Some((mantissa, exponent)) if !exponent.starts_with('-') => {
32                format!("{mantissa}e+{exponent}")
33            }
34            _ => formatted,
35        };
36    }
37
38    format!("{value}")
39}
40
41/// Percent-encodes text like JavaScript's `encodeURIComponent`, with a single linear pass.
42pub(crate) fn encode_uri_component(text: &str) -> String {
43    const HEX: &[u8; 16] = b"0123456789ABCDEF";
44    let mut out = String::with_capacity(text.len());
45
46    for byte in text.bytes() {
47        let unreserved = byte.is_ascii_alphanumeric()
48            || matches!(
49                byte,
50                b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
51            );
52
53        if unreserved {
54            out.push(char::from(byte));
55        } else {
56            out.push('%');
57            out.push(char::from(HEX[usize::from(byte >> 4)]));
58            out.push(char::from(HEX[usize::from(byte & 0x0f)]));
59        }
60    }
61
62    out
63}
64
65/// Escapes the five XML special characters with one linear scan.
66pub(crate) fn escape_xml(text: &str) -> String {
67    let mut out = String::with_capacity(text.len());
68
69    for character in text.chars() {
70        match character {
71            '&' => out.push_str("&"),
72            '<' => out.push_str("&lt;"),
73            '>' => out.push_str("&gt;"),
74            '"' => out.push_str("&quot;"),
75            '\'' => out.push_str("&apos;"),
76            other => out.push(other),
77        }
78    }
79
80    out
81}
82
83/// Clamps a heading level to 1-6, like `resolveLumenHeadingLevel` in `lumen-core`.
84pub(crate) fn heading_level(value: Option<i64>, fallback: u8) -> u8 {
85    value.map_or(fallback, |level| {
86        u8::try_from(level.clamp(1, 6)).unwrap_or(fallback)
87    })
88}
89
90/// Renders `h1`-`h6` with the given attributes and content.
91pub(crate) fn heading(level: u8, attributes: Vec<Attribute>, children: Element) -> Element {
92    match level {
93        1 => rsx! { h1 { ..attributes, {children} } },
94        2 => rsx! { h2 { ..attributes, {children} } },
95        3 => rsx! { h3 { ..attributes, {children} } },
96        4 => rsx! { h4 { ..attributes, {children} } },
97        5 => rsx! { h5 { ..attributes, {children} } },
98        _ => rsx! { h6 { ..attributes, {children} } },
99    }
100}
101
102/// A text attribute.
103pub(crate) fn attr(name: &'static str, value: impl Into<String>) -> Attribute {
104    Attribute::new(name, value.into(), None, false)
105}
106
107/// Joins inline style declarations, skipping empty parts.
108pub(crate) fn join_style<'a>(parts: impl IntoIterator<Item = Option<&'a str>>) -> Option<String> {
109    let mut out = String::new();
110
111    for part in parts.into_iter().flatten() {
112        let part = part.trim().trim_end_matches(';').trim();
113
114        if part.is_empty() {
115            continue;
116        }
117
118        if !out.is_empty() {
119            out.push_str("; ");
120        }
121
122        out.push_str(part);
123    }
124
125    (!out.is_empty()).then_some(out)
126}
127
128/// The element rendered by [`Container`](super::Container), [`Grid`](super::Grid),
129/// [`Stack`](super::Stack), and [`ResizablePanel`](super::ResizablePanel), like the `as` prop of
130/// `@santi020k/lumen-react`.
131#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132#[non_exhaustive]
133pub enum ContainerElement {
134    /// `<div>`.
135    #[default]
136    Div,
137    /// `<section>`.
138    Section,
139    /// `<main>`.
140    Main,
141    /// `<article>`.
142    Article,
143    /// `<aside>`.
144    Aside,
145    /// `<header>`.
146    Header,
147    /// `<footer>`.
148    Footer,
149    /// `<nav>`.
150    Nav,
151    /// `<ul>`.
152    Ul,
153    /// `<ol>`.
154    Ol,
155    /// `<li>`.
156    Li,
157    /// `<form>`.
158    Form,
159    /// `<span>`.
160    Span,
161}
162
163/// The element rendered by [`Stack`](super::Stack).
164pub type StackElement = ContainerElement;
165
166/// The element rendered by [`Grid`](super::Grid).
167pub type GridElement = ContainerElement;
168
169/// Renders the chosen element with the given attributes and content.
170pub(crate) fn element(
171    tag: ContainerElement,
172    attributes: Vec<Attribute>,
173    children: Element,
174) -> Element {
175    match tag {
176        ContainerElement::Div => rsx! { div { ..attributes, {children} } },
177        ContainerElement::Section => rsx! { section { ..attributes, {children} } },
178        ContainerElement::Main => rsx! { main { ..attributes, {children} } },
179        ContainerElement::Article => rsx! { article { ..attributes, {children} } },
180        ContainerElement::Aside => rsx! { aside { ..attributes, {children} } },
181        ContainerElement::Header => rsx! { header { ..attributes, {children} } },
182        ContainerElement::Footer => rsx! { footer { ..attributes, {children} } },
183        ContainerElement::Nav => rsx! { nav { ..attributes, {children} } },
184        ContainerElement::Ul => rsx! { ul { ..attributes, {children} } },
185        ContainerElement::Ol => rsx! { ol { ..attributes, {children} } },
186        ContainerElement::Li => rsx! { li { ..attributes, {children} } },
187        ContainerElement::Form => rsx! { form { ..attributes, {children} } },
188        ContainerElement::Span => rsx! { span { ..attributes, {children} } },
189    }
190}
191
192/// The visual arrow key: swaps Left and Right in a right-to-left direction, like
193/// `getLumenDirectionalKey` in `lumen-core`.
194pub(crate) fn directional_key(key: &Key, right_to_left: bool) -> Key {
195    match key {
196        Key::ArrowLeft if right_to_left => Key::ArrowRight,
197        Key::ArrowRight if right_to_left => Key::ArrowLeft,
198        other => other.clone(),
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::{encode_uri_component, escape_xml, heading_level, join_style, js_number};
205
206    #[test]
207    fn numbers_match_javascript_strings() {
208        assert_eq!(js_number(16.0), "16");
209        assert_eq!(js_number(-22.0), "-22");
210        assert_eq!(js_number(12.5), "12.5");
211        assert_eq!(js_number(28.000_000_000_000_004), "28.000000000000004");
212        assert_eq!(js_number(-0.0), "0");
213        assert_eq!(js_number(f64::NAN), "NaN");
214        assert_eq!(js_number(f64::INFINITY), "Infinity");
215        assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
216        assert_eq!(js_number(1e21), "1e+21");
217        assert_eq!(js_number(1.5e-8), "1.5e-8");
218        assert_eq!(js_number(1e-7), "1e-7");
219        assert_eq!(js_number(0.000_001), "0.000001");
220    }
221
222    #[test]
223    fn uri_components_match_javascript() {
224        assert_eq!(encode_uri_component("a b/c"), "a%20b%2Fc");
225        assert_eq!(encode_uri_component("-_.!~*'()"), "-_.!~*'()");
226        assert_eq!(encode_uri_component("é"), "%C3%A9");
227        assert_eq!(encode_uri_component("<&>\""), "%3C%26%3E%22");
228    }
229
230    #[test]
231    fn long_input_encodes_linearly() {
232        let input = "<&".repeat(50_000);
233        let encoded = encode_uri_component(&escape_xml(&input));
234
235        assert_eq!(
236            encoded.len(),
237            50_000 * ("%26lt%3B".len() + "%26amp%3B".len())
238        );
239    }
240
241    #[test]
242    fn xml_escapes_every_special_character() {
243        assert_eq!(
244            escape_xml(r#"<a href="x">'&'</a>"#),
245            "&lt;a href=&quot;x&quot;&gt;&apos;&amp;&apos;&lt;/a&gt;"
246        );
247    }
248
249    #[test]
250    fn heading_levels_clamp() {
251        assert_eq!(heading_level(None, 2), 2);
252        assert_eq!(heading_level(Some(9), 1), 6);
253        assert_eq!(heading_level(Some(0), 3), 1);
254        assert_eq!(heading_level(Some(-4), 3), 1);
255        assert_eq!(heading_level(Some(4), 1), 4);
256    }
257
258    #[test]
259    fn styles_join_without_empty_parts() {
260        assert_eq!(
261            join_style([Some("a: 1;"), None, Some(" "), Some("b: 2")]).as_deref(),
262            Some("a: 1; b: 2")
263        );
264        assert_eq!(join_style([None, Some("")]), None);
265    }
266}