Skip to main content

freya_components/
slider.rs

1use freya_core::prelude::*;
2use torin::prelude::*;
3
4use crate::{
5    get_theme,
6    theming::component_themes::SliderThemePartial,
7};
8
9/// Slider component.
10///
11/// You must pass a percentage from 0.0 to 100.0 and listen for value changes with `on_moved` and then decide if this changes are applicable,
12/// and if so, apply them.
13///
14/// # Example
15/// ```rust
16/// # use freya::prelude::*;
17/// fn app() -> impl IntoElement {
18///     let mut percentage = use_state(|| 25.0);
19///
20///     Slider::new(move |per| percentage.set(per)).value(percentage())
21/// }
22///
23/// # use freya_testing::prelude::*;
24/// # launch_doc(|| {
25/// #   rect().padding(48.).center().expanded().child(app())
26/// # }, "./images/gallery_slider.png").render();
27/// ```
28/// # Preview
29/// ![Slider Preview][slider]
30#[cfg_attr(feature = "docs",
31    doc = embed_doc_image::embed_image!("slider", "images/gallery_slider.png")
32)]
33#[derive(Clone, PartialEq)]
34pub struct Slider {
35    pub(crate) theme: Option<SliderThemePartial>,
36    value: f64,
37    on_moved: EventHandler<f64>,
38    size: Size,
39    direction: Direction,
40    enabled: bool,
41    key: DiffKey,
42}
43
44impl KeyExt for Slider {
45    fn write_key(&mut self) -> &mut DiffKey {
46        &mut self.key
47    }
48}
49
50impl Slider {
51    pub fn new(on_moved: impl Into<EventHandler<f64>>) -> Self {
52        Self {
53            theme: None,
54            value: 0.0,
55            on_moved: on_moved.into(),
56            size: Size::fill(),
57            direction: Direction::Horizontal,
58            enabled: true,
59            key: DiffKey::None,
60        }
61    }
62
63    pub fn enabled(mut self, enabled: impl Into<bool>) -> Self {
64        self.enabled = enabled.into();
65        self
66    }
67
68    pub fn value(mut self, value: f64) -> Self {
69        self.value = value.clamp(0.0, 100.0);
70        self
71    }
72
73    pub fn theme(mut self, theme: SliderThemePartial) -> Self {
74        self.theme = Some(theme);
75        self
76    }
77
78    pub fn size(mut self, size: Size) -> Self {
79        self.size = size;
80        self
81    }
82
83    pub fn direction(mut self, direction: Direction) -> Self {
84        self.direction = direction;
85        self
86    }
87}
88
89impl Component for Slider {
90    fn render(&self) -> impl IntoElement {
91        let theme = get_theme!(&self.theme, slider);
92        let focus = use_focus();
93        let focus_status = use_focus_status(focus);
94        let mut hovering = use_state(|| false);
95        let mut clicking = use_state(|| false);
96        let mut size = use_state(Area::default);
97
98        let enabled = use_reactive(&self.enabled);
99        use_drop(move || {
100            if hovering() {
101                Cursor::set(CursorIcon::default());
102            }
103        });
104
105        let direction_is_vertical = self.direction == Direction::Vertical;
106        let value = self.value;
107        let on_moved = self.on_moved.clone();
108
109        let on_key_down = {
110            let on_moved = self.on_moved.clone();
111            move |e: Event<KeyboardEventData>| match e.key {
112                Key::Named(NamedKey::ArrowLeft) if !direction_is_vertical => {
113                    e.stop_propagation();
114                    on_moved.call((value - 4.0).clamp(0.0, 100.0));
115                }
116                Key::Named(NamedKey::ArrowRight) if !direction_is_vertical => {
117                    e.stop_propagation();
118                    on_moved.call((value + 4.0).clamp(0.0, 100.0));
119                }
120                Key::Named(NamedKey::ArrowUp) if direction_is_vertical => {
121                    e.stop_propagation();
122                    on_moved.call((value + 4.0).clamp(0.0, 100.0));
123                }
124                Key::Named(NamedKey::ArrowDown) if direction_is_vertical => {
125                    e.stop_propagation();
126                    on_moved.call((value - 4.0).clamp(0.0, 100.0));
127                }
128                _ => {}
129            }
130        };
131
132        let on_pointer_enter = move |_| {
133            hovering.set(true);
134            if enabled() {
135                Cursor::set(CursorIcon::Pointer);
136            } else {
137                Cursor::set(CursorIcon::NotAllowed);
138            }
139        };
140
141        let on_pointer_leave = move |_| {
142            Cursor::set(CursorIcon::default());
143            hovering.set(false);
144        };
145
146        let calc_percentage = move |x: f64, y: f64| -> f64 {
147            let pct = if direction_is_vertical {
148                let y = y - 8.0;
149                100. - (y / (size.read().height() as f64 - 15.0) * 100.0)
150            } else {
151                let x = x - 8.0;
152                x / (size.read().width() as f64 - 15.) * 100.0
153            };
154            pct.clamp(0.0, 100.0)
155        };
156
157        let on_pointer_down = {
158            let on_moved = self.on_moved.clone();
159            move |e: Event<PointerEventData>| {
160                focus.request_focus();
161                clicking.set(true);
162                e.stop_propagation();
163                let coordinates = e.element_location();
164                on_moved.call(calc_percentage(coordinates.x, coordinates.y));
165            }
166        };
167
168        let on_global_pointer_press = move |_: Event<PointerEventData>| {
169            clicking.set(false);
170        };
171
172        let on_global_pointer_move = move |e: Event<PointerEventData>| {
173            e.stop_propagation();
174            if *clicking.peek() {
175                let coordinates = e.global_location();
176                on_moved.call(calc_percentage(
177                    coordinates.x - size.read().min_x() as f64,
178                    coordinates.y - size.read().min_y() as f64,
179                ));
180            }
181        };
182
183        let border = if focus_status() == FocusStatus::Keyboard {
184            Border::new()
185                .fill(theme.border_fill)
186                .width(2.)
187                .alignment(BorderAlignment::Inner)
188        } else {
189            Border::new()
190                .fill(Color::TRANSPARENT)
191                .width(0.)
192                .alignment(BorderAlignment::Inner)
193        };
194
195        let (slider_width, slider_height) = if direction_is_vertical {
196            (Size::px(6.), self.size.clone())
197        } else {
198            (self.size.clone(), Size::px(6.))
199        };
200
201        let track_size = Size::func_data(
202            move |ctx| Some(value as f32 / 100. * (ctx.parent - 15.)),
203            &(value as i32),
204        );
205
206        let (track_width, track_height) = if direction_is_vertical {
207            (Size::px(6.), track_size)
208        } else {
209            (track_size, Size::px(6.))
210        };
211
212        let (thumb_offset_x, thumb_offset_y) = if direction_is_vertical {
213            (-6., 3.)
214        } else {
215            (-3., -6.)
216        };
217
218        let thumb_main_align = if direction_is_vertical {
219            Alignment::end()
220        } else {
221            Alignment::start()
222        };
223
224        let padding = if direction_is_vertical {
225            (0., 8.)
226        } else {
227            (8., 0.)
228        };
229
230        let thumb = rect()
231            .width(Size::fill())
232            .offset_x(thumb_offset_x)
233            .offset_y(thumb_offset_y)
234            .child(
235                rect()
236                    .width(Size::px(18.))
237                    .height(Size::px(18.))
238                    .corner_radius(50.)
239                    .background(theme.thumb_background.mul_if(!self.enabled, 0.85))
240                    .padding(4.)
241                    .child(
242                        rect()
243                            .width(Size::fill())
244                            .height(Size::fill())
245                            .background(theme.thumb_inner_background.mul_if(!self.enabled, 0.85))
246                            .corner_radius(50.),
247                    ),
248            );
249
250        let track = rect()
251            .width(track_width)
252            .height(track_height)
253            .background(theme.thumb_inner_background.mul_if(!self.enabled, 0.85))
254            .corner_radius(50.);
255
256        rect()
257            .a11y_id(focus.a11y_id())
258            .a11y_focusable(self.enabled)
259            .a11y_role(AccessibilityRole::Slider)
260            .on_sized(move |e: Event<SizedEventData>| size.set(e.area))
261            .maybe(self.enabled, |rect| {
262                rect.on_key_down(on_key_down)
263                    .on_pointer_down(on_pointer_down)
264                    .on_global_pointer_move(on_global_pointer_move)
265                    .on_global_pointer_press(on_global_pointer_press)
266            })
267            .on_pointer_enter(on_pointer_enter)
268            .on_pointer_leave(on_pointer_leave)
269            .border(border)
270            .corner_radius(50.)
271            .padding(padding)
272            .child(
273                rect()
274                    .width(slider_width)
275                    .height(slider_height)
276                    .background(theme.background.mul_if(!self.enabled, 0.85))
277                    .corner_radius(50.)
278                    .direction(self.direction)
279                    .main_align(thumb_main_align)
280                    .children(if direction_is_vertical {
281                        vec![thumb.into(), track.into()]
282                    } else {
283                        vec![track.into(), thumb.into()]
284                    }),
285            )
286    }
287
288    fn render_key(&self) -> DiffKey {
289        self.key.clone().or(self.default_key())
290    }
291}