iced_widget/
slider.rs

1//! Sliders let users set a value by moving an indicator.
2//!
3//! # Example
4//! ```no_run
5//! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
6//! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
7//! #
8//! use iced::widget::slider;
9//!
10//! struct State {
11//!    value: f32,
12//! }
13//!
14//! #[derive(Debug, Clone)]
15//! enum Message {
16//!     ValueChanged(f32),
17//! }
18//!
19//! fn view(state: &State) -> Element<'_, Message> {
20//!     slider(0.0..=100.0, state.value, Message::ValueChanged).into()
21//! }
22//!
23//! fn update(state: &mut State, message: Message) {
24//!     match message {
25//!         Message::ValueChanged(value) => {
26//!             state.value = value;
27//!         }
28//!     }
29//! }
30//! ```
31use crate::core::border::{self, Border};
32use crate::core::keyboard;
33use crate::core::keyboard::key::{self, Key};
34use crate::core::layout;
35use crate::core::mouse;
36use crate::core::renderer;
37use crate::core::touch;
38use crate::core::widget::tree::{self, Tree};
39use crate::core::window;
40use crate::core::{
41    self, Background, Clipboard, Color, Element, Event, Layout, Length, Pixels,
42    Point, Rectangle, Shell, Size, Theme, Widget,
43};
44
45use std::ops::RangeInclusive;
46
47/// An horizontal bar and a handle that selects a single value from a range of
48/// values.
49///
50/// A [`Slider`] will try to fill the horizontal space of its container.
51///
52/// The [`Slider`] range of numeric values is generic and its step size defaults
53/// to 1 unit.
54///
55/// # Example
56/// ```no_run
57/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
58/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
59/// #
60/// use iced::widget::slider;
61///
62/// struct State {
63///    value: f32,
64/// }
65///
66/// #[derive(Debug, Clone)]
67/// enum Message {
68///     ValueChanged(f32),
69/// }
70///
71/// fn view(state: &State) -> Element<'_, Message> {
72///     slider(0.0..=100.0, state.value, Message::ValueChanged).into()
73/// }
74///
75/// fn update(state: &mut State, message: Message) {
76///     match message {
77///         Message::ValueChanged(value) => {
78///             state.value = value;
79///         }
80///     }
81/// }
82/// ```
83#[allow(missing_debug_implementations)]
84pub struct Slider<'a, T, Message, Theme = crate::Theme>
85where
86    Theme: Catalog,
87{
88    range: RangeInclusive<T>,
89    step: T,
90    shift_step: Option<T>,
91    value: T,
92    default: Option<T>,
93    on_change: Box<dyn Fn(T) -> Message + 'a>,
94    on_release: Option<Message>,
95    width: Length,
96    height: f32,
97    class: Theme::Class<'a>,
98    status: Option<Status>,
99}
100
101impl<'a, T, Message, Theme> Slider<'a, T, Message, Theme>
102where
103    T: Copy + From<u8> + PartialOrd,
104    Message: Clone,
105    Theme: Catalog,
106{
107    /// The default height of a [`Slider`].
108    pub const DEFAULT_HEIGHT: f32 = 16.0;
109
110    /// Creates a new [`Slider`].
111    ///
112    /// It expects:
113    ///   * an inclusive range of possible values
114    ///   * the current value of the [`Slider`]
115    ///   * a function that will be called when the [`Slider`] is dragged.
116    ///     It receives the new value of the [`Slider`] and must produce a
117    ///     `Message`.
118    pub fn new<F>(range: RangeInclusive<T>, value: T, on_change: F) -> Self
119    where
120        F: 'a + Fn(T) -> Message,
121    {
122        let value = if value >= *range.start() {
123            value
124        } else {
125            *range.start()
126        };
127
128        let value = if value <= *range.end() {
129            value
130        } else {
131            *range.end()
132        };
133
134        Slider {
135            value,
136            default: None,
137            range,
138            step: T::from(1),
139            shift_step: None,
140            on_change: Box::new(on_change),
141            on_release: None,
142            width: Length::Fill,
143            height: Self::DEFAULT_HEIGHT,
144            class: Theme::default(),
145            status: None,
146        }
147    }
148
149    /// Sets the optional default value for the [`Slider`].
150    ///
151    /// If set, the [`Slider`] will reset to this value when ctrl-clicked or command-clicked.
152    pub fn default(mut self, default: impl Into<T>) -> Self {
153        self.default = Some(default.into());
154        self
155    }
156
157    /// Sets the release message of the [`Slider`].
158    /// This is called when the mouse is released from the slider.
159    ///
160    /// Typically, the user's interaction with the slider is finished when this message is produced.
161    /// This is useful if you need to spawn a long-running task from the slider's result, where
162    /// the default on_change message could create too many events.
163    pub fn on_release(mut self, on_release: Message) -> Self {
164        self.on_release = Some(on_release);
165        self
166    }
167
168    /// Sets the width of the [`Slider`].
169    pub fn width(mut self, width: impl Into<Length>) -> Self {
170        self.width = width.into();
171        self
172    }
173
174    /// Sets the height of the [`Slider`].
175    pub fn height(mut self, height: impl Into<Pixels>) -> Self {
176        self.height = height.into().0;
177        self
178    }
179
180    /// Sets the step size of the [`Slider`].
181    pub fn step(mut self, step: impl Into<T>) -> Self {
182        self.step = step.into();
183        self
184    }
185
186    /// Sets the optional "shift" step for the [`Slider`].
187    ///
188    /// If set, this value is used as the step while the shift key is pressed.
189    pub fn shift_step(mut self, shift_step: impl Into<T>) -> Self {
190        self.shift_step = Some(shift_step.into());
191        self
192    }
193
194    /// Sets the style of the [`Slider`].
195    #[must_use]
196    pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
197    where
198        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
199    {
200        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
201        self
202    }
203
204    /// Sets the style class of the [`Slider`].
205    #[cfg(feature = "advanced")]
206    #[must_use]
207    pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
208        self.class = class.into();
209        self
210    }
211}
212
213impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
214    for Slider<'_, T, Message, Theme>
215where
216    T: Copy + Into<f64> + num_traits::FromPrimitive,
217    Message: Clone,
218    Theme: Catalog,
219    Renderer: core::Renderer,
220{
221    fn tag(&self) -> tree::Tag {
222        tree::Tag::of::<State>()
223    }
224
225    fn state(&self) -> tree::State {
226        tree::State::new(State::default())
227    }
228
229    fn size(&self) -> Size<Length> {
230        Size {
231            width: self.width,
232            height: Length::Shrink,
233        }
234    }
235
236    fn layout(
237        &self,
238        _tree: &mut Tree,
239        _renderer: &Renderer,
240        limits: &layout::Limits,
241    ) -> layout::Node {
242        layout::atomic(limits, self.width, self.height)
243    }
244
245    fn update(
246        &mut self,
247        tree: &mut Tree,
248        event: &Event,
249        layout: Layout<'_>,
250        cursor: mouse::Cursor,
251        _renderer: &Renderer,
252        _clipboard: &mut dyn Clipboard,
253        shell: &mut Shell<'_, Message>,
254        _viewport: &Rectangle,
255    ) {
256        let state = tree.state.downcast_mut::<State>();
257
258        let mut update = || {
259            let current_value = self.value;
260
261            let locate = |cursor_position: Point| -> Option<T> {
262                let bounds = layout.bounds();
263
264                if cursor_position.x <= bounds.x {
265                    Some(*self.range.start())
266                } else if cursor_position.x >= bounds.x + bounds.width {
267                    Some(*self.range.end())
268                } else {
269                    let step = if state.keyboard_modifiers.shift() {
270                        self.shift_step.unwrap_or(self.step)
271                    } else {
272                        self.step
273                    }
274                    .into();
275
276                    let start = (*self.range.start()).into();
277                    let end = (*self.range.end()).into();
278
279                    let percent = f64::from(cursor_position.x - bounds.x)
280                        / f64::from(bounds.width);
281
282                    let steps = (percent * (end - start) / step).round();
283                    let value = steps * step + start;
284
285                    T::from_f64(value.min(end))
286                }
287            };
288
289            let increment = |value: T| -> Option<T> {
290                let step = if state.keyboard_modifiers.shift() {
291                    self.shift_step.unwrap_or(self.step)
292                } else {
293                    self.step
294                }
295                .into();
296
297                let steps = (value.into() / step).round();
298                let new_value = step * (steps + 1.0);
299
300                if new_value > (*self.range.end()).into() {
301                    return Some(*self.range.end());
302                }
303
304                T::from_f64(new_value)
305            };
306
307            let decrement = |value: T| -> Option<T> {
308                let step = if state.keyboard_modifiers.shift() {
309                    self.shift_step.unwrap_or(self.step)
310                } else {
311                    self.step
312                }
313                .into();
314
315                let steps = (value.into() / step).round();
316                let new_value = step * (steps - 1.0);
317
318                if new_value < (*self.range.start()).into() {
319                    return Some(*self.range.start());
320                }
321
322                T::from_f64(new_value)
323            };
324
325            let change = |new_value: T| {
326                if (self.value.into() - new_value.into()).abs() > f64::EPSILON {
327                    shell.publish((self.on_change)(new_value));
328
329                    self.value = new_value;
330                }
331            };
332
333            match &event {
334                Event::Mouse(mouse::Event::ButtonPressed(
335                    mouse::Button::Left,
336                ))
337                | Event::Touch(touch::Event::FingerPressed { .. }) => {
338                    if let Some(cursor_position) =
339                        cursor.position_over(layout.bounds())
340                    {
341                        if state.keyboard_modifiers.command() {
342                            let _ = self.default.map(change);
343                            state.is_dragging = false;
344                        } else {
345                            let _ = locate(cursor_position).map(change);
346                            state.is_dragging = true;
347                        }
348
349                        shell.capture_event();
350                    }
351                }
352                Event::Mouse(mouse::Event::ButtonReleased(
353                    mouse::Button::Left,
354                ))
355                | Event::Touch(touch::Event::FingerLifted { .. })
356                | Event::Touch(touch::Event::FingerLost { .. }) => {
357                    if state.is_dragging {
358                        if let Some(on_release) = self.on_release.clone() {
359                            shell.publish(on_release);
360                        }
361                        state.is_dragging = false;
362
363                        shell.capture_event();
364                    }
365                }
366                Event::Mouse(mouse::Event::CursorMoved { .. })
367                | Event::Touch(touch::Event::FingerMoved { .. }) => {
368                    if state.is_dragging {
369                        let _ = cursor.position().and_then(locate).map(change);
370
371                        shell.capture_event();
372                    }
373                }
374                Event::Mouse(mouse::Event::WheelScrolled { delta })
375                    if state.keyboard_modifiers.control() =>
376                {
377                    if cursor.is_over(layout.bounds()) {
378                        let delta = match delta {
379                            mouse::ScrollDelta::Lines { x: _, y } => y,
380                            mouse::ScrollDelta::Pixels { x: _, y } => y,
381                        };
382
383                        if *delta < 0.0 {
384                            let _ = decrement(current_value).map(change);
385                        } else {
386                            let _ = increment(current_value).map(change);
387                        }
388
389                        shell.capture_event();
390                    }
391                }
392                Event::Keyboard(keyboard::Event::KeyPressed {
393                    key, ..
394                }) => {
395                    if cursor.is_over(layout.bounds()) {
396                        match key {
397                            Key::Named(key::Named::ArrowUp) => {
398                                let _ = increment(current_value).map(change);
399                            }
400                            Key::Named(key::Named::ArrowDown) => {
401                                let _ = decrement(current_value).map(change);
402                            }
403                            _ => (),
404                        }
405
406                        shell.capture_event();
407                    }
408                }
409                Event::Keyboard(keyboard::Event::ModifiersChanged(
410                    modifiers,
411                )) => {
412                    state.keyboard_modifiers = *modifiers;
413                }
414                _ => {}
415            }
416        };
417
418        update();
419
420        let current_status = if state.is_dragging {
421            Status::Dragged
422        } else if cursor.is_over(layout.bounds()) {
423            Status::Hovered
424        } else {
425            Status::Active
426        };
427
428        if let Event::Window(window::Event::RedrawRequested(_now)) = event {
429            self.status = Some(current_status);
430        } else if self.status.is_some_and(|status| status != current_status) {
431            shell.request_redraw();
432        }
433    }
434
435    fn draw(
436        &self,
437        _tree: &Tree,
438        renderer: &mut Renderer,
439        theme: &Theme,
440        _style: &renderer::Style,
441        layout: Layout<'_>,
442        _cursor: mouse::Cursor,
443        _viewport: &Rectangle,
444    ) {
445        let bounds = layout.bounds();
446
447        let style =
448            theme.style(&self.class, self.status.unwrap_or(Status::Active));
449
450        let (handle_width, handle_height, handle_border_radius) =
451            match style.handle.shape {
452                HandleShape::Circle { radius } => {
453                    (radius * 2.0, radius * 2.0, radius.into())
454                }
455                HandleShape::Rectangle {
456                    width,
457                    border_radius,
458                } => (f32::from(width), bounds.height, border_radius),
459            };
460
461        let value = self.value.into() as f32;
462        let (range_start, range_end) = {
463            let (start, end) = self.range.clone().into_inner();
464
465            (start.into() as f32, end.into() as f32)
466        };
467
468        let offset = if range_start >= range_end {
469            0.0
470        } else {
471            (bounds.width - handle_width) * (value - range_start)
472                / (range_end - range_start)
473        };
474
475        let rail_y = bounds.y + bounds.height / 2.0;
476
477        renderer.fill_quad(
478            renderer::Quad {
479                bounds: Rectangle {
480                    x: bounds.x,
481                    y: rail_y - style.rail.width / 2.0,
482                    width: offset + handle_width / 2.0,
483                    height: style.rail.width,
484                },
485                border: style.rail.border,
486                ..renderer::Quad::default()
487            },
488            style.rail.backgrounds.0,
489        );
490
491        renderer.fill_quad(
492            renderer::Quad {
493                bounds: Rectangle {
494                    x: bounds.x + offset + handle_width / 2.0,
495                    y: rail_y - style.rail.width / 2.0,
496                    width: bounds.width - offset - handle_width / 2.0,
497                    height: style.rail.width,
498                },
499                border: style.rail.border,
500                ..renderer::Quad::default()
501            },
502            style.rail.backgrounds.1,
503        );
504
505        renderer.fill_quad(
506            renderer::Quad {
507                bounds: Rectangle {
508                    x: bounds.x + offset,
509                    y: rail_y - handle_height / 2.0,
510                    width: handle_width,
511                    height: handle_height,
512                },
513                border: Border {
514                    radius: handle_border_radius,
515                    width: style.handle.border_width,
516                    color: style.handle.border_color,
517                },
518                ..renderer::Quad::default()
519            },
520            style.handle.background,
521        );
522    }
523
524    fn mouse_interaction(
525        &self,
526        tree: &Tree,
527        layout: Layout<'_>,
528        cursor: mouse::Cursor,
529        _viewport: &Rectangle,
530        _renderer: &Renderer,
531    ) -> mouse::Interaction {
532        let state = tree.state.downcast_ref::<State>();
533        let bounds = layout.bounds();
534        let is_mouse_over = cursor.is_over(bounds);
535
536        if state.is_dragging {
537            mouse::Interaction::Grabbing
538        } else if is_mouse_over {
539            mouse::Interaction::Grab
540        } else {
541            mouse::Interaction::default()
542        }
543    }
544}
545
546impl<'a, T, Message, Theme, Renderer> From<Slider<'a, T, Message, Theme>>
547    for Element<'a, Message, Theme, Renderer>
548where
549    T: Copy + Into<f64> + num_traits::FromPrimitive + 'a,
550    Message: Clone + 'a,
551    Theme: Catalog + 'a,
552    Renderer: core::Renderer + 'a,
553{
554    fn from(
555        slider: Slider<'a, T, Message, Theme>,
556    ) -> Element<'a, Message, Theme, Renderer> {
557        Element::new(slider)
558    }
559}
560
561#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
562struct State {
563    is_dragging: bool,
564    keyboard_modifiers: keyboard::Modifiers,
565}
566
567/// The possible status of a [`Slider`].
568#[derive(Debug, Clone, Copy, PartialEq, Eq)]
569pub enum Status {
570    /// The [`Slider`] can be interacted with.
571    Active,
572    /// The [`Slider`] is being hovered.
573    Hovered,
574    /// The [`Slider`] is being dragged.
575    Dragged,
576}
577
578/// The appearance of a slider.
579#[derive(Debug, Clone, Copy, PartialEq)]
580pub struct Style {
581    /// The colors of the rail of the slider.
582    pub rail: Rail,
583    /// The appearance of the [`Handle`] of the slider.
584    pub handle: Handle,
585}
586
587impl Style {
588    /// Changes the [`HandleShape`] of the [`Style`] to a circle
589    /// with the given radius.
590    pub fn with_circular_handle(mut self, radius: impl Into<Pixels>) -> Self {
591        self.handle.shape = HandleShape::Circle {
592            radius: radius.into().0,
593        };
594        self
595    }
596}
597
598/// The appearance of a slider rail
599#[derive(Debug, Clone, Copy, PartialEq)]
600pub struct Rail {
601    /// The backgrounds of the rail of the slider.
602    pub backgrounds: (Background, Background),
603    /// The width of the stroke of a slider rail.
604    pub width: f32,
605    /// The border of the rail.
606    pub border: Border,
607}
608
609/// The appearance of the handle of a slider.
610#[derive(Debug, Clone, Copy, PartialEq)]
611pub struct Handle {
612    /// The shape of the handle.
613    pub shape: HandleShape,
614    /// The [`Background`] of the handle.
615    pub background: Background,
616    /// The border width of the handle.
617    pub border_width: f32,
618    /// The border [`Color`] of the handle.
619    pub border_color: Color,
620}
621
622/// The shape of the handle of a slider.
623#[derive(Debug, Clone, Copy, PartialEq)]
624pub enum HandleShape {
625    /// A circular handle.
626    Circle {
627        /// The radius of the circle.
628        radius: f32,
629    },
630    /// A rectangular shape.
631    Rectangle {
632        /// The width of the rectangle.
633        width: u16,
634        /// The border radius of the corners of the rectangle.
635        border_radius: border::Radius,
636    },
637}
638
639/// The theme catalog of a [`Slider`].
640pub trait Catalog: Sized {
641    /// The item class of the [`Catalog`].
642    type Class<'a>;
643
644    /// The default class produced by the [`Catalog`].
645    fn default<'a>() -> Self::Class<'a>;
646
647    /// The [`Style`] of a class with the given status.
648    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
649}
650
651/// A styling function for a [`Slider`].
652pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
653
654impl Catalog for Theme {
655    type Class<'a> = StyleFn<'a, Self>;
656
657    fn default<'a>() -> Self::Class<'a> {
658        Box::new(default)
659    }
660
661    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
662        class(self, status)
663    }
664}
665
666/// The default style of a [`Slider`].
667pub fn default(theme: &Theme, status: Status) -> Style {
668    let palette = theme.extended_palette();
669
670    let color = match status {
671        Status::Active => palette.primary.base.color,
672        Status::Hovered => palette.primary.strong.color,
673        Status::Dragged => palette.primary.weak.color,
674    };
675
676    Style {
677        rail: Rail {
678            backgrounds: (color.into(), palette.background.strong.color.into()),
679            width: 4.0,
680            border: Border {
681                radius: 2.0.into(),
682                width: 0.0,
683                color: Color::TRANSPARENT,
684            },
685        },
686        handle: Handle {
687            shape: HandleShape::Circle { radius: 7.0 },
688            background: color.into(),
689            border_color: Color::TRANSPARENT,
690            border_width: 0.0,
691        },
692    }
693}