lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Helpers shared by the motion components: JavaScript-compatible number text, style merging,
//! grapheme splitting, the motion probe, and the scroll reveal state.
// cspell:words feff onvisible

use std::time::Duration;

use dioxus::prelude::*;

use crate::time::sleep;

/// Named motion durations from Lumen's tokens, used by [`ScrollReveal`](super::ScrollReveal),
/// [`RevealGroup`](super::RevealGroup), [`SplitText`](super::SplitText), and
/// [`AnimatedNumber`](super::AnimatedNumber).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MotionDuration {
    /// `--ui-duration-fast` (120 ms by default).
    Fast,
    /// `--ui-duration-standard` (160 ms by default).
    Standard,
    /// `--ui-duration-slow` (300 ms by default).
    #[default]
    Slow,
    /// `--ui-duration-entrance` (700 ms by default).
    Entrance,
    /// `--ui-duration-scene` (1000 ms by default).
    Scene,
}

impl MotionDuration {
    /// The `ui-motion-duration-*` class suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Fast => "fast",
            Self::Standard => "standard",
            Self::Slow => "slow",
            Self::Entrance => "entrance",
            Self::Scene => "scene",
        }
    }

    /// The default token value in milliseconds, from `lumenDurations` in `lumen-core`.
    pub fn milliseconds(self) -> u64 {
        match self {
            Self::Fast => 120,
            Self::Standard => 160,
            Self::Slow => 300,
            Self::Entrance => 700,
            Self::Scene => 1000,
        }
    }

    pub(crate) fn class(self) -> String {
        format!("ui-motion-duration-{}", self.as_str())
    }
}

/// Formats a number the way JavaScript's `String(number)` does, so inline styles and data
/// attributes match lumen-react: integers have no `.0`, `-0` prints as `0`, and very large or
/// small magnitudes use exponent notation.
pub(crate) fn js_number(value: f64) -> String {
    if value.is_nan() {
        return "NaN".to_string();
    }

    if value.is_infinite() {
        return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
    }

    if value == 0.0 {
        return "0".to_string();
    }

    let magnitude = value.abs();

    if (1e-6..1e21).contains(&magnitude) {
        return format!("{value}");
    }

    let exponent = format!("{value:e}");

    match exponent.split_once('e') {
        Some((mantissa, power)) if !power.starts_with('-') => format!("{mantissa}e+{power}"),
        _ => exponent,
    }
}

/// Rounds like JavaScript's `Math.round`: halves go toward positive infinity.
pub(crate) fn js_round(value: f64) -> f64 {
    (value + 0.5).floor()
}

/// Appends component custom properties to an optional user style, like spreading `style` before
/// the component's own properties in lumen-react.
pub(crate) fn merge_style(user: Option<&str>, own: &str) -> String {
    let user = user
        .map(|style| style.trim().trim_end_matches(';').trim_end())
        .filter(|style| !style.is_empty());

    match user {
        Some(user) if own.is_empty() => user.to_string(),
        Some(user) => format!("{user}; {own}"),
        None => own.to_string(),
    }
}

/// Whether a string is empty or only whitespace, like `value.trim() === ''` in JavaScript.
pub(crate) fn is_blank(value: &str) -> bool {
    value.chars().all(|c| c.is_whitespace() || c == '\u{feff}')
}

