Skip to main content

lumen_dioxus/motion/
shared.rs

1//! Helpers shared by the motion components: JavaScript-compatible number text, style merging,
2//! grapheme splitting, the motion probe, and the scroll reveal state.
3// cspell:words feff onvisible
4
5use std::time::Duration;
6
7use dioxus::prelude::*;
8
9use crate::time::sleep;
10
11/// Named motion durations from Lumen's tokens, used by [`ScrollReveal`](super::ScrollReveal),
12/// [`RevealGroup`](super::RevealGroup), [`SplitText`](super::SplitText), and
13/// [`AnimatedNumber`](super::AnimatedNumber).
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum MotionDuration {
17    /// `--ui-duration-fast` (120 ms by default).
18    Fast,
19    /// `--ui-duration-standard` (160 ms by default).
20    Standard,
21    /// `--ui-duration-slow` (300 ms by default).
22    #[default]
23    Slow,
24    /// `--ui-duration-entrance` (700 ms by default).
25    Entrance,
26    /// `--ui-duration-scene` (1000 ms by default).
27    Scene,
28}
29
30impl MotionDuration {
31    /// The `ui-motion-duration-*` class suffix.
32    pub fn as_str(self) -> &'static str {
33        match self {
34            Self::Fast => "fast",
35            Self::Standard => "standard",
36            Self::Slow => "slow",
37            Self::Entrance => "entrance",
38            Self::Scene => "scene",
39        }
40    }
41
42    /// The default token value in milliseconds, from `lumenDurations` in `lumen-core`.
43    pub fn milliseconds(self) -> u64 {
44        match self {
45            Self::Fast => 120,
46            Self::Standard => 160,
47            Self::Slow => 300,
48            Self::Entrance => 700,
49            Self::Scene => 1000,
50        }
51    }
52
53    pub(crate) fn class(self) -> String {
54        format!("ui-motion-duration-{}", self.as_str())
55    }
56}
57
58/// Formats a number the way JavaScript's `String(number)` does, so inline styles and data
59/// attributes match lumen-react: integers have no `.0`, `-0` prints as `0`, and very large or
60/// small magnitudes use exponent notation.
61pub(crate) fn js_number(value: f64) -> String {
62    if value.is_nan() {
63        return "NaN".to_string();
64    }
65
66    if value.is_infinite() {
67        return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
68    }
69
70    if value == 0.0 {
71        return "0".to_string();
72    }
73
74    let magnitude = value.abs();
75
76    if (1e-6..1e21).contains(&magnitude) {
77        return format!("{value}");
78    }
79
80    let exponent = format!("{value:e}");
81
82    match exponent.split_once('e') {
83        Some((mantissa, power)) if !power.starts_with('-') => format!("{mantissa}e+{power}"),
84        _ => exponent,
85    }
86}
87
88/// Rounds like JavaScript's `Math.round`: halves go toward positive infinity.
89pub(crate) fn js_round(value: f64) -> f64 {
90    (value + 0.5).floor()
91}
92
93/// Appends component custom properties to an optional user style, like spreading `style` before
94/// the component's own properties in lumen-react.
95pub(crate) fn merge_style(user: Option<&str>, own: &str) -> String {
96    let user = user
97        .map(|style| style.trim().trim_end_matches(';').trim_end())
98        .filter(|style| !style.is_empty());
99
100    match user {
101        Some(user) if own.is_empty() => user.to_string(),
102        Some(user) => format!("{user}; {own}"),
103        None => own.to_string(),
104    }
105}
106
107/// Whether a string is empty or only whitespace, like `value.trim() === ''` in JavaScript.
108pub(crate) fn is_blank(value: &str) -> bool {
109    value.chars().all(|c| c.is_whitespace() || c == '\u{feff}')
110}
111
112/// Combining marks of common scripts, an approximation of `\p{M}` without Unicode tables.
113const COMBINING_MARKS: &[(u32, u32)] = &[
114    (0x0300, 0x036F),
115    (0x0483, 0x0489),
116    (0x0591, 0x05BD),
117    (0x05BF, 0x05BF),
118    (0x05C1, 0x05C2),
119    (0x05C4, 0x05C5),
120    (0x05C7, 0x05C7),
121    (0x0610, 0x061A),
122    (0x064B, 0x065F),
123    (0x0670, 0x0670),
124    (0x06D6, 0x06DC),
125    (0x06DF, 0x06E4),
126    (0x06E7, 0x06E8),
127    (0x06EA, 0x06ED),
128    (0x0900, 0x0903),
129    (0x093A, 0x093C),
130    (0x093E, 0x094F),
131    (0x0951, 0x0957),
132    (0x0962, 0x0963),
133    (0x0981, 0x0983),
134    (0x09BC, 0x09BC),
135    (0x09BE, 0x09C4),
136    (0x09C7, 0x09C8),
137    (0x09CB, 0x09CD),
138    (0x09D7, 0x09D7),
139    (0x09E2, 0x09E3),
140    (0x0E31, 0x0E31),
141    (0x0E34, 0x0E3A),
142    (0x0E47, 0x0E4E),
143    (0x1AB0, 0x1AFF),
144    (0x1DC0, 0x1DFF),
145    (0x20D0, 0x20FF),
146    (0x3099, 0x309A),
147    (0xFE20, 0xFE2F),
148];
149
150fn is_combining_mark(code: u32) -> bool {
151    COMBINING_MARKS
152        .iter()
153        .any(|(start, end)| (*start..=*end).contains(&code))
154}
155
156fn is_regional_indicator(code: u32) -> bool {
157    (0x1F1E6..=0x1F1FF).contains(&code)
158}
159
160/// Code points that extend the previous grapheme: joiners, variation selectors, skin tones, tag
161/// characters, and combining marks.
162fn extends_cluster(code: u32) -> bool {
163    code == 0x200D
164        || (0xFE00..=0xFE0F).contains(&code)
165        || (0x1F3FB..=0x1F3FF).contains(&code)
166        || (0xE0020..=0xE007F).contains(&code)
167        || (0xE0100..=0xE01EF).contains(&code)
168        || is_combining_mark(code)
169}
170
171/// Splits text into user-perceived characters with one linear scan, the same fallback
172/// `lumen-core` uses where `Intl.Segmenter` is missing: emoji sequences, flags, and combining
173/// marks stay whole.
174pub(crate) fn graphemes(text: &str) -> Vec<&str> {
175    let mut clusters = Vec::new();
176    let mut start: Option<usize> = None;
177    let mut join_next = false;
178    let mut pending_regional = false;
179
180    for (index, character) in text.char_indices() {
181        let code = u32::from(character);
182        let regional = is_regional_indicator(code);
183
184        match start {
185            Some(_) if join_next || extends_cluster(code) || (regional && pending_regional) => {
186                pending_regional = false;
187            }
188            Some(begin) => {
189                clusters.push(&text[begin..index]);
190                start = Some(index);
191                pending_regional = regional;
192            }
193            None => {
194                start = Some(index);
195                pending_regional = regional;
196            }
197        }
198
199        join_next = code == 0x200D;
200    }
201
202    if let Some(begin) = start {
203        clusters.push(&text[begin..]);
204    }
205
206    clusters
207}
208
209/// What the current renderer reported about motion.
210#[derive(Clone, Copy, Debug, PartialEq)]
211pub(crate) enum MotionSupport {
212    /// The probe has not answered yet.
213    Pending,
214    /// The renderer runs no JavaScript: Dioxus Native or server rendering.
215    Unsupported,
216    /// A browser or webview answered.
217    Browser {
218        /// `prefers-reduced-motion: reduce` matches.
219        reduced: bool,
220        /// `IntersectionObserver` exists, so `onvisible` events arrive.
221        observer: bool,
222        /// A `Math.random()` value for decorative variation.
223        random: f64,
224    },
225}
226
227impl MotionSupport {
228    /// Whether scroll-triggered motion can run: a browser with an observer and no reduced motion.
229    pub(crate) fn observes(self) -> bool {
230        matches!(
231            self,
232            Self::Browser {
233                reduced: false,
234                observer: true,
235                ..
236            }
237        )
238    }
239
240    /// Whether the user asked for reduced motion.
241    pub(crate) fn reduced(self) -> bool {
242        matches!(self, Self::Browser { reduced: true, .. })
243    }
244}
245
246const MOTION_PROBE: &str = "return [matchMedia('(prefers-reduced-motion: reduce)').matches ? 1 : 0, typeof IntersectionObserver === 'function' ? 1 : 0, Math.random()];";
247
248/// Asks the renderer about reduced motion and `IntersectionObserver`. Renderers without
249/// JavaScript, such as Dioxus Native, answer [`MotionSupport::Unsupported`] immediately.
250pub(crate) async fn probe_motion() -> MotionSupport {
251    match document::eval(MOTION_PROBE).join::<Vec<f64>>().await {
252        Ok(values) => match values.as_slice() {
253            [reduced, observer, random] => MotionSupport::Browser {
254                reduced: *reduced > 0.5,
255                observer: *observer > 0.5,
256                random: *random,
257            },
258            _ => MotionSupport::Unsupported,
259        },
260        Err(_) => MotionSupport::Unsupported,
261    }
262}
263
264/// Probes the renderer once after the first render. Reading the signal re-renders the caller
265/// when the answer arrives.
266pub(crate) fn use_motion_support() -> Signal<MotionSupport> {
267    let mut support = use_signal(|| MotionSupport::Pending);
268
269    use_effect(move || {
270        spawn(async move {
271            support.set(probe_motion().await);
272        });
273    });
274
275    support
276}
277
278/// Time for the hidden state to paint before the first reveal transition starts.
279const REVEAL_SETTLE: Duration = Duration::from_millis(32);
280
281/// The scroll reveal state behind `ScrollReveal`, `RevealGroup`, and `SplitText`, ported from
282/// `createLumenRevealController` in `lumen-core`.
283///
284/// The first render matches lumen-react's server markup: no `data-ui-scroll-reveal-bound`, no
285/// `is-revealed`, so content is visible. After mount, browsers and webviews with
286/// `IntersectionObserver` and no reduced-motion preference bind the element (hiding it) and
287/// reveal it from `onvisible` events. Everywhere else, including Dioxus Native, it shows without
288/// animation.
289#[derive(Clone, Copy)]
290pub(crate) struct Reveal {
291    bound: Signal<bool>,
292    revealed: Signal<bool>,
293    in_view: CopyValue<bool>,
294    finished: CopyValue<bool>,
295    once: CopyValue<bool>,
296}
297
298impl Reveal {
299    /// `Some("true")` while bound, for `data-ui-scroll-reveal-bound`.
300    pub(crate) fn bound_attribute(self) -> Option<&'static str> {
301        (self.bound)().then_some("true")
302    }
303
304    /// Whether the `is-revealed` class applies.
305    pub(crate) fn revealed(self) -> bool {
306        (self.revealed)()
307    }
308
309    fn show_without_animation(mut self) {
310        self.finished.set(true);
311        self.bound.set(false);
312
313        if !*self.revealed.peek() {
314            self.revealed.set(true);
315        }
316    }
317
318    fn show(mut self, visible: bool) {
319        if *self.revealed.peek() != visible {
320            self.revealed.set(visible);
321        }
322
323        if visible && *self.once.peek() {
324            self.finished.set(true);
325        }
326    }
327
328    /// Handles an `onvisible` event from the element.
329    pub(crate) fn on_visible(mut self, event: &VisibleEvent) {
330        let visible = event.is_intersecting().unwrap_or(false);
331        self.in_view.set(visible);
332
333        if *self.bound.peek() && !*self.finished.peek() {
334            self.show(visible);
335        }
336    }
337
338    /// Focus inside a bound element shows it at once, so keyboard users never land on hidden
339    /// content.
340    pub(crate) fn on_focus_in(self) {
341        if *self.bound.peek() && !*self.finished.peek() {
342            self.show_without_animation();
343        }
344    }
345}
346
347/// Keeps the reveal state for one element. `enabled` is read when the probe answers; `on_bind`
348/// runs once the element is bound.
349pub(crate) fn use_reveal(once: bool, enabled: bool, on_bind: Option<fn()>) -> Reveal {
350    let bound = use_signal(|| false);
351    let revealed = use_signal(|| false);
352    let in_view = use_hook(|| CopyValue::new(false));
353    let finished = use_hook(|| CopyValue::new(false));
354    let mut once_store = use_hook(|| CopyValue::new(once));
355    let mut enabled_store = use_hook(|| CopyValue::new(enabled));
356
357    if *once_store.peek() != once {
358        once_store.set(once);
359    }
360
361    if *enabled_store.peek() != enabled {
362        enabled_store.set(enabled);
363    }
364
365    let reveal = Reveal {
366        bound,
367        revealed,
368        in_view,
369        finished,
370        once: once_store,
371    };
372
373    use_effect(move || {
374        spawn(async move {
375            let support = probe_motion().await;
376
377            if !*enabled_store.peek() {
378                return;
379            }
380
381            if !support.observes() {
382                reveal.show_without_animation();
383                return;
384            }
385
386            let mut bound = reveal.bound;
387            bound.set(true);
388
389            if let Some(callback) = on_bind {
390                callback();
391            }
392
393            sleep(REVEAL_SETTLE).await;
394
395            if *reveal.in_view.peek() && !*reveal.finished.peek() {
396                reveal.show(true);
397            }
398        });
399    });
400
401    reveal
402}
403
404#[cfg(test)]
405mod tests {
406    use super::{MotionDuration, graphemes, is_blank, js_number, js_round, merge_style};
407
408    #[test]
409    fn numbers_print_like_javascript() {
410        assert_eq!(js_number(6.0), "6");
411        assert_eq!(js_number(-6.0), "-6");
412        assert_eq!(js_number(-0.0), "0");
413        assert_eq!(js_number(0.15), "0.15");
414        assert_eq!(js_number(12.25), "12.25");
415        assert_eq!(js_number(1e21), "1e+21");
416        assert_eq!(js_number(1.5e-7), "1.5e-7");
417        assert_eq!(js_number(0.000_001), "0.000001");
418        assert_eq!(js_number(f64::NAN), "NaN");
419        assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
420    }
421
422    #[test]
423    fn rounding_matches_math_round() {
424        assert!((js_round(2.5) - 3.0).abs() < f64::EPSILON);
425        assert!((js_round(-2.5) - -2.0).abs() < f64::EPSILON);
426        assert!((js_round(-2.6) - -3.0).abs() < f64::EPSILON);
427    }
428
429    #[test]
430    fn styles_merge_after_the_user_style() {
431        assert_eq!(merge_style(None, "--a: 1"), "--a: 1");
432        assert_eq!(
433            merge_style(Some("color: red; "), "--a: 1"),
434            "color: red; --a: 1"
435        );
436        assert_eq!(merge_style(Some("  "), "--a: 1"), "--a: 1");
437        assert_eq!(merge_style(Some("color: red"), ""), "color: red");
438    }
439
440    #[test]
441    fn blank_text_includes_unicode_spaces() {
442        assert!(is_blank(""));
443        assert!(is_blank(" \u{a0}\u{3000}\u{feff}"));
444        assert!(!is_blank(" a "));
445    }
446
447    #[test]
448    fn graphemes_keep_clusters_whole() {
449        assert_eq!(graphemes("abc"), vec!["a", "b", "c"]);
450        assert_eq!(graphemes("e\u{301}x"), vec!["e\u{301}", "x"]);
451        assert_eq!(
452            graphemes("\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}!"),
453            vec!["\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}", "!"]
454        );
455        assert_eq!(
456            graphemes("\u{1F1FA}\u{1F1F8}\u{1F1E8}\u{1F1E6}"),
457            vec!["\u{1F1FA}\u{1F1F8}", "\u{1F1E8}\u{1F1E6}"]
458        );
459        assert_eq!(graphemes("\u{1F44D}\u{1F3FD}"), vec!["\u{1F44D}\u{1F3FD}"]);
460        assert_eq!(graphemes(""), Vec::<&str>::new());
461    }
462
463    #[test]
464    fn graphemes_stay_linear_on_long_input() {
465        let text = "e\u{301}".repeat(50_000);
466        assert_eq!(graphemes(&text).len(), 50_000);
467
468        let joiners = "\u{200D}".repeat(100_000);
469        assert_eq!(graphemes(&joiners).len(), 1);
470    }
471
472    #[test]
473    fn durations_follow_the_tokens() {
474        assert_eq!(MotionDuration::default(), MotionDuration::Slow);
475        assert_eq!(MotionDuration::Slow.class(), "ui-motion-duration-slow");
476        assert_eq!(MotionDuration::Scene.milliseconds(), 1000);
477    }
478}