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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! `SwipeCard` and the gesture math ported from `lumen-core/swipe-card`.
// cspell:words signum onpointercancel

use std::rc::Rc;

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_unique_id;

use super::util::is_rtl;

/// Logical swipe outcome. `Start` follows the reading direction: left in LTR, right in RTL.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SwipeCardDirection {
    /// Toward the inline start (left in LTR).
    Start,
    /// Toward the inline end (right in LTR).
    End,
}

impl SwipeCardDirection {
    /// The `data-direction` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Start => "start",
            Self::End => "end",
        }
    }
}

/// Semantic tone of a swipe action's button and cue.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SwipeCardTone {
    /// Brand color.
    Brand,
    /// Destructive.
    Danger,
    /// Quiet.
    Neutral,
    /// Positive.
    Success,
    /// Cautionary.
    Warning,
}

impl SwipeCardTone {
    /// The `data-tone` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Brand => "brand",
            Self::Danger => "danger",
            Self::Neutral => "neutral",
            Self::Success => "success",
            Self::Warning => "warning",
        }
    }
}

/// One of the two actions of a [`SwipeCard`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwipeCardAction {
    /// Visible button label and cue text, such as `Skip` or `Save`.
    pub label: String,
    /// Text announced after the action commits. Defaults to the label.
    pub announcement: Option<String>,
    /// Button and cue tone. Defaults to neutral for start and brand for end.
    pub tone: Option<SwipeCardTone>,
}

impl SwipeCardAction {
    /// An action labelled `label`.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            announcement: None,
            tone: None,
        }
    }

    /// The same action with a tone.
    #[must_use]
    pub fn tone(mut self, tone: SwipeCardTone) -> Self {
        self.tone = Some(tone);
        self
    }

    fn resolved_tone(&self, direction: SwipeCardDirection) -> SwipeCardTone {
        self.tone.unwrap_or(match direction {
            SwipeCardDirection::Start => SwipeCardTone::Neutral,
            SwipeCardDirection::End => SwipeCardTone::Brand,
        })
    }

    fn announcement_text(&self) -> String {
        self.announcement
            .as_deref()
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .or_else(|| Some(self.label.trim()).filter(|text| !text.is_empty()))
            .unwrap_or_default()
            .to_string()
    }
}

/// Share of the card width a drag must travel to commit.
pub const SWIPE_CARD_DISTANCE_RATIO: f64 = 0.35;
/// Smallest commit distance in pixels.
pub const SWIPE_CARD_MIN_DISTANCE: f64 = 48.0;
/// Release speed in pixels per millisecond that commits a shorter flick.
pub const SWIPE_CARD_VELOCITY_THRESHOLD: f64 = 0.5;
/// Travel a flick needs before its velocity counts, in pixels.
pub const SWIPE_CARD_FLICK_DISTANCE: f64 = 24.0;
/// Travel in pixels before a drag is locked to one axis.
pub const SWIPE_CARD_AXIS_SLOP: f64 = 8.0;

fn finite(value: f64) -> f64 {
    if value.is_finite() { value } else { 0.0 }
}

/// Distance in pixels a drag must travel on a card of `width` to commit.
pub fn swipe_card_commit_distance(width: f64) -> f64 {
    (finite(width).max(0.0) * SWIPE_CARD_DISTANCE_RATIO).max(SWIPE_CARD_MIN_DISTANCE)
}

/// Logical direction of a horizontal movement. Zero has no direction.
pub fn swipe_card_direction(delta_x: f64, rtl: bool) -> Option<SwipeCardDirection> {
    let delta = finite(delta_x);

    if delta == 0.0 {
        return None;
    }

    Some(if (delta < 0.0) == rtl {
        SwipeCardDirection::End
    } else {
        SwipeCardDirection::Start
    })
}

/// Physical sign (-1 left, 1 right) a card travels when it leaves toward `direction`.
pub fn swipe_card_physical_sign(direction: SwipeCardDirection, rtl: bool) -> f64 {
    if (direction == SwipeCardDirection::Start) == rtl {
        1.0
    } else {
        -1.0
    }
}