/// Combining marks of common scripts, an approximation of `\p{M}` without Unicode tables.
const COMBINING_MARKS: &[(u32, u32)] = &[
    (0x0300, 0x036F),
    (0x0483, 0x0489),
    (0x0591, 0x05BD),
    (0x05BF, 0x05BF),
    (0x05C1, 0x05C2),
    (0x05C4, 0x05C5),
    (0x05C7, 0x05C7),
    (0x0610, 0x061A),
    (0x064B, 0x065F),
    (0x0670, 0x0670),
    (0x06D6, 0x06DC),
    (0x06DF, 0x06E4),
    (0x06E7, 0x06E8),
    (0x06EA, 0x06ED),
    (0x0900, 0x0903),
    (0x093A, 0x093C),
    (0x093E, 0x094F),
    (0x0951, 0x0957),
    (0x0962, 0x0963),
    (0x0981, 0x0983),
    (0x09BC, 0x09BC),
    (0x09BE, 0x09C4),
    (0x09C7, 0x09C8),
    (0x09CB, 0x09CD),
    (0x09D7, 0x09D7),
    (0x09E2, 0x09E3),
    (0x0E31, 0x0E31),
    (0x0E34, 0x0E3A),
    (0x0E47, 0x0E4E),
    (0x1AB0, 0x1AFF),
    (0x1DC0, 0x1DFF),
    (0x20D0, 0x20FF),
    (0x3099, 0x309A),
    (0xFE20, 0xFE2F),
];

fn is_combining_mark(code: u32) -> bool {
    COMBINING_MARKS
        .iter()
        .any(|(start, end)| (*start..=*end).contains(&code))
}

fn is_regional_indicator(code: u32) -> bool {
    (0x1F1E6..=0x1F1FF).contains(&code)
}

/// Code points that extend the previous grapheme: joiners, variation selectors, skin tones, tag
/// characters, and combining marks.
fn extends_cluster(code: u32) -> bool {
    code == 0x200D
        || (0xFE00..=0xFE0F).contains(&code)
        || (0x1F3FB..=0x1F3FF).contains(&code)
        || (0xE0020..=0xE007F).contains(&code)
        || (0xE0100..=0xE01EF).contains(&code)
        || is_combining_mark(code)
}

/// Splits text into user-perceived characters with one linear scan, the same fallback
/// `lumen-core` uses where `Intl.Segmenter` is missing: emoji sequences, flags, and combining
/// marks stay whole.
pub(crate) fn graphemes(text: &str) -> Vec<&str> {
    let mut clusters = Vec::new();
    let mut start: Option<usize> = None;
    let mut join_next = false;
    let mut pending_regional = false;

    for (index, character) in text.char_indices() {
        let code = u32::from(character);
        let regional = is_regional_indicator(code);

        match start {
            Some(_) if join_next || extends_cluster(code) || (regional && pending_regional) => {
                pending_regional = false;
            }
            Some(begin) => {
                clusters.push(&text[begin..index]);
                start = Some(index);
                pending_regional = regional;
            }
            None => {
                start = Some(index);
                pending_regional = regional;
            }
        }

        join_next = code == 0x200D;
    }

    if let Some(begin) = start {
        clusters.push(&text[begin..]);
    }

    clusters
}

/// What the current renderer reported about motion.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum MotionSupport {
    /// The probe has not answered yet.
    Pending,
    /// The renderer runs no JavaScript: Dioxus Native or server rendering.
    Unsupported,
    /// A browser or webview answered.
    Browser {
        /// `prefers-reduced-motion: reduce` matches.
        reduced: bool,
        /// `IntersectionObserver` exists, so `onvisible` events arrive.
        observer: bool,
        /// A `Math.random()` value for decorative variation.
        random: f64,
    },
}

impl MotionSupport {
    /// Whether scroll-triggered motion can run: a browser with an observer and no reduced motion.
    pub(crate) fn observes(self) -> bool {
        matches!(
            self,
            Self::Browser {
                reduced: false,
                observer: true,
                ..
            }
        )
    }

    /// Whether the user asked for reduced motion.
    pub(crate) fn reduced(self) -> bool {
        matches!(self, Self::Browser { reduced: true, .. })
    }
}

const MOTION_PROBE: &str = "return [matchMedia('(prefers-reduced-motion: reduce)').matches ? 1 : 0, typeof IntersectionObserver === 'function' ? 1 : 0, Math.random()];";

