Skip to main content

lumen_dioxus/motion/
split_text.rs

1//! Text split into masked words or characters that rise in sequence.
2// cspell:words onfocusin onvisible
3
4use dioxus::prelude::*;
5
6use super::shared::{
7    MotionDuration, MotionSupport, graphemes, merge_style, use_motion_support, use_reveal,
8};
9use crate::class::compose;
10
11/// The element a [`SplitText`] renders, lumen-react's `as` prop.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum SplitTextElement {
15    /// `<div>`.
16    Div,
17    /// `<h1>`.
18    H1,
19    /// `<h2>`.
20    H2,
21    /// `<h3>`.
22    H3,
23    /// `<h4>`.
24    H4,
25    /// `<h5>`.
26    H5,
27    /// `<h6>`.
28    H6,
29    /// `<p>`.
30    P,
31    /// `<span>`.
32    #[default]
33    Span,
34}
35
36/// How a [`SplitText`] label is split.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum SplitTextBy {
40    /// One masked item per grapheme.
41    Char,
42    /// One masked item per word.
43    #[default]
44    Word,
45    /// Words grouped into rendered lines. Grouping needs browser layout, so lumen-dioxus animates
46    /// each word, like lumen-react before its layout pass.
47    Line,
48}
49
50impl SplitTextBy {
51    /// The `data-by` value.
52    pub fn as_str(self) -> &'static str {
53        match self {
54            Self::Char => "char",
55            Self::Word => "word",
56            Self::Line => "line",
57        }
58    }
59}
60
61/// When a [`SplitText`] animates.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum SplitTextTrigger {
65    /// On first paint, with a CSS animation.
66    Load,
67    /// Never on its own; an ancestor reveal (such as a bound `ScrollReveal`) drives it.
68    None,
69    /// When it scrolls into view.
70    #[default]
71    Visible,
72}
73
74impl SplitTextTrigger {
75    /// The `data-trigger` value.
76    pub fn as_str(self) -> &'static str {
77        match self {
78            Self::Load => "load",
79            Self::None => "none",
80            Self::Visible => "visible",
81        }
82    }
83}
84
85/// One masked, independently animated piece of text.
86#[derive(Clone, Debug, PartialEq)]
87pub(crate) struct SplitTextItem<'a> {
88    pub(crate) index: u32,
89    pub(crate) value: &'a str,
90}
91
92/// A word keeps its items together on one line; whitespace stays outside every mask.
93#[derive(Clone, Debug, PartialEq)]
94pub(crate) enum SplitTextPart<'a> {
95    Space(&'a str),
96    Word(Vec<SplitTextItem<'a>>),
97}
98
99/// Breaking whitespace only; no-break spaces stay inside words, like `lumen-core`.
100fn is_breaking_space(character: char) -> bool {
101    matches!(
102        character,
103        '\u{20}' | '\u{1680}' | '\u{2028}' | '\u{2029}' | '\u{205f}' | '\u{3000}' | '\t'..='\r'
104    ) || (('\u{2000}'..='\u{200a}').contains(&character) && character != '\u{2007}')
105}
106
107/// Appends one run of text: whitespace as-is, a word as masked items.
108fn push_run<'a>(
109    parts: &mut Vec<SplitTextPart<'a>>,
110    run: &'a str,
111    space: bool,
112    by: SplitTextBy,
113    next_index: &mut u32,
114) {
115    if run.is_empty() {
116        return;
117    }
118
119    if space {
120        parts.push(SplitTextPart::Space(run));
121        return;
122    }
123
124    let pieces = match by {
125        SplitTextBy::Char => graphemes(run),
126        SplitTextBy::Word | SplitTextBy::Line => vec![run],
127    };
128    let items = pieces
129        .into_iter()
130        .map(|piece| {
131            let index = *next_index;
132            *next_index = next_index.saturating_add(1);
133            SplitTextItem {
134                index,
135                value: piece,
136            }
137        })
138        .collect();
139
140    parts.push(SplitTextPart::Word(items));
141}
142
143/// Splits a label into words and whitespace with one linear scan, like `splitLumenText`.
144/// Character splitting keeps grapheme clusters whole. Returns the parts and the item count.
145pub(crate) fn split_text(
146    value: &str,
147    by: SplitTextBy,
148    offset: u32,
149) -> (Vec<SplitTextPart<'_>>, u32) {
150    let mut parts = Vec::new();
151    let mut next_index = offset;
152    let mut start = 0;
153    let mut previous_space = None;
154
155    for (index, character) in value.char_indices() {
156        let space = is_breaking_space(character);
157
158        if let Some(previous) = previous_space
159            && previous != space
160        {
161            push_run(
162                &mut parts,
163                &value[start..index],
164                previous,
165                by,
166                &mut next_index,
167            );
168            start = index;
169        }
170
171        previous_space = Some(space);
172    }
173
174    if let Some(space) = previous_space {
175        push_run(&mut parts, &value[start..], space, by, &mut next_index);
176    }
177
178    (parts, next_index - offset)
179}
180
181/// A positive count, or `fallback` for zero, like `normalizeLumenSplitTextCount`.
182fn positive_or(value: Option<u32>, fallback: u32) -> u32 {
183    value.filter(|count| *count > 0).unwrap_or(fallback)
184}
185
186/// The custom properties every adapter writes, like `lumenSplitTextStyleProperties`:
187/// `--ui-split-last` is the last stagger index, and `--ui-split-max-delay` caps the total wait.
188fn split_style(stagger: Option<u32>, max_delay: Option<u32>, offset: u32, count: u32) -> String {
189    let last = (offset + count).saturating_sub(1).max(1);
190    let stagger = positive_or(stagger, 40);
191
192    match max_delay {
193        Some(max_delay) => format!(
194            "--ui-split-stagger: {stagger}ms; --ui-split-last: {last}; --ui-split-max-delay: {max_delay}ms"
195        ),
196        None => format!("--ui-split-stagger: {stagger}ms; --ui-split-last: {last}"),
197    }
198}
199
200/// Props for [`SplitText`].
201#[derive(Props, Clone, PartialEq)]
202pub struct SplitTextProps {
203    /// The text to split.
204    #[props(into)]
205    pub text: String,
206    /// The root element, lumen-react's `as`.
207    #[props(default)]
208    pub element: SplitTextElement,
209    /// Split into words or characters.
210    #[props(default)]
211    pub by: SplitTextBy,
212    /// Transition length of each item.
213    #[props(default)]
214    pub duration: MotionDuration,
215    /// Starting stagger index, so several runs inside one heading continue one sequence.
216    #[props(into)]
217    pub offset: Option<u32>,
218    /// Milliseconds between items. Defaults to 40; zero also uses the default.
219    #[props(into)]
220    pub stagger: Option<u32>,
221    /// Longest wait, in milliseconds, before the last item starts; longer runs shorten the step.
222    #[props(into)]
223    pub max_delay: Option<u32>,
224    /// When the items animate.
225    #[props(default)]
226    pub trigger: SplitTextTrigger,
227    /// Inline style; the stagger is appended to it.
228    #[props(into)]
229    pub style: Option<String>,
230    /// Extra classes appended after the Lumen classes.
231    #[props(into)]
232    pub class: Option<String>,
233    /// Any other global attribute.
234    #[props(extends = GlobalAttributes)]
235    pub attributes: Vec<Attribute>,
236}
237
238fn render_part(part: SplitTextPart<'_>) -> Element {
239    match part {
240        SplitTextPart::Space(space) => rsx! { span { "data-ui-split-value": space.to_string() } },
241        SplitTextPart::Word(items) => {
242            let key = items.first().map_or(0, |item| item.index);
243
244            rsx! {
245                span { key: "{key}", class: "ui-split-text__word",
246                    for item in items {
247                        span { key: "{item.index}", class: "ui-split-text__mask",
248                            span {
249                                class: "ui-split-text__item",
250                                "data-ui-split-value": item.value.to_string(),
251                                style: "--ui-split-index: {item.index}",
252                            }
253                        }
254                    }
255                }
256            }
257        }
258    }
259}
260
261macro_rules! split_root {
262    ($tag:ident, $props:ident, $class:ident, $style:ident, $reveal:ident, $content:ident) => {
263        rsx! {
264            $tag {
265                class: $class,
266                "data-by": $props.by.as_str(),
267                "data-trigger": $props.trigger.as_str(),
268                "data-ui-split-text": "",
269                "data-ui-scroll-reveal-bound": $reveal.bound_attribute(),
270                style: $style,
271                onvisible: move |event| $reveal.on_visible(&event),
272                onfocusin: move |_| $reveal.on_focus_in(),
273                ..$props.attributes,
274                {$content}
275            }
276        }
277    };
278}
279
280/// Splits text into masked spans that rise in sequence; assistive technology reads one visually
281/// hidden copy.
282///
283/// `Load` animates with CSS in browsers and webviews. `Visible` reveals through `onvisible`;
284/// reduced motion shows the fragments without animation. Renderers without JavaScript, including
285/// Dioxus Native, show the full text directly rather than relying on generated `attr()` content.
286#[component]
287pub fn SplitText(props: SplitTextProps) -> Element {
288    let reveal = use_reveal(true, props.trigger == SplitTextTrigger::Visible, None);
289    let support = use_motion_support();
290    let offset = positive_or(props.offset, 0);
291    let (parts, count) = split_text(&props.text, props.by, offset);
292    let duration = props.duration.class();
293    let class = compose([
294        Some("ui-split-text"),
295        Some(duration.as_str()),
296        props.class.as_deref(),
297        reveal.revealed().then_some("is-revealed"),
298    ]);
299    let style = merge_style(
300        props.style.as_deref(),
301        &split_style(props.stagger, props.max_delay, offset, count),
302    );
303    let label = props.text.clone();
304    let content = if matches!(support(), MotionSupport::Unsupported) {
305        rsx! { {label} }
306    } else {
307        rsx! {
308            span { class: "ui-sr-only ui-split-text__label", {label} }
309            span { aria_hidden: "true", class: "ui-split-text__visual",
310                for part in parts {
311                    {render_part(part)}
312                }
313            }
314        }
315    };
316
317    match props.element {
318        SplitTextElement::Div => split_root!(div, props, class, style, reveal, content),
319        SplitTextElement::H1 => split_root!(h1, props, class, style, reveal, content),
320        SplitTextElement::H2 => split_root!(h2, props, class, style, reveal, content),
321        SplitTextElement::H3 => split_root!(h3, props, class, style, reveal, content),
322        SplitTextElement::H4 => split_root!(h4, props, class, style, reveal, content),
323        SplitTextElement::H5 => split_root!(h5, props, class, style, reveal, content),
324        SplitTextElement::H6 => split_root!(h6, props, class, style, reveal, content),
325        SplitTextElement::P => split_root!(p, props, class, style, reveal, content),
326        SplitTextElement::Span => split_root!(span, props, class, style, reveal, content),
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::{SplitTextBy, SplitTextPart, positive_or, split_text};
333
334    fn words(parts: &[SplitTextPart<'_>]) -> Vec<Vec<(u32, String)>> {
335        parts
336            .iter()
337            .filter_map(|part| match part {
338                SplitTextPart::Word(items) => Some(
339                    items
340                        .iter()
341                        .map(|item| (item.index, item.value.to_string()))
342                        .collect(),
343                ),
344                SplitTextPart::Space(_) => None,
345            })
346            .collect()
347    }
348
349    #[test]
350    fn words_split_on_breaking_whitespace_only() {
351        let (parts, count) = split_text("Ship\u{a0}it  now", SplitTextBy::Word, 0);
352
353        assert_eq!(count, 2);
354        assert_eq!(parts.len(), 3);
355        assert_eq!(parts[1], SplitTextPart::Space("  "));
356        assert_eq!(
357            words(&parts),
358            vec![
359                vec![(0, "Ship\u{a0}it".to_string())],
360                vec![(1, "now".to_string())]
361            ]
362        );
363    }
364
365    #[test]
366    fn characters_continue_from_the_offset() {
367        let (parts, count) = split_text(" Hi e\u{301}", SplitTextBy::Char, 3);
368
369        assert_eq!(count, 3);
370        assert_eq!(parts[0], SplitTextPart::Space(" "));
371        assert_eq!(
372            words(&parts),
373            vec![
374                vec![(3, "H".to_string()), (4, "i".to_string())],
375                vec![(5, "e\u{301}".to_string())]
376            ]
377        );
378    }
379
380    #[test]
381    fn empty_text_has_no_parts() {
382        let (parts, count) = split_text("", SplitTextBy::Char, 0);
383
384        assert_eq!(parts, Vec::new());
385        assert_eq!(count, 0);
386    }
387
388    #[test]
389    fn counts_fall_back_when_not_positive() {
390        assert_eq!(positive_or(None, 40), 40);
391        assert_eq!(positive_or(Some(0), 40), 40);
392        assert_eq!(positive_or(Some(12), 40), 12);
393    }
394
395    #[test]
396    fn long_text_splits_linearly() {
397        let text = "ab ".repeat(50_000);
398        let (parts, count) = split_text(&text, SplitTextBy::Char, 0);
399
400        assert_eq!(count, 100_000);
401        assert_eq!(parts.len(), 100_000);
402    }
403}