Skip to main content

lumen_dioxus/navigation/
swipe_card.rs

1//! `SwipeCard` and the gesture math ported from `lumen-core/swipe-card`.
2// cspell:words signum onpointercancel
3
4use std::rc::Rc;
5
6use dioxus::prelude::*;
7
8use crate::class::compose;
9use crate::hooks::use_unique_id;
10
11use super::util::is_rtl;
12
13/// Logical swipe outcome. `Start` follows the reading direction: left in LTR, right in RTL.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum SwipeCardDirection {
16    /// Toward the inline start (left in LTR).
17    Start,
18    /// Toward the inline end (right in LTR).
19    End,
20}
21
22impl SwipeCardDirection {
23    /// The `data-direction` value.
24    pub fn as_str(self) -> &'static str {
25        match self {
26            Self::Start => "start",
27            Self::End => "end",
28        }
29    }
30}
31
32/// Semantic tone of a swipe action's button and cue.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum SwipeCardTone {
36    /// Brand color.
37    Brand,
38    /// Destructive.
39    Danger,
40    /// Quiet.
41    Neutral,
42    /// Positive.
43    Success,
44    /// Cautionary.
45    Warning,
46}
47
48impl SwipeCardTone {
49    /// The `data-tone` value.
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::Brand => "brand",
53            Self::Danger => "danger",
54            Self::Neutral => "neutral",
55            Self::Success => "success",
56            Self::Warning => "warning",
57        }
58    }
59}
60
61/// One of the two actions of a [`SwipeCard`].
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct SwipeCardAction {
64    /// Visible button label and cue text, such as `Skip` or `Save`.
65    pub label: String,
66    /// Text announced after the action commits. Defaults to the label.
67    pub announcement: Option<String>,
68    /// Button and cue tone. Defaults to neutral for start and brand for end.
69    pub tone: Option<SwipeCardTone>,
70}
71
72impl SwipeCardAction {
73    /// An action labelled `label`.
74    pub fn new(label: impl Into<String>) -> Self {
75        Self {
76            label: label.into(),
77            announcement: None,
78            tone: None,
79        }
80    }
81
82    /// The same action with a tone.
83    #[must_use]
84    pub fn tone(mut self, tone: SwipeCardTone) -> Self {
85        self.tone = Some(tone);
86        self
87    }
88
89    fn resolved_tone(&self, direction: SwipeCardDirection) -> SwipeCardTone {
90        self.tone.unwrap_or(match direction {
91            SwipeCardDirection::Start => SwipeCardTone::Neutral,
92            SwipeCardDirection::End => SwipeCardTone::Brand,
93        })
94    }
95
96    fn announcement_text(&self) -> String {
97        self.announcement
98            .as_deref()
99            .map(str::trim)
100            .filter(|text| !text.is_empty())
101            .or_else(|| Some(self.label.trim()).filter(|text| !text.is_empty()))
102            .unwrap_or_default()
103            .to_string()
104    }
105}
106
107/// Share of the card width a drag must travel to commit.
108pub const SWIPE_CARD_DISTANCE_RATIO: f64 = 0.35;
109/// Smallest commit distance in pixels.
110pub const SWIPE_CARD_MIN_DISTANCE: f64 = 48.0;
111/// Release speed in pixels per millisecond that commits a shorter flick.
112pub const SWIPE_CARD_VELOCITY_THRESHOLD: f64 = 0.5;
113/// Travel a flick needs before its velocity counts, in pixels.
114pub const SWIPE_CARD_FLICK_DISTANCE: f64 = 24.0;
115/// Travel in pixels before a drag is locked to one axis.
116pub const SWIPE_CARD_AXIS_SLOP: f64 = 8.0;
117
118fn finite(value: f64) -> f64 {
119    if value.is_finite() { value } else { 0.0 }
120}
121
122/// Distance in pixels a drag must travel on a card of `width` to commit.
123pub fn swipe_card_commit_distance(width: f64) -> f64 {
124    (finite(width).max(0.0) * SWIPE_CARD_DISTANCE_RATIO).max(SWIPE_CARD_MIN_DISTANCE)
125}
126
127/// Logical direction of a horizontal movement. Zero has no direction.
128pub fn swipe_card_direction(delta_x: f64, rtl: bool) -> Option<SwipeCardDirection> {
129    let delta = finite(delta_x);
130
131    if delta == 0.0 {
132        return None;
133    }
134
135    Some(if (delta < 0.0) == rtl {
136        SwipeCardDirection::End
137    } else {
138        SwipeCardDirection::Start
139    })
140}
141
142/// Physical sign (-1 left, 1 right) a card travels when it leaves toward `direction`.
143pub fn swipe_card_physical_sign(direction: SwipeCardDirection, rtl: bool) -> f64 {
144    if (direction == SwipeCardDirection::Start) == rtl {
145        1.0
146    } else {
147        -1.0
148    }
149}
150
151/// Maps `ArrowLeft` and `ArrowRight` to the action on that side of the card.
152pub fn swipe_card_key_direction(key: &Key, rtl: bool) -> Option<SwipeCardDirection> {
153    match (key, rtl) {
154        (Key::ArrowLeft, false) | (Key::ArrowRight, true) => Some(SwipeCardDirection::Start),
155        (Key::ArrowRight, false) | (Key::ArrowLeft, true) => Some(SwipeCardDirection::End),
156        _ => None,
157    }
158}
159
160/// Axis a drag is locked to once it travels past the slop. Ties resolve to vertical so a card
161/// never hijacks page scrolling.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum SwipeCardAxis {
164    /// A swipe.
165    Horizontal,
166    /// Page scrolling.
167    Vertical,
168}
169
170/// The locked axis of a drag, or `None` while it is within the slop.
171pub fn swipe_card_axis(delta_x: f64, delta_y: f64) -> Option<SwipeCardAxis> {
172    let x = finite(delta_x).abs();
173    let y = finite(delta_y).abs();
174
175    if x.max(y) < SWIPE_CARD_AXIS_SLOP {
176        return None;
177    }
178
179    Some(if x > y {
180        SwipeCardAxis::Horizontal
181    } else {
182        SwipeCardAxis::Vertical
183    })
184}
185
186/// Whether a released drag commits: past the distance threshold, or on a flick moving the same
187/// way as the drag. Anything else springs back.
188pub fn swipe_card_release(
189    delta_x: f64,
190    velocity_x: f64,
191    width: f64,
192    rtl: bool,
193) -> Option<SwipeCardDirection> {
194    let delta = finite(delta_x);
195    let velocity = finite(velocity_x);
196    let direction = swipe_card_direction(delta, rtl)?;
197
198    if delta.abs() >= swipe_card_commit_distance(width) {
199        return Some(direction);
200    }
201
202    let flick = delta.abs() >= SWIPE_CARD_FLICK_DISTANCE
203        && velocity != 0.0
204        && velocity.signum() == delta.signum()
205        && velocity.abs() >= SWIPE_CARD_VELOCITY_THRESHOLD;
206
207    flick.then_some(direction)
208}
209
210/// Signed drag progress from -1 to 1, relative to the commit distance.
211pub fn swipe_card_progress(delta_x: f64, width: f64) -> f64 {
212    (finite(delta_x) / swipe_card_commit_distance(width)).clamp(-1.0, 1.0)
213}
214
215/// Opacity of the start and end cues while dragging.
216pub fn swipe_card_cue_opacity(delta_x: f64, width: f64, rtl: bool) -> (f64, f64) {
217    let progress = swipe_card_progress(delta_x, width);
218    let amount = progress.abs();
219
220    match swipe_card_direction(progress, rtl) {
221        Some(SwipeCardDirection::Start) => (amount, 0.0),
222        Some(SwipeCardDirection::End) => (0.0, amount),
223        None => (0.0, 0.0),
224    }
225}
226
227/// Milliseconds on a monotonic clock.
228#[cfg(not(target_family = "wasm"))]
229fn now_ms() -> f64 {
230    use std::sync::OnceLock;
231    use std::time::Instant;
232
233    static START: OnceLock<Instant> = OnceLock::new();
234
235    START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0
236}
237
238/// Browsers built for wasm have no `Instant`, so flick velocity is not measured there (the
239/// tracker ignores non-finite times) and only distance commits a swipe.
240#[cfg(target_family = "wasm")]
241fn now_ms() -> f64 {
242    f64::NAN
243}
244
245/// Recent pointer samples, to estimate release velocity in pixels per millisecond.
246#[derive(Clone, Debug, Default, PartialEq)]
247struct VelocityTracker {
248    samples: Vec<(f64, f64)>,
249}
250
251impl VelocityTracker {
252    const WINDOW_MS: f64 = 100.0;
253
254    fn add(&mut self, x: f64, time: f64) {
255        if !x.is_finite() || !time.is_finite() {
256            return;
257        }
258
259        self.samples.push((time, x));
260        let cutoff = time - Self::WINDOW_MS;
261
262        // Keep one sample older than the window so a slow, steady drag still has a baseline.
263        if let Some(first_recent) = self.samples.iter().position(|(time, _)| *time >= cutoff)
264            && first_recent > 1
265        {
266            self.samples.drain(..first_recent - 1);
267        }
268    }
269
270    fn velocity(&self) -> f64 {
271        match (self.samples.first(), self.samples.last()) {
272            (Some((start, first)), Some((end, last))) if end > start => {
273                (last - first) / (end - start)
274            }
275            _ => 0.0,
276        }
277    }
278}
279
280/// Interaction state of a [`SwipeCard`].
281#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
282enum SwipeState {
283    #[default]
284    Idle,
285    Dragging,
286    Swiped,
287}
288
289impl SwipeState {
290    fn as_str(self) -> &'static str {
291        match self {
292            Self::Idle => "idle",
293            Self::Dragging => "dragging",
294            Self::Swiped => "swiped",
295        }
296    }
297}
298
299#[derive(Clone, Debug, Default, PartialEq)]
300struct Drag {
301    pointer: Option<i32>,
302    origin: (f64, f64),
303    delta_x: f64,
304    axis: Option<SwipeCardAxis>,
305    tracker: VelocityTracker,
306}
307
308/// Props for [`SwipeCard`].
309#[derive(Props, Clone, PartialEq)]
310pub struct SwipeCardProps {
311    /// Accessible name of the card group.
312    #[props(into)]
313    pub label: Option<String>,
314    /// Action chosen by swiping toward the inline start. Defaults to `Skip`.
315    #[props(default = SwipeCardAction::new("Skip"))]
316    pub start_action: SwipeCardAction,
317    /// Action chosen by swiping toward the inline end. Defaults to `Save`.
318    #[props(default = SwipeCardAction::new("Save"))]
319    pub end_action: SwipeCardAction,
320    /// Screen-reader hint describing the gesture and keyboard alternatives.
321    #[props(
322        default = "Swipe the card, press the left or right arrow key, or use the buttons below.".to_string(),
323        into
324    )]
325    pub hint: String,
326    /// Called once per committed swipe, button press, or arrow key. The card stays dismissed;
327    /// render the next item with a new `key` to show a fresh card.
328    pub on_swipe: Option<EventHandler<SwipeCardDirection>>,
329    /// Extra classes appended after the Lumen class.
330    #[props(into)]
331    pub class: Option<String>,
332    /// Any other `<div>` or global attribute. `dir: "rtl"` swaps the physical sides.
333    #[props(extends = GlobalAttributes, extends = div)]
334    pub attributes: Vec<Attribute>,
335    /// Card content.
336    pub children: Element,
337}
338
339/// A card the user swipes toward the start or end to choose one of two actions.
340///
341/// Every swipe action is also a visible button, and the focused card accepts `ArrowLeft` and
342/// `ArrowRight`. Pointer drags lock to the horizontal axis after a few pixels, so vertical drags
343/// still scroll the page.
344#[component]
345#[allow(clippy::too_many_lines)]
346pub fn SwipeCard(props: SwipeCardProps) -> Element {
347    let hint_id = format!("{}-hint", use_unique_id());
348    let rtl = is_rtl(&props.attributes);
349    let mut enhanced = use_signal(|| false);
350    let mut state = use_signal(SwipeState::default);
351    let mut swiped = use_signal(|| None::<SwipeCardDirection>);
352    let mut offset = use_signal(|| None::<f64>);
353    let mut status = use_signal(String::new);
354    let mut drag = use_hook(|| CopyValue::new(Drag::default()));
355    let mut width = use_hook(|| CopyValue::new(0.0_f64));
356    let mut card = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
357    let on_swipe = props.on_swipe;
358    let mut announcements = use_hook(|| CopyValue::new((String::new(), String::new())));
359
360    announcements.set((
361        props.start_action.announcement_text(),
362        props.end_action.announcement_text(),
363    ));
364
365    use_effect(move || enhanced.set(true));
366
367    let mut commit = move |direction: SwipeCardDirection| {
368        if *state.peek() == SwipeState::Swiped {
369            return;
370        }
371
372        drag.set(Drag::default());
373        state.set(SwipeState::Swiped);
374        swiped.set(Some(direction));
375        offset.set(Some(
376            swipe_card_physical_sign(direction, rtl)
377                * width.peek().max(SWIPE_CARD_MIN_DISTANCE)
378                * 1.5,
379        ));
380        status.set(match direction {
381            SwipeCardDirection::Start => announcements.peek().0.clone(),
382            SwipeCardDirection::End => announcements.peek().1.clone(),
383        });
384
385        if let Some(handler) = on_swipe {
386            handler.call(direction);
387        }
388    };
389    let mut spring_back = move || {
390        drag.set(Drag::default());
391
392        if *state.peek() == SwipeState::Dragging {
393            state.set(SwipeState::Idle);
394        }
395
396        offset.set(None);
397    };
398
399    let is_enhanced = enhanced();
400    let current = state();
401    let class = compose([Some("ui-swipe-card"), props.class.as_deref()]);
402    let style = offset().map(|delta| {
403        let card_width = *width.peek();
404        let (start, end) = swipe_card_cue_opacity(delta, card_width, rtl);
405        let rotate = swipe_card_progress(delta, card_width) * 8.0;
406
407        format!(
408            "--ui-swipe-card-offset: {delta}px; --ui-swipe-card-rotate: {rotate}deg; --ui-swipe-card-start-opacity: {start}; --ui-swipe-card-end-opacity: {end};"
409        )
410    });
411    let is_swiped = current == SwipeState::Swiped;
412    let actions = [
413        (SwipeCardDirection::Start, props.start_action.clone()),
414        (SwipeCardDirection::End, props.end_action.clone()),
415    ];
416
417    rsx! {
418        div {
419            aria_label: props.label,
420            class,
421            "data-enhanced": is_enhanced.then_some("true"),
422            "data-slot": "swipe-card",
423            "data-state": is_enhanced.then_some(current.as_str()),
424            "data-swipe-direction": swiped().map(SwipeCardDirection::as_str),
425            "data-ui-owner": "dioxus",
426            "data-ui-swipe-card": "true",
427            role: "group",
428            style,
429            ..props.attributes,
430            div {
431                aria_describedby: hint_id.clone(),
432                class: "ui-swipe-card__card",
433                "data-slot": "swipe-card-card",
434                inert: is_swiped,
435                tabindex: is_enhanced.then_some("0"),
436                onmounted: move |event| card.set(Some(event.data())),
437                onkeydown: move |event| {
438                    let modifiers = event.modifiers();
439
440                    if event.is_composing() || modifiers.alt() || modifiers.ctrl() || modifiers.meta() {
441                        return;
442                    }
443
444                    if let Some(direction) = swipe_card_key_direction(&event.key(), rtl)
445                        && *state.peek() != SwipeState::Swiped
446                    {
447                        event.prevent_default();
448                        commit(direction);
449                    }
450                },
451                onpointerdown: move |event| {
452                    let primary = event.trigger_button().is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);
453
454                    if *state.peek() != SwipeState::Idle || drag.peek().pointer.is_some() || !event.is_primary() || !primary {
455                        return;
456                    }
457
458                    let point = event.client_coordinates();
459                    let mut tracker = VelocityTracker::default();
460                    tracker.add(point.x, now_ms());
461                    drag.set(Drag {
462                        pointer: Some(event.pointer_id()),
463                        origin: (point.x, point.y),
464                        delta_x: 0.0,
465                        axis: None,
466                        tracker,
467                    });
468
469                    if let Some(node) = card.peek().clone() {
470                        spawn(async move {
471                            if let Ok(rect) = node.get_client_rect().await {
472                                width.set(rect.width());
473                            }
474                        });
475                    }
476                },
477                onpointermove: move |event| {
478                    if drag.peek().pointer != Some(event.pointer_id()) || *state.peek() == SwipeState::Swiped {
479                        return;
480                    }
481
482                    let point = event.client_coordinates();
483                    let (origin_x, origin_y) = drag.peek().origin;
484                    let dx = point.x - origin_x;
485                    let axis = drag.peek().axis.or_else(|| swipe_card_axis(dx, point.y - origin_y));
486
487                    match axis {
488                        None => {}
489                        Some(SwipeCardAxis::Vertical) => spring_back(),
490                        Some(SwipeCardAxis::Horizontal) => {
491                            if *state.peek() != SwipeState::Dragging {
492                                state.set(SwipeState::Dragging);
493                            }
494
495                            event.prevent_default();
496                            let mut next = drag.peek().clone();
497                            next.axis = axis;
498                            next.delta_x = dx;
499                            next.tracker.add(point.x, now_ms());
500                            drag.set(next);
501                            offset.set(Some(dx));
502                        }
503                    }
504                },
505                onpointerup: move |event| {
506                    if drag.peek().pointer != Some(event.pointer_id()) {
507                        return;
508                    }
509
510                    if *state.peek() != SwipeState::Dragging {
511                        spring_back();
512                        return;
513                    }
514
515                    let mut tracker = drag.peek().tracker.clone();
516                    tracker.add(event.client_coordinates().x, now_ms());
517                    let delta = drag.peek().delta_x;
518
519                    match swipe_card_release(delta, tracker.velocity(), *width.peek(), rtl) {
520                        Some(direction) => commit(direction),
521                        None => spring_back(),
522                    }
523                },
524                onpointercancel: move |event| {
525                    if drag.peek().pointer == Some(event.pointer_id()) {
526                        spring_back();
527                    }
528                },
529                div { class: "ui-swipe-card__content", "data-slot": "swipe-card-content", {props.children} }
530                for (direction, action) in actions.clone() {
531                    span {
532                        key: "{direction.as_str()}",
533                        aria_hidden: "true",
534                        class: "ui-swipe-card__cue",
535                        "data-direction": direction.as_str(),
536                        "data-slot": "swipe-card-cue",
537                        "data-tone": action.resolved_tone(direction).as_str(),
538                        "{action.label}"
539                    }
540                }
541            }
542            div { class: "ui-swipe-card__actions", "data-slot": "swipe-card-actions",
543                for (direction, action) in actions {
544                    button {
545                        key: "{direction.as_str()}",
546                        aria_disabled: is_swiped.then_some("true"),
547                        class: "ui-button ui-button--outline ui-swipe-card__action",
548                        "data-announcement": action.announcement.clone(),
549                        "data-slot": "swipe-card-action",
550                        "data-tone": action.resolved_tone(direction).as_str(),
551                        "data-ui-swipe-card-action": direction.as_str(),
552                        r#type: "button",
553                        onclick: move |_| commit(direction),
554                        "{action.label}"
555                    }
556                }
557            }
558            span { class: "ui-sr-only", "data-slot": "swipe-card-hint", id: hint_id, "{props.hint}" }
559            span {
560                aria_atomic: "true",
561                aria_live: "polite",
562                class: "ui-sr-only",
563                "data-slot": "swipe-card-status",
564                role: "status",
565                "{status}"
566            }
567        }
568    }
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574
575    #[test]
576    fn commit_distance_has_a_floor() {
577        assert!((swipe_card_commit_distance(400.0) - 140.0).abs() < 1e-9);
578        assert!((swipe_card_commit_distance(10.0) - 48.0).abs() < 1e-9);
579        assert!((swipe_card_commit_distance(f64::NAN) - 48.0).abs() < 1e-9);
580    }
581
582    #[test]
583    fn directions_follow_reading_order() {
584        assert_eq!(
585            swipe_card_direction(-5.0, false),
586            Some(SwipeCardDirection::Start)
587        );
588        assert_eq!(
589            swipe_card_direction(5.0, false),
590            Some(SwipeCardDirection::End)
591        );
592        assert_eq!(
593            swipe_card_direction(-5.0, true),
594            Some(SwipeCardDirection::End)
595        );
596        assert_eq!(swipe_card_direction(0.0, false), None);
597        assert!((swipe_card_physical_sign(SwipeCardDirection::Start, false) + 1.0).abs() < 1e-9);
598        assert!((swipe_card_physical_sign(SwipeCardDirection::Start, true) - 1.0).abs() < 1e-9);
599        assert_eq!(
600            swipe_card_key_direction(&Key::ArrowLeft, false),
601            Some(SwipeCardDirection::Start)
602        );
603        assert_eq!(
604            swipe_card_key_direction(&Key::ArrowLeft, true),
605            Some(SwipeCardDirection::End)
606        );
607        assert_eq!(swipe_card_key_direction(&Key::Enter, false), None);
608    }
609
610    #[test]
611    fn drags_lock_to_an_axis() {
612        assert_eq!(swipe_card_axis(3.0, 2.0), None);
613        assert_eq!(swipe_card_axis(12.0, 3.0), Some(SwipeCardAxis::Horizontal));
614        assert_eq!(swipe_card_axis(10.0, 10.0), Some(SwipeCardAxis::Vertical));
615    }
616
617    #[test]
618    fn releases_commit_on_distance_or_flick() {
619        assert_eq!(
620            swipe_card_release(150.0, 0.0, 400.0, false),
621            Some(SwipeCardDirection::End)
622        );
623        assert_eq!(swipe_card_release(100.0, 0.0, 400.0, false), None);
624        assert_eq!(
625            swipe_card_release(-30.0, -0.8, 400.0, false),
626            Some(SwipeCardDirection::Start)
627        );
628        assert_eq!(swipe_card_release(-30.0, 0.8, 400.0, false), None);
629        assert_eq!(swipe_card_release(20.0, 2.0, 400.0, false), None);
630        assert_eq!(swipe_card_release(0.0, 2.0, 400.0, false), None);
631    }
632
633    #[test]
634    fn cues_fade_in_toward_the_drag() {
635        assert_eq!(swipe_card_cue_opacity(70.0, 400.0, false), (0.0, 0.5));
636        assert_eq!(swipe_card_cue_opacity(-500.0, 400.0, false), (1.0, 0.0));
637        assert!((swipe_card_progress(-500.0, 400.0) + 1.0).abs() < 1e-9);
638    }
639
640    #[test]
641    fn velocity_uses_recent_samples() {
642        let mut tracker = VelocityTracker::default();
643        tracker.add(0.0, 0.0);
644        tracker.add(10.0, 50.0);
645        tracker.add(60.0, 150.0);
646        tracker.add(100.0, 200.0);
647        // The 0 ms sample falls out; the 50 ms one stays as the baseline.
648        assert!((tracker.velocity() - 0.6).abs() < 1e-9);
649        tracker.add(f64::NAN, 300.0);
650        tracker.add(1.0, f64::NAN);
651        assert_eq!(tracker.samples.len(), 3);
652        assert!((VelocityTracker::default().velocity()).abs() < 1e-9);
653    }
654}