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