Skip to main content

lumen_dioxus/motion/
text_roll.rs

1//! A label that rolls upward on hover or focus of its link or button.
2
3use dioxus::prelude::*;
4
5use super::shared::{graphemes, is_blank, js_round, merge_style};
6use crate::class::compose;
7
8/// How a [`TextRoll`] label moves.
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum TextRollMode {
12    /// The whole line rolls at once.
13    #[default]
14    Line,
15    /// Each character rolls in turn, staggered across the label.
16    Chars,
17}
18
19impl TextRollMode {
20    /// The `data-mode` value.
21    pub fn as_str(self) -> &'static str {
22        match self {
23            Self::Line => "line",
24            Self::Chars => "chars",
25        }
26    }
27}
28
29const DEFAULT_STAGGER: u32 = 18;
30const MAX_STAGGER: f64 = 60.0;
31
32/// Labels with more glyphs than this render in line mode even when chars mode is requested, so
33/// untrusted input cannot produce an unbounded number of nodes or delay.
34pub(crate) const TEXT_ROLL_MAX_GLYPHS: usize = 160;
35
36/// One glyph of a chars-mode label and its index across the whole label.
37#[derive(Clone, Debug, PartialEq)]
38pub(crate) struct TextRollGlyph<'a> {
39    pub(crate) character: &'a str,
40    pub(crate) index: usize,
41}
42
43/// A word of glyphs or the whitespace between words.
44#[derive(Clone, Debug, PartialEq)]
45pub(crate) enum TextRollToken<'a> {
46    Word(Vec<TextRollGlyph<'a>>),
47    Space(String),
48}
49
50/// Groups a label into words of indexed glyphs and the whitespace runs between them, like
51/// `segmentLumenTextRoll`. Whitespace is kept verbatim and never receives an index.
52pub(crate) fn segment_text_roll(text: &str) -> Vec<TextRollToken<'_>> {
53    let mut tokens = Vec::new();
54    let mut word = Vec::new();
55    let mut space = String::new();
56    let mut index = 0;
57
58    for grapheme in graphemes(text) {
59        if is_blank(grapheme) {
60            if !word.is_empty() {
61                tokens.push(TextRollToken::Word(std::mem::take(&mut word)));
62            }
63
64            space.push_str(grapheme);
65        } else {
66            if !space.is_empty() {
67                tokens.push(TextRollToken::Space(std::mem::take(&mut space)));
68            }
69
70            word.push(TextRollGlyph {
71                character: grapheme,
72                index,
73            });
74            index += 1;
75        }
76    }
77
78    if !word.is_empty() {
79        tokens.push(TextRollToken::Word(word));
80    }
81
82    if !space.is_empty() {
83        tokens.push(TextRollToken::Space(space));
84    }
85
86    tokens
87}
88
89/// Clamps the per-glyph stagger to 0..=60 ms like `normalizeLumenTextRollStagger`; a missing or
90/// non-finite value uses 18 ms.
91pub(crate) fn normalize_text_roll_stagger(value: Option<f64>) -> u32 {
92    match value {
93        Some(value) if value.is_finite() => {
94            let clamped = js_round(value).clamp(0.0, MAX_STAGGER);
95            // The clamp keeps the value a whole number in 0..=60; find it without a lossy cast.
96            (0..=60u32)
97                .find(|step| f64::from(*step) >= clamped)
98                .unwrap_or(DEFAULT_STAGGER)
99        }
100        _ => DEFAULT_STAGGER,
101    }
102}
103
104/// What a [`TextRoll`] renders, like `resolveLumenTextRoll`: chars mode degrades to line mode for
105/// blank labels and labels over [`TEXT_ROLL_MAX_GLYPHS`].
106pub(crate) fn resolve_text_roll(mode: TextRollMode, text: &str) -> Option<Vec<TextRollToken<'_>>> {
107    if mode == TextRollMode::Line || is_blank(text) {
108        return None;
109    }
110
111    let tokens = segment_text_roll(text);
112    let glyphs: usize = tokens
113        .iter()
114        .map(|token| match token {
115            TextRollToken::Word(glyphs) => glyphs.len(),
116            TextRollToken::Space(_) => 0,
117        })
118        .sum();
119
120    (glyphs <= TEXT_ROLL_MAX_GLYPHS).then_some(tokens)
121}
122
123/// Props for [`TextRoll`].
124#[derive(Props, Clone, PartialEq)]
125pub struct TextRollProps {
126    /// The label.
127    #[props(into)]
128    pub text: String,
129    /// Whole-line or per-character roll.
130    #[props(default)]
131    pub mode: TextRollMode,
132    /// Milliseconds between glyphs in chars mode, clamped to 0..=60. Defaults to 18.
133    #[props(into)]
134    pub stagger: Option<f64>,
135    /// Inline style; the stagger is appended to it.
136    #[props(into)]
137    pub style: Option<String>,
138    /// Extra classes appended after the Lumen class.
139    #[props(into)]
140    pub class: Option<String>,
141    /// Any other `<span>` or global attribute.
142    #[props(extends = GlobalAttributes, extends = span)]
143    pub attributes: Vec<Attribute>,
144}
145
146/// A short label inside a link or button that rolls upward when its nearest interactive ancestor
147/// is hovered or receives keyboard focus. Assistive technology reads the label once.
148///
149/// The roll is pure CSS, so it runs wherever the renderer supports the transitions.
150#[component]
151pub fn TextRoll(props: TextRollProps) -> Element {
152    let stagger = normalize_text_roll_stagger(props.stagger);
153    let style = merge_style(
154        props.style.as_deref(),
155        &format!("--ui-text-roll-stagger: {stagger}ms"),
156    );
157    let class = compose([Some("ui-text-roll"), props.class.as_deref()]);
158    let text = props.text.clone();
159
160    let Some(tokens) = resolve_text_roll(props.mode, &props.text) else {
161        return rsx! {
162            span { class, "data-mode": "line", style, ..props.attributes,
163                span { class: "ui-text-roll__line", {text} }
164            }
165        };
166    };
167
168    rsx! {
169        span { class, "data-mode": "chars", style, ..props.attributes,
170            span { class: "ui-sr-only", {text} }
171            span { aria_hidden: "true", class: "ui-text-roll__glyphs",
172                for (position, token) in tokens.into_iter().enumerate() {
173                    {render_token(position, token)}
174                }
175            }
176        }
177    }
178}
179
180fn render_token(position: usize, token: TextRollToken<'_>) -> Element {
181    match token {
182        TextRollToken::Space(space) => rsx! { {space} },
183        TextRollToken::Word(glyphs) => {
184            let start = glyphs.first().map_or(position, |glyph| glyph.index);
185
186            rsx! {
187                span { key: "word-{start}", class: "ui-text-roll__word",
188                    for glyph in glyphs {
189                        span {
190                            key: "{glyph.index}",
191                            class: "ui-text-roll__glyph",
192                            style: "--ui-text-roll-index: {glyph.index}",
193                            {glyph.character.to_string()}
194                        }
195                    }
196                }
197            }
198        }
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::{
205        TEXT_ROLL_MAX_GLYPHS, TextRollMode, TextRollToken, normalize_text_roll_stagger,
206        resolve_text_roll, segment_text_roll,
207    };
208
209    #[test]
210    fn stagger_clamps_like_lumen_core() {
211        assert_eq!(normalize_text_roll_stagger(None), 18);
212        assert_eq!(normalize_text_roll_stagger(Some(f64::NAN)), 18);
213        assert_eq!(normalize_text_roll_stagger(Some(-4.0)), 0);
214        assert_eq!(normalize_text_roll_stagger(Some(99.0)), 60);
215        assert_eq!(normalize_text_roll_stagger(Some(24.5)), 25);
216        assert_eq!(normalize_text_roll_stagger(Some(24.4)), 24);
217    }
218
219    #[test]
220    fn words_keep_one_index_sequence() {
221        let tokens = segment_text_roll("Go  on");
222
223        assert_eq!(tokens.len(), 3);
224        assert!(matches!(&tokens[1], TextRollToken::Space(space) if space == "  "));
225
226        let TextRollToken::Word(last) = &tokens[2] else {
227            panic!("expected a word");
228        };
229
230        assert_eq!(last[0].index, 2);
231        assert_eq!(last[1].character, "n");
232    }
233
234    #[test]
235    fn chars_mode_degrades_to_line_mode() {
236        assert!(resolve_text_roll(TextRollMode::Line, "Read").is_none());
237        assert!(resolve_text_roll(TextRollMode::Chars, "   ").is_none());
238        assert!(resolve_text_roll(TextRollMode::Chars, "Read").is_some());
239
240        let long = "a".repeat(TEXT_ROLL_MAX_GLYPHS + 1);
241        assert!(resolve_text_roll(TextRollMode::Chars, &long).is_none());
242
243        let limit = "a".repeat(TEXT_ROLL_MAX_GLYPHS);
244        assert!(resolve_text_roll(TextRollMode::Chars, &limit).is_some());
245    }
246
247    #[test]
248    fn long_labels_segment_linearly() {
249        let text = "word ".repeat(40_000);
250        assert_eq!(segment_text_roll(&text).len(), 80_000);
251    }
252}