lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! A looping band of short items.

use dioxus::prelude::*;

use super::shared::{js_number, merge_style};
use crate::class::compose;

/// Loop speed preset of a [`Marquee`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarqueeSpeed {
    /// A slow loop.
    Slow,
    /// The default loop.
    #[default]
    Normal,
    /// A fast loop.
    Fast,
}

impl MarqueeSpeed {
    /// The `data-speed` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Slow => "slow",
            Self::Normal => "normal",
            Self::Fast => "fast",
        }
    }
}

/// Travel direction of a [`Marquee`]. Inline directions follow the text direction; vertical
/// directions loop within a fixed block size.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarqueeDirection {
    /// Toward the inline start.
    #[default]
    Start,
    /// Toward the inline end.
    End,
    /// Upward.
    Up,
    /// Downward.
    Down,
}

impl MarqueeDirection {
    /// The `data-direction` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Start => "start",
            Self::End => "end",
            Self::Up => "up",
            Self::Down => "down",
        }
    }
}

/// Space between [`Marquee`] items, from the shared spacing scale. Leave it unset for the
/// responsive default.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarqueeGap {
    /// Small.
    Sm,
    /// Medium.
    Md,
    /// Large.
    Lg,
    /// Extra large.
    Xl,
}

impl MarqueeGap {
    /// The `data-gap` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Sm => "sm",
            Self::Md => "md",
            Self::Lg => "lg",
            Self::Xl => "xl",
        }
    }
}

/// Outline treatment of [`Marquee`] text items.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarqueeOutline {
    /// Every item is solid.
    #[default]
    None,
    /// Every second item is outlined.
    Alternate,
}

impl MarqueeOutline {
    /// The `data-outline` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Alternate => "alternate",
        }
    }
}

const MIN_DURATION: f64 = 2.0;
const MAX_DURATION: f64 = 600.0;

/// The `--ui-marquee-duration` value for an explicit loop length in seconds, clamped to 2..=600,
/// or `None` when it is missing, non-finite, or not positive so the speed preset applies.
pub(crate) fn resolve_marquee_duration(seconds: Option<f64>) -> Option<String> {
    seconds
        .filter(|value| value.is_finite() && *value > 0.0)
        .map(|value| format!("{}s", js_number(value.clamp(MIN_DURATION, MAX_DURATION))))
}

/// Trims items and drops blank ones, like lumen-react.
pub(crate) fn visible_marquee_items(items: &[String]) -> Vec<String> {
    items
        .iter()
        .map(|item| item.trim())
        .filter(|item| !item.is_empty())
        .map(str::to_string)
        .collect()
}

/// Whether an `Element` holds anything to render.
fn has_children(children: &Element) -> bool {
    match children {
        Ok(node) => *node != VNode::placeholder() && !node.template.roots.is_empty(),
        Err(_) => false,
    }
}

/// Props for [`Marquee`].
#[derive(Props, Clone, PartialEq)]
pub struct MarqueeProps {
    /// Short text items. Leave empty to pass `li` children instead.
    #[props(default, into)]
    pub items: Vec<String>,
    /// Hides the moving content from assistive technology. Defaults to true for `items` (which
    /// then also exposes no plain list) and false for `li` children.
    #[props(into)]
    pub decorative: Option<bool>,
    /// Travel direction.
    #[props(default)]
    pub direction: MarqueeDirection,
    /// Seconds per loop, clamped to 2..=600; overrides `speed`.
    #[props(into)]
    pub duration: Option<f64>,
    /// Masks both travel edges while the band moves.
    #[props(default)]
    pub fade: bool,
    /// Space between items; unset keeps the responsive default.
    #[props(into)]
    pub gap: Option<MarqueeGap>,
    /// Accessible group name, used only when the marquee is not decorative.
    #[props(into)]
    pub label: Option<String>,
    /// Outlines every second text item.
    #[props(default)]
    pub outline: MarqueeOutline,
    /// Renders a native checkbox that pauses the band.
    #[props(default = true)]
    pub pause_control: bool,
    /// Text of the pause control. Defaults to "Pause animation".
    #[props(into)]
    pub pause_label: Option<String>,
    /// Pauses while hovered.
    #[props(default = true)]
    pub pause_on_hover: bool,
    /// Text drawn after each item. Empty for none.
    #[props(default = "•".to_string(), into)]
    pub separator: String,
    /// Loop speed preset.
    #[props(default)]
    pub speed: MarqueeSpeed,
    /// Inline style; an explicit duration is appended to it.
    #[props(into)]
    pub style: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// `li` items, used when `items` is empty. They render once in the visible list and again in
    /// an `aria-hidden`, `inert` loop copy, so do not give them `id` attributes.
    pub children: Element,
}

