lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Slider`: a range input, with a native-safe ARIA slider on Dioxus Native.

// cspell:words onmousedown onmousemove onmouseup

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

use super::number_field_host::use_scripting;
use crate::class::compose;

/// Most hit zones the Dioxus Native slider renders; finer values are reached with the keyboard.
const MAX_ZONES: usize = 100;

/// Resolved bounds of a slider, following the HTML range input rules.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct SliderRange {
    pub min: f64,
    pub max: f64,
    pub step: f64,
}

/// Decimal places of a finite number's shortest representation, capped at 15.
fn decimals(value: f64) -> i32 {
    let text = format!("{value}");

    text.split_once('.').map_or(0, |(_, fraction)| {
        i32::try_from(fraction.len()).unwrap_or(15).min(15)
    })
}

impl SliderRange {
    /// Defaults `min` 0, `max` 100, and `step` 1; a `max` below `min` becomes `min`, and a
    /// missing, zero, negative, or non-finite step becomes 1, like the HTML range input.
    pub(crate) fn new(min: Option<f64>, max: Option<f64>, step: Option<f64>) -> Self {
        let min = min.filter(|value| value.is_finite()).unwrap_or(0.0);
        let max = max
            .filter(|value| value.is_finite())
            .unwrap_or(100.0)
            .max(min);
        let step = step
            .filter(|value| value.is_finite() && *value > 0.0)
            .unwrap_or(1.0);

        Self { min, max, step }
    }

    /// Rounds away floating-point noise to the precision of `min` and `step`.
    fn round(&self, value: f64) -> f64 {
        let places = decimals(self.step).max(decimals(self.min));
        let factor = 10_f64.powi(places);

        (value * factor).round() / factor
    }

    /// The largest value reachable from `min` in whole steps.
    fn top(&self) -> f64 {
        self.round(self.min + ((self.max - self.min) / self.step).floor() * self.step)
    }

    /// Clamps to the range and snaps to the nearest step from `min`, like the value sanitization
    /// of `<input type="range">`.
    pub(crate) fn sanitize(&self, value: f64) -> f64 {
        if !value.is_finite() {
            return self.default_value();
        }

        let clamped = value.clamp(self.min, self.max);
        let snapped = self.round(self.min + ((clamped - self.min) / self.step).round() * self.step);

        if snapped > self.max {
            self.top()
        } else {
            snapped
        }
    }

    /// The value of a range input without a value: the midpoint, snapped.
    pub(crate) fn default_value(&self) -> f64 {
        self.sanitize(self.min + (self.max - self.min) / 2.0)
    }

    /// Position of a value along the track, from 0 to 100.
    pub(crate) fn percent(&self, value: f64) -> f64 {
        if self.max <= self.min {
            return 0.0;
        }

        ((value - self.min) / (self.max - self.min) * 100.0).clamp(0.0, 100.0)
    }

    /// Whole steps between `min` and `max`.
    fn steps(&self) -> usize {
        let steps = ((self.max - self.min) / self.step).floor();

        if steps.is_finite() && steps >= 0.0 {
            // Bounded above, so the conversion cannot truncate meaningfully.
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let steps = steps.min(1e9) as usize;
            steps
        } else {
            0
        }
    }

    /// How many hit zones divide the track (one per step, at most [`MAX_ZONES`]).
    pub(crate) fn zone_count(&self) -> usize {
        self.steps().clamp(1, MAX_ZONES)
    }

    /// The value of hit zone `index` of `zones` (zone `0` is `min`, zone `zones` is `max`).
    pub(crate) fn zone_value(&self, index: usize, zones: usize) -> f64 {
        #[allow(clippy::cast_precision_loss)]
        let fraction = index.min(zones) as f64 / zones.max(1) as f64;

        self.sanitize(self.min + fraction * (self.max - self.min))
    }

    /// The value after a slider key, or `None` for other keys.
    pub(crate) fn key_value(&self, value: f64, key: &Key) -> Option<f64> {
        #[allow(clippy::cast_precision_loss)]
        let page = self.step * ((self.steps() as f64) / 10.0).round().max(1.0);

        let next = match key {
            Key::ArrowRight | Key::ArrowUp => value + self.step,
            Key::ArrowLeft | Key::ArrowDown => value - self.step,
            Key::PageUp => value + page,
            Key::PageDown => value - page,
            Key::Home => self.min,
            Key::End => self.max,
            _ => return None,
        };

        Some(self.sanitize(next))
    }
}

/// Formats a number for an attribute the way JavaScript's `String(number)` does for ordinary
/// values (`40`, `0.5`).
fn number_text(value: f64) -> String {
    format!("{value}")
}

/// Props for [`Slider`].
#[derive(Props, Clone, PartialEq)]
pub struct SliderProps {
    /// Controlled value. Leave unset to let the slider manage itself.
    pub value: Option<f64>,
    /// Initial value when uncontrolled. Defaults to the midpoint of the range.
    pub default_value: Option<f64>,
    /// Lower bound. Defaults to 0.
    pub min: Option<f64>,
    /// Upper bound. Defaults to 100.
    pub max: Option<f64>,
    /// Step size. Defaults to 1.
    pub step: Option<f64>,
    /// Disables the slider.
    #[props(default)]
    pub disabled: bool,
    /// Form field name.
    #[props(into)]
    pub name: Option<String>,
    /// Called with the new value while the user drags or presses keys.
    pub on_value_change: Option<EventHandler<f64>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute, such as `id`, `aria_label`, or
    /// `aria_valuetext`.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// A range slider: `<input type="range" class="ui-slider">`, like lumen-react.
///
/// Browsers and desktop webviews draw and drive the native range input. Dioxus Native (Blitz)
/// cannot draw `type="range"`, so there the slider renders a `role="slider"` element with a
/// track, a filled range, a thumb, and invisible hit zones: clicking or dragging across the track
/// sets the value, and the arrow keys, `PageUp`, `PageDown`, `Home`, and `End` move it once the slider has
/// keyboard focus (Tab). A hidden input submits the value under `name`.
#[component]
pub fn Slider(props: SliderProps) -> Element {
    let range = SliderRange::new(props.min, props.max, props.step);
    // The web markup keeps the authored value, like lumen-react; the browser snaps it.
    let mut internal = use_signal(|| props.default_value);
    let mut dragging = use_signal(|| false);
    let scripting = use_scripting();
    let controlled = props.value;
    let attribute_value = controlled.or_else(|| *internal.read());
    let on_value_change = props.on_value_change;
    let disabled = props.disabled;
    let class = compose([Some("ui-slider"), props.class.as_deref()]);

    let mut commit = move |next: f64| {
        if controlled.is_none() {
            internal.set(Some(next));
        }

        if let Some(handler) = on_value_change {
            handler.call(next);
        }
    };

    if scripting != Some(false) {
        return rsx! {
            input {
                class,
                disabled,
                max: props.max.map(number_text),
                min: props.min.map(number_text),
                name: props.name.clone(),
                step: props.step.map(number_text),
                r#type: "range",
                value: attribute_value.map(number_text),
                oninput: move |event| {
                    if let Ok(next) = event.value().trim().parse::<f64>() {
                        commit(next);
                    }
                },
                ..props.attributes,
            }
        };
    }

    let value = range.sanitize(attribute_value.unwrap_or_else(|| range.default_value()));
    let percent = range.percent(value);
    let zones = range.zone_count();
    let native_class = compose([Some("ui-slider ui-dioxus-slider"), props.class.as_deref()]);

    rsx! {
        div {
            aria_disabled: disabled.then_some("true"),
            aria_orientation: "horizontal",
            aria_valuemax: number_text(range.max),
            aria_valuemin: number_text(range.min),
            aria_valuenow: number_text(value),
            class: native_class,
            "data-disabled": disabled.then_some("true"),
            role: "slider",
            tabindex: if disabled { None } else { Some("0") },
            onkeydown: move |event| {
                if disabled {
                    return;
                }

                if let Some(next) = range.key_value(value, &event.key()) {
                    event.prevent_default();

                    if (next - value).abs() > f64::EPSILON {
                        commit(next);
                    }
                }
            },
            // Blitz clears focus on clicks that hit no form control; keep keyboard focus.
            onclick: move |event| event.prevent_default(),
            onmouseup: move |_| dragging.set(false),
            ..props.attributes,
            div { class: "ui-dioxus-slider__track",
                div {
                    class: "ui-dioxus-slider__range",
                    style: "width: {percent}%",
                }
            }
            div {
                class: "ui-dioxus-slider__thumb",
                style: "left: {percent}%",
            }
            div { class: "ui-dioxus-slider__zones",
                for index in 0..=zones {
                    div {
                        key: "{index}",
                        class: "ui-dioxus-slider__zone",
                        onmousedown: move |event| {
                            if disabled || event.trigger_button() != Some(MouseButton::Primary) {
                                return;
                            }

                            event.prevent_default();
                            dragging.set(true);
                            commit(range.zone_value(index, zones));
                        },
                        onmousemove: move |event| {
                            if !*dragging.peek() {
                                return;
                            }

                            if !event.held_buttons().contains(MouseButton::Primary) {
                                dragging.set(false);
                                return;
                            }

                            let next = range.zone_value(index, zones);

                            if (next - value).abs() > f64::EPSILON {
                                commit(next);
                            }
                        },
                    }
                }
            }
        }
        if let Some(name) = props.name.clone() {
            input { r#type: "hidden", name, value: number_text(value) }
        }
    }
}

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

    use super::{Slider, SliderRange};
    use crate::inputs::number_field_host::set_scripting_for_tests;

    #[test]
    fn values_snap_to_steps_and_clamp_like_range_inputs() {
        let range = SliderRange::new(Some(0.0), Some(1.0), Some(0.1));

        assert!((range.sanitize(0.3) - 0.3).abs() < f64::EPSILON);
        assert!((range.sanitize(0.34) - 0.3).abs() < f64::EPSILON);
        assert!((range.sanitize(7.0) - 1.0).abs() < f64::EPSILON);
        assert!((range.sanitize(f64::NAN) - 0.5).abs() < f64::EPSILON);

        let uneven = SliderRange::new(Some(0.0), Some(10.0), Some(3.0));

        assert!((uneven.sanitize(10.0) - 9.0).abs() < f64::EPSILON);
        assert!((uneven.default_value() - 6.0).abs() < f64::EPSILON);

        let inverted = SliderRange::new(Some(5.0), Some(1.0), Some(-2.0));

        assert_eq!(
            inverted,
            SliderRange {
                min: 5.0,
                max: 5.0,
                step: 1.0
            }
        );
        assert!(inverted.percent(5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn keys_move_by_step_page_and_to_the_ends() {
        let range = SliderRange::new(None, None, None);

        assert_eq!(range.key_value(40.0, &Key::ArrowRight), Some(41.0));
        assert_eq!(range.key_value(40.0, &Key::ArrowDown), Some(39.0));
        assert_eq!(range.key_value(40.0, &Key::PageUp), Some(50.0));
        assert_eq!(range.key_value(5.0, &Key::PageDown), Some(0.0));
        assert_eq!(range.key_value(40.0, &Key::Home), Some(0.0));
        assert_eq!(range.key_value(40.0, &Key::End), Some(100.0));
        assert_eq!(range.key_value(40.0, &Key::Enter), None);
    }

    #[test]
    fn hit_zones_cover_the_track_from_min_to_max() {
        let range = SliderRange::new(Some(0.0), Some(1000.0), Some(1.0));
        let zones = range.zone_count();

        assert_eq!(zones, 100);
        assert!((range.zone_value(0, zones)).abs() < f64::EPSILON);
        assert!((range.zone_value(37, zones) - 370.0).abs() < f64::EPSILON);
        assert!((range.zone_value(zones, zones) - 1000.0).abs() < f64::EPSILON);
        assert_eq!(
            SliderRange::new(Some(0.0), Some(4.0), Some(1.0)).zone_count(),
            4
        );
        assert_eq!(SliderRange::new(Some(0.0), Some(0.0), None).zone_count(), 1);
    }

    #[test]
    fn native_renders_an_aria_slider_with_a_hidden_form_value() {
        set_scripting_for_tests(Some(false));
        let html = dioxus_ssr::render_element(rsx! {
            Slider { aria_label: "Volume", default_value: 40.0, name: "volume", step: 10.0 }
        });
        set_scripting_for_tests(None);

        assert!(html.contains("role=\"slider\""), "{html}");
        assert!(html.contains("aria-valuenow=\"40\""), "{html}");
        assert!(html.contains("aria-label=\"Volume\""), "{html}");
        assert!(html.contains("width: 40%"), "{html}");
        assert!(html.contains("name=\"volume\""), "{html}");
        assert_eq!(
            html.matches("ui-dioxus-slider__zone\"").count(),
            11,
            "{html}"
        );
    }
}