Skip to main content

crabshell_ui/
slider.rs

1//! [`Slider`], a handle dragged along a track, made of a [`Button`] and
2//! boxes that share the track's free space by `grow`, so the handle sits
3//! at its fraction of the way with no size worked out by hand.
4
5use std::cell::Cell;
6use std::rc::Rc;
7
8use crabshell_reactive::{Memo, Signal, untrack};
9
10use crate::cx::Cx;
11use crate::input::{Drag, DragPhase, PIXELS_PER_STEP, Wheel};
12use crate::keyboard::{Key, KeyEvent};
13use crate::prop::{IntoProp, Prop};
14use crate::scroll::Built;
15use crate::style::Style;
16use crate::widgets::{Align, Button, Column, Common, Element, Row, Stack, Widget};
17
18/// A shared style property, or the empty style when unset.
19type StyleFn = Rc<dyn Fn() -> Style>;
20
21/// A value picked by dragging a handle along a track, as Qt's `Slider`.
22/// The slider writes the value back to its signal, and setting the signal
23/// moves the handle.
24///
25/// A press anywhere on the slider moves the value there and drags it from
26/// there. The wheel moves it one wheel step a notch, by default the step,
27/// or a twentieth of the range when it has no step, and a touchpad in
28/// proportion; so do the arrow keys while it has the keyboard focus, which
29/// Tab gives it. The value written is always within the range, at or under
30/// the limit, and on a step, and only a change is written. A value set
31/// from outside the range shows at that end, and NaN at the start.
32///
33/// It draws nothing until styled: `style` sets the track's box, 120 by 4
34/// logical pixels unless it sets a size, `fill_style` the part from the
35/// start to the handle, and `handle_style` the handle, 16 by 16 unless it
36/// sets a size. The slider is as large as the track, or the handle where
37/// that is larger.
38///
39/// ```
40/// use crabshell_ui::{Color, Cx, Slider, Style};
41///
42/// const TRACK: Style = Style::new().width(200.0).height(4.0).radius(2.0)
43///     .background(Color::rgb(0x45, 0x47, 0x5a));
44/// const FILL: Style = Style::new().radius(2.0).background(Color::rgb(0x89, 0xb4, 0xfa));
45/// const HANDLE: Style = Style::new().radius(8.0).background(Color::rgb(0xcd, 0xd6, 0xf4));
46///
47/// fn volume(cx: &Cx) -> Slider {
48///     let volume = cx.signal(50.0);
49///     Slider::new(volume).range(0.0, 100.0).step(5.0)
50///         .style(TRACK).fill_style(FILL).handle_style(HANDLE)
51/// }
52/// ```
53pub struct Slider {
54  props: SliderProps,
55  common: Common,
56}
57
58struct SliderProps {
59  value: Signal<f32>,
60  min: Option<Prop<f32>>,
61  max: Option<Prop<f32>>,
62  step: Option<Prop<f32>>,
63  limit: Option<Prop<Option<f32>>>,
64  wheel_step: Option<Prop<f32>>,
65  vertical: Option<Prop<bool>>,
66  enabled: Option<Prop<bool>>,
67  style: Option<Prop<Style>>,
68  fill_style: Option<Prop<Style>>,
69  handle_style: Option<Prop<Style>>,
70  dragging: Option<Signal<bool>>,
71}
72
73/// The track's size when its style sets none, along and across.
74const TRACK: (f32, f32) = (120.0, 4.0);
75
76/// The handle's size when its style sets none.
77const HANDLE: f32 = 16.0;
78
79/// The parts of the range the wheel and the keys move a slider without a
80/// step.
81const PARTS: f32 = 20.0;
82
83impl Slider {
84  /// A slider showing `value` and writing it back as it is dragged.
85  pub fn new(value: Signal<f32>) -> Slider {
86    Slider {
87      props: SliderProps {
88        value,
89        min: None,
90        max: None,
91        step: None,
92        limit: None,
93        wheel_step: None,
94        vertical: None,
95        enabled: None,
96        style: None,
97        fill_style: None,
98        handle_style: None,
99        dragging: None,
100      },
101      common: Common::default(),
102    }
103  }
104
105  /// Sets the values at the start and the end, 0 and 1 by default. A range
106  /// whose end isn't above its start holds only the start.
107  pub fn range(mut self, min: impl IntoProp<f32>, max: impl IntoProp<f32>) -> Slider {
108    self.props.min = Some(min.into_prop());
109    self.props.max = Some(max.into_prop());
110    self
111  }
112
113  /// Snaps the value to whole steps from the start of the range. 0, the
114  /// default, or a step that isn't a number above 0, slides freely.
115  pub fn step(mut self, step: impl IntoProp<f32>) -> Slider {
116    self.props.step = Some(step.into_prop());
117    self
118  }
119
120  /// Caps what a drag, the wheel, the keys or a screen reader can set,
121  /// below the range's end, as a brightness slider held to half in a power
122  /// saver mode; the track still shows the whole range. `None`, the
123  /// default, a cap that isn't a number or one past the end is the end,
124  /// and one under the start is the start. With a step, a cap between
125  /// steps stops at the step under it. A value set from outside past the
126  /// cap shows where it is, and the next move from there lands at or
127  /// under the cap.
128  pub fn limit(mut self, max: impl IntoProp<Option<f32>>) -> Slider {
129    self.props.limit = Some(max.into_prop());
130    self
131  }
132
133  /// Sets how far one wheel notch or arrow key moves the value, so a
134  /// slider of whole steps can move 5 a notch. By default, or when it
135  /// isn't a number above 0, it is the step, or a twentieth of the range
136  /// without one. With a step, it is rounded to a whole number of steps,
137  /// at least one, so 4 on a step of 10 moves 10 and 25 moves 30 (half
138  /// rounds away from zero).
139  pub fn wheel_step(mut self, step: impl IntoProp<f32>) -> Slider {
140    self.props.wheel_step = Some(step.into_prop());
141    self
142  }
143
144  /// Makes the slider run from the bottom up instead of left to right.
145  pub fn vertical(mut self, vertical: impl IntoProp<bool>) -> Slider {
146    self.props.vertical = Some(vertical.into_prop());
147    self
148  }
149
150  /// Turns the slider on or off, as [`Button::enabled`]: off, nothing
151  /// moves it and Tab skips it.
152  pub fn enabled(mut self, enabled: impl IntoProp<bool>) -> Slider {
153    self.props.enabled = Some(enabled.into_prop());
154    self
155  }
156
157  /// Sets the track's style, its size included.
158  pub fn style(mut self, style: impl IntoProp<Style>) -> Slider {
159    self.props.style = Some(style.into_prop());
160    self
161  }
162
163  /// Sets the style of the part of the track from the start to the
164  /// handle's middle. Its size comes from the value.
165  pub fn fill_style(mut self, style: impl IntoProp<Style>) -> Slider {
166    self.props.fill_style = Some(style.into_prop());
167    self
168  }
169
170  /// Sets the handle's style, its width and height included.
171  pub fn handle_style(mut self, style: impl IntoProp<Style>) -> Slider {
172    self.props.handle_style = Some(style.into_prop());
173    self
174  }
175
176  /// Shares whether the slider is being dragged: `true` from the press
177  /// until the release, as Qt's `pressed`. Written only on a change.
178  pub fn dragging(mut self, dragging: Signal<bool>) -> Slider {
179    self.props.dragging = Some(dragging);
180    self
181  }
182
183  crate::widgets::visibility_methods!();
184}
185
186impl Widget for Slider {
187  fn into_element(self: Box<Self>) -> Element {
188    let Slider { props, common } = *self;
189    let mut once = Some(props);
190    // A keyed list of one gives the slider a context for its memos.
191    let mut element = Box::new(Stack::new().children_keyed(
192      || vec![()],
193      |_| (),
194      move |cx, _| {
195        Built(
196          once
197            .take()
198            .map(|props| Box::new(build(cx, props)).into_element()),
199        )
200      },
201    ))
202    .into_element();
203    element.name = "Slider";
204    element.common = common;
205    element
206  }
207}
208
209/// Where a slider is and how it moves, shared by its handlers.
210#[derive(Clone, Copy)]
211pub(crate) struct Range {
212  pub(crate) value: Signal<f32>,
213  min: Memo<f32>,
214  max: Memo<f32>,
215  step: Memo<f32>,
216  limit: Memo<Option<f32>>,
217  wheel_step: Memo<f32>,
218}
219
220impl Range {
221  /// The start and end, the end never below the start. A bound that
222  /// isn't a number, or whose closure panicked first, is 0.
223  fn bounds(self) -> (f32, f32) {
224    let number = |n: Option<f32>| n.filter(|n| !n.is_nan()).unwrap_or(0.0);
225    let min = number(self.min.try_get());
226    (min, number(self.max.try_get()).max(min))
227  }
228
229  /// The range and value as a screen reader reads them, the value within
230  /// the range.
231  pub(crate) fn access(self) -> crate::access::AccessValue {
232    untrack(|| {
233      let (min, max) = self.bounds();
234      crate::access::AccessValue {
235        min: f64::from(min),
236        max: f64::from(max),
237        current: f64::from(self.now().clamp(min, max)),
238        increment: f64::from(self.unit()),
239      }
240    })
241  }
242
243  /// How far along the value is, from 0 to 1.
244  fn fraction(self) -> f32 {
245    let (min, max) = self.bounds();
246    let value = self.value.get();
247    if max > min && !value.is_nan() {
248      ((value - min) / (max - min)).clamp(0.0, 1.0)
249    } else {
250      0.0
251    }
252  }
253
254  /// One step of the wheel or the keys: the wheel step in whole steps,
255  /// at least one, when there is a step.
256  fn unit(self) -> f32 {
257    let (min, max) = self.bounds();
258    let wheel =
259      untrack(|| self.wheel_step.try_get()).filter(|step| step.is_finite() && *step > 0.0);
260    match (wheel, self.snap()) {
261      (Some(wheel), Some(step)) => (wheel / step).round().max(1.0) * step,
262      (Some(wheel), None) => wheel,
263      (None, Some(step)) => step,
264      (None, None) => (max - min) / PARTS,
265    }
266  }
267
268  /// The highest value a move can write: the limit within the range,
269  /// down to a step when there is one, so the value stays on a step.
270  fn cap(self) -> f32 {
271    let (min, max) = self.bounds();
272    match untrack(|| self.limit.try_get()).flatten() {
273      Some(limit) if limit < max => match self.snap() {
274        Some(step) => (min + ((limit - min) / step).floor() * step).max(min),
275        None => limit.max(min),
276      },
277      _ => max,
278    }
279  }
280
281  /// The step, unless it slides freely.
282  fn snap(self) -> Option<f32> {
283    untrack(|| self.step.try_get()).filter(|step| step.is_finite() && *step > 0.0)
284  }
285
286  /// The value read now, NaN as the start, outside any binding.
287  fn now(self) -> f32 {
288    untrack(|| {
289      let (min, _) = self.bounds();
290      self.value.try_get().filter(|v| !v.is_nan()).unwrap_or(min)
291    })
292  }
293
294  /// Writes `value`, within the range, at or under the cap and on a
295  /// step, if that changes it.
296  pub(crate) fn write(self, value: f32) {
297    untrack(|| {
298      let (min, _) = self.bounds();
299      let mut value = if value.is_nan() { min } else { value };
300      if let Some(step) = self.snap() {
301        value = min + ((value - min) / step).round() * step;
302      }
303      let value = value.max(min).min(self.cap());
304      if self.value.try_get() != Some(value) {
305        self.value.try_set(value);
306      }
307    });
308  }
309
310  /// Writes the value `t` of the way along.
311  fn write_fraction(self, t: f32) {
312    let (min, max) = untrack(|| self.bounds());
313    self.write(min + t.clamp(0.0, 1.0) * (max - min));
314  }
315}
316
317fn build(cx: &Cx, props: SliderProps) -> Button {
318  let SliderProps {
319    value,
320    min,
321    max,
322    step,
323    limit,
324    wheel_step,
325    vertical,
326    enabled,
327    style,
328    fill_style,
329    handle_style,
330    dragging,
331  } = props;
332  let range = Range {
333    value,
334    min: cx.memo(shared_or(min, 0.0)),
335    max: cx.memo(shared_or(max, 1.0)),
336    step: cx.memo(shared_or(step, 0.0)),
337    limit: cx.memo(shared_or(limit, None)),
338    wheel_step: cx.memo(shared_or(wheel_step, 0.0)),
339  };
340  if let Some(dragging) = dragging {
341    // Kept under the slider's context, so it drops when the slider goes.
342    cx.signal(LetGo(dragging));
343  }
344  let vertical = cx.memo(shared_or(vertical, false));
345  let style = shared_style(style);
346  let fill_style = shared_style(fill_style);
347  let handle = {
348    let handle_style = shared_style(handle_style);
349    cx.memo(move || {
350      Style::new()
351        .width(HANDLE)
352        .height(HANDLE)
353        .merge(handle_style())
354        .shrink(0.0)
355    })
356  };
357  let fraction = cx.memo(move || range.fraction());
358
359  let on_drag = move |_: &Cx, drag: Drag| {
360    if let Some(dragging) = dragging {
361      let held = drag.phase != DragPhase::End;
362      if untrack(|| dragging.try_get()) != Some(held) {
363        dragging.try_set(held);
364      }
365    }
366    if drag.phase == DragPhase::End {
367      return;
368    }
369    let vertical = untrack(|| vertical.get());
370    let handle = untrack(|| handle.get());
371    let (at, length, size) = if vertical {
372      (drag.position.y, drag.size.height, handle.height)
373    } else {
374      (drag.position.x, drag.size.width, handle.width)
375    };
376    let size = size.unwrap_or(HANDLE).max(0.0);
377    // The handle's middle follows the pointer.
378    let travel = length - size;
379    let t = if travel > 0.0 {
380      (at - size / 2.0) / travel
381    } else if length > 0.0 {
382      at / length
383    } else {
384      0.0
385    };
386    range.write_fraction(if vertical { 1.0 - t } else { t });
387  };
388  // Whole steps of a wheel or touchpad that haven't added up yet.
389  let partial = Cell::new(0.0_f32);
390  let on_wheel = move |_: &Cx, wheel: Wheel| {
391    // Up and right move it up.
392    let notches = wheel.x.notches - wheel.y.notches;
393    let steps = if notches != 0.0 {
394      notches
395    } else {
396      (wheel.x.pixels - wheel.y.pixels) / PIXELS_PER_STEP
397    };
398    if !steps.is_finite() {
399      return;
400    }
401    let unit = untrack(|| range.unit());
402    if range.snap().is_some() {
403      let total = partial.get() + steps;
404      let whole = total.trunc();
405      partial.set(total - whole);
406      if whole != 0.0 {
407        range.write(range.now() + whole * unit);
408      }
409    } else if steps != 0.0 {
410      range.write(range.now() + steps * unit);
411    }
412    if wheel.x.stop || wheel.y.stop {
413      partial.set(0.0);
414    }
415  };
416  let on_key = move |_: &Cx, event: &KeyEvent| {
417    let steps = match event.key {
418      Key::Left | Key::Down => -1.0,
419      Key::Right | Key::Up => 1.0,
420      _ => return false,
421    };
422    range.write(range.now() + steps * untrack(|| range.unit()));
423    true
424  };
425
426  let body = |column: bool| {
427    let parts = Parts {
428      style: Rc::clone(&style),
429      fill_style: Rc::clone(&fill_style),
430      handle,
431      fraction,
432      column,
433    };
434    parts.area().visible(move || vertical.get() == column)
435  };
436  let mut button = Button::new(Stack::new().child(body(false)).child(body(true)))
437    .on_drag(on_drag)
438    .on_wheel(on_wheel)
439    .on_key(on_key);
440  if let Some(enabled) = enabled {
441    button = button.enabled(enabled);
442  }
443  button.button.value = Some(range);
444  button
445}
446
447/// Writes `false` to a slider's `dragging` signal when the slider goes
448/// while held, as no drag `End` comes then.
449struct LetGo(Signal<bool>);
450
451impl Drop for LetGo {
452  fn drop(&mut self) {
453    if untrack(|| self.0.try_get()) == Some(true) {
454      self.0.try_set(false);
455    }
456  }
457}
458
459/// What one orientation of a slider is drawn from.
460struct Parts {
461  style: StyleFn,
462  fill_style: StyleFn,
463  handle: Memo<Style>,
464  fraction: Memo<f32>,
465  /// Bottom to top, rather than left to right.
466  column: bool,
467}
468
469impl Parts {
470  /// The track with its fill, and over it the handle, in one cell.
471  fn area(self) -> Stack {
472    let Parts {
473      style,
474      fill_style,
475      handle,
476      fraction,
477      column,
478    } = self;
479    let (along, across) = TRACK;
480    let size = if column {
481      Style::new().width(across).height(along)
482    } else {
483      Style::new().width(along).height(across)
484    };
485    let half = move || {
486      let handle = handle.get();
487      let size = if column { handle.height } else { handle.width };
488      size.unwrap_or(HANDLE).max(0.0) / 2.0
489    };
490    // The free space past both halves of the handle goes before and after
491    // it by the fraction, as it does around the handle below.
492    let fill = Stack::new().style(move || fill_style().basis(half()).grow(fraction.get()));
493    let rest = Stack::new().style(move || Style::new().basis(half()).grow(1.0 - fraction.get()));
494    let track_style = move || {
495      size
496        .align_self(Align::Center)
497        .justify_self(Align::Center)
498        .merge(style())
499    };
500    let before = Stack::new().style(move || Style::new().basis(0.0).grow(fraction.get()));
501    let after = Stack::new().style(move || Style::new().basis(0.0).grow(1.0 - fraction.get()));
502    let knob = Stack::new().style(move || handle.get());
503    if column {
504      Stack::new()
505        .child(
506          Column::new()
507            .reverse(true)
508            .style(track_style)
509            .child(fill)
510            .child(rest),
511        )
512        .child(
513          Column::new()
514            .reverse(true)
515            .align(Align::Center)
516            .child(before)
517            .child(knob)
518            .child(after),
519        )
520    } else {
521      Stack::new()
522        .child(Row::new().style(track_style).child(fill).child(rest))
523        .child(
524          Row::new()
525            .align(Align::Center)
526            .child(before)
527            .child(knob)
528            .child(after),
529        )
530    }
531  }
532}
533
534/// `prop` as a closure for a memo, or `default` when unset.
535fn shared_or<T: Clone + 'static>(prop: Option<Prop<T>>, default: T) -> impl FnMut() -> T + 'static {
536  let prop = prop.map(Prop::shared);
537  move || prop.as_ref().map_or_else(|| default.clone(), |prop| prop())
538}
539
540fn shared_style(prop: Option<Prop<Style>>) -> StyleFn {
541  match prop {
542    Some(prop) => prop.shared(),
543    None => Rc::new(Style::new),
544  }
545}