1use std::ops::RangeInclusive;
32
33pub use crate::slider::{Catalog, Handle, HandleShape, Status, Style, StyleFn, default};
34
35use crate::core::border::Border;
36use crate::core::keyboard;
37use crate::core::keyboard::key::{self, Key};
38use crate::core::layout::{self, Layout};
39use crate::core::mouse;
40use crate::core::renderer;
41use crate::core::touch;
42use crate::core::widget::tree::{self, Tree};
43use crate::core::window;
44use crate::core::{self, Element, Event, Length, Pixels, Point, Rectangle, Shell, Size, Widget};
45
46pub struct VerticalSlider<'a, T, Message, Theme = crate::Theme>
83where
84 Theme: Catalog,
85{
86 range: RangeInclusive<T>,
87 step: T,
88 shift_step: Option<T>,
89 value: T,
90 default: Option<T>,
91 on_change: Box<dyn Fn(T) -> Message + 'a>,
92 on_release: Option<Message>,
93 width: f32,
94 height: Length,
95 class: Theme::Class<'a>,
96 status: Option<Status>,
97}
98
99impl<'a, T, Message, Theme> VerticalSlider<'a, T, Message, Theme>
100where
101 T: Copy + From<u8> + std::cmp::PartialOrd,
102 Message: Clone,
103 Theme: Catalog,
104{
105 pub const DEFAULT_WIDTH: f32 = 16.0;
107
108 pub fn new<F>(range: RangeInclusive<T>, value: T, on_change: F) -> Self
117 where
118 F: 'a + Fn(T) -> Message,
119 {
120 let value = if value >= *range.start() {
121 value
122 } else {
123 *range.start()
124 };
125
126 let value = if value <= *range.end() {
127 value
128 } else {
129 *range.end()
130 };
131
132 VerticalSlider {
133 value,
134 default: None,
135 range,
136 step: T::from(1),
137 shift_step: None,
138 on_change: Box::new(on_change),
139 on_release: None,
140 width: Self::DEFAULT_WIDTH,
141 height: Length::Fill,
142 class: Theme::default(),
143 status: None,
144 }
145 }
146
147 pub fn default(mut self, default: impl Into<T>) -> Self {
151 self.default = Some(default.into());
152 self
153 }
154
155 pub fn on_release(mut self, on_release: Message) -> Self {
162 self.on_release = Some(on_release);
163 self
164 }
165
166 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
168 self.width = width.into().0;
169 self
170 }
171
172 pub fn height(mut self, height: impl Into<Length>) -> Self {
174 self.height = height.into();
175 self
176 }
177
178 pub fn step(mut self, step: T) -> Self {
180 self.step = step;
181 self
182 }
183
184 pub fn shift_step(mut self, shift_step: impl Into<T>) -> Self {
188 self.shift_step = Some(shift_step.into());
189 self
190 }
191
192 #[must_use]
194 pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
195 where
196 Theme::Class<'a>: From<StyleFn<'a, Theme>>,
197 {
198 self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
199 self
200 }
201
202 #[cfg(feature = "advanced")]
204 #[must_use]
205 pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
206 self.class = class.into();
207 self
208 }
209}
210
211impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
212 for VerticalSlider<'_, 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: Length::Shrink,
230 height: self.height,
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 let is_dragging = state.is_dragging;
255 let current_value = self.value;
256
257 let locate = |cursor_position: Point| -> Option<T> {
258 let bounds = layout.bounds();
259
260 if cursor_position.y >= bounds.y + bounds.height {
261 Some(*self.range.start())
262 } else if cursor_position.y <= bounds.y {
263 Some(*self.range.end())
264 } else {
265 let step = if state.keyboard_modifiers.shift() {
266 self.shift_step.unwrap_or(self.step)
267 } else {
268 self.step
269 }
270 .into();
271
272 let start = (*self.range.start()).into();
273 let end = (*self.range.end()).into();
274
275 let percent =
276 1.0 - f64::from(cursor_position.y - bounds.y) / f64::from(bounds.height);
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.control() || 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 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 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 let current_status = if state.is_dragging {
400 Status::Dragged
401 } else if cursor.is_over(layout.bounds()) {
402 Status::Hovered
403 } else {
404 Status::Active
405 };
406
407 if let Event::Window(window::Event::RedrawRequested(_now)) = event {
408 self.status = Some(current_status);
409 } else if self.status.is_some_and(|status| status != current_status) {
410 shell.request_redraw();
411 }
412 }
413
414 fn draw(
415 &self,
416 _tree: &Tree,
417 renderer: &mut Renderer,
418 theme: &Theme,
419 _style: &renderer::Style,
420 layout: Layout<'_>,
421 _cursor: mouse::Cursor,
422 _viewport: &Rectangle,
423 ) {
424 let bounds = layout.bounds();
425
426 let style = theme.style(&self.class, self.status.unwrap_or(Status::Active));
427
428 let (handle_width, handle_height, handle_border_radius) = match style.handle.shape {
429 HandleShape::Circle { radius } => (radius * 2.0, radius * 2.0, radius.into()),
430 HandleShape::Rectangle {
431 width,
432 border_radius,
433 } => (f32::from(width), bounds.width, border_radius),
434 };
435
436 let value = self.value.into() as f32;
437 let (range_start, range_end) = {
438 let (start, end) = self.range.clone().into_inner();
439
440 (start.into() as f32, end.into() as f32)
441 };
442
443 let offset = if range_start >= range_end {
444 0.0
445 } else {
446 (bounds.height - handle_width) * (value - range_end) / (range_start - range_end)
447 };
448
449 let rail_x = bounds.x + bounds.width / 2.0;
450
451 renderer.fill_quad(
452 renderer::Quad {
453 bounds: Rectangle {
454 x: rail_x - style.rail.width / 2.0,
455 y: bounds.y,
456 width: style.rail.width,
457 height: offset + handle_width / 2.0,
458 },
459 border: style.rail.border,
460 ..renderer::Quad::default()
461 },
462 style.rail.backgrounds.1,
463 );
464
465 renderer.fill_quad(
466 renderer::Quad {
467 bounds: Rectangle {
468 x: rail_x - style.rail.width / 2.0,
469 y: bounds.y + offset + handle_width / 2.0,
470 width: style.rail.width,
471 height: bounds.height - offset - handle_width / 2.0,
472 },
473 border: style.rail.border,
474 ..renderer::Quad::default()
475 },
476 style.rail.backgrounds.0,
477 );
478
479 renderer.fill_quad(
480 renderer::Quad {
481 bounds: Rectangle {
482 x: rail_x - handle_height / 2.0,
483 y: bounds.y + offset,
484 width: handle_height,
485 height: handle_width,
486 },
487 border: Border {
488 radius: handle_border_radius,
489 width: style.handle.border_width,
490 color: style.handle.border_color,
491 },
492 ..renderer::Quad::default()
493 },
494 style.handle.background,
495 );
496 }
497
498 fn mouse_interaction(
499 &self,
500 tree: &Tree,
501 layout: Layout<'_>,
502 cursor: mouse::Cursor,
503 _viewport: &Rectangle,
504 _renderer: &Renderer,
505 ) -> mouse::Interaction {
506 let state = tree.state.downcast_ref::<State>();
507
508 if state.is_dragging {
509 if cfg!(target_os = "windows") {
512 mouse::Interaction::Pointer
513 } else {
514 mouse::Interaction::Grabbing
515 }
516 } else if cursor.is_over(layout.bounds()) {
517 if cfg!(target_os = "windows") {
518 mouse::Interaction::Pointer
519 } else {
520 mouse::Interaction::Grab
521 }
522 } else {
523 mouse::Interaction::default()
524 }
525 }
526}
527
528impl<'a, T, Message, Theme, Renderer> From<VerticalSlider<'a, T, Message, Theme>>
529 for Element<'a, Message, Theme, Renderer>
530where
531 T: Copy + Into<f64> + num_traits::FromPrimitive + 'a,
532 Message: Clone + 'a,
533 Theme: Catalog + 'a,
534 Renderer: core::Renderer + 'a,
535{
536 fn from(
537 slider: VerticalSlider<'a, T, Message, Theme>,
538 ) -> Element<'a, Message, Theme, Renderer> {
539 Element::new(slider)
540 }
541}
542
543#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
544struct State {
545 is_dragging: bool,
546 keyboard_modifiers: keyboard::Modifiers,
547}