lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `ImageComparison`: a before and after image comparison with a reveal slider.
// cspell:words figcaption onmousedown onmouseleave onmousemove onmouseup onpointercancel

use std::rc::Rc;

use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;

use super::image::ImageFit;
use super::number_format::{FormattedNumberFormat, FormattedNumberValue, NumberFormatOptions};
use super::util::js_number;
use crate::class::compose;
use crate::hooks::use_controllable;

/// How an [`ImageComparison`] shows its images. Switching modes keeps the reveal position.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImageComparisonMode {
    /// The after image covers the before image up to the slider position.
    #[default]
    Reveal,
    /// Both images next to each other.
    SideBySide,
    /// Only the before image.
    Before,
    /// Only the after image.
    After,
}

impl ImageComparisonMode {
    /// The `data-mode` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Reveal => "reveal",
            Self::SideBySide => "side-by-side",
            Self::Before => "before",
            Self::After => "after",
        }
    }
}

/// Clamps a reveal position to 0 through 100 and rounds it to the slider step; non-finite values
/// become 50, like `normalizeLumenImageComparisonValue`.
pub fn normalize_image_comparison_value(value: f64) -> f64 {
    if value.is_finite() {
        // `Math.round` rounds halves toward positive infinity.
        (value.clamp(0.0, 100.0) + 0.5).floor()
    } else {
        50.0
    }
}

fn normalize_ratio(ratio: f64) -> f64 {
    if ratio.is_finite() && ratio > 0.0 {
        ratio
    } else {
        16.0 / 9.0
    }
}

/// The slider's `aria-valuetext`, such as "50% After".
fn value_text(value: f64, after_label: &str, locale: Option<&str>) -> String {
    let options = NumberFormatOptions {
        format: FormattedNumberFormat::Percent,
        locale: locale.map(str::to_string),
        ..NumberFormatOptions::default()
    };
    let percent = super::number_format::format_lumen_number(
        &FormattedNumberValue::Number(normalize_image_comparison_value(value) / 100.0),
        &options,
        "",
    );

    format!("{} {after_label}", percent.text)
}

/// The new value for a slider key, or `None` for other keys.
fn key_value(key: &Key, value: f64) -> Option<f64> {
    let next = match key {
        Key::ArrowLeft | Key::ArrowDown => value - 1.0,
        Key::ArrowRight | Key::ArrowUp => value + 1.0,
        Key::PageDown => value - 10.0,
        Key::PageUp => value + 10.0,
        Key::Home => 0.0,
        Key::End => 100.0,
        _ => return None,
    };

    Some(normalize_image_comparison_value(next))
}

/// A divider drag in progress.
#[derive(Clone, Copy, Debug, PartialEq)]
struct RevealDrag {
    start_x: f64,
    start_value: f64,
    touch: bool,
}

/// The position for a pointer at `x`: under the pointer when the frame was measured as
/// `(left, width)`, otherwise moved by the drag distance over `extent` pixels.
fn drag_value(drag: RevealDrag, x: f64, frame: Option<(f64, f64)>, extent: f64) -> f64 {
    match frame {
        Some((left, width)) if width > 0.0 => {
            normalize_image_comparison_value((x - left) / width * 100.0)
        }
        _ => {
            let extent = if extent.is_finite() && extent >= 1.0 {
                extent
            } else {
                640.0
            };

            normalize_image_comparison_value(drag.start_value + (x - drag.start_x) / extent * 100.0)
        }
    }
}

