1use dioxus::prelude::*;
4
5use crate::class::compose;
6
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum StatAs {
11 #[default]
13 Div,
14 Article,
16 Section,
18}
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum StatVariant {
24 #[default]
26 Default,
27 Accent,
29 Bare,
31 Glass,
33}
34
35impl StatVariant {
36 pub fn as_str(self) -> &'static str {
38 match self {
39 Self::Default => "default",
40 Self::Accent => "accent",
41 Self::Bare => "bare",
42 Self::Glass => "glass",
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum StatTone {
51 #[default]
53 Default,
54 Success,
56 Warning,
58 Danger,
60 Brand,
62}
63
64impl StatTone {
65 pub fn as_str(self) -> &'static str {
67 match self {
68 Self::Default => "default",
69 Self::Success => "success",
70 Self::Warning => "warning",
71 Self::Danger => "danger",
72 Self::Brand => "brand",
73 }
74 }
75}
76
77#[derive(Props, Clone, PartialEq)]
79pub struct StatProps {
80 #[props(default)]
82 pub r#as: StatAs,
83 #[props(into)]
85 pub label: Option<String>,
86 #[props(into)]
88 pub value: Option<String>,
89 #[props(default)]
91 pub variant: StatVariant,
92 #[props(default)]
94 pub tone: StatTone,
95 #[props(into)]
97 pub class: Option<String>,
98 #[props(extends = GlobalAttributes, extends = div)]
100 pub attributes: Vec<Attribute>,
101 pub children: Element,
103}
104
105#[component]
107pub fn Stat(props: StatProps) -> Element {
108 let variant = (props.variant != StatVariant::Default)
109 .then(|| format!("ui-stat--{}", props.variant.as_str()));
110 let tone =
111 (props.tone != StatTone::Default).then(|| format!("ui-stat--tone-{}", props.tone.as_str()));
112 let class = compose([
113 Some("ui-stat"),
114 variant.as_deref(),
115 tone.as_deref(),
116 props.class.as_deref(),
117 ]);
118 let data_tone = (props.tone != StatTone::Default).then_some(props.tone.as_str());
119 let data_variant = props.variant.as_str();
120 let body = rsx! {
121 if let Some(label) = props.label.filter(|label| !label.is_empty()) {
122 div { class: "ui-stat-label", "data-slot": "stat-label", "{label}" }
123 }
124 if let Some(value) = props.value.filter(|value| !value.is_empty()) {
125 div { class: "ui-stat-value", "data-slot": "stat-value", "{value}" }
126 }
127 {props.children}
128 };
129
130 match props.r#as {
131 StatAs::Div => rsx! {
132 div { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
133 },
134 StatAs::Article => rsx! {
135 article { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
136 },
137 StatAs::Section => rsx! {
138 section { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
139 },
140 }
141}
142
143#[derive(Props, Clone, PartialEq)]
145pub struct StatPartProps {
146 #[props(default)]
148 pub r#as: StatAs,
149 #[props(into)]
151 pub class: Option<String>,
152 #[props(extends = GlobalAttributes, extends = div)]
154 pub attributes: Vec<Attribute>,
155 pub children: Element,
157}
158
159fn stat_part(base: &str, slot: &'static str, props: StatPartProps) -> Element {
160 let class = compose([Some(base), props.class.as_deref()]);
161
162 match props.r#as {
163 StatAs::Div => rsx! {
164 div { class, "data-slot": slot, ..props.attributes, {props.children} }
165 },
166 StatAs::Article => rsx! {
167 article { class, "data-slot": slot, ..props.attributes, {props.children} }
168 },
169 StatAs::Section => rsx! {
170 section { class, "data-slot": slot, ..props.attributes, {props.children} }
171 },
172 }
173}
174
175#[component]
177pub fn StatLabel(props: StatPartProps) -> Element {
178 stat_part("ui-stat-label", "stat-label", props)
179}
180
181#[component]
183pub fn StatValue(props: StatPartProps) -> Element {
184 stat_part("ui-stat-value", "stat-value", props)
185}
186
187#[component]
189pub fn StatDescription(props: StatPartProps) -> Element {
190 stat_part("ui-stat-description", "stat-description", props)
191}
192
193#[derive(Props, Clone, PartialEq)]
195pub struct StatIconProps {
196 #[props(into)]
198 pub class: Option<String>,
199 #[props(extends = GlobalAttributes, extends = span)]
201 pub attributes: Vec<Attribute>,
202 pub children: Element,
204}
205
206#[component]
208pub fn StatIcon(props: StatIconProps) -> Element {
209 let class = compose([Some("ui-stat-icon"), props.class.as_deref()]);
210
211 rsx! {
212 span { class, "data-slot": "stat-icon", ..props.attributes, {props.children} }
213 }
214}
215
216#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
218#[non_exhaustive]
219pub enum StatTrendTone {
220 #[default]
222 Neutral,
223 Success,
225 Warning,
227 Danger,
229}
230
231impl StatTrendTone {
232 pub fn as_str(self) -> &'static str {
234 match self {
235 Self::Neutral => "neutral",
236 Self::Success => "success",
237 Self::Warning => "warning",
238 Self::Danger => "danger",
239 }
240 }
241}
242
243#[derive(Props, Clone, PartialEq)]
245pub struct StatTrendProps {
246 #[props(default)]
248 pub tone: StatTrendTone,
249 #[props(into)]
251 pub class: Option<String>,
252 #[props(extends = GlobalAttributes, extends = span)]
254 pub attributes: Vec<Attribute>,
255 pub children: Element,
257}
258
259#[component]
261pub fn StatTrend(props: StatTrendProps) -> Element {
262 let tone = format!("ui-stat-trend--{}", props.tone.as_str());
263 let class = compose([
264 Some("ui-stat-trend"),
265 Some(tone.as_str()),
266 props.class.as_deref(),
267 ]);
268
269 rsx! {
270 span {
271 class,
272 "data-slot": "stat-trend",
273 "data-tone": props.tone.as_str(),
274 ..props.attributes,
275 {props.children}
276 }
277 }
278}
279
280#[derive(Props, Clone, PartialEq)]
282pub struct StatGroupProps {
283 #[props(default)]
285 pub dividers: bool,
286 #[props(into)]
288 pub class: Option<String>,
289 #[props(extends = GlobalAttributes, extends = div)]
291 pub attributes: Vec<Attribute>,
292 pub children: Element,
294}
295
296#[component]
298pub fn StatGroup(props: StatGroupProps) -> Element {
299 let class = compose([
300 Some("ui-stat-group"),
301 props.dividers.then_some("ui-stat-group--dividers"),
302 props.class.as_deref(),
303 ]);
304
305 rsx! {
306 div {
307 class,
308 "data-dividers": props.dividers.then_some(""),
309 "data-slot": "stat-group",
310 role: "group",
311 ..props.attributes,
312 {props.children}
313 }
314 }
315}
316
317pub const METER_MAX_SEGMENTS: u32 = 24;
319
320pub const METER_DEFAULT_VALUE_LABEL: &str = "{value} of {max}";
322
323pub fn resolve_meter_segments(segments: Option<u32>) -> Option<u32> {
325 segments.filter(|count| (2..=METER_MAX_SEGMENTS).contains(count))
326}
327
328#[derive(Clone, Copy, Debug, PartialEq)]
330pub struct MeterRange {
331 pub min: f64,
333 pub max: f64,
335 pub value: f64,
337}
338
339fn finite(value: Option<f64>) -> Option<f64> {
340 value.filter(|number| number.is_finite())
341}
342
343pub fn resolve_meter_range(min: Option<f64>, max: Option<f64>, value: f64) -> MeterRange {
345 let min = finite(min).unwrap_or(0.0);
346 let fallback_max = if min < 100.0 { 100.0 } else { min + 1.0 };
347 let max = finite(max).unwrap_or(fallback_max).max(min);
348 let value = finite(Some(value)).unwrap_or(min).clamp(min, max);
349
350 MeterRange { min, max, value }
351}
352
353pub(crate) fn fill_template(template: &str, values: &[(&str, &str)]) -> String {
355 let mut out = String::with_capacity(template.len());
356 let mut rest = template;
357
358 while let Some(open) = rest.find('{') {
359 out.push_str(&rest[..open]);
360 let after = &rest[open + 1..];
361
362 match after.find(['}', '{']) {
363 Some(close) if after.as_bytes()[close] == b'}' => {
364 let name = &after[..close];
365
366 if let Some((_, value)) = values.iter().find(|(key, _)| *key == name) {
367 out.push_str(value);
368 } else {
369 out.push('{');
370 out.push_str(name);
371 out.push('}');
372 }
373
374 rest = &after[close + 1..];
375 }
376 _ => {
377 out.push('{');
378 rest = after;
379 }
380 }
381 }
382
383 out.push_str(rest);
384 out
385}
386
387pub(crate) fn format_en_number(value: f64) -> String {
390 if value.is_nan() {
391 return "NaN".to_string();
392 }
393
394 if value.is_infinite() {
395 return if value > 0.0 { "∞" } else { "-∞" }.to_string();
396 }
397
398 let negative = value.is_sign_negative();
399 let digits = format!("{}", value.abs());
400 let (integer, fraction) = digits.split_once('.').unwrap_or((digits.as_str(), ""));
401 let mut whole: Vec<u8> = integer.bytes().map(|byte| byte - b'0').collect();
402 let mut kept: Vec<u8> = fraction.bytes().take(3).map(|byte| byte - b'0').collect();
403
404 if fraction
405 .as_bytes()
406 .get(3)
407 .is_some_and(|digit| *digit >= b'5')
408 {
409 let mut carry = true;
410
411 for digit in kept.iter_mut().rev().chain(whole.iter_mut().rev()) {
412 if !carry {
413 break;
414 }
415
416 if *digit == 9 {
417 *digit = 0;
418 } else {
419 *digit += 1;
420 carry = false;
421 }
422 }
423
424 if carry {
425 whole.insert(0, 1);
426 }
427 }
428
429 while kept.last() == Some(&0) {
430 kept.pop();
431 }
432
433 let mut out = String::new();
434
435 if negative {
436 out.push('-');
437 }
438
439 for (index, digit) in whole.iter().enumerate() {
440 if index > 0 && (whole.len() - index).is_multiple_of(3) {
441 out.push(',');
442 }
443
444 out.push(char::from(b'0' + digit));
445 }
446
447 if !kept.is_empty() {
448 out.push('.');
449 out.extend(kept.iter().map(|digit| char::from(b'0' + digit)));
450 }
451
452 out
453}
454
455pub fn resolve_meter_value_text(
458 range: MeterRange,
459 segmented: bool,
460 value_label: Option<&str>,
461) -> Option<String> {
462 let label = value_label.filter(|label| !label.trim().is_empty());
463
464 match label {
465 None if !segmented => None,
466 None => Some(fill_template(
467 METER_DEFAULT_VALUE_LABEL,
468 &[
469 ("max", &format_en_number(range.max - range.min)),
470 ("value", &format_en_number(range.value - range.min)),
471 ],
472 )),
473 Some(label) => Some(fill_template(
474 label,
475 &[
476 ("max", &format_en_number(range.max)),
477 ("min", &format_en_number(range.min)),
478 ("value", &format_en_number(range.value)),
479 ],
480 )),
481 }
482}
483
484#[derive(Props, Clone, PartialEq)]
486pub struct MeterProps {
487 #[props(default)]
489 pub value: f64,
490 pub min: Option<f64>,
492 pub max: Option<f64>,
494 pub segments: Option<u32>,
497 #[props(into)]
500 pub value_label: Option<String>,
501 #[props(into)]
503 pub aria_valuetext: Option<String>,
504 #[props(into)]
506 pub class: Option<String>,
507 #[props(extends = GlobalAttributes, extends = meter)]
509 pub attributes: Vec<Attribute>,
510 pub children: Element,
512}
513
514#[component]
518pub fn Meter(props: MeterProps) -> Element {
519 let segments = resolve_meter_segments(props.segments);
520 let range = resolve_meter_range(props.min, props.max, props.value);
521 let value_text =
522 resolve_meter_value_text(range, segments.is_some(), props.value_label.as_deref());
523 let class = compose([
524 Some("ui-meter"),
525 segments.is_some().then_some("ui-meter--segmented"),
526 props.class.as_deref(),
527 ]);
528 let has_children = super::has_content(&props.children);
529 let aria_valuetext = props.aria_valuetext.or_else(|| value_text.clone());
530
531 rsx! {
532 meter {
533 aria_valuetext,
534 class,
535 "data-segments": segments.map(|count| count.to_string()),
536 style: segments.map(|count| format!("--ui-meter-segments:{count}")),
537 max: props.max.map(|max| max.to_string()),
538 min: props.min.map(|min| min.to_string()),
539 value: "{props.value}",
540 ..props.attributes,
541 if has_children {
542 {props.children}
543 } else if let Some(text) = value_text {
544 "{text}"
545 }
546 }
547 }
548}
549
550#[cfg(test)]
551mod tests {
552 use super::{
553 MeterRange, fill_template, format_en_number, resolve_meter_range, resolve_meter_segments,
554 resolve_meter_value_text,
555 };
556
557 #[test]
558 fn english_numbers_match_intl() {
559 assert_eq!(format_en_number(1.0005), "1.001");
560 assert_eq!(format_en_number(0.0625), "0.063");
561 assert_eq!(format_en_number(-1.5), "-1.5");
562 assert_eq!(format_en_number(1_234_567.891_5), "1,234,567.892");
563 assert_eq!(format_en_number(1e21), "1,000,000,000,000,000,000,000");
564 assert_eq!(format_en_number(0.1 + 0.2), "0.3");
565 assert_eq!(format_en_number(-0.0004), "-0");
566 assert_eq!(format_en_number(0.9996), "1");
567 assert_eq!(format_en_number(999.9999), "1,000");
568 assert_eq!(format_en_number(0.0), "0");
569 }
570
571 #[test]
572 fn meter_segments_are_whole_counts_from_two_to_twenty_four() {
573 assert_eq!(resolve_meter_segments(Some(5)), Some(5));
574 assert_eq!(resolve_meter_segments(Some(1)), None);
575 assert_eq!(resolve_meter_segments(Some(25)), None);
576 assert_eq!(resolve_meter_segments(None), None);
577 }
578
579 #[test]
580 fn meter_range_clamps_like_the_native_element() {
581 assert_eq!(
582 resolve_meter_range(None, None, 150.0),
583 MeterRange {
584 min: 0.0,
585 max: 100.0,
586 value: 100.0
587 }
588 );
589 assert_eq!(
590 resolve_meter_range(Some(200.0), Some(10.0), 5.0),
591 MeterRange {
592 min: 200.0,
593 max: 200.0,
594 value: 200.0
595 }
596 );
597 assert_eq!(
598 resolve_meter_range(Some(150.0), None, f64::NAN),
599 MeterRange {
600 min: 150.0,
601 max: 151.0,
602 value: 150.0
603 }
604 );
605 }
606
607 #[test]
608 fn meter_value_text_counts_segments_from_min() {
609 let range = resolve_meter_range(Some(10.0), Some(20.0), 15.0);
610
611 assert_eq!(
612 resolve_meter_value_text(range, true, None).as_deref(),
613 Some("5 of 10")
614 );
615 assert_eq!(resolve_meter_value_text(range, false, None), None);
616 assert_eq!(
617 resolve_meter_value_text(range, false, Some("{value} of {max} ({min})")).as_deref(),
618 Some("15 of 20 (10)")
619 );
620 assert_eq!(resolve_meter_value_text(range, false, Some(" ")), None);
621 }
622
623 #[test]
624 fn templates_keep_unknown_and_unbalanced_placeholders() {
625 assert_eq!(fill_template("{a} {b} {", &[("a", "1")]), "1 {b} {");
626 assert_eq!(fill_template("{{a}", &[("a", "1")]), "{1");
627 let long = "{".repeat(100_000);
628 assert_eq!(fill_template(&long, &[]).len(), 100_000);
629 }
630}