Skip to main content

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