/// Props for [`ImageComparison`].
#[derive(Props, Clone, PartialEq)]
pub struct ImageComparisonProps {
    /// The before image.
    pub before: Element,
    /// The after image.
    pub after: Element,
    /// Accessible name of the slider, shown next to it.
    #[props(into)]
    pub label: String,
    /// Label of the before image.
    #[props(default = "Before".to_string(), into)]
    pub before_label: String,
    /// Label of the after image, also read in the slider value.
    #[props(default = "After".to_string(), into)]
    pub after_label: String,
    /// Controlled reveal position, 0 through 100.
    pub value: Option<f64>,
    /// Initial reveal position when uncontrolled. Defaults to 50.
    #[props(default = 50.0)]
    pub default_value: f64,
    /// Called with the new position.
    pub on_value_change: Option<EventHandler<f64>>,
    /// Display mode.
    #[props(default)]
    pub mode: ImageComparisonMode,
    /// How the images fill the frame.
    #[props(default)]
    pub fit: ImageFit,
    /// Width to height ratio of the frame. Defaults to 16 / 9.
    #[props(default = 16.0 / 9.0)]
    pub ratio: f64,
    /// Disables the slider.
    #[props(default)]
    pub disabled: bool,
    /// Frame width in pixels used to turn drag distance into a position when the renderer cannot
    /// measure the frame (Dioxus Native). The web and desktop measure it. Defaults to 640.
    #[props(default = 640.0)]
    pub drag_extent: f64,
    /// Form field name of the slider.
    #[props(into)]
    pub name: Option<String>,
    /// BCP 47 locale of the slider value text; defaults to English.
    #[props(into)]
    pub locale: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
    /// Caption content after the slider.
    pub children: Element,
}

/// Compares a before and after image. In reveal mode, the slider, a drag on the frame, or the
/// arrow, Page Up, Page Down, Home, and End keys move the divider.
#[component]
pub fn ImageComparison(props: ImageComparisonProps) -> Element {
    let position = use_controllable(
        props.value.map(normalize_image_comparison_value),
        || normalize_image_comparison_value(props.default_value),
        props.on_value_change,
    );
    let mut frame = use_signal(|| None::<Rc<MountedData>>);
    let mut measured = use_signal(|| None::<(f64, f64)>);
    let mut drag = use_signal(|| None::<RevealDrag>);
    let value = position.get();
    let interactive = !props.disabled && props.mode == ImageComparisonMode::Reveal;
    let mode = props.mode;
    let extent = props.drag_extent;
    let frame_style = format!(
        "--ui-image-comparison-position: {}%; --ui-image-comparison-ratio: {}",
        js_number(value),
        js_number(normalize_ratio(props.ratio))
    );
    let class = compose([Some("ui-image-comparison"), props.class.as_deref()]);
    let value_text = value_text(value, &props.after_label, props.locale.as_deref());
    let mut start = move |x: f64, touch: bool| {
        if !interactive {
            return;
        }

        let started = RevealDrag {
            start_x: x,
            start_value: position.peek(),
            touch,
        };

        drag.set(Some(started));

        if measured.peek().is_some() {
            position.set(drag_value(started, x, *measured.peek(), extent));
        }

        // Measure the frame where the renderer supports it (web and desktop), then place the
        // divider under the pointer.
        if let Some(mounted) = frame.peek().clone() {
            spawn(async move {
                if let Ok(rect) = mounted.get_client_rect().await {
                    measured.set(Some((rect.origin.x, rect.size.width)));

                    if drag.peek().is_some() {
                        position.set(drag_value(started, x, *measured.peek(), extent));
                    }
                }
            });
        }
    };
    let follow = move |x: f64, touch: bool| {
        if let Some(active) = *drag.peek()
            && active.touch == touch
            && interactive
        {
            position.set(drag_value(active, x, *measured.peek(), extent));
        }
    };
    let mut stop = move |touch: bool| {
        if drag.peek().is_some_and(|active| active.touch == touch) {
            drag.set(None);
        }
    };

    rsx! {
        figure {
            class,
            "data-fit": props.fit.as_str(),
            "data-mode": mode.as_str(),
            ..props.attributes,
            div {
                class: "ui-image-comparison__frame",
                style: frame_style,
                onmounted: move |event| frame.set(Some(event.data())),
                // Mouse events reach every renderer, Dioxus Native included.
                onmousedown: move |event: MouseEvent| {
                    if event.trigger_button() == Some(MouseButton::Primary) && interactive {
                        event.prevent_default();
                        start(event.client_coordinates().x, false);
                    }
                },
                onmousemove: move |event: MouseEvent| follow(event.client_coordinates().x, false),
                onmouseup: move |_| stop(false),
                onmouseleave: move |_| stop(false),
                // Touch and pen input arrives as pointer events on the web and desktop.
                onpointerdown: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        start(event.client_coordinates().x, true);
                    }
                },
                onpointermove: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        follow(event.client_coordinates().x, true);
                    }
                },
                onpointerup: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        stop(true);
                    }
                },
                onpointercancel: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        stop(true);
                    }
                },
                div { class: "ui-image-comparison__before", hidden: mode == ImageComparisonMode::After, {props.before} }
                div { class: "ui-image-comparison__after", hidden: mode == ImageComparisonMode::Before, {props.after} }
                div { aria_hidden: "true", class: "ui-image-comparison__divider" }
            }
            div { aria_hidden: "true", class: "ui-image-comparison__labels",
                span { hidden: mode == ImageComparisonMode::After, {props.before_label.clone()} }
                span { hidden: mode == ImageComparisonMode::Before, {props.after_label.clone()} }
            }
            figcaption { class: "ui-image-comparison__caption",
                label { class: "ui-image-comparison__control", hidden: mode != ImageComparisonMode::Reveal,
                    span { {props.label.clone()} }
                    input {
                        aria_valuetext: value_text,
                        class: "ui-slider ui-image-comparison__range",
                        disabled: !interactive,
                        max: "100",
                        min: "0",
                        name: props.name.clone(),
                        step: "1",
                        r#type: "range",
                        value: js_number(value),
                        oninput: move |event: FormEvent| {
                            if !interactive {
                                return;
                            }

                            if let Ok(next) = event.value().trim().parse::<f64>() {
                                position.set(normalize_image_comparison_value(next));
                            }
                        },
                        onkeydown: move |event: KeyboardEvent| {
                            if !interactive {
                                return;
                            }

                            if let Some(next) = key_value(&event.key(), position.peek()) {
                                event.prevent_default();
                                position.set(next);
                            }
                        },
                    }
                }
                {props.children}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Key, RevealDrag, drag_value, key_value, normalize_image_comparison_value, normalize_ratio,
        value_text,
    };

    #[test]
    fn drags_map_to_positions() {
        let drag = RevealDrag {
            start_x: 100.0,
            start_value: 50.0,
            touch: false,
        };

        assert!((drag_value(drag, 175.0, Some((100.0, 300.0)), 640.0) - 25.0).abs() < f64::EPSILON);
        assert!(
            (drag_value(drag, 900.0, Some((100.0, 300.0)), 640.0) - 100.0).abs() < f64::EPSILON
        );
        assert!((drag_value(drag, 164.0, None, 640.0) - 60.0).abs() < f64::EPSILON);
        assert!((drag_value(drag, 164.0, None, f64::NAN) - 60.0).abs() < f64::EPSILON);
        assert!(drag_value(drag, -10_000.0, None, 640.0).abs() < f64::EPSILON);
    }

    #[test]
    fn values_clamp_and_round_like_lumen_core() {
        assert!((normalize_image_comparison_value(120.0) - 100.0).abs() < f64::EPSILON);
        assert!(normalize_image_comparison_value(-3.0).abs() < f64::EPSILON);
        assert!((normalize_image_comparison_value(30.5) - 31.0).abs() < f64::EPSILON);
        assert!((normalize_image_comparison_value(f64::NAN) - 50.0).abs() < f64::EPSILON);
        assert!((normalize_ratio(-1.0) - 16.0 / 9.0).abs() < f64::EPSILON);
        assert!((normalize_ratio(1.5) - 1.5).abs() < f64::EPSILON);
    }

    #[test]
    fn keys_step_the_slider() {
        assert_eq!(key_value(&Key::ArrowRight, 50.0), Some(51.0));
        assert_eq!(key_value(&Key::ArrowDown, 0.0), Some(0.0));
        assert_eq!(key_value(&Key::PageUp, 95.0), Some(100.0));
        assert_eq!(key_value(&Key::Home, 40.0), Some(0.0));
        assert_eq!(key_value(&Key::End, 40.0), Some(100.0));
        assert_eq!(key_value(&Key::Enter, 40.0), None);
    }

    #[test]
    fn value_text_reads_the_percentage() {
        assert_eq!(value_text(30.0, "Edited", None), "30% Edited");
        assert_eq!(value_text(150.0, "After", Some("en")), "100% After");
    }
}