Skip to main content

lumen_dioxus/content/
image_comparison.rs

1//! `ImageComparison`: a before and after image comparison with a reveal slider.
2// cspell:words figcaption onmousedown onmouseleave onmousemove onmouseup onpointercancel
3
4use std::rc::Rc;
5
6use dioxus::html::input_data::MouseButton;
7use dioxus::prelude::*;
8
9use super::image::ImageFit;
10use super::number_format::{FormattedNumberFormat, FormattedNumberValue, NumberFormatOptions};
11use super::util::js_number;
12use crate::class::compose;
13use crate::hooks::use_controllable;
14
15/// How an [`ImageComparison`] shows its images. Switching modes keeps the reveal position.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum ImageComparisonMode {
19    /// The after image covers the before image up to the slider position.
20    #[default]
21    Reveal,
22    /// Both images next to each other.
23    SideBySide,
24    /// Only the before image.
25    Before,
26    /// Only the after image.
27    After,
28}
29
30impl ImageComparisonMode {
31    /// The `data-mode` value.
32    pub fn as_str(self) -> &'static str {
33        match self {
34            Self::Reveal => "reveal",
35            Self::SideBySide => "side-by-side",
36            Self::Before => "before",
37            Self::After => "after",
38        }
39    }
40}
41
42/// Clamps a reveal position to 0 through 100 and rounds it to the slider step; non-finite values
43/// become 50, like `normalizeLumenImageComparisonValue`.
44pub fn normalize_image_comparison_value(value: f64) -> f64 {
45    if value.is_finite() {
46        // `Math.round` rounds halves toward positive infinity.
47        (value.clamp(0.0, 100.0) + 0.5).floor()
48    } else {
49        50.0
50    }
51}
52
53fn normalize_ratio(ratio: f64) -> f64 {
54    if ratio.is_finite() && ratio > 0.0 {
55        ratio
56    } else {
57        16.0 / 9.0
58    }
59}
60
61/// The slider's `aria-valuetext`, such as "50% After".
62fn value_text(value: f64, after_label: &str, locale: Option<&str>) -> String {
63    let options = NumberFormatOptions {
64        format: FormattedNumberFormat::Percent,
65        locale: locale.map(str::to_string),
66        ..NumberFormatOptions::default()
67    };
68    let percent = super::number_format::format_lumen_number(
69        &FormattedNumberValue::Number(normalize_image_comparison_value(value) / 100.0),
70        &options,
71        "",
72    );
73
74    format!("{} {after_label}", percent.text)
75}
76
77/// The new value for a slider key, or `None` for other keys.
78fn key_value(key: &Key, value: f64) -> Option<f64> {
79    let next = match key {
80        Key::ArrowLeft | Key::ArrowDown => value - 1.0,
81        Key::ArrowRight | Key::ArrowUp => value + 1.0,
82        Key::PageDown => value - 10.0,
83        Key::PageUp => value + 10.0,
84        Key::Home => 0.0,
85        Key::End => 100.0,
86        _ => return None,
87    };
88
89    Some(normalize_image_comparison_value(next))
90}
91
92/// A divider drag in progress.
93#[derive(Clone, Copy, Debug, PartialEq)]
94struct RevealDrag {
95    start_x: f64,
96    start_value: f64,
97    touch: bool,
98}
99
100/// The position for a pointer at `x`: under the pointer when the frame was measured as
101/// `(left, width)`, otherwise moved by the drag distance over `extent` pixels.
102fn drag_value(drag: RevealDrag, x: f64, frame: Option<(f64, f64)>, extent: f64) -> f64 {
103    match frame {
104        Some((left, width)) if width > 0.0 => {
105            normalize_image_comparison_value((x - left) / width * 100.0)
106        }
107        _ => {
108            let extent = if extent.is_finite() && extent >= 1.0 {
109                extent
110            } else {
111                640.0
112            };
113
114            normalize_image_comparison_value(drag.start_value + (x - drag.start_x) / extent * 100.0)
115        }
116    }
117}
118
119/// Props for [`ImageComparison`].
120#[derive(Props, Clone, PartialEq)]
121pub struct ImageComparisonProps {
122    /// The before image.
123    pub before: Element,
124    /// The after image.
125    pub after: Element,
126    /// Accessible name of the slider, shown next to it.
127    #[props(into)]
128    pub label: String,
129    /// Label of the before image.
130    #[props(default = "Before".to_string(), into)]
131    pub before_label: String,
132    /// Label of the after image, also read in the slider value.
133    #[props(default = "After".to_string(), into)]
134    pub after_label: String,
135    /// Controlled reveal position, 0 through 100.
136    pub value: Option<f64>,
137    /// Initial reveal position when uncontrolled. Defaults to 50.
138    #[props(default = 50.0)]
139    pub default_value: f64,
140    /// Called with the new position.
141    pub on_value_change: Option<EventHandler<f64>>,
142    /// Display mode.
143    #[props(default)]
144    pub mode: ImageComparisonMode,
145    /// How the images fill the frame.
146    #[props(default)]
147    pub fit: ImageFit,
148    /// Width to height ratio of the frame. Defaults to 16 / 9.
149    #[props(default = 16.0 / 9.0)]
150    pub ratio: f64,
151    /// Disables the slider.
152    #[props(default)]
153    pub disabled: bool,
154    /// Frame width in pixels used to turn drag distance into a position when the renderer cannot
155    /// measure the frame (Dioxus Native). The web and desktop measure it. Defaults to 640.
156    #[props(default = 640.0)]
157    pub drag_extent: f64,
158    /// Form field name of the slider.
159    #[props(into)]
160    pub name: Option<String>,
161    /// BCP 47 locale of the slider value text; defaults to English.
162    #[props(into)]
163    pub locale: Option<String>,
164    /// Extra classes appended after the Lumen class.
165    #[props(into)]
166    pub class: Option<String>,
167    /// Any other `<figure>` or global attribute.
168    #[props(extends = GlobalAttributes, extends = figure)]
169    pub attributes: Vec<Attribute>,
170    /// Caption content after the slider.
171    pub children: Element,
172}
173
174/// Compares a before and after image. In reveal mode, the slider, a drag on the frame, or the
175/// arrow, Page Up, Page Down, Home, and End keys move the divider.
176#[component]
177pub fn ImageComparison(props: ImageComparisonProps) -> Element {
178    let position = use_controllable(
179        props.value.map(normalize_image_comparison_value),
180        || normalize_image_comparison_value(props.default_value),
181        props.on_value_change,
182    );
183    let mut frame = use_signal(|| None::<Rc<MountedData>>);
184    let mut measured = use_signal(|| None::<(f64, f64)>);
185    let mut drag = use_signal(|| None::<RevealDrag>);
186    let value = position.get();
187    let interactive = !props.disabled && props.mode == ImageComparisonMode::Reveal;
188    let mode = props.mode;
189    let extent = props.drag_extent;
190    let frame_style = format!(
191        "--ui-image-comparison-position: {}%; --ui-image-comparison-ratio: {}",
192        js_number(value),
193        js_number(normalize_ratio(props.ratio))
194    );
195    let class = compose([Some("ui-image-comparison"), props.class.as_deref()]);
196    let value_text = value_text(value, &props.after_label, props.locale.as_deref());
197    let mut start = move |x: f64, touch: bool| {
198        if !interactive {
199            return;
200        }
201
202        let started = RevealDrag {
203            start_x: x,
204            start_value: position.peek(),
205            touch,
206        };
207
208        drag.set(Some(started));
209
210        if measured.peek().is_some() {
211            position.set(drag_value(started, x, *measured.peek(), extent));
212        }
213
214        // Measure the frame where the renderer supports it (web and desktop), then place the
215        // divider under the pointer.
216        if let Some(mounted) = frame.peek().clone() {
217            spawn(async move {
218                if let Ok(rect) = mounted.get_client_rect().await {
219                    measured.set(Some((rect.origin.x, rect.size.width)));
220
221                    if drag.peek().is_some() {
222                        position.set(drag_value(started, x, *measured.peek(), extent));
223                    }
224                }
225            });
226        }
227    };
228    let follow = move |x: f64, touch: bool| {
229        if let Some(active) = *drag.peek()
230            && active.touch == touch
231            && interactive
232        {
233            position.set(drag_value(active, x, *measured.peek(), extent));
234        }
235    };
236    let mut stop = move |touch: bool| {
237        if drag.peek().is_some_and(|active| active.touch == touch) {
238            drag.set(None);
239        }
240    };
241
242    rsx! {
243        figure {
244            class,
245            "data-fit": props.fit.as_str(),
246            "data-mode": mode.as_str(),
247            ..props.attributes,
248            div {
249                class: "ui-image-comparison__frame",
250                style: frame_style,
251                onmounted: move |event| frame.set(Some(event.data())),
252                // Mouse events reach every renderer, Dioxus Native included.
253                onmousedown: move |event: MouseEvent| {
254                    if event.trigger_button() == Some(MouseButton::Primary) && interactive {
255                        event.prevent_default();
256                        start(event.client_coordinates().x, false);
257                    }
258                },
259                onmousemove: move |event: MouseEvent| follow(event.client_coordinates().x, false),
260                onmouseup: move |_| stop(false),
261                onmouseleave: move |_| stop(false),
262                // Touch and pen input arrives as pointer events on the web and desktop.
263                onpointerdown: move |event: PointerEvent| {
264                    if event.pointer_type() != "mouse" {
265                        start(event.client_coordinates().x, true);
266                    }
267                },
268                onpointermove: move |event: PointerEvent| {
269                    if event.pointer_type() != "mouse" {
270                        follow(event.client_coordinates().x, true);
271                    }
272                },
273                onpointerup: move |event: PointerEvent| {
274                    if event.pointer_type() != "mouse" {
275                        stop(true);
276                    }
277                },
278                onpointercancel: move |event: PointerEvent| {
279                    if event.pointer_type() != "mouse" {
280                        stop(true);
281                    }
282                },
283                div { class: "ui-image-comparison__before", hidden: mode == ImageComparisonMode::After, {props.before} }
284                div { class: "ui-image-comparison__after", hidden: mode == ImageComparisonMode::Before, {props.after} }
285                div { aria_hidden: "true", class: "ui-image-comparison__divider" }
286            }
287            div { aria_hidden: "true", class: "ui-image-comparison__labels",
288                span { hidden: mode == ImageComparisonMode::After, {props.before_label.clone()} }
289                span { hidden: mode == ImageComparisonMode::Before, {props.after_label.clone()} }
290            }
291            figcaption { class: "ui-image-comparison__caption",
292                label { class: "ui-image-comparison__control", hidden: mode != ImageComparisonMode::Reveal,
293                    span { {props.label.clone()} }
294                    input {
295                        aria_valuetext: value_text,
296                        class: "ui-slider ui-image-comparison__range",
297                        disabled: !interactive,
298                        max: "100",
299                        min: "0",
300                        name: props.name.clone(),
301                        step: "1",
302                        r#type: "range",
303                        value: js_number(value),
304                        oninput: move |event: FormEvent| {
305                            if !interactive {
306                                return;
307                            }
308
309                            if let Ok(next) = event.value().trim().parse::<f64>() {
310                                position.set(normalize_image_comparison_value(next));
311                            }
312                        },
313                        onkeydown: move |event: KeyboardEvent| {
314                            if !interactive {
315                                return;
316                            }
317
318                            if let Some(next) = key_value(&event.key(), position.peek()) {
319                                event.prevent_default();
320                                position.set(next);
321                            }
322                        },
323                    }
324                }
325                {props.children}
326            }
327        }
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::{
334        Key, RevealDrag, drag_value, key_value, normalize_image_comparison_value, normalize_ratio,
335        value_text,
336    };
337
338    #[test]
339    fn drags_map_to_positions() {
340        let drag = RevealDrag {
341            start_x: 100.0,
342            start_value: 50.0,
343            touch: false,
344        };
345
346        assert!((drag_value(drag, 175.0, Some((100.0, 300.0)), 640.0) - 25.0).abs() < f64::EPSILON);
347        assert!(
348            (drag_value(drag, 900.0, Some((100.0, 300.0)), 640.0) - 100.0).abs() < f64::EPSILON
349        );
350        assert!((drag_value(drag, 164.0, None, 640.0) - 60.0).abs() < f64::EPSILON);
351        assert!((drag_value(drag, 164.0, None, f64::NAN) - 60.0).abs() < f64::EPSILON);
352        assert!(drag_value(drag, -10_000.0, None, 640.0).abs() < f64::EPSILON);
353    }
354
355    #[test]
356    fn values_clamp_and_round_like_lumen_core() {
357        assert!((normalize_image_comparison_value(120.0) - 100.0).abs() < f64::EPSILON);
358        assert!(normalize_image_comparison_value(-3.0).abs() < f64::EPSILON);
359        assert!((normalize_image_comparison_value(30.5) - 31.0).abs() < f64::EPSILON);
360        assert!((normalize_image_comparison_value(f64::NAN) - 50.0).abs() < f64::EPSILON);
361        assert!((normalize_ratio(-1.0) - 16.0 / 9.0).abs() < f64::EPSILON);
362        assert!((normalize_ratio(1.5) - 1.5).abs() < f64::EPSILON);
363    }
364
365    #[test]
366    fn keys_step_the_slider() {
367        assert_eq!(key_value(&Key::ArrowRight, 50.0), Some(51.0));
368        assert_eq!(key_value(&Key::ArrowDown, 0.0), Some(0.0));
369        assert_eq!(key_value(&Key::PageUp, 95.0), Some(100.0));
370        assert_eq!(key_value(&Key::Home, 40.0), Some(0.0));
371        assert_eq!(key_value(&Key::End, 40.0), Some(100.0));
372        assert_eq!(key_value(&Key::Enter, 40.0), None);
373    }
374
375    #[test]
376    fn value_text_reads_the_percentage() {
377        assert_eq!(value_text(30.0, "Edited", None), "30% Edited");
378        assert_eq!(value_text(150.0, "After", Some("en")), "100% After");
379    }
380}