/// Maps `ArrowLeft` and `ArrowRight` to the action on that side of the card.
pub fn swipe_card_key_direction(key: &Key, rtl: bool) -> Option<SwipeCardDirection> {
    match (key, rtl) {
        (Key::ArrowLeft, false) | (Key::ArrowRight, true) => Some(SwipeCardDirection::Start),
        (Key::ArrowRight, false) | (Key::ArrowLeft, true) => Some(SwipeCardDirection::End),
        _ => None,
    }
}

/// Axis a drag is locked to once it travels past the slop. Ties resolve to vertical so a card
/// never hijacks page scrolling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SwipeCardAxis {
    /// A swipe.
    Horizontal,
    /// Page scrolling.
    Vertical,
}

/// The locked axis of a drag, or `None` while it is within the slop.
pub fn swipe_card_axis(delta_x: f64, delta_y: f64) -> Option<SwipeCardAxis> {
    let x = finite(delta_x).abs();
    let y = finite(delta_y).abs();

    if x.max(y) < SWIPE_CARD_AXIS_SLOP {
        return None;
    }

    Some(if x > y {
        SwipeCardAxis::Horizontal
    } else {
        SwipeCardAxis::Vertical
    })
}

/// Whether a released drag commits: past the distance threshold, or on a flick moving the same
/// way as the drag. Anything else springs back.
pub fn swipe_card_release(
    delta_x: f64,
    velocity_x: f64,
    width: f64,
    rtl: bool,
) -> Option<SwipeCardDirection> {
    let delta = finite(delta_x);
    let velocity = finite(velocity_x);
    let direction = swipe_card_direction(delta, rtl)?;

    if delta.abs() >= swipe_card_commit_distance(width) {
        return Some(direction);
    }

    let flick = delta.abs() >= SWIPE_CARD_FLICK_DISTANCE
        && velocity != 0.0
        && velocity.signum() == delta.signum()
        && velocity.abs() >= SWIPE_CARD_VELOCITY_THRESHOLD;

    flick.then_some(direction)
}

/// Signed drag progress from -1 to 1, relative to the commit distance.
pub fn swipe_card_progress(delta_x: f64, width: f64) -> f64 {
    (finite(delta_x) / swipe_card_commit_distance(width)).clamp(-1.0, 1.0)
}

/// Opacity of the start and end cues while dragging.
pub fn swipe_card_cue_opacity(delta_x: f64, width: f64, rtl: bool) -> (f64, f64) {
    let progress = swipe_card_progress(delta_x, width);
    let amount = progress.abs();

    match swipe_card_direction(progress, rtl) {
        Some(SwipeCardDirection::Start) => (amount, 0.0),
        Some(SwipeCardDirection::End) => (0.0, amount),
        None => (0.0, 0.0),
    }
}

/// Milliseconds on a monotonic clock.
#[cfg(not(target_family = "wasm"))]
fn now_ms() -> f64 {
    use std::sync::OnceLock;
    use std::time::Instant;

    static START: OnceLock<Instant> = OnceLock::new();

    START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0
}

/// Browsers built for wasm have no `Instant`, so flick velocity is not measured there (the
/// tracker ignores non-finite times) and only distance commits a swipe.
#[cfg(target_family = "wasm")]
fn now_ms() -> f64 {
    f64::NAN
}

/// Recent pointer samples, to estimate release velocity in pixels per millisecond.
#[derive(Clone, Debug, Default, PartialEq)]
struct VelocityTracker {
    samples: Vec<(f64, f64)>,
}

impl VelocityTracker {
    const WINDOW_MS: f64 = 100.0;

    fn add(&mut self, x: f64, time: f64) {
        if !x.is_finite() || !time.is_finite() {
            return;
        }

        self.samples.push((time, x));
        let cutoff = time - Self::WINDOW_MS;

        // Keep one sample older than the window so a slow, steady drag still has a baseline.
        if let Some(first_recent) = self.samples.iter().position(|(time, _)| *time >= cutoff)
            && first_recent > 1
        {
            self.samples.drain(..first_recent - 1);
        }
    }

    fn velocity(&self) -> f64 {
        match (self.samples.first(), self.samples.last()) {
            (Some((start, first)), Some((end, last))) if end > start => {
                (last - first) / (end - start)
            }
            _ => 0.0,
        }
    }
}

/// Interaction state of a [`SwipeCard`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum SwipeState {
    #[default]
    Idle,
    Dragging,
    Swiped,
}

