use std::sync::Arc;
use super::form_field::form_field;
use crate::{
app::ctx::Ctx,
components::Control,
core::Signal,
node::Element,
ui::{self, Length, SliderPart},
};
#[derive(Clone, Debug, PartialEq, crate::DevtoolsInspectable)]
pub struct FormRangeSliderInputProps {
pub control: Control<(f64, f64)>,
pub label: Option<Arc<str>>,
pub hint: Option<Arc<str>>,
pub min: i32,
pub max: i32,
}
impl FormRangeSliderInputProps {
pub fn new(control: Control<(f64, f64)>) -> Self {
Self {
control,
label: None,
hint: None,
min: 0,
max: 100,
}
}
pub fn label(mut self, label: impl Into<Arc<str>>) -> Self {
self.label = Some(label.into());
self
}
pub fn hint(mut self, hint: impl Into<Arc<str>>) -> Self {
self.hint = Some(hint.into());
self
}
pub fn range(mut self, min: i32, max: i32) -> Self {
self.min = min;
self.max = max;
self
}
}
pub struct FormRangeSliderInput {
values: Signal<(i32, i32)>,
}
impl crate::app::component::Component for FormRangeSliderInput {
type Props = FormRangeSliderInputProps;
fn create(ctx: &mut Ctx) -> Self {
let props = ctx.props::<Self::Props>().clone();
let field_values = props.control.field().value();
let slider_values = ctx.signal(clamp_range(field_values.get_untracked(), props.min, props.max));
let field_from_slider = field_values.clone();
ctx.watch(&slider_values, move |(low, high)| {
let next = (*low as f64, *high as f64);
if field_from_slider.get_untracked() != next {
field_from_slider.set(next);
}
});
let slider_from_field = slider_values.clone();
ctx.watch(&field_values, move |values| {
let next = clamp_range(*values, props.min, props.max);
if slider_from_field.get_untracked() != next {
slider_from_field.set(next);
}
});
Self { values: slider_values }
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<Self::Props>().clone();
let control = ctx.form_control(&props.control);
let blur_control = control.clone();
let (min, max) = (props.min.min(props.max), props.min.max(props.max));
let slider = ui::RangeSlider::new(self.values.clone())
.min(min)
.max(max)
.name(control.name())
.style(SliderPart::Root, |s| s.width(Length::Fill))
.on_leave(move || {
blur_control.mark_touched();
blur_control.validate();
});
form_field(&control, props.label.as_deref(), props.hint.as_deref(), slider)
}
}
fn clamp_range((low, high): (f64, f64), min: i32, max: i32) -> (i32, i32) {
let (min, max) = if min <= max { (min, max) } else { (max, min) };
let clamp = |value: f64| value.round().clamp(min as f64, max as f64) as i32;
let (low, high) = (clamp(low), clamp(high));
(low.min(high), low.max(high))
}