1use dioxus::prelude::*;
7
8pub(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
41pub(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
65pub(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("<"),
73 '>' => out.push_str(">"),
74 '"' => out.push_str("""),
75 '\'' => out.push_str("'"),
76 other => out.push(other),
77 }
78 }
79
80 out
81}
82
83pub(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
90pub(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
102pub(crate) fn attr(name: &'static str, value: impl Into<String>) -> Attribute {
104 Attribute::new(name, value.into(), None, false)
105}
106
107pub(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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132#[non_exhaustive]
133pub enum ContainerElement {
134 #[default]
136 Div,
137 Section,
139 Main,
141 Article,
143 Aside,
145 Header,
147 Footer,
149 Nav,
151 Ul,
153 Ol,
155 Li,
157 Form,
159 Span,
161}
162
163pub type StackElement = ContainerElement;
165
166pub type GridElement = ContainerElement;
168
169pub(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
192pub(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 "<a href="x">'&'</a>"
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}