lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! A label that rolls upward on hover or focus of its link or button.

use dioxus::prelude::*;

use super::shared::{graphemes, is_blank, js_round, merge_style};
use crate::class::compose;

/// How a [`TextRoll`] label moves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TextRollMode {
    /// The whole line rolls at once.
    #[default]
    Line,
    /// Each character rolls in turn, staggered across the label.
    Chars,
}

impl TextRollMode {
    /// The `data-mode` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Line => "line",
            Self::Chars => "chars",
        }
    }
}

const DEFAULT_STAGGER: u32 = 18;
const MAX_STAGGER: f64 = 60.0;

/// Labels with more glyphs than this render in line mode even when chars mode is requested, so
/// untrusted input cannot produce an unbounded number of nodes or delay.
pub(crate) const TEXT_ROLL_MAX_GLYPHS: usize = 160;

/// One glyph of a chars-mode label and its index across the whole label.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct TextRollGlyph<'a> {
    pub(crate) character: &'a str,
    pub(crate) index: usize,
}

/// A word of glyphs or the whitespace between words.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum TextRollToken<'a> {
    Word(Vec<TextRollGlyph<'a>>),
    Space(String),
}

/// Groups a label into words of indexed glyphs and the whitespace runs between them, like
/// `segmentLumenTextRoll`. Whitespace is kept verbatim and never receives an index.
pub(crate) fn segment_text_roll(text: &str) -> Vec<TextRollToken<'_>> {
    let mut tokens = Vec::new();
    let mut word = Vec::new();
    let mut space = String::new();
    let mut index = 0;

    for grapheme in graphemes(text) {
        if is_blank(grapheme) {
            if !word.is_empty() {
                tokens.push(TextRollToken::Word(std::mem::take(&mut word)));
            }

            space.push_str(grapheme);
        } else {
            if !space.is_empty() {
                tokens.push(TextRollToken::Space(std::mem::take(&mut space)));
            }

            word.push(TextRollGlyph {
                character: grapheme,
                index,
            });
            index += 1;
        }
    }

    if !word.is_empty() {
        tokens.push(TextRollToken::Word(word));
    }

    if !space.is_empty() {
        tokens.push(TextRollToken::Space(space));
    }

    tokens
}

/// Clamps the per-glyph stagger to 0..=60 ms like `normalizeLumenTextRollStagger`; a missing or
/// non-finite value uses 18 ms.
pub(crate) fn normalize_text_roll_stagger(value: Option<f64>) -> u32 {
    match value {
        Some(value) if value.is_finite() => {
            let clamped = js_round(value).clamp(0.0, MAX_STAGGER);
            // The clamp keeps the value a whole number in 0..=60; find it without a lossy cast.
            (0..=60u32)
                .find(|step| f64::from(*step) >= clamped)
                .unwrap_or(DEFAULT_STAGGER)
        }
        _ => DEFAULT_STAGGER,
    }
}

/// What a [`TextRoll`] renders, like `resolveLumenTextRoll`: chars mode degrades to line mode for
/// blank labels and labels over [`TEXT_ROLL_MAX_GLYPHS`].
pub(crate) fn resolve_text_roll(mode: TextRollMode, text: &str) -> Option<Vec<TextRollToken<'_>>> {
    if mode == TextRollMode::Line || is_blank(text) {
        return None;
    }

    let tokens = segment_text_roll(text);
    let glyphs: usize = tokens
        .iter()
        .map(|token| match token {
            TextRollToken::Word(glyphs) => glyphs.len(),
            TextRollToken::Space(_) => 0,
        })
        .sum();

    (glyphs <= TEXT_ROLL_MAX_GLYPHS).then_some(tokens)
}

/// Props for [`TextRoll`].
#[derive(Props, Clone, PartialEq)]
pub struct TextRollProps {
    /// The label.
    #[props(into)]
    pub text: String,
    /// Whole-line or per-character roll.
    #[props(default)]
    pub mode: TextRollMode,
    /// Milliseconds between glyphs in chars mode, clamped to 0..=60. Defaults to 18.
    #[props(into)]
    pub stagger: Option<f64>,
    /// Inline style; the stagger 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 `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
}

