Skip to main content

lumen_dioxus/motion/
marquee.rs

1//! A looping band of short items.
2
3use dioxus::prelude::*;
4
5use super::shared::{js_number, merge_style};
6use crate::class::compose;
7
8/// Loop speed preset of a [`Marquee`].
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum MarqueeSpeed {
12    /// A slow loop.
13    Slow,
14    /// The default loop.
15    #[default]
16    Normal,
17    /// A fast loop.
18    Fast,
19}
20
21impl MarqueeSpeed {
22    /// The `data-speed` value.
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Self::Slow => "slow",
26            Self::Normal => "normal",
27            Self::Fast => "fast",
28        }
29    }
30}
31
32/// Travel direction of a [`Marquee`]. Inline directions follow the text direction; vertical
33/// directions loop within a fixed block size.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum MarqueeDirection {
37    /// Toward the inline start.
38    #[default]
39    Start,
40    /// Toward the inline end.
41    End,
42    /// Upward.
43    Up,
44    /// Downward.
45    Down,
46}
47
48impl MarqueeDirection {
49    /// The `data-direction` value.
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::Start => "start",
53            Self::End => "end",
54            Self::Up => "up",
55            Self::Down => "down",
56        }
57    }
58}
59
60/// Space between [`Marquee`] items, from the shared spacing scale. Leave it unset for the
61/// responsive default.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum MarqueeGap {
65    /// Small.
66    Sm,
67    /// Medium.
68    Md,
69    /// Large.
70    Lg,
71    /// Extra large.
72    Xl,
73}
74
75impl MarqueeGap {
76    /// The `data-gap` value.
77    pub fn as_str(self) -> &'static str {
78        match self {
79            Self::Sm => "sm",
80            Self::Md => "md",
81            Self::Lg => "lg",
82            Self::Xl => "xl",
83        }
84    }
85}
86
87/// Outline treatment of [`Marquee`] text items.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum MarqueeOutline {
91    /// Every item is solid.
92    #[default]
93    None,
94    /// Every second item is outlined.
95    Alternate,
96}
97
98impl MarqueeOutline {
99    /// The `data-outline` value.
100    pub fn as_str(self) -> &'static str {
101        match self {
102            Self::None => "none",
103            Self::Alternate => "alternate",
104        }
105    }
106}
107
108const MIN_DURATION: f64 = 2.0;
109const MAX_DURATION: f64 = 600.0;
110
111/// The `--ui-marquee-duration` value for an explicit loop length in seconds, clamped to 2..=600,
112/// or `None` when it is missing, non-finite, or not positive so the speed preset applies.
113pub(crate) fn resolve_marquee_duration(seconds: Option<f64>) -> Option<String> {
114    seconds
115        .filter(|value| value.is_finite() && *value > 0.0)
116        .map(|value| format!("{}s", js_number(value.clamp(MIN_DURATION, MAX_DURATION))))
117}
118
119/// Trims items and drops blank ones, like lumen-react.
120pub(crate) fn visible_marquee_items(items: &[String]) -> Vec<String> {
121    items
122        .iter()
123        .map(|item| item.trim())
124        .filter(|item| !item.is_empty())
125        .map(str::to_string)
126        .collect()
127}
128
129/// Whether an `Element` holds anything to render.
130fn has_children(children: &Element) -> bool {
131    match children {
132        Ok(node) => *node != VNode::placeholder() && !node.template.roots.is_empty(),
133        Err(_) => false,
134    }
135}
136
137/// Props for [`Marquee`].
138#[derive(Props, Clone, PartialEq)]
139pub struct MarqueeProps {
140    /// Short text items. Leave empty to pass `li` children instead.
141    #[props(default, into)]
142    pub items: Vec<String>,
143    /// Hides the moving content from assistive technology. Defaults to true for `items` (which
144    /// then also exposes no plain list) and false for `li` children.
145    #[props(into)]
146    pub decorative: Option<bool>,
147    /// Travel direction.
148    #[props(default)]
149    pub direction: MarqueeDirection,
150    /// Seconds per loop, clamped to 2..=600; overrides `speed`.
151    #[props(into)]
152    pub duration: Option<f64>,
153    /// Masks both travel edges while the band moves.
154    #[props(default)]
155    pub fade: bool,
156    /// Space between items; unset keeps the responsive default.
157    #[props(into)]
158    pub gap: Option<MarqueeGap>,
159    /// Accessible group name, used only when the marquee is not decorative.
160    #[props(into)]
161    pub label: Option<String>,
162    /// Outlines every second text item.
163    #[props(default)]
164    pub outline: MarqueeOutline,
165    /// Renders a native checkbox that pauses the band.
166    #[props(default = true)]
167    pub pause_control: bool,
168    /// Text of the pause control. Defaults to "Pause animation".
169    #[props(into)]
170    pub pause_label: Option<String>,
171    /// Pauses while hovered.
172    #[props(default = true)]
173    pub pause_on_hover: bool,
174    /// Text drawn after each item. Empty for none.
175    #[props(default = "•".to_string(), into)]
176    pub separator: String,
177    /// Loop speed preset.
178    #[props(default)]
179    pub speed: MarqueeSpeed,
180    /// Inline style; an explicit duration is appended to it.
181    #[props(into)]
182    pub style: Option<String>,
183    /// Extra classes appended after the Lumen class.
184    #[props(into)]
185    pub class: Option<String>,
186    /// Any other `<div>` or global attribute.
187    #[props(extends = GlobalAttributes, extends = div)]
188    pub attributes: Vec<Attribute>,
189    /// `li` items, used when `items` is empty. They render once in the visible list and again in
190    /// an `aria-hidden`, `inert` loop copy, so do not give them `id` attributes.
191    pub children: Element,
192}
193
194fn render_item_set(
195    items: &[String],
196    copy: bool,
197    outline: MarqueeOutline,
198    separator: &str,
199) -> Element {
200    let alternate = outline == MarqueeOutline::Alternate;
201
202    rsx! {
203        div {
204            aria_hidden: copy.then_some("true"),
205            class: "ui-marquee__set",
206            "data-copy": copy.then_some(""),
207            inert: copy.then_some(true),
208            for (index, item) in items.iter().enumerate() {
209                span {
210                    key: "{index}-{item}",
211                    class: "ui-marquee__item",
212                    "data-outline": (alternate && index % 2 == 1).then_some(""),
213                    {item.clone()}
214                    if !separator.is_empty() {
215                        span { aria_hidden: "true", class: "ui-marquee__separator", {separator.to_string()} }
216                    }
217                }
218            }
219        }
220    }
221}
222
223/// A looping band of short items such as logos, tags, or announcements.
224///
225/// The loop is a CSS animation over two copies of the content; the second copy is `aria-hidden`
226/// and `inert`. Text `items` are decorative by default; `li` children stay readable as a list.
227/// The pause control is a native checkbox that stops the band through CSS, without JavaScript.
228#[component]
229pub fn Marquee(props: MarqueeProps) -> Element {
230    let items = visible_marquee_items(&props.items);
231    let uses_list = items.is_empty() && has_children(&props.children);
232
233    if items.is_empty() && !uses_list {
234        return rsx! {};
235    }
236
237    let decorative = props.decorative.unwrap_or(!uses_list);
238    let group_label = if decorative {
239        None
240    } else {
241        props
242            .label
243            .as_deref()
244            .map(str::trim)
245            .filter(|text| !text.is_empty())
246            .map(str::to_string)
247    };
248    let pause_label = props
249        .pause_label
250        .as_deref()
251        .map(str::trim)
252        .filter(|text| !text.is_empty())
253        .unwrap_or("Pause animation")
254        .to_string();
255    let style = resolve_marquee_duration(props.duration).map(|duration| {
256        merge_style(
257            props.style.as_deref(),
258            &format!("--ui-marquee-duration: {duration}"),
259        )
260    });
261    let style = style.or(props.style.clone());
262    let class = compose([Some("ui-marquee"), props.class.as_deref()]);
263
264    let track = if uses_list {
265        rsx! {
266            div {
267                aria_hidden: decorative.then_some("true"),
268                class: "ui-marquee__track",
269                inert: decorative.then_some(true),
270                ul { class: "ui-marquee__set ui-marquee__list", role: "list", {props.children.clone()} }
271                ul {
272                    aria_hidden: "true",
273                    class: "ui-marquee__set ui-marquee__list",
274                    "data-copy": "",
275                    inert: true,
276                    {props.children.clone()}
277                }
278            }
279        }
280    } else {
281        rsx! {
282            if !decorative {
283                ul { class: "ui-sr-only",
284                    for (index, item) in items.iter().enumerate() {
285                        li { key: "{index}-{item}", {item.clone()} }
286                    }
287                }
288            }
289            div { aria_hidden: "true", class: "ui-marquee__track",
290                {render_item_set(&items, false, props.outline, &props.separator)}
291                {render_item_set(&items, true, props.outline, &props.separator)}
292            }
293        }
294    };
295
296    rsx! {
297        div {
298            aria_label: group_label,
299            class,
300            "data-direction": props.direction.as_str(),
301            "data-fade": props.fade.then_some(""),
302            "data-gap": props.gap.map(MarqueeGap::as_str),
303            "data-outline": props.outline.as_str(),
304            "data-pause-on-hover": props.pause_on_hover.then_some(""),
305            "data-speed": props.speed.as_str(),
306            role: (!decorative).then_some("group"),
307            style,
308            ..props.attributes,
309            {track}
310            if props.pause_control {
311                label { class: "ui-marquee__control",
312                    input { class: "ui-marquee__toggle", r#type: "checkbox" }
313                    span { {pause_label} }
314                }
315            }
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::{resolve_marquee_duration, visible_marquee_items};
323
324    #[test]
325    fn durations_clamp_like_lumen_core() {
326        assert_eq!(resolve_marquee_duration(Some(1.0)).as_deref(), Some("2s"));
327        assert_eq!(
328            resolve_marquee_duration(Some(12.5)).as_deref(),
329            Some("12.5s")
330        );
331        assert_eq!(
332            resolve_marquee_duration(Some(900.0)).as_deref(),
333            Some("600s")
334        );
335        assert_eq!(resolve_marquee_duration(Some(0.0)), None);
336        assert_eq!(resolve_marquee_duration(Some(f64::NAN)), None);
337        assert_eq!(resolve_marquee_duration(None), None);
338    }
339
340    #[test]
341    fn blank_items_are_dropped() {
342        let items = vec![
343            " Rust ".to_string(),
344            "   ".to_string(),
345            "Dioxus".to_string(),
346        ];
347
348        assert_eq!(visible_marquee_items(&items), vec!["Rust", "Dioxus"]);
349    }
350}