fn render_item_set(
    items: &[String],
    copy: bool,
    outline: MarqueeOutline,
    separator: &str,
) -> Element {
    let alternate = outline == MarqueeOutline::Alternate;

    rsx! {
        div {
            aria_hidden: copy.then_some("true"),
            class: "ui-marquee__set",
            "data-copy": copy.then_some(""),
            inert: copy.then_some(true),
            for (index, item) in items.iter().enumerate() {
                span {
                    key: "{index}-{item}",
                    class: "ui-marquee__item",
                    "data-outline": (alternate && index % 2 == 1).then_some(""),
                    {item.clone()}
                    if !separator.is_empty() {
                        span { aria_hidden: "true", class: "ui-marquee__separator", {separator.to_string()} }
                    }
                }
            }
        }
    }
}

/// A looping band of short items such as logos, tags, or announcements.
///
/// The loop is a CSS animation over two copies of the content; the second copy is `aria-hidden`
/// and `inert`. Text `items` are decorative by default; `li` children stay readable as a list.
/// The pause control is a native checkbox that stops the band through CSS, without JavaScript.
#[component]
pub fn Marquee(props: MarqueeProps) -> Element {
    let items = visible_marquee_items(&props.items);
    let uses_list = items.is_empty() && has_children(&props.children);

    if items.is_empty() && !uses_list {
        return rsx! {};
    }

    let decorative = props.decorative.unwrap_or(!uses_list);
    let group_label = if decorative {
        None
    } else {
        props
            .label
            .as_deref()
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .map(str::to_string)
    };
    let pause_label = props
        .pause_label
        .as_deref()
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .unwrap_or("Pause animation")
        .to_string();
    let style = resolve_marquee_duration(props.duration).map(|duration| {
        merge_style(
            props.style.as_deref(),
            &format!("--ui-marquee-duration: {duration}"),
        )
    });
    let style = style.or(props.style.clone());
    let class = compose([Some("ui-marquee"), props.class.as_deref()]);

    let track = if uses_list {
        rsx! {
            div {
                aria_hidden: decorative.then_some("true"),
                class: "ui-marquee__track",
                inert: decorative.then_some(true),
                ul { class: "ui-marquee__set ui-marquee__list", role: "list", {props.children.clone()} }
                ul {
                    aria_hidden: "true",
                    class: "ui-marquee__set ui-marquee__list",
                    "data-copy": "",
                    inert: true,
                    {props.children.clone()}
                }
            }
        }
    } else {
        rsx! {
            if !decorative {
                ul { class: "ui-sr-only",
                    for (index, item) in items.iter().enumerate() {
                        li { key: "{index}-{item}", {item.clone()} }
                    }
                }
            }
            div { aria_hidden: "true", class: "ui-marquee__track",
                {render_item_set(&items, false, props.outline, &props.separator)}
                {render_item_set(&items, true, props.outline, &props.separator)}
            }
        }
    };

    rsx! {
        div {
            aria_label: group_label,
            class,
            "data-direction": props.direction.as_str(),
            "data-fade": props.fade.then_some(""),
            "data-gap": props.gap.map(MarqueeGap::as_str),
            "data-outline": props.outline.as_str(),
            "data-pause-on-hover": props.pause_on_hover.then_some(""),
            "data-speed": props.speed.as_str(),
            role: (!decorative).then_some("group"),
            style,
            ..props.attributes,
            {track}
            if props.pause_control {
                label { class: "ui-marquee__control",
                    input { class: "ui-marquee__toggle", r#type: "checkbox" }
                    span { {pause_label} }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{resolve_marquee_duration, visible_marquee_items};

    #[test]
    fn durations_clamp_like_lumen_core() {
        assert_eq!(resolve_marquee_duration(Some(1.0)).as_deref(), Some("2s"));
        assert_eq!(
            resolve_marquee_duration(Some(12.5)).as_deref(),
            Some("12.5s")
        );
        assert_eq!(
            resolve_marquee_duration(Some(900.0)).as_deref(),
            Some("600s")
        );
        assert_eq!(resolve_marquee_duration(Some(0.0)), None);
        assert_eq!(resolve_marquee_duration(Some(f64::NAN)), None);
        assert_eq!(resolve_marquee_duration(None), None);
    }

    #[test]
    fn blank_items_are_dropped() {
        let items = vec![
            " Rust ".to_string(),
            "   ".to_string(),
            "Dioxus".to_string(),
        ];

        assert_eq!(visible_marquee_items(&items), vec!["Rust", "Dioxus"]);
    }
}