Skip to main content

lumen_dioxus/
feedback.rs

1//! Feedback and identity: `Progress`, `Spinner`, `Avatar`, and `Separator`.
2
3use dioxus::prelude::*;
4
5use crate::class::{Orientation, compose};
6
7const DEFAULT_PROGRESS_MAX: f64 = 100.0;
8
9/// The clamped values a [`Progress`] renders, matching `normalizeLumenProgress` in `lumen-core`.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct ProgressState {
12    /// A finite maximum above zero; falls back to 100.
13    pub max: f64,
14    /// The value clamped to `0..=max`; non-finite values become 0.
15    pub value: f64,
16    /// `value / max * 100`.
17    pub percentage: f64,
18}
19
20/// Clamp a progress value and maximum the same way every Lumen adapter does.
21pub fn normalize_progress(max: f64, value: f64) -> ProgressState {
22    let max = if max.is_finite() && max > 0.0 {
23        max
24    } else {
25        DEFAULT_PROGRESS_MAX
26    };
27    let value = if value.is_finite() {
28        value.clamp(0.0, max)
29    } else {
30        0.0
31    };
32
33    ProgressState {
34        max,
35        value,
36        percentage: value / max * 100.0,
37    }
38}
39
40/// Props for [`Progress`].
41#[derive(Props, Clone, PartialEq)]
42pub struct ProgressProps {
43    /// Current value.
44    #[props(default)]
45    pub value: f64,
46    /// Maximum value. Defaults to 100.
47    #[props(default = DEFAULT_PROGRESS_MAX)]
48    pub max: f64,
49    /// Shows the value beside the bar. The root keeps its `progressbar` role and values.
50    #[props(default)]
51    pub show_value: bool,
52    /// With `show_value`, the visible value text, also set as `aria-valuetext`. Defaults to the
53    /// rounded percentage, such as `62%`.
54    #[props(into)]
55    pub value_label: Option<String>,
56    /// Extra classes appended after the Lumen classes.
57    #[props(into)]
58    pub class: Option<String>,
59    /// Any other `<div>` or global attribute. Give the bar an `aria_label`.
60    #[props(extends = GlobalAttributes, extends = div)]
61    pub attributes: Vec<Attribute>,
62}
63
64/// The visible value of a [`Progress`] with `show_value`: the label when given, otherwise the
65/// percentage rounded like JavaScript's `Math.round`, such as `62%`.
66fn progress_value_text(state: ProgressState, label: Option<&str>) -> String {
67    label.map_or_else(
68        // `percentage` is finite and within 0..=100, so `floor(x + 0.5)` is `Math.round`.
69        || format!("{}%", (state.percentage + 0.5).floor()),
70        str::to_string,
71    )
72}
73
74/// A determinate progress bar with `progressbar` semantics.
75///
76/// With `show_value`, the bar sits in a track beside a visible, `aria-hidden` value; assistive
77/// technology reads the root's values, or `value_label` as `aria-valuetext`.
78#[component]
79pub fn Progress(props: ProgressProps) -> Element {
80    let state = normalize_progress(props.max, props.value);
81    let show_value = props.show_value;
82    let class = compose([
83        Some("ui-progress"),
84        show_value.then_some("ui-progress--with-value"),
85        props.class.as_deref(),
86    ]);
87    // An empty label falls back to the percentage, as in Elements, instead of an empty
88    // aria-valuetext.
89    let value_label = props
90        .value_label
91        .filter(|label| show_value && !label.is_empty());
92    let value_text = show_value.then(|| progress_value_text(state, value_label.as_deref()));
93
94    rsx! {
95        div {
96            aria_valuemax: "{state.max}",
97            aria_valuemin: "0",
98            aria_valuenow: "{state.value}",
99            aria_valuetext: value_label,
100            class,
101            role: "progressbar",
102            ..props.attributes,
103            if let Some(text) = value_text {
104                span { class: "ui-progress__track",
105                    span {
106                        class: "ui-progress__bar",
107                        "data-slot": "progress-indicator",
108                        style: "width: {state.percentage}%",
109                    }
110                }
111                span { aria_hidden: "true", class: "ui-progress__value", "{text}" }
112            } else {
113                span {
114                    class: "ui-progress__bar",
115                    "data-slot": "progress-indicator",
116                    style: "width: {state.percentage}%",
117                }
118            }
119        }
120    }
121}
122
123fn has_name(value: Option<&str>) -> bool {
124    value.is_some_and(|text| !text.trim().is_empty())
125}
126
127/// Props for [`Spinner`].
128#[derive(Props, Clone, PartialEq)]
129pub struct SpinnerProps {
130    /// Accessible name. A named spinner gets `role="status"`; an unnamed one is hidden.
131    #[props(into)]
132    pub aria_label: Option<String>,
133    /// Id of the element that names the spinner.
134    #[props(into)]
135    pub aria_labelledby: Option<String>,
136    /// Overrides the computed role.
137    #[props(into)]
138    pub role: Option<String>,
139    /// Overrides the computed `aria-hidden`.
140    pub aria_hidden: Option<bool>,
141    /// Extra classes appended after the Lumen class.
142    #[props(into)]
143    pub class: Option<String>,
144    /// Any other `<span>` or global attribute.
145    #[props(extends = GlobalAttributes, extends = span)]
146    pub attributes: Vec<Attribute>,
147}
148
149/// An indeterminate loading indicator.
150///
151/// Follows `resolveLumenLoadingSemantics`: named spinners announce as `status`,
152/// unnamed ones are decorative and hidden from assistive technology.
153#[component]
154pub fn Spinner(props: SpinnerProps) -> Element {
155    let named = has_name(props.aria_label.as_deref()) || has_name(props.aria_labelledby.as_deref());
156    let aria_hidden = match props.aria_hidden {
157        Some(hidden) => Some(hidden.to_string()),
158        None if named => None,
159        None => Some("true".to_string()),
160    };
161    let role = match props.role {
162        Some(role) => Some(role),
163        None if named => Some("status".to_string()),
164        None => None,
165    };
166    let class = compose([Some("ui-spinner"), props.class.as_deref()]);
167
168    rsx! {
169        span {
170            aria_hidden,
171            aria_label: props.aria_label,
172            aria_labelledby: props.aria_labelledby,
173            class,
174            role,
175            ..props.attributes,
176        }
177    }
178}
179
180/// Size of an [`Avatar`].
181#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
182#[non_exhaustive]
183pub enum AvatarSize {
184    /// Smaller than the default, for dense rows.
185    Sm,
186    /// The default size. Inside a `Table` or `DataTable`, the stylesheet shrinks an avatar that
187    /// keeps this size.
188    #[default]
189    Md,
190    /// Larger than the default.
191    Lg,
192}
193
194impl AvatarSize {
195    /// The `ui-avatar--*` class; `Md` adds none.
196    pub fn class(self) -> Option<&'static str> {
197        match self {
198            Self::Sm => Some("ui-avatar--sm"),
199            Self::Md => None,
200            Self::Lg => Some("ui-avatar--lg"),
201        }
202    }
203}
204
205/// Props for [`Avatar`].
206#[derive(Props, Clone, PartialEq)]
207pub struct AvatarProps {
208    /// Image URL. Without it, the fallback renders.
209    #[props(into)]
210    pub src: Option<String>,
211    /// Alternative text for the image.
212    #[props(default, into)]
213    pub alt: String,
214    /// Text shown when there is no image, usually initials.
215    #[props(default, into)]
216    pub fallback: String,
217    /// Size. Defaults to `Md`.
218    #[props(default)]
219    pub size: AvatarSize,
220    /// Extra classes appended after the Lumen classes.
221    #[props(into)]
222    pub class: Option<String>,
223    /// Any other `<span>` or global attribute.
224    #[props(extends = GlobalAttributes, extends = span)]
225    pub attributes: Vec<Attribute>,
226    /// Extra content such as a status badge.
227    pub children: Element,
228}
229
230/// A user or entity image with a text fallback. Without a fallback, text children such as initials
231/// render as the avatar's only, centered content. Without `src`, a non-empty `alt` names the avatar as
232/// an image.
233#[component]
234pub fn Avatar(props: AvatarProps) -> Element {
235    let class = compose([
236        Some("ui-avatar"),
237        props.size.class(),
238        props.class.as_deref(),
239    ]);
240    let named = props.src.is_none() && !props.alt.is_empty();
241    let role = named.then_some("img");
242    let aria_label = named.then(|| props.alt.clone());
243
244    rsx! {
245        span { aria_label, class, role, ..props.attributes,
246            if let Some(src) = props.src {
247                img { alt: props.alt, src }
248            } else if !props.fallback.is_empty() {
249                span { {props.fallback} }
250            }
251            {props.children}
252        }
253    }
254}
255
256/// Props for [`Separator`].
257#[derive(Props, Clone, PartialEq)]
258pub struct SeparatorProps {
259    /// Direction of the line.
260    #[props(default)]
261    pub orientation: Orientation,
262    /// Extra classes appended after the Lumen classes.
263    #[props(into)]
264    pub class: Option<String>,
265    /// Any other `<hr>` or global attribute.
266    #[props(extends = GlobalAttributes, extends = hr)]
267    pub attributes: Vec<Attribute>,
268}
269
270/// A thematic break between groups of content.
271#[component]
272pub fn Separator(props: SeparatorProps) -> Element {
273    let orientation = props.orientation.as_str();
274    let modifier = format!("ui-separator--{orientation}");
275    let class = compose([
276        Some("ui-separator"),
277        Some(modifier.as_str()),
278        props.class.as_deref(),
279    ]);
280
281    rsx! {
282        hr {
283            aria_orientation: orientation,
284            class,
285            "data-orientation": orientation,
286            ..props.attributes,
287        }
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::{AvatarSize, normalize_progress, progress_value_text};
294
295    #[test]
296    fn progress_value_text_rounds_like_math_round() {
297        assert_eq!(
298            progress_value_text(normalize_progress(100.0, 62.0), None),
299            "62%"
300        );
301        assert_eq!(
302            progress_value_text(normalize_progress(100.0, 62.5), None),
303            "63%"
304        );
305        assert_eq!(
306            progress_value_text(normalize_progress(100.0, 62.49), None),
307            "62%"
308        );
309        assert_eq!(
310            progress_value_text(normalize_progress(3.0, 1.0), None),
311            "33%"
312        );
313        assert_eq!(
314            progress_value_text(normalize_progress(f64::NAN, f64::NAN), None),
315            "0%"
316        );
317        assert_eq!(
318            progress_value_text(normalize_progress(50.0, 80.0), None),
319            "100%"
320        );
321        assert_eq!(
322            progress_value_text(normalize_progress(100.0, 62.0), Some("3 of 5 files")),
323            "3 of 5 files"
324        );
325        assert_eq!(
326            progress_value_text(normalize_progress(100.0, 62.0), Some("")),
327            ""
328        );
329    }
330
331    #[test]
332    fn avatar_sizes_map_to_classes() {
333        assert_eq!(AvatarSize::default(), AvatarSize::Md);
334        assert_eq!(AvatarSize::Sm.class(), Some("ui-avatar--sm"));
335        assert_eq!(AvatarSize::Md.class(), None);
336        assert_eq!(AvatarSize::Lg.class(), Some("ui-avatar--lg"));
337    }
338
339    #[test]
340    fn progress_clamps_like_lumen_core() {
341        let state = normalize_progress(100.0, 62.0);
342        assert!((state.percentage - 62.0).abs() < f64::EPSILON);
343
344        let over = normalize_progress(50.0, 80.0);
345        assert!((over.value - 50.0).abs() < f64::EPSILON);
346        assert!((over.percentage - 100.0).abs() < f64::EPSILON);
347
348        let invalid = normalize_progress(f64::NAN, f64::INFINITY);
349        assert!((invalid.max - 100.0).abs() < f64::EPSILON);
350        assert!(invalid.value.abs() < f64::EPSILON);
351
352        let negative = normalize_progress(-5.0, -10.0);
353        assert!((negative.max - 100.0).abs() < f64::EPSILON);
354        assert!(negative.value.abs() < f64::EPSILON);
355    }
356}