impl SwipeState {
    fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Dragging => "dragging",
            Self::Swiped => "swiped",
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
struct Drag {
    pointer: Option<i32>,
    origin: (f64, f64),
    delta_x: f64,
    axis: Option<SwipeCardAxis>,
    tracker: VelocityTracker,
}

/// Props for [`SwipeCard`].
#[derive(Props, Clone, PartialEq)]
pub struct SwipeCardProps {
    /// Accessible name of the card group.
    #[props(into)]
    pub label: Option<String>,
    /// Action chosen by swiping toward the inline start. Defaults to `Skip`.
    #[props(default = SwipeCardAction::new("Skip"))]
    pub start_action: SwipeCardAction,
    /// Action chosen by swiping toward the inline end. Defaults to `Save`.
    #[props(default = SwipeCardAction::new("Save"))]
    pub end_action: SwipeCardAction,
    /// Screen-reader hint describing the gesture and keyboard alternatives.
    #[props(
        default = "Swipe the card, press the left or right arrow key, or use the buttons below.".to_string(),
        into
    )]
    pub hint: String,
    /// Called once per committed swipe, button press, or arrow key. The card stays dismissed;
    /// render the next item with a new `key` to show a fresh card.
    pub on_swipe: Option<EventHandler<SwipeCardDirection>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. `dir: "rtl"` swaps the physical sides.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Card content.
    pub children: Element,
}

