ailloli_ui_widgets/controls/
slider.rs

1//! Single- and dual-thumb sliders with controlled or two-way bound values.
2
3use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
8use ailloli_ui_core::geometry::{Constraints, Rect, Size};
9use ailloli_ui_core::slider::{SliderRangeValue, SliderSpec, SliderThumb};
10use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
11use ailloli_ui_core::{Color, Theme};
12use ailloli_ui_runtime::component::{
13    Binding, ComponentNode, Context, IntoView, Memo, Signal, View, Widget,
14};
15use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, FocusPolicy};
16use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
17use ailloli_ui_runtime::scene::PaintCtx;
18use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, DrawRect};
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21/// Built-in slider geometry sizes.
22///
23/// # Examples
24///
25/// ```
26/// use ailloli_ui_widgets::controls::SliderSize;
27/// let sizes = [SliderSize::Compact, SliderSize::Default];
28/// assert_eq!(sizes.len(), 2);
29/// assert_eq!(SliderSize::default(), SliderSize::Default);
30/// ```
31pub enum SliderSize {
32    /// 180×22 horizontal or 22×120 vertical logical pixels.
33    Compact,
34    /// 260×28 horizontal or 28×160 vertical logical pixels; the default.
35    #[default]
36    Default,
37}
38
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40/// Slider axis and increasing-value direction.
41///
42/// # Examples
43///
44/// ```
45/// use ailloli_ui_widgets::controls::SliderOrientation;
46/// let orientations = [SliderOrientation::Horizontal, SliderOrientation::Vertical];
47/// assert_eq!(orientations.len(), 2);
48/// assert_eq!(SliderOrientation::default(), SliderOrientation::Horizontal);
49/// ```
50pub enum SliderOrientation {
51    /// Minimum at left and maximum at right; the default.
52    #[default]
53    Horizontal,
54    /// Minimum at bottom and maximum at top.
55    Vertical,
56}
57
58#[derive(Clone, Debug, PartialEq)]
59/// Resolved slider colors, borders, and logical-pixel geometry.
60///
61/// Geometry is not validated. `disabled_opacity` is retained for compatibility
62/// but is not currently read; disabled colors already encode their alpha.
63///
64/// # Examples
65///
66/// ```
67/// use ailloli_ui_core::Theme;
68/// use ailloli_ui_widgets::controls::{SliderSize, SliderStyle};
69/// let style = SliderStyle::from_theme(Theme::dark(), SliderSize::Compact);
70/// assert_eq!((style.horizontal_width, style.vertical_height), (180.0, 120.0));
71/// assert_eq!(style.thumb_size, 14.0);
72/// ```
73pub struct SliderStyle {
74    /// Resting inactive track fill.
75    pub track: Color,
76    /// Hovered inactive track fill.
77    pub track_hovered: Color,
78    /// Resting active-range fill.
79    pub active_track: Color,
80    /// Hovered or dragged active-range fill.
81    pub active_track_hovered: Color,
82    /// Resting thumb fill.
83    pub thumb: Color,
84    /// Hovered thumb fill.
85    pub thumb_hovered: Color,
86    /// Pressed or dragged thumb fill.
87    pub thumb_pressed: Color,
88    /// Disabled inactive-track fill.
89    pub disabled_track: Color,
90    /// Disabled active-range fill.
91    pub disabled_active_track: Color,
92    /// Disabled thumb fill.
93    pub disabled_thumb: Color,
94    /// Tick-mark color.
95    pub tick: Color,
96    /// Border painted around each thumb.
97    pub border: Border,
98    /// Border painted around complete widget bounds while focused.
99    pub focus_ring: Border,
100    /// Horizontal intrinsic width in logical pixels.
101    pub horizontal_width: f32,
102    /// Horizontal intrinsic height in logical pixels.
103    pub horizontal_height: f32,
104    /// Vertical intrinsic width in logical pixels.
105    pub vertical_width: f32,
106    /// Vertical intrinsic height in logical pixels.
107    pub vertical_height: f32,
108    /// Track thickness in logical pixels.
109    pub track_thickness: f32,
110    /// Square thumb width/height in logical pixels.
111    pub thumb_size: f32,
112    /// Gap between thumb fill and border ring; border width is added on top.
113    pub thumb_border_offset: f32,
114    /// Focus-ring inflation beyond widget bounds in logical pixels.
115    pub focus_ring_offset: f32,
116    /// Reserved compatibility value; the current painter does not read it.
117    pub disabled_opacity: f32,
118}
119
120impl Default for SliderStyle {
121    fn default() -> Self {
122        Self::from_theme(Theme::default(), SliderSize::Default)
123    }
124}
125
126impl SliderStyle {
127    /// Resolves slider colors and geometry from a theme and built-in size.
128    ///
129    /// # Examples
130    ///
131    /// ```
132    /// use ailloli_ui_core::Theme;
133    /// use ailloli_ui_widgets::controls::{SliderSize, SliderStyle};
134    /// let style = SliderStyle::from_theme(Theme::default(), SliderSize::Default);
135    /// assert_eq!((style.horizontal_width, style.horizontal_height), (260.0, 28.0));
136    /// assert_eq!((style.track_thickness, style.thumb_size), (4.0, 16.0));
137    /// ```
138    pub fn from_theme(theme: Theme, size: SliderSize) -> Self {
139        let palette = theme.palette();
140        let (horizontal_width, horizontal_height, vertical_width, vertical_height, thumb_size) =
141            match size {
142                SliderSize::Compact => (180.0, 22.0, 22.0, 120.0, 14.0),
143                SliderSize::Default => (260.0, 28.0, 28.0, 160.0, 16.0),
144            };
145        Self {
146            track: palette.surface_elevated,
147            track_hovered: Color::hex_rgb(0x20252A),
148            active_track: palette.accent,
149            active_track_hovered: theme.button_bg_hover,
150            thumb: palette.text,
151            thumb_hovered: Color::hex_rgb(0xFFFFFF),
152            thumb_pressed: Color::hex_rgb(0xFFE0CC),
153            disabled_track: palette.surface.with_alpha(0.58),
154            disabled_active_track: palette.accent.with_alpha(0.42),
155            disabled_thumb: palette.text_muted.with_alpha(0.72),
156            tick: palette.text_muted.with_alpha(0.68),
157            border: Border::new(1.0, palette.border),
158            focus_ring: Border::new(2.0, palette.focus),
159            horizontal_width,
160            horizontal_height,
161            vertical_width,
162            vertical_height,
163            track_thickness: 4.0,
164            thumb_size,
165            thumb_border_offset: 0.0,
166            focus_ring_offset: 3.0,
167            disabled_opacity: 0.48,
168        }
169    }
170
171    /// Returns horizontal or vertical intrinsic size.
172    fn intrinsic_size(&self, orientation: SliderOrientation) -> Size {
173        match orientation {
174            SliderOrientation::Horizontal => {
175                Size::new(self.horizontal_width, self.horizontal_height)
176            }
177            SliderOrientation::Vertical => Size::new(self.vertical_width, self.vertical_height),
178        }
179    }
180
181    /// Inflates layout visual bounds for a visible focus ring.
182    fn visual_bounds(&self, rect: Rect) -> Rect {
183        if self.focus_ring.is_visible() {
184            let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
185            rect.inflate(inflate, inflate)
186        } else {
187            rect
188        }
189    }
190}
191
192/// Shared single-value change callback.
193type SliderChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, f32)>;
194/// Shared ordered-range change callback.
195type RangeChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, SliderRangeValue)>;
196
197/// A single-thumb slider over a sanitized [`SliderSpec`].
198///
199/// `value` configures controlled input: user interaction only becomes observable
200/// through `on_change` and the consumer must rebuild/update its source. `bind`
201/// additionally writes a signal. Display and emitted values are clamped/snapped.
202/// Horizontal values increase rightward; vertical values increase upward.
203///
204/// # Examples
205///
206/// ```
207/// use ailloli_ui_widgets::controls::Slider;
208/// let slider: Slider<()> = Slider::new().range(0.0, 1.0).step(0.1).value(0.5);
209/// let _ = slider;
210/// ```
211pub struct Slider<A = ()> {
212    /// Layout configuration applied to intrinsic slider geometry.
213    pub(crate) layout: LayoutStyle,
214    /// Flex behavior used by the parent layout.
215    pub(crate) flex_item: FlexItemStyle,
216    /// Static or reactive controlled value.
217    value: Binding<f32>,
218    /// Writable value signal in bound mode.
219    bound: Option<Signal<f32>>,
220    /// Live disabled state.
221    disabled: Binding<bool>,
222    /// Sanitized numeric domain and optional step.
223    spec: SliderSpec,
224    /// Axis and value direction.
225    orientation: SliderOrientation,
226    /// Optional change notification.
227    on_change: Option<SliderChangeHandler<A>>,
228    /// Resolved paint and geometry.
229    style: SliderStyle,
230}
231
232crate::impl_layout_builders!(Slider);
233
234impl<A: 'static> Default for Slider<A> {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240impl<A: 'static> Slider<A> {
241    /// Creates a horizontal continuous `0.0..=100.0` slider at zero.
242    ///
243    /// It is enabled but read-only until bound or given a change callback.
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// use ailloli_ui_widgets::controls::Slider;
249    /// let slider: Slider<()> = Slider::new();
250    /// let _ = slider;
251    /// ```
252    pub fn new() -> Self {
253        Self {
254            layout: LayoutStyle::default(),
255            flex_item: FlexItemStyle::default(),
256            value: Binding::Static(0.0),
257            bound: None,
258            disabled: Binding::Static(false),
259            spec: SliderSpec::default(),
260            orientation: SliderOrientation::Horizontal,
261            on_change: None,
262            style: SliderStyle::default(),
263        }
264    }
265
266    /// Creates a default slider whose value increases bottom-to-top.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// use ailloli_ui_widgets::controls::Slider;
272    /// let slider: Slider<()> = Slider::vertical();
273    /// let _ = slider;
274    /// ```
275    pub fn vertical() -> Self {
276        Self::new().orientation(SliderOrientation::Vertical)
277    }
278
279    /// Sets static or reactive controlled value and clears bound mode.
280    ///
281    /// Painting clamps/snaps the value; this method does not mutate its source.
282    ///
283    /// # Examples
284    ///
285    /// ```
286    /// use ailloli_ui_widgets::controls::Slider;
287    /// let slider: Slider<()> = Slider::new().value(150.0);
288    /// let _ = slider;
289    /// ```
290    pub fn value(mut self, value: impl Into<Binding<f32>>) -> Self {
291        self.value = value.into();
292        self.bound = None;
293        self
294    }
295
296    /// Installs a writable signal for two-way interaction.
297    ///
298    /// Values written by the widget are clamped/snapped and only written when
299    /// they differ by more than [`f32::EPSILON`] from the displayed value.
300    ///
301    /// # Examples
302    ///
303    /// ```
304    /// use std::{cell::RefCell, rc::Rc};
305    /// use ailloli_ui_runtime::component::Signal;
306    /// use ailloli_ui_widgets::controls::Slider;
307    /// let value = Signal::new(Rc::new(RefCell::new(50.0)), Rc::new(|| {}));
308    /// let slider: Slider<()> = Slider::new().bind(value);
309    /// let _ = slider;
310    /// ```
311    pub fn bind(mut self, value: impl Into<Signal<f32>>) -> Self {
312        let signal = value.into();
313        self.value = Binding::Signal(signal.clone());
314        self.bound = Some(signal);
315        self
316    }
317
318    /// Sets static or reactive disabled state.
319    ///
320    /// Disabled sliders are not focusable and ignore pointer/keyboard input.
321    ///
322    /// # Examples
323    ///
324    /// ```
325    /// use ailloli_ui_widgets::controls::Slider;
326    /// let slider: Slider<()> = Slider::new().disabled(true);
327    /// let _ = slider;
328    /// ```
329    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
330        self.disabled = disabled.into();
331        self
332    }
333
334    /// Sets disabled state from a derived memo.
335    ///
336    /// # Examples
337    ///
338    /// ```
339    /// use ailloli_ui_runtime::component::Memo;
340    /// use ailloli_ui_widgets::controls::Slider;
341    /// let slider: Slider<()> = Slider::new().disabled_signal(Memo::new(|| false));
342    /// let _ = slider;
343    /// ```
344    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
345        self.disabled(disabled)
346    }
347
348    /// Sets and sanitizes inclusive minimum/maximum bounds.
349    ///
350    /// Reversed bounds swap; any non-finite bound resets both to `0..=100`;
351    /// equal bounds are widened upward by one when representable.
352    ///
353    /// # Examples
354    ///
355    /// ```
356    /// use ailloli_ui_widgets::controls::Slider;
357    /// let slider: Slider<()> = Slider::new().range(-1.0, 1.0);
358    /// let _ = slider;
359    /// ```
360    pub fn range(mut self, min: f32, max: f32) -> Self {
361        self.spec.min = min;
362        self.spec.max = max;
363        self.spec = self.spec.sanitized();
364        self
365    }
366
367    /// Sets and sanitizes the snapping interval.
368    ///
369    /// A non-positive or non-finite step becomes continuous (`None`). Valid
370    /// values round to the nearest step relative to the minimum.
371    ///
372    /// # Examples
373    ///
374    /// ```
375    /// use ailloli_ui_widgets::controls::Slider;
376    /// let slider: Slider<()> = Slider::new().step(5.0);
377    /// let _ = slider;
378    /// ```
379    pub fn step(mut self, step: f32) -> Self {
380        self.spec.step = Some(step);
381        self.spec = self.spec.sanitized();
382        self
383    }
384
385    /// Replaces and sanitizes the complete numeric specification.
386    ///
387    /// # Examples
388    ///
389    /// ```
390    /// use ailloli_ui_core::SliderSpec;
391    /// use ailloli_ui_widgets::controls::Slider;
392    /// let slider: Slider<()> = Slider::new().slider_spec(SliderSpec::new(0.0, 10.0).with_step(2.0));
393    /// let _ = slider;
394    /// ```
395    pub fn slider_spec(mut self, spec: SliderSpec) -> Self {
396        self.spec = spec.sanitized();
397        self
398    }
399
400    /// Sets horizontal or bottom-to-top vertical orientation.
401    ///
402    /// # Examples
403    ///
404    /// ```
405    /// use ailloli_ui_widgets::controls::{Slider, SliderOrientation};
406    /// let slider: Slider<()> = Slider::new().orientation(SliderOrientation::Vertical);
407    /// let _ = slider;
408    /// ```
409    pub fn orientation(mut self, orientation: SliderOrientation) -> Self {
410        self.orientation = orientation;
411        self
412    }
413
414    /// Replaces complete colors and geometry without changing layout size.
415    ///
416    /// Unlike [`Self::slider_size`], this does not rewrite explicit layout
417    /// dimensions; intrinsic values apply when layout remains automatic.
418    ///
419    /// # Examples
420    ///
421    /// ```
422    /// use ailloli_ui_widgets::controls::{Slider, SliderStyle};
423    /// let slider: Slider<()> = Slider::new().slider_style(SliderStyle::default());
424    /// let _ = slider;
425    /// ```
426    pub fn slider_style(mut self, style: SliderStyle) -> Self {
427        self.style = style;
428        self
429    }
430
431    /// Replaces style with a default-theme built-in size.
432    ///
433    /// # Examples
434    ///
435    /// ```
436    /// use ailloli_ui_widgets::controls::{Slider, SliderSize};
437    /// let slider: Slider<()> = Slider::new().slider_size(SliderSize::Compact);
438    /// let _ = slider;
439    /// ```
440    pub fn slider_size(mut self, size: SliderSize) -> Self {
441        self.style = SliderStyle::from_theme(Theme::default(), size);
442        self
443    }
444
445    /// Maps each changed, clamped/snapped value to an application action.
446    ///
447    /// The callback does not make a controlled value writable; use [`Self::bind`]
448    /// for two-way state. A later callback builder replaces it.
449    ///
450    /// # Examples
451    ///
452    /// ```
453    /// use ailloli_ui_widgets::controls::Slider;
454    /// #[derive(Clone)]
455    /// enum Action { Changed(f32) }
456    /// let slider = Slider::new().on_change(Action::Changed);
457    /// let _ = slider;
458    /// ```
459    pub fn on_change(mut self, f: impl Fn(f32) -> A + 'static) -> Self {
460        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
461        self
462    }
463
464    /// Installs a context-aware changed-value handler.
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// use ailloli_ui_widgets::controls::Slider;
470    /// let slider = Slider::<()>::new().on_change_ctx(|_ctx, value| assert!(value.is_finite()));
471    /// let _ = slider;
472    /// ```
473    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, f32) + 'static) -> Self {
474        self.on_change = Some(Rc::new(f));
475        self
476    }
477}
478
479/// A two-thumb slider representing an ordered inclusive subrange.
480///
481/// Source values are clamped, snapped, and ordered for display. Moving a thumb
482/// cannot cross the other; both may meet at a zero-width range. Pointer presses
483/// choose the nearest thumb (ties choose the end), while keyboard input defaults
484/// to the end thumb until another thumb becomes active.
485///
486/// # Examples
487///
488/// ```
489/// use ailloli_ui_core::SliderRangeValue;
490/// use ailloli_ui_widgets::controls::RangeSlider;
491/// let slider: RangeSlider<()> = RangeSlider::new()
492///     .range(0.0, 100.0)
493///     .values(SliderRangeValue::new(20.0, 80.0));
494/// let _ = slider;
495/// ```
496pub struct RangeSlider<A = ()> {
497    /// Layout configuration applied to intrinsic slider geometry.
498    pub(crate) layout: LayoutStyle,
499    /// Flex behavior used by the parent layout.
500    pub(crate) flex_item: FlexItemStyle,
501    /// Static or reactive controlled ordered range.
502    values: Binding<SliderRangeValue>,
503    /// Writable range signal in bound mode.
504    bound: Option<Signal<SliderRangeValue>>,
505    /// Live disabled state.
506    disabled: Binding<bool>,
507    /// Sanitized numeric domain and optional step.
508    spec: SliderSpec,
509    /// Axis and value direction.
510    orientation: SliderOrientation,
511    /// Optional ordered-range change notification.
512    on_change: Option<RangeChangeHandler<A>>,
513    /// Resolved paint and geometry.
514    style: SliderStyle,
515}
516
517crate::impl_layout_builders!(RangeSlider);
518
519impl<A: 'static> Default for RangeSlider<A> {
520    fn default() -> Self {
521        Self::new()
522    }
523}
524
525impl<A: 'static> RangeSlider<A> {
526    /// Creates a horizontal `0..=100` slider selecting `25..=75`.
527    ///
528    /// It is enabled but read-only until bound or given a change callback.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// use ailloli_ui_widgets::controls::RangeSlider;
534    /// let slider: RangeSlider<()> = RangeSlider::new();
535    /// let _ = slider;
536    /// ```
537    pub fn new() -> Self {
538        Self {
539            layout: LayoutStyle::default(),
540            flex_item: FlexItemStyle::default(),
541            values: Binding::Static(SliderRangeValue::new(25.0, 75.0)),
542            bound: None,
543            disabled: Binding::Static(false),
544            spec: SliderSpec::default(),
545            orientation: SliderOrientation::Horizontal,
546            on_change: None,
547            style: SliderStyle::default(),
548        }
549    }
550
551    /// Creates a default range slider increasing bottom-to-top.
552    ///
553    /// # Examples
554    ///
555    /// ```
556    /// use ailloli_ui_widgets::controls::RangeSlider;
557    /// let slider: RangeSlider<()> = RangeSlider::vertical();
558    /// let _ = slider;
559    /// ```
560    pub fn vertical() -> Self {
561        Self::new().orientation(SliderOrientation::Vertical)
562    }
563
564    /// Sets static or reactive controlled values and clears bound mode.
565    ///
566    /// Display clamps, snaps, and orders endpoints without mutating this source.
567    ///
568    /// # Examples
569    ///
570    /// ```
571    /// use ailloli_ui_core::SliderRangeValue;
572    /// use ailloli_ui_widgets::controls::RangeSlider;
573    /// let slider: RangeSlider<()> = RangeSlider::new().values(SliderRangeValue::new(80.0, 20.0));
574    /// let _ = slider;
575    /// ```
576    pub fn values(mut self, values: impl Into<Binding<SliderRangeValue>>) -> Self {
577        self.values = values.into();
578        self.bound = None;
579        self
580    }
581
582    /// Installs a writable signal for two-way ordered-range interaction.
583    ///
584    /// # Examples
585    ///
586    /// ```
587    /// use std::{cell::RefCell, rc::Rc};
588    /// use ailloli_ui_core::SliderRangeValue;
589    /// use ailloli_ui_runtime::component::Signal;
590    /// use ailloli_ui_widgets::controls::RangeSlider;
591    /// let values = Signal::new(Rc::new(RefCell::new(SliderRangeValue::new(20.0, 80.0))), Rc::new(|| {}));
592    /// let slider: RangeSlider<()> = RangeSlider::new().bind(values);
593    /// let _ = slider;
594    /// ```
595    pub fn bind(mut self, values: impl Into<Signal<SliderRangeValue>>) -> Self {
596        let signal = values.into();
597        self.values = Binding::Signal(signal.clone());
598        self.bound = Some(signal);
599        self
600    }
601
602    /// Sets static or reactive disabled state.
603    ///
604    /// Disabled sliders are not focusable and ignore pointer/keyboard input.
605    ///
606    /// # Examples
607    ///
608    /// ```
609    /// use ailloli_ui_widgets::controls::RangeSlider;
610    /// let slider: RangeSlider<()> = RangeSlider::new().disabled(true);
611    /// let _ = slider;
612    /// ```
613    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
614        self.disabled = disabled.into();
615        self
616    }
617
618    /// Sets disabled state from a derived memo.
619    ///
620    /// # Examples
621    ///
622    /// ```
623    /// use ailloli_ui_runtime::component::Memo;
624    /// use ailloli_ui_widgets::controls::RangeSlider;
625    /// let slider: RangeSlider<()> = RangeSlider::new().disabled_signal(Memo::new(|| false));
626    /// let _ = slider;
627    /// ```
628    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
629        self.disabled(disabled)
630    }
631
632    /// Sets and sanitizes inclusive minimum/maximum bounds.
633    ///
634    /// Reversed bounds swap; any non-finite bound resets both to `0..=100`;
635    /// equal bounds are widened upward by one when representable.
636    ///
637    /// # Examples
638    ///
639    /// ```
640    /// use ailloli_ui_widgets::controls::RangeSlider;
641    /// let slider: RangeSlider<()> = RangeSlider::new().range(-50.0, 50.0);
642    /// let _ = slider;
643    /// ```
644    pub fn range(mut self, min: f32, max: f32) -> Self {
645        self.spec.min = min;
646        self.spec.max = max;
647        self.spec = self.spec.sanitized();
648        self
649    }
650
651    /// Sets and sanitizes the snapping interval.
652    ///
653    /// A non-positive or non-finite step restores continuous behavior.
654    ///
655    /// # Examples
656    ///
657    /// ```
658    /// use ailloli_ui_widgets::controls::RangeSlider;
659    /// let slider: RangeSlider<()> = RangeSlider::new().step(10.0);
660    /// let _ = slider;
661    /// ```
662    pub fn step(mut self, step: f32) -> Self {
663        self.spec.step = Some(step);
664        self.spec = self.spec.sanitized();
665        self
666    }
667
668    /// Replaces and sanitizes the complete numeric specification.
669    ///
670    /// # Examples
671    ///
672    /// ```
673    /// use ailloli_ui_core::SliderSpec;
674    /// use ailloli_ui_widgets::controls::RangeSlider;
675    /// let slider: RangeSlider<()> = RangeSlider::new().slider_spec(SliderSpec::new(0.0, 1.0));
676    /// let _ = slider;
677    /// ```
678    pub fn slider_spec(mut self, spec: SliderSpec) -> Self {
679        self.spec = spec.sanitized();
680        self
681    }
682
683    /// Sets horizontal or bottom-to-top vertical orientation.
684    ///
685    /// # Examples
686    ///
687    /// ```
688    /// use ailloli_ui_widgets::controls::{RangeSlider, SliderOrientation};
689    /// let slider: RangeSlider<()> = RangeSlider::new().orientation(SliderOrientation::Vertical);
690    /// let _ = slider;
691    /// ```
692    pub fn orientation(mut self, orientation: SliderOrientation) -> Self {
693        self.orientation = orientation;
694        self
695    }
696
697    /// Replaces complete colors and intrinsic geometry.
698    ///
699    /// # Examples
700    ///
701    /// ```
702    /// use ailloli_ui_widgets::controls::{RangeSlider, SliderStyle};
703    /// let slider: RangeSlider<()> = RangeSlider::new().slider_style(SliderStyle::default());
704    /// let _ = slider;
705    /// ```
706    pub fn slider_style(mut self, style: SliderStyle) -> Self {
707        self.style = style;
708        self
709    }
710
711    /// Replaces style with a default-theme built-in size.
712    ///
713    /// # Examples
714    ///
715    /// ```
716    /// use ailloli_ui_widgets::controls::{RangeSlider, SliderSize};
717    /// let slider: RangeSlider<()> = RangeSlider::new().slider_size(SliderSize::Compact);
718    /// let _ = slider;
719    /// ```
720    pub fn slider_size(mut self, size: SliderSize) -> Self {
721        self.style = SliderStyle::from_theme(Theme::default(), size);
722        self
723    }
724
725    /// Maps each changed ordered range to an application action.
726    ///
727    /// The callback does not make a controlled source writable; use [`Self::bind`]
728    /// for two-way state.
729    ///
730    /// # Examples
731    ///
732    /// ```
733    /// use ailloli_ui_core::SliderRangeValue;
734    /// use ailloli_ui_widgets::controls::RangeSlider;
735    /// #[derive(Clone)]
736    /// enum Action { Changed(SliderRangeValue) }
737    /// let slider = RangeSlider::new().on_change(Action::Changed);
738    /// let _ = slider;
739    /// ```
740    pub fn on_change(mut self, f: impl Fn(SliderRangeValue) -> A + 'static) -> Self {
741        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
742        self
743    }
744
745    /// Installs a context-aware ordered-range handler.
746    ///
747    /// # Examples
748    ///
749    /// ```
750    /// use ailloli_ui_widgets::controls::RangeSlider;
751    /// let slider = RangeSlider::<()>::new()
752    ///     .on_change_ctx(|_ctx, range| assert!(range.start <= range.end));
753    /// let _ = slider;
754    /// ```
755    pub fn on_change_ctx(
756        mut self,
757        f: impl Fn(&mut EventCtx<A>, SliderRangeValue) + 'static,
758    ) -> Self {
759        self.on_change = Some(Rc::new(f));
760        self
761    }
762}
763
764/// Component properties used to allocate single-thumb drag state.
765struct SliderComponent<A> {
766    /// Outer logical sizing policy.
767    layout: LayoutStyle,
768    /// Readable scalar value.
769    value: Binding<f32>,
770    /// Optional writable scalar value.
771    bound: Option<Signal<f32>>,
772    /// Reactive interaction-disable flag.
773    disabled: Binding<bool>,
774    /// Finite range, step, and normalization policy.
775    spec: SliderSpec,
776    /// Horizontal or vertical track orientation.
777    orientation: SliderOrientation,
778    /// Optional callback receiving normalized stepped values.
779    on_change: Option<SliderChangeHandler<A>>,
780    /// Track/thumb colors and logical-pixel geometry.
781    style: SliderStyle,
782}
783
784/// Component properties used to allocate active range-thumb state.
785struct RangeSliderComponent<A> {
786    /// Outer logical sizing policy.
787    layout: LayoutStyle,
788    /// Readable lower/upper values.
789    values: Binding<SliderRangeValue>,
790    /// Optional writable lower/upper values.
791    bound: Option<Signal<SliderRangeValue>>,
792    /// Reactive interaction-disable flag.
793    disabled: Binding<bool>,
794    /// Finite range, step, and normalization policy.
795    spec: SliderSpec,
796    /// Horizontal or vertical track orientation.
797    orientation: SliderOrientation,
798    /// Optional callback receiving normalized stepped value pairs.
799    on_change: Option<RangeChangeHandler<A>>,
800    /// Track/thumb colors and logical-pixel geometry.
801    style: SliderStyle,
802}
803
804impl<A: 'static> ComponentNode<A> for SliderComponent<A> {
805    fn build(&self, context: &mut Context<A>) -> View<A> {
806        View::leaf(SliderWidget {
807            layout: self.layout,
808            value: self.value.clone(),
809            bound: self.bound.clone(),
810            disabled: self.disabled.clone(),
811            spec: self.spec,
812            orientation: self.orientation,
813            on_change: self.on_change.clone(),
814            style: self.style.clone(),
815            dragging: context.signal(false),
816        })
817    }
818}
819
820impl<A: 'static> ComponentNode<A> for RangeSliderComponent<A> {
821    fn build(&self, context: &mut Context<A>) -> View<A> {
822        View::leaf(RangeSliderWidget {
823            layout: self.layout,
824            values: self.values.clone(),
825            bound: self.bound.clone(),
826            disabled: self.disabled.clone(),
827            spec: self.spec,
828            orientation: self.orientation,
829            on_change: self.on_change.clone(),
830            style: self.style.clone(),
831            active_thumb: context.signal(None),
832        })
833    }
834}
835
836/// Retained single-thumb widget implementing paint and interaction.
837struct SliderWidget<A> {
838    /// Outer logical sizing policy.
839    layout: LayoutStyle,
840    /// Readable scalar value.
841    value: Binding<f32>,
842    /// Optional writable scalar value.
843    bound: Option<Signal<f32>>,
844    /// Reactive interaction-disable flag.
845    disabled: Binding<bool>,
846    /// Finite range, step, and normalization policy.
847    spec: SliderSpec,
848    /// Horizontal or vertical track orientation.
849    orientation: SliderOrientation,
850    /// Optional retained change callback.
851    on_change: Option<SliderChangeHandler<A>>,
852    /// Track/thumb colors and logical-pixel geometry.
853    style: SliderStyle,
854    /// Whether this slider currently owns a captured pointer drag.
855    dragging: Signal<bool>,
856}
857
858/// Retained range widget implementing nearest-thumb interaction.
859struct RangeSliderWidget<A> {
860    /// Outer logical sizing policy.
861    layout: LayoutStyle,
862    /// Readable lower/upper values.
863    values: Binding<SliderRangeValue>,
864    /// Optional writable lower/upper values.
865    bound: Option<Signal<SliderRangeValue>>,
866    /// Reactive interaction-disable flag.
867    disabled: Binding<bool>,
868    /// Finite range, step, and normalization policy.
869    spec: SliderSpec,
870    /// Horizontal or vertical track orientation.
871    orientation: SliderOrientation,
872    /// Optional retained change callback.
873    on_change: Option<RangeChangeHandler<A>>,
874    /// Track/thumb colors and logical-pixel geometry.
875    style: SliderStyle,
876    /// Lower or upper thumb currently captured by pointer input.
877    active_thumb: Signal<Option<SliderThumb>>,
878}
879
880impl<A: 'static> Widget<A> for SliderWidget<A> {
881    fn debug_name(&self) -> &'static str {
882        "Slider"
883    }
884
885    fn layout(
886        &self,
887        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
888        _ctx: &mut LayoutCtx<'_>,
889        _children: &mut [LayoutChild],
890        constraints: Constraints,
891    ) -> LayoutResult {
892        slider_layout_result(
893            self.style.intrinsic_size(self.orientation),
894            self.layout,
895            constraints,
896            &self.style,
897        )
898    }
899
900    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
901        let value = self.spec.snap_value(self.value.read());
902        let disabled = self.disabled.read();
903        paint_slider(
904            ctx,
905            SliderPaintParams {
906                bounds,
907                orientation: self.orientation,
908                spec: self.spec,
909                value: SliderPaintValue::Single(value),
910                disabled,
911                dragging: self.dragging.read(),
912                style: &self.style,
913            },
914        );
915    }
916
917    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
918        if self.disabled.read() {
919            return;
920        }
921
922        match event {
923            Event::Pointer(PointerEvent::Button {
924                pos,
925                button: MouseButton::Left,
926                pressed: true,
927                ..
928            }) if bounds.contains(pos.x, pos.y) => {
929                self.dragging.set(true);
930                self.set_from_point(ctx, bounds, pos.x, pos.y);
931                ctx.request_repaint();
932                ctx.stop_propagation();
933            }
934            Event::Pointer(PointerEvent::Button {
935                button: MouseButton::Left,
936                pressed: false,
937                ..
938            }) if self.dragging.read() => {
939                self.dragging.set(false);
940                ctx.request_repaint();
941                ctx.stop_propagation();
942            }
943            Event::Pointer(PointerEvent::Moved { pos, .. }) if self.dragging.read() => {
944                self.set_from_point(ctx, bounds, pos.x, pos.y);
945                ctx.stop_propagation();
946            }
947            Event::Pointer(PointerEvent::Cancelled { .. }) if self.dragging.read() => {
948                self.dragging.set(false);
949                ctx.request_repaint();
950                ctx.stop_propagation();
951            }
952            Event::Keyboard(key) if key.state == KeyState::Pressed => {
953                if let Some(next) = slider_key_value(self.spec, self.value.read(), &key.key) {
954                    self.set_value(ctx, next);
955                }
956            }
957            _ => {}
958        }
959    }
960
961    fn focus_policy(&self) -> FocusPolicy {
962        if self.disabled.read() {
963            FocusPolicy::NotFocusable
964        } else {
965            FocusPolicy::Focusable
966        }
967    }
968
969    fn activation_policy(&self) -> ActivationPolicy {
970        ActivationPolicy::AllowOnFocusOnly
971    }
972}
973
974impl<A: 'static> SliderWidget<A> {
975    /// Maps a pointer position to the numeric domain and applies it.
976    fn set_from_point(&self, ctx: &mut EventCtx<A>, bounds: Rect, x: f32, y: f32) {
977        let fraction = fraction_at_point(bounds, self.orientation, &self.style, x, y);
978        self.set_value(ctx, self.spec.value_for_fraction(fraction));
979    }
980
981    /// Writes/notifies a distinct snapped value when an output path exists.
982    fn set_value(&self, ctx: &mut EventCtx<A>, next: f32) {
983        if self.bound.is_none() && self.on_change.is_none() {
984            return;
985        }
986
987        let next = self.spec.snap_value(next);
988        if values_equal(self.spec.snap_value(self.value.read()), next) {
989            return;
990        }
991
992        if let Some(bound) = &self.bound {
993            bound.set(next);
994        }
995        if let Some(on_change) = &self.on_change {
996            on_change(ctx, next);
997        }
998        ctx.request_repaint();
999        ctx.stop_propagation();
1000    }
1001}
1002
1003impl<A: 'static> Widget<A> for RangeSliderWidget<A> {
1004    fn debug_name(&self) -> &'static str {
1005        "RangeSlider"
1006    }
1007
1008    fn layout(
1009        &self,
1010        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1011        _ctx: &mut LayoutCtx<'_>,
1012        _children: &mut [LayoutChild],
1013        constraints: Constraints,
1014    ) -> LayoutResult {
1015        slider_layout_result(
1016            self.style.intrinsic_size(self.orientation),
1017            self.layout,
1018            constraints,
1019            &self.style,
1020        )
1021    }
1022
1023    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
1024        let values = self.spec.clamp_range_value(self.values.read());
1025        let disabled = self.disabled.read();
1026        paint_slider(
1027            ctx,
1028            SliderPaintParams {
1029                bounds,
1030                orientation: self.orientation,
1031                spec: self.spec,
1032                value: SliderPaintValue::Range(values),
1033                disabled,
1034                dragging: self.active_thumb.read().is_some(),
1035                style: &self.style,
1036            },
1037        );
1038    }
1039
1040    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1041        if self.disabled.read() {
1042            return;
1043        }
1044
1045        match event {
1046            Event::Pointer(PointerEvent::Button {
1047                pos,
1048                button: MouseButton::Left,
1049                pressed: true,
1050                ..
1051            }) if bounds.contains(pos.x, pos.y) => {
1052                let fraction =
1053                    fraction_at_point(bounds, self.orientation, &self.style, pos.x, pos.y);
1054                let target = self.spec.value_for_fraction(fraction);
1055                let thumb = self.spec.nearest_thumb(self.values.read(), target);
1056                self.active_thumb.set(Some(thumb));
1057                self.set_thumb_value(ctx, thumb, target);
1058                ctx.request_repaint();
1059                ctx.stop_propagation();
1060            }
1061            Event::Pointer(PointerEvent::Button {
1062                button: MouseButton::Left,
1063                pressed: false,
1064                ..
1065            }) if self.active_thumb.read().is_some() => {
1066                self.active_thumb.set(None);
1067                ctx.request_repaint();
1068                ctx.stop_propagation();
1069            }
1070            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
1071                if let Some(thumb) = self.active_thumb.read() {
1072                    let fraction =
1073                        fraction_at_point(bounds, self.orientation, &self.style, pos.x, pos.y);
1074                    self.set_thumb_value(ctx, thumb, self.spec.value_for_fraction(fraction));
1075                    ctx.stop_propagation();
1076                }
1077            }
1078            Event::Pointer(PointerEvent::Cancelled { .. })
1079                if self.active_thumb.read().is_some() =>
1080            {
1081                self.active_thumb.set(None);
1082                ctx.request_repaint();
1083                ctx.stop_propagation();
1084            }
1085            Event::Keyboard(key) if key.state == KeyState::Pressed => {
1086                let thumb = self.active_thumb.read().unwrap_or(SliderThumb::End);
1087                let values = self.spec.clamp_range_value(self.values.read());
1088                let current = match thumb {
1089                    SliderThumb::Start => values.start,
1090                    SliderThumb::End => values.end,
1091                };
1092                if let Some(next) = slider_key_value(self.spec, current, &key.key) {
1093                    self.active_thumb.set(Some(thumb));
1094                    self.set_thumb_value(ctx, thumb, next);
1095                }
1096            }
1097            _ => {}
1098        }
1099    }
1100
1101    fn focus_policy(&self) -> FocusPolicy {
1102        if self.disabled.read() {
1103            FocusPolicy::NotFocusable
1104        } else {
1105            FocusPolicy::Focusable
1106        }
1107    }
1108
1109    fn activation_policy(&self) -> ActivationPolicy {
1110        ActivationPolicy::AllowOnFocusOnly
1111    }
1112}
1113
1114impl<A: 'static> RangeSliderWidget<A> {
1115    /// Moves one thumb without crossing and writes/notifies a distinct range.
1116    fn set_thumb_value(&self, ctx: &mut EventCtx<A>, thumb: SliderThumb, next: f32) {
1117        if self.bound.is_none() && self.on_change.is_none() {
1118            return;
1119        }
1120
1121        let before = self.spec.clamp_range_value(self.values.read());
1122        let after = self.spec.set_range_thumb(before, thumb, next);
1123        if range_values_equal(before, after) {
1124            return;
1125        }
1126
1127        if let Some(bound) = &self.bound {
1128            bound.set(after);
1129        }
1130        if let Some(on_change) = &self.on_change {
1131            on_change(ctx, after);
1132        }
1133        ctx.request_repaint();
1134        ctx.stop_propagation();
1135    }
1136}
1137
1138impl<A: 'static> IntoView<A> for Slider<A> {
1139    fn into_view(self) -> View<A> {
1140        finish_view_sized(
1141            View::component(SliderComponent {
1142                layout: self.layout,
1143                value: self.value,
1144                bound: self.bound,
1145                disabled: self.disabled,
1146                spec: self.spec,
1147                orientation: self.orientation,
1148                on_change: self.on_change,
1149                style: self.style,
1150            }),
1151            self.flex_item,
1152            LayoutSizeHint::from_layout(self.layout),
1153        )
1154    }
1155}
1156
1157impl<A: 'static> IntoView<A> for RangeSlider<A> {
1158    fn into_view(self) -> View<A> {
1159        finish_view_sized(
1160            View::component(RangeSliderComponent {
1161                layout: self.layout,
1162                values: self.values,
1163                bound: self.bound,
1164                disabled: self.disabled,
1165                spec: self.spec,
1166                orientation: self.orientation,
1167                on_change: self.on_change,
1168                style: self.style,
1169            }),
1170            self.flex_item,
1171            LayoutSizeHint::from_layout(self.layout),
1172        )
1173    }
1174}
1175
1176/// Builds childless layout and focus-ring-aware visual bounds.
1177fn slider_layout_result(
1178    intrinsic: Size,
1179    layout: LayoutStyle,
1180    constraints: Constraints,
1181    style: &SliderStyle,
1182) -> LayoutResult {
1183    let size = apply_layout_size(intrinsic, layout, constraints);
1184    let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1185    LayoutResult {
1186        size,
1187        children: Vec::new(),
1188        paint_bounds,
1189        visual_bounds: style.visual_bounds(paint_bounds),
1190        overlay_hit_bounds: Vec::new(),
1191        clip: None,
1192        is_window_root_clip: false,
1193        artifact: None,
1194    }
1195}
1196
1197/// Maps arrows/pages/Home/End to small, large, minimum, or maximum changes.
1198fn slider_key_value(spec: SliderSpec, value: f32, key: &Key) -> Option<f32> {
1199    match key {
1200        Key::Named(NamedKey::ArrowLeft) | Key::Named(NamedKey::ArrowDown) => {
1201            Some(spec.nudge_value(value, -1.0, false))
1202        }
1203        Key::Named(NamedKey::ArrowRight) | Key::Named(NamedKey::ArrowUp) => {
1204            Some(spec.nudge_value(value, 1.0, false))
1205        }
1206        Key::Named(NamedKey::PageDown) => Some(spec.nudge_value(value, -1.0, true)),
1207        Key::Named(NamedKey::PageUp) => Some(spec.nudge_value(value, 1.0, true)),
1208        Key::Named(NamedKey::Home) => Some(spec.sanitized().min),
1209        Key::Named(NamedKey::End) => Some(spec.sanitized().max),
1210        _ => None,
1211    }
1212}
1213
1214#[derive(Debug, Clone, Copy)]
1215/// Single value or ordered range passed to the shared painter.
1216enum SliderPaintValue {
1217    /// One thumb with active track from minimum.
1218    Single(f32),
1219    /// Two thumbs with active track between them.
1220    Range(SliderRangeValue),
1221}
1222
1223/// Complete borrowed parameter set for shared slider painting.
1224struct SliderPaintParams<'a> {
1225    /// Slider bounds in logical window coordinates.
1226    bounds: Rect,
1227    /// Horizontal or vertical track orientation.
1228    orientation: SliderOrientation,
1229    /// Finite range used to normalize paint positions.
1230    spec: SliderSpec,
1231    /// Scalar or lower/upper normalized values to paint.
1232    value: SliderPaintValue,
1233    /// Whether disabled opacity should be applied.
1234    disabled: bool,
1235    /// Whether active-drag styling should be applied.
1236    dragging: bool,
1237    /// Borrowed track/thumb visual configuration.
1238    style: &'a SliderStyle,
1239}
1240
1241/// Paints track, active range, optional ticks, thumbs, and focus ring.
1242fn paint_slider(ctx: &mut PaintCtx<'_>, params: SliderPaintParams<'_>) {
1243    let SliderPaintParams {
1244        bounds,
1245        orientation,
1246        spec,
1247        value,
1248        disabled,
1249        dragging,
1250        style,
1251    } = params;
1252    let interaction = ctx.interaction();
1253    let track = track_rect(bounds, orientation, style);
1254    let radius = Radius::uniform(style.track_thickness * 0.5);
1255    let track_color = if disabled {
1256        style.disabled_track
1257    } else if interaction.hovered {
1258        style.track_hovered
1259    } else {
1260        style.track
1261    };
1262    ctx.push(DrawCmd::RRect(DrawRRect {
1263        rect: track,
1264        radius: radius.tl,
1265        color: track_color,
1266    }));
1267
1268    let active_color = if disabled {
1269        style.disabled_active_track
1270    } else if interaction.hovered || dragging {
1271        style.active_track_hovered
1272    } else {
1273        style.active_track
1274    };
1275    let active = match value {
1276        SliderPaintValue::Single(value) => {
1277            active_rect_single(bounds, orientation, spec, value, style)
1278        }
1279        SliderPaintValue::Range(value) => {
1280            active_rect_range(bounds, orientation, spec, value, style)
1281        }
1282    };
1283    if active.w > 0.0 && active.h > 0.0 {
1284        ctx.push(DrawCmd::RRect(DrawRRect {
1285            rect: active,
1286            radius: radius.tl,
1287            color: active_color,
1288        }));
1289    }
1290
1291    paint_ticks(ctx, bounds, orientation, spec, style, disabled);
1292
1293    match value {
1294        SliderPaintValue::Single(value) => {
1295            paint_thumb(
1296                ctx,
1297                thumb_rect(bounds, orientation, spec, value, style),
1298                disabled,
1299                dragging,
1300                style,
1301            );
1302        }
1303        SliderPaintValue::Range(value) => {
1304            let value = spec.clamp_range_value(value);
1305            paint_thumb(
1306                ctx,
1307                thumb_rect(bounds, orientation, spec, value.start, style),
1308                disabled,
1309                dragging,
1310                style,
1311            );
1312            paint_thumb(
1313                ctx,
1314                thumb_rect(bounds, orientation, spec, value.end, style),
1315                disabled,
1316                dragging,
1317                style,
1318            );
1319        }
1320    }
1321
1322    if interaction.focused && !disabled && style.focus_ring.is_visible() {
1323        ctx.push(DrawCmd::Border(DrawBorder {
1324            rect: bounds.inflate(style.focus_ring_offset, style.focus_ring_offset),
1325            radius: Radius::uniform(style.thumb_size * 0.5 + style.focus_ring_offset),
1326            border: style.focus_ring,
1327        }));
1328    }
1329}
1330
1331/// Insets track endpoints by half a thumb and centers its thickness.
1332fn track_rect(bounds: Rect, orientation: SliderOrientation, style: &SliderStyle) -> Rect {
1333    match orientation {
1334        SliderOrientation::Horizontal => Rect::new(
1335            bounds.x + style.thumb_size * 0.5,
1336            bounds.y + (bounds.h - style.track_thickness) * 0.5,
1337            (bounds.w - style.thumb_size).max(0.0),
1338            style.track_thickness,
1339        ),
1340        SliderOrientation::Vertical => Rect::new(
1341            bounds.x + (bounds.w - style.track_thickness) * 0.5,
1342            bounds.y + style.thumb_size * 0.5,
1343            style.track_thickness,
1344            (bounds.h - style.thumb_size).max(0.0),
1345        ),
1346    }
1347}
1348
1349/// Maps a pointer to a clamped fraction, reversing the vertical axis.
1350fn fraction_at_point(
1351    bounds: Rect,
1352    orientation: SliderOrientation,
1353    style: &SliderStyle,
1354    x: f32,
1355    y: f32,
1356) -> f32 {
1357    let track = track_rect(bounds, orientation, style);
1358    match orientation {
1359        SliderOrientation::Horizontal => ((x - track.x) / track.w.max(1.0)).clamp(0.0, 1.0),
1360        SliderOrientation::Vertical => ((track.bottom() - y) / track.h.max(1.0)).clamp(0.0, 1.0),
1361    }
1362}
1363
1364/// Maps a clamped domain value to the appropriate track-axis coordinate.
1365fn point_for_value(
1366    bounds: Rect,
1367    orientation: SliderOrientation,
1368    spec: SliderSpec,
1369    value: f32,
1370    style: &SliderStyle,
1371) -> f32 {
1372    let track = track_rect(bounds, orientation, style);
1373    let fraction = spec.fraction_for_value(value);
1374    match orientation {
1375        SliderOrientation::Horizontal => track.x + track.w * fraction,
1376        SliderOrientation::Vertical => track.bottom() - track.h * fraction,
1377    }
1378}
1379
1380/// Returns active track from the minimum endpoint to a single value.
1381fn active_rect_single(
1382    bounds: Rect,
1383    orientation: SliderOrientation,
1384    spec: SliderSpec,
1385    value: f32,
1386    style: &SliderStyle,
1387) -> Rect {
1388    let track = track_rect(bounds, orientation, style);
1389    let point = point_for_value(bounds, orientation, spec, value, style);
1390    match orientation {
1391        SliderOrientation::Horizontal => {
1392            Rect::new(track.x, track.y, (point - track.x).max(0.0), track.h)
1393        }
1394        SliderOrientation::Vertical => {
1395            Rect::new(track.x, point, track.w, (track.bottom() - point).max(0.0))
1396        }
1397    }
1398}
1399
1400/// Returns active track between the two ordered/clamped range values.
1401fn active_rect_range(
1402    bounds: Rect,
1403    orientation: SliderOrientation,
1404    spec: SliderSpec,
1405    value: SliderRangeValue,
1406    style: &SliderStyle,
1407) -> Rect {
1408    let track = track_rect(bounds, orientation, style);
1409    let value = spec.clamp_range_value(value);
1410    let start = point_for_value(bounds, orientation, spec, value.start, style);
1411    let end = point_for_value(bounds, orientation, spec, value.end, style);
1412    match orientation {
1413        SliderOrientation::Horizontal => {
1414            Rect::new(start.min(end), track.y, (end - start).abs(), track.h)
1415        }
1416        SliderOrientation::Vertical => {
1417            Rect::new(track.x, end.min(start), track.w, (end - start).abs())
1418        }
1419    }
1420}
1421
1422/// Centers a square thumb on the track coordinate for a value.
1423fn thumb_rect(
1424    bounds: Rect,
1425    orientation: SliderOrientation,
1426    spec: SliderSpec,
1427    value: f32,
1428    style: &SliderStyle,
1429) -> Rect {
1430    let point = point_for_value(bounds, orientation, spec, value, style);
1431    match orientation {
1432        SliderOrientation::Horizontal => Rect::new(
1433            point - style.thumb_size * 0.5,
1434            bounds.y + (bounds.h - style.thumb_size) * 0.5,
1435            style.thumb_size,
1436            style.thumb_size,
1437        ),
1438        SliderOrientation::Vertical => Rect::new(
1439            bounds.x + (bounds.w - style.thumb_size) * 0.5,
1440            point - style.thumb_size * 0.5,
1441            style.thumb_size,
1442            style.thumb_size,
1443        ),
1444    }
1445}
1446
1447/// Paints interaction-state thumb fill and its optionally offset border.
1448fn paint_thumb(
1449    ctx: &mut PaintCtx<'_>,
1450    rect: Rect,
1451    disabled: bool,
1452    dragging: bool,
1453    style: &SliderStyle,
1454) {
1455    let interaction = ctx.interaction();
1456    let color = if disabled {
1457        style.disabled_thumb
1458    } else if dragging || interaction.pressed {
1459        style.thumb_pressed
1460    } else if interaction.hovered {
1461        style.thumb_hovered
1462    } else {
1463        style.thumb
1464    };
1465    ctx.push(DrawCmd::RRect(DrawRRect {
1466        rect,
1467        radius: style.thumb_size * 0.5,
1468        color,
1469    }));
1470    if style.border.is_visible() {
1471        let border_w = max_border_width(style.border);
1472        let inflate = style.thumb_border_offset + border_w;
1473        ctx.push(DrawCmd::Border(DrawBorder {
1474            rect: rect.inflate(inflate, inflate),
1475            radius: Radius::uniform(style.thumb_size * 0.5 + inflate),
1476            border: style.border,
1477        }));
1478    }
1479}
1480
1481/// Paints step ticks only when the rounded interval count is `1..=32`.
1482fn paint_ticks(
1483    ctx: &mut PaintCtx<'_>,
1484    bounds: Rect,
1485    orientation: SliderOrientation,
1486    spec: SliderSpec,
1487    style: &SliderStyle,
1488    disabled: bool,
1489) {
1490    let spec = spec.sanitized();
1491    let Some(step) = spec.step else {
1492        return;
1493    };
1494    let count = (spec.span() / step).round() as usize;
1495    if count == 0 || count > 32 {
1496        return;
1497    }
1498    let color = if disabled {
1499        style.tick.with_alpha(0.32)
1500    } else {
1501        style.tick
1502    };
1503    for idx in 0..=count {
1504        let value = spec.min + idx as f32 * step;
1505        let point = point_for_value(bounds, orientation, spec, value, style);
1506        let rect = match orientation {
1507            SliderOrientation::Horizontal => {
1508                Rect::new(point - 0.5, bounds.y + bounds.h * 0.5 - 5.0, 1.0, 10.0)
1509            }
1510            SliderOrientation::Vertical => {
1511                Rect::new(bounds.x + bounds.w * 0.5 - 5.0, point - 0.5, 10.0, 1.0)
1512            }
1513        };
1514        ctx.push(DrawCmd::Rect(DrawRect { rect, color }));
1515    }
1516}
1517
1518/// Compares two values using absolute [`f32::EPSILON`] tolerance.
1519fn values_equal(a: f32, b: f32) -> bool {
1520    (a - b).abs() <= f32::EPSILON
1521}
1522
1523/// Applies epsilon equality independently to both ordered endpoints.
1524fn range_values_equal(a: SliderRangeValue, b: SliderRangeValue) -> bool {
1525    values_equal(a.start, b.start) && values_equal(a.end, b.end)
1526}
1527
1528/// Returns the maximum of four per-edge border widths.
1529fn max_border_width(border: Border) -> f32 {
1530    border
1531        .widths
1532        .left
1533        .max(border.widths.top)
1534        .max(border.widths.right)
1535        .max(border.widths.bottom)
1536}