/// A short label inside a link or button that rolls upward when its nearest interactive ancestor
/// is hovered or receives keyboard focus. Assistive technology reads the label once.
///
/// The roll is pure CSS, so it runs wherever the renderer supports the transitions.
#[component]
pub fn TextRoll(props: TextRollProps) -> Element {
    let stagger = normalize_text_roll_stagger(props.stagger);
    let style = merge_style(
        props.style.as_deref(),
        &format!("--ui-text-roll-stagger: {stagger}ms"),
    );
    let class = compose([Some("ui-text-roll"), props.class.as_deref()]);
    let text = props.text.clone();

    let Some(tokens) = resolve_text_roll(props.mode, &props.text) else {
        return rsx! {
            span { class, "data-mode": "line", style, ..props.attributes,
                span { class: "ui-text-roll__line", {text} }
            }
        };
    };

    rsx! {
        span { class, "data-mode": "chars", style, ..props.attributes,
            span { class: "ui-sr-only", {text} }
            span { aria_hidden: "true", class: "ui-text-roll__glyphs",
                for (position, token) in tokens.into_iter().enumerate() {
                    {render_token(position, token)}
                }
            }
        }
    }
}

fn render_token(position: usize, token: TextRollToken<'_>) -> Element {
    match token {
        TextRollToken::Space(space) => rsx! { {space} },
        TextRollToken::Word(glyphs) => {
            let start = glyphs.first().map_or(position, |glyph| glyph.index);

            rsx! {
                span { key: "word-{start}", class: "ui-text-roll__word",
                    for glyph in glyphs {
                        span {
                            key: "{glyph.index}",
                            class: "ui-text-roll__glyph",
                            style: "--ui-text-roll-index: {glyph.index}",
                            {glyph.character.to_string()}
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        TEXT_ROLL_MAX_GLYPHS, TextRollMode, TextRollToken, normalize_text_roll_stagger,
        resolve_text_roll, segment_text_roll,
    };

    #[test]
    fn stagger_clamps_like_lumen_core() {
        assert_eq!(normalize_text_roll_stagger(None), 18);
        assert_eq!(normalize_text_roll_stagger(Some(f64::NAN)), 18);
        assert_eq!(normalize_text_roll_stagger(Some(-4.0)), 0);
        assert_eq!(normalize_text_roll_stagger(Some(99.0)), 60);
        assert_eq!(normalize_text_roll_stagger(Some(24.5)), 25);
        assert_eq!(normalize_text_roll_stagger(Some(24.4)), 24);
    }

    #[test]
    fn words_keep_one_index_sequence() {
        let tokens = segment_text_roll("Go  on");

        assert_eq!(tokens.len(), 3);
        assert!(matches!(&tokens[1], TextRollToken::Space(space) if space == "  "));

        let TextRollToken::Word(last) = &tokens[2] else {
            panic!("expected a word");
        };

        assert_eq!(last[0].index, 2);
        assert_eq!(last[1].character, "n");
    }

    #[test]
    fn chars_mode_degrades_to_line_mode() {
        assert!(resolve_text_roll(TextRollMode::Line, "Read").is_none());
        assert!(resolve_text_roll(TextRollMode::Chars, "   ").is_none());
        assert!(resolve_text_roll(TextRollMode::Chars, "Read").is_some());

        let long = "a".repeat(TEXT_ROLL_MAX_GLYPHS + 1);
        assert!(resolve_text_roll(TextRollMode::Chars, &long).is_none());

        let limit = "a".repeat(TEXT_ROLL_MAX_GLYPHS);
        assert!(resolve_text_roll(TextRollMode::Chars, &limit).is_some());
    }

    #[test]
    fn long_labels_segment_linearly() {
        let text = "word ".repeat(40_000);
        assert_eq!(segment_text_roll(&text).len(), 80_000);
    }
}