/// Asks the renderer about reduced motion and `IntersectionObserver`. Renderers without
/// JavaScript, such as Dioxus Native, answer [`MotionSupport::Unsupported`] immediately.
pub(crate) async fn probe_motion() -> MotionSupport {
    match document::eval(MOTION_PROBE).join::<Vec<f64>>().await {
        Ok(values) => match values.as_slice() {
            [reduced, observer, random] => MotionSupport::Browser {
                reduced: *reduced > 0.5,
                observer: *observer > 0.5,
                random: *random,
            },
            _ => MotionSupport::Unsupported,
        },
        Err(_) => MotionSupport::Unsupported,
    }
}

/// Probes the renderer once after the first render. Reading the signal re-renders the caller
/// when the answer arrives.
pub(crate) fn use_motion_support() -> Signal<MotionSupport> {
    let mut support = use_signal(|| MotionSupport::Pending);

    use_effect(move || {
        spawn(async move {
            support.set(probe_motion().await);
        });
    });

    support
}

/// Time for the hidden state to paint before the first reveal transition starts.
const REVEAL_SETTLE: Duration = Duration::from_millis(32);

/// The scroll reveal state behind `ScrollReveal`, `RevealGroup`, and `SplitText`, ported from
/// `createLumenRevealController` in `lumen-core`.
///
/// The first render matches lumen-react's server markup: no `data-ui-scroll-reveal-bound`, no
/// `is-revealed`, so content is visible. After mount, browsers and webviews with
/// `IntersectionObserver` and no reduced-motion preference bind the element (hiding it) and
/// reveal it from `onvisible` events. Everywhere else, including Dioxus Native, it shows without
/// animation.
#[derive(Clone, Copy)]
pub(crate) struct Reveal {
    bound: Signal<bool>,
    revealed: Signal<bool>,
    in_view: CopyValue<bool>,
    finished: CopyValue<bool>,
    once: CopyValue<bool>,
}

impl Reveal {
    /// `Some("true")` while bound, for `data-ui-scroll-reveal-bound`.
    pub(crate) fn bound_attribute(self) -> Option<&'static str> {
        (self.bound)().then_some("true")
    }

    /// Whether the `is-revealed` class applies.
    pub(crate) fn revealed(self) -> bool {
        (self.revealed)()
    }

    fn show_without_animation(mut self) {
        self.finished.set(true);
        self.bound.set(false);

        if !*self.revealed.peek() {
            self.revealed.set(true);
        }
    }

    fn show(mut self, visible: bool) {
        if *self.revealed.peek() != visible {
            self.revealed.set(visible);
        }

        if visible && *self.once.peek() {
            self.finished.set(true);
        }
    }

    /// Handles an `onvisible` event from the element.
    pub(crate) fn on_visible(mut self, event: &VisibleEvent) {
        let visible = event.is_intersecting().unwrap_or(false);
        self.in_view.set(visible);

        if *self.bound.peek() && !*self.finished.peek() {
            self.show(visible);
        }
    }

    /// Focus inside a bound element shows it at once, so keyboard users never land on hidden
    /// content.
    pub(crate) fn on_focus_in(self) {
        if *self.bound.peek() && !*self.finished.peek() {
            self.show_without_animation();
        }
    }
}

/// Keeps the reveal state for one element. `enabled` is read when the probe answers; `on_bind`
/// runs once the element is bound.
pub(crate) fn use_reveal(once: bool, enabled: bool, on_bind: Option<fn()>) -> Reveal {
    let bound = use_signal(|| false);
    let revealed = use_signal(|| false);
    let in_view = use_hook(|| CopyValue::new(false));
    let finished = use_hook(|| CopyValue::new(false));
    let mut once_store = use_hook(|| CopyValue::new(once));
    let mut enabled_store = use_hook(|| CopyValue::new(enabled));

    if *once_store.peek() != once {
        once_store.set(once);
    }

    if *enabled_store.peek() != enabled {
        enabled_store.set(enabled);
    }

    let reveal = Reveal {
        bound,
        revealed,
        in_view,
        finished,
        once: once_store,
    };

    use_effect(move || {
        spawn(async move {
            let support = probe_motion().await;

            if !*enabled_store.peek() {
                return;
            }

            if !support.observes() {
                reveal.show_without_animation();
                return;
            }

            let mut bound = reveal.bound;
            bound.set(true);

            if let Some(callback) = on_bind {
                callback();
            }

            sleep(REVEAL_SETTLE).await;

            if *reveal.in_view.peek() && !*reveal.finished.peek() {
                reveal.show(true);
            }
        });
    });

    reveal
}

#[cfg(test)]
mod tests {
    use super::{MotionDuration, graphemes, is_blank, js_number, js_round, merge_style};

    #[test]
    fn numbers_print_like_javascript() {
        assert_eq!(js_number(6.0), "6");
        assert_eq!(js_number(-6.0), "-6");
        assert_eq!(js_number(-0.0), "0");
        assert_eq!(js_number(0.15), "0.15");
        assert_eq!(js_number(12.25), "12.25");
        assert_eq!(js_number(1e21), "1e+21");
        assert_eq!(js_number(1.5e-7), "1.5e-7");
        assert_eq!(js_number(0.000_001), "0.000001");
        assert_eq!(js_number(f64::NAN), "NaN");
        assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
    }

    #[test]
    fn rounding_matches_math_round() {
        assert!((js_round(2.5) - 3.0).abs() < f64::EPSILON);
        assert!((js_round(-2.5) - -2.0).abs() < f64::EPSILON);
        assert!((js_round(-2.6) - -3.0).abs() < f64::EPSILON);
    }

    #[test]
    fn styles_merge_after_the_user_style() {
        assert_eq!(merge_style(None, "--a: 1"), "--a: 1");
        assert_eq!(
            merge_style(Some("color: red; "), "--a: 1"),
            "color: red; --a: 1"
        );
        assert_eq!(merge_style(Some("  "), "--a: 1"), "--a: 1");
        assert_eq!(merge_style(Some("color: red"), ""), "color: red");
    }

    #[test]
    fn blank_text_includes_unicode_spaces() {
        assert!(is_blank(""));
        assert!(is_blank(" \u{a0}\u{3000}\u{feff}"));
        assert!(!is_blank(" a "));
    }

    #[test]
    fn graphemes_keep_clusters_whole() {
        assert_eq!(graphemes("abc"), vec!["a", "b", "c"]);
        assert_eq!(graphemes("e\u{301}x"), vec!["e\u{301}", "x"]);
        assert_eq!(
            graphemes("\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}!"),
            vec!["\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}", "!"]
        );
        assert_eq!(
            graphemes("\u{1F1FA}\u{1F1F8}\u{1F1E8}\u{1F1E6}"),
            vec!["\u{1F1FA}\u{1F1F8}", "\u{1F1E8}\u{1F1E6}"]
        );
        assert_eq!(graphemes("\u{1F44D}\u{1F3FD}"), vec!["\u{1F44D}\u{1F3FD}"]);
        assert_eq!(graphemes(""), Vec::<&str>::new());
    }

    #[test]
    fn graphemes_stay_linear_on_long_input() {
        let text = "e\u{301}".repeat(50_000);
        assert_eq!(graphemes(&text).len(), 50_000);

        let joiners = "\u{200D}".repeat(100_000);
        assert_eq!(graphemes(&joiners).len(), 1);
    }

    #[test]
    fn durations_follow_the_tokens() {
        assert_eq!(MotionDuration::default(), MotionDuration::Slow);
        assert_eq!(MotionDuration::Slow.class(), "ui-motion-duration-slow");
        assert_eq!(MotionDuration::Scene.milliseconds(), 1000);
    }
}