/// A card the user swipes toward the start or end to choose one of two actions.
///
/// Every swipe action is also a visible button, and the focused card accepts `ArrowLeft` and
/// `ArrowRight`. Pointer drags lock to the horizontal axis after a few pixels, so vertical drags
/// still scroll the page.
#[component]
#[allow(clippy::too_many_lines)]
pub fn SwipeCard(props: SwipeCardProps) -> Element {
    let hint_id = format!("{}-hint", use_unique_id());
    let rtl = is_rtl(&props.attributes);
    let mut enhanced = use_signal(|| false);
    let mut state = use_signal(SwipeState::default);
    let mut swiped = use_signal(|| None::<SwipeCardDirection>);
    let mut offset = use_signal(|| None::<f64>);
    let mut status = use_signal(String::new);
    let mut drag = use_hook(|| CopyValue::new(Drag::default()));
    let mut width = use_hook(|| CopyValue::new(0.0_f64));
    let mut card = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
    let on_swipe = props.on_swipe;
    let mut announcements = use_hook(|| CopyValue::new((String::new(), String::new())));

    announcements.set((
        props.start_action.announcement_text(),
        props.end_action.announcement_text(),
    ));

    use_effect(move || enhanced.set(true));

    let mut commit = move |direction: SwipeCardDirection| {
        if *state.peek() == SwipeState::Swiped {
            return;
        }

        drag.set(Drag::default());
        state.set(SwipeState::Swiped);
        swiped.set(Some(direction));
        offset.set(Some(
            swipe_card_physical_sign(direction, rtl)
                * width.peek().max(SWIPE_CARD_MIN_DISTANCE)
                * 1.5,
        ));
        status.set(match direction {
            SwipeCardDirection::Start => announcements.peek().0.clone(),
            SwipeCardDirection::End => announcements.peek().1.clone(),
        });

        if let Some(handler) = on_swipe {
            handler.call(direction);
        }
    };
    let mut spring_back = move || {
        drag.set(Drag::default());

        if *state.peek() == SwipeState::Dragging {
            state.set(SwipeState::Idle);
        }

        offset.set(None);
    };

    let is_enhanced = enhanced();
    let current = state();
    let class = compose([Some("ui-swipe-card"), props.class.as_deref()]);
    let style = offset().map(|delta| {
        let card_width = *width.peek();
        let (start, end) = swipe_card_cue_opacity(delta, card_width, rtl);
        let rotate = swipe_card_progress(delta, card_width) * 8.0;

        format!(
            "--ui-swipe-card-offset: {delta}px; --ui-swipe-card-rotate: {rotate}deg; --ui-swipe-card-start-opacity: {start}; --ui-swipe-card-end-opacity: {end};"
        )
    });
    let is_swiped = current == SwipeState::Swiped;
    let actions = [
        (SwipeCardDirection::Start, props.start_action.clone()),
        (SwipeCardDirection::End, props.end_action.clone()),
    ];

    rsx! {
        div {
            aria_label: props.label,
            class,
            "data-enhanced": is_enhanced.then_some("true"),
            "data-slot": "swipe-card",
            "data-state": is_enhanced.then_some(current.as_str()),
            "data-swipe-direction": swiped().map(SwipeCardDirection::as_str),
            "data-ui-owner": "dioxus",
            "data-ui-swipe-card": "true",
            role: "group",
            style,
            ..props.attributes,
            div {
                aria_describedby: hint_id.clone(),
                class: "ui-swipe-card__card",
                "data-slot": "swipe-card-card",
                inert: is_swiped,
                tabindex: is_enhanced.then_some("0"),
                onmounted: move |event| card.set(Some(event.data())),
                onkeydown: move |event| {
                    let modifiers = event.modifiers();

                    if event.is_composing() || modifiers.alt() || modifiers.ctrl() || modifiers.meta() {
                        return;
                    }

                    if let Some(direction) = swipe_card_key_direction(&event.key(), rtl)
                        && *state.peek() != SwipeState::Swiped
                    {
                        event.prevent_default();
                        commit(direction);
                    }
                },
                onpointerdown: move |event| {
                    let primary = event.trigger_button().is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);

                    if *state.peek() != SwipeState::Idle || drag.peek().pointer.is_some() || !event.is_primary() || !primary {
                        return;
                    }

                    let point = event.client_coordinates();
                    let mut tracker = VelocityTracker::default();
                    tracker.add(point.x, now_ms());
                    drag.set(Drag {
                        pointer: Some(event.pointer_id()),
                        origin: (point.x, point.y),
                        delta_x: 0.0,
                        axis: None,
                        tracker,
                    });

                    if let Some(node) = card.peek().clone() {
                        spawn(async move {
                            if let Ok(rect) = node.get_client_rect().await {
                                width.set(rect.width());
                            }
                        });
                    }
                },
                onpointermove: move |event| {
                    if drag.peek().pointer != Some(event.pointer_id()) || *state.peek() == SwipeState::Swiped {
                        return;
                    }

                    let point = event.client_coordinates();
                    let (origin_x, origin_y) = drag.peek().origin;
                    let dx = point.x - origin_x;
                    let axis = drag.peek().axis.or_else(|| swipe_card_axis(dx, point.y - origin_y));

                    match axis {
                        None => {}
                        Some(SwipeCardAxis::Vertical) => spring_back(),
                        Some(SwipeCardAxis::Horizontal) => {
                            if *state.peek() != SwipeState::Dragging {
                                state.set(SwipeState::Dragging);
                            }

                            event.prevent_default();
                            let mut next = drag.peek().clone();
                            next.axis = axis;
                            next.delta_x = dx;
                            next.tracker.add(point.x, now_ms());
                            drag.set(next);
                            offset.set(Some(dx));
                        }
                    }
                },
                onpointerup: move |event| {
                    if drag.peek().pointer != Some(event.pointer_id()) {
                        return;
                    }

                    if *state.peek() != SwipeState::Dragging {
                        spring_back();
                        return;
                    }

                    let mut tracker = drag.peek().tracker.clone();
                    tracker.add(event.client_coordinates().x, now_ms());
                    let delta = drag.peek().delta_x;

                    match swipe_card_release(delta, tracker.velocity(), *width.peek(), rtl) {
                        Some(direction) => commit(direction),
                        None => spring_back(),
                    }
                },
                onpointercancel: move |event| {
                    if drag.peek().pointer == Some(event.pointer_id()) {
                        spring_back();
                    }
                },
                div { class: "ui-swipe-card__content", "data-slot": "swipe-card-content", {props.children} }
                for (direction, action) in actions.clone() {
                    span {
                        key: "{direction.as_str()}",
                        aria_hidden: "true",
                        class: "ui-swipe-card__cue",
                        "data-direction": direction.as_str(),
                        "data-slot": "swipe-card-cue",
                        "data-tone": action.resolved_tone(direction).as_str(),
                        "{action.label}"
                    }
                }
            }
            div { class: "ui-swipe-card__actions", "data-slot": "swipe-card-actions",
                for (direction, action) in actions {
                    button {
                        key: "{direction.as_str()}",
                        aria_disabled: is_swiped.then_some("true"),
                        class: "ui-button ui-button--outline ui-swipe-card__action",
                        "data-announcement": action.announcement.clone(),
                        "data-slot": "swipe-card-action",
                        "data-tone": action.resolved_tone(direction).as_str(),
                        "data-ui-swipe-card-action": direction.as_str(),
                        r#type: "button",
                        onclick: move |_| commit(direction),
                        "{action.label}"
                    }
                }
            }
            span { class: "ui-sr-only", "data-slot": "swipe-card-hint", id: hint_id, "{props.hint}" }
            span {
                aria_atomic: "true",
                aria_live: "polite",
                class: "ui-sr-only",
                "data-slot": "swipe-card-status",
                role: "status",
                "{status}"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn commit_distance_has_a_floor() {
        assert!((swipe_card_commit_distance(400.0) - 140.0).abs() < 1e-9);
        assert!((swipe_card_commit_distance(10.0) - 48.0).abs() < 1e-9);
        assert!((swipe_card_commit_distance(f64::NAN) - 48.0).abs() < 1e-9);
    }

    #[test]
    fn directions_follow_reading_order() {
        assert_eq!(
            swipe_card_direction(-5.0, false),
            Some(SwipeCardDirection::Start)
        );
        assert_eq!(
            swipe_card_direction(5.0, false),
            Some(SwipeCardDirection::End)
        );
        assert_eq!(
            swipe_card_direction(-5.0, true),
            Some(SwipeCardDirection::End)
        );
        assert_eq!(swipe_card_direction(0.0, false), None);
        assert!((swipe_card_physical_sign(SwipeCardDirection::Start, false) + 1.0).abs() < 1e-9);
        assert!((swipe_card_physical_sign(SwipeCardDirection::Start, true) - 1.0).abs() < 1e-9);
        assert_eq!(
            swipe_card_key_direction(&Key::ArrowLeft, false),
            Some(SwipeCardDirection::Start)
        );
        assert_eq!(
            swipe_card_key_direction(&Key::ArrowLeft, true),
            Some(SwipeCardDirection::End)
        );
        assert_eq!(swipe_card_key_direction(&Key::Enter, false), None);
    }

    #[test]
    fn drags_lock_to_an_axis() {
        assert_eq!(swipe_card_axis(3.0, 2.0), None);
        assert_eq!(swipe_card_axis(12.0, 3.0), Some(SwipeCardAxis::Horizontal));
        assert_eq!(swipe_card_axis(10.0, 10.0), Some(SwipeCardAxis::Vertical));
    }

    #[test]
    fn releases_commit_on_distance_or_flick() {
        assert_eq!(
            swipe_card_release(150.0, 0.0, 400.0, false),
            Some(SwipeCardDirection::End)
        );
        assert_eq!(swipe_card_release(100.0, 0.0, 400.0, false), None);
        assert_eq!(
            swipe_card_release(-30.0, -0.8, 400.0, false),
            Some(SwipeCardDirection::Start)
        );
        assert_eq!(swipe_card_release(-30.0, 0.8, 400.0, false), None);
        assert_eq!(swipe_card_release(20.0, 2.0, 400.0, false), None);
        assert_eq!(swipe_card_release(0.0, 2.0, 400.0, false), None);
    }

    #[test]
    fn cues_fade_in_toward_the_drag() {
        assert_eq!(swipe_card_cue_opacity(70.0, 400.0, false), (0.0, 0.5));
        assert_eq!(swipe_card_cue_opacity(-500.0, 400.0, false), (1.0, 0.0));
        assert!((swipe_card_progress(-500.0, 400.0) + 1.0).abs() < 1e-9);
    }

    #[test]
    fn velocity_uses_recent_samples() {
        let mut tracker = VelocityTracker::default();
        tracker.add(0.0, 0.0);
        tracker.add(10.0, 50.0);
        tracker.add(60.0, 150.0);
        tracker.add(100.0, 200.0);
        // The 0 ms sample falls out; the 50 ms one stays as the baseline.
        assert!((tracker.velocity() - 0.6).abs() < 1e-9);
        tracker.add(f64::NAN, 300.0);
        tracker.add(1.0, f64::NAN);
        assert_eq!(tracker.samples.len(), 3);
        assert!((VelocityTracker::default().velocity()).abs() < 1e-9);
    }
}