Skip to main content

mitsuami_widgets/
ranges.rs

1//! Numbers in a range: sliders and number inputs.
2
3use std::rc::Rc;
4
5use mitsuami_core::{
6    Element, ElementBuilder, EventValue, NodeId, Orientation, Prop, Tweak, Ui, UiEvent, View, WidgetKind,
7};
8use mitsuami_reactive::{IntoValue, Signal, Value};
9
10/// A slider: a number in a range, as the platform's slider shows it,
11/// horizontal or vertical. Its label is its accessible name. What its step does is the platform's:
12/// AppKit shows it as tick marks the knob stops at, WinUI and GTK snap the
13/// user's moves to it, and Qt moves by it from the keyboard.
14///
15/// ```ignore
16/// let volume = signal(50.0);
17/// Slider::new("Volume").range(0.0, 100.0).step(10.0).bind(volume)
18/// ```
19pub struct Slider {
20    element: Element,
21    range: Value<(f64, f64)>,
22    value: Value<f64>,
23}
24
25impl ElementBuilder for Slider {
26    fn element(&mut self) -> &mut Element {
27        &mut self.element
28    }
29}
30
31impl View for Slider {
32    fn build(mut self, ui: &Ui) -> NodeId {
33        // Clamped as the native slider clamps it.
34        let clamp = |v: f64, (min, max): (f64, f64)| v.max(min).min(max);
35        let value = match (self.value, self.range.clone()) {
36            (Value::Static(v), Value::Static(range)) => Value::Static(clamp(v, range)),
37            (value, range) => Value::Dynamic(Rc::new(move || clamp(value.get(), range.get()))),
38        };
39        self.element.prop(self.range, |(min, max)| Prop::Range { min, max });
40        self.element.prop(value, Prop::Number);
41        self.element.build(ui)
42    }
43}
44
45impl Slider {
46    /// From 0 to 100, at 0.
47    pub fn new(label: impl IntoValue<String>) -> Slider {
48        let mut element = Element::new(WidgetKind::Slider);
49        element.prop(label.into_value(), Prop::Label);
50        Slider { element, range: Value::Static((0.0, 100.0)), value: Value::Static(0.0) }
51    }
52
53    /// Its label: the accessible name, which `new` takes. In `view!`,
54    /// `<Slider label="…"/>`.
55    pub fn label(mut self, label: impl IntoValue<String>) -> Slider {
56        self.element.prop(label.into_value(), Prop::Label);
57        self
58    }
59
60    pub fn range(mut self, min: f64, max: f64) -> Slider {
61        self.range = Value::Static((min, max));
62        self
63    }
64
65    /// A range that changes: `(min, max)`.
66    pub fn range_with(mut self, range: impl IntoValue<(f64, f64)>) -> Slider {
67        self.range = range.into_value();
68        self
69    }
70
71    /// The step the platform snaps to (where its sliders snap) and moves by
72    /// from the keyboard. Without one, the platform's default.
73    pub fn step(mut self, step: impl IntoValue<f64>) -> Slider {
74        let step = step.into_value();
75        let step = match step {
76            Value::Static(s) => Value::Static(Some(s)),
77            dynamic => Value::Dynamic(Rc::new(move || Some(dynamic.get()))),
78        };
79        self.element.prop(step, Prop::Step);
80        self
81    }
82
83    pub fn value(mut self, value: impl IntoValue<f64>) -> Slider {
84        self.value = value.into_value();
85        self
86    }
87
88    /// Two-way binding, Vue's `v-model`.
89    pub fn bind(self, signal: Signal<f64>) -> Slider {
90        self.value(signal).on_change(move |value| signal.set(value))
91    }
92
93    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> Slider {
94        self.element.prop(enabled.into_value(), Prop::Enabled);
95        self
96    }
97
98    /// Which way it runs; larger values are up when vertical.
99    pub fn orientation(mut self, orientation: impl IntoValue<Orientation>) -> Slider {
100        self.element.prop(orientation.into_value(), Prop::Orientation);
101        self
102    }
103
104    /// Raw platform settings, past the semantic ones: see [`Tweak`].
105    pub fn native(mut self, tweak: Tweak<Slider>) -> Slider {
106        tweak.apply(&mut self.element);
107        self
108    }
109
110    /// Called with the new value as the user moves the slider.
111    pub fn on_change(mut self, handler: impl Fn(f64) + 'static) -> Slider {
112        self.element.on(move |event| {
113            if let UiEvent::Changed(EventValue::Number(value)) = event {
114                handler(*value);
115            }
116        });
117        self
118    }
119}
120
121/// A field for a whole number, with buttons that step it up and down, as
122/// the platform's spin box shows it. Its label is its accessible name; show
123/// one beside it with a `Text`. Typing reports the number when the edit is
124/// done (Return, or leaving the field), as each platform commits one.
125/// Whole numbers in an `i32`, because Qt's spin box holds an `int`.
126///
127/// ```ignore
128/// let memory = signal(64);
129/// NumberInput::new("Memory (MB)").range(16, 512).step(16).bind(memory)
130/// ```
131pub struct NumberInput {
132    element: Element,
133    range: Value<(i32, i32)>,
134    value: Value<i32>,
135}
136
137impl ElementBuilder for NumberInput {
138    fn element(&mut self) -> &mut Element {
139        &mut self.element
140    }
141}
142
143impl View for NumberInput {
144    fn build(mut self, ui: &Ui) -> NodeId {
145        // Clamped as the native spin box clamps it.
146        let clamp = |v: i32, (min, max): (i32, i32)| v.max(min).min(max);
147        let value = match (self.value, self.range.clone()) {
148            (Value::Static(v), Value::Static(range)) => Value::Static(clamp(v, range)),
149            (value, range) => Value::Dynamic(Rc::new(move || clamp(value.get(), range.get()))),
150        };
151        self.element.prop(self.range, |(min, max)| Prop::Range { min: min.into(), max: max.into() });
152        self.element.prop(value, |v| Prop::Number(v.into()));
153        self.element.build(ui)
154    }
155}
156
157impl NumberInput {
158    /// From 0 to 100, at 0.
159    pub fn new(label: impl IntoValue<String>) -> NumberInput {
160        let mut element = Element::new(WidgetKind::NumberInput);
161        element.prop(label.into_value(), Prop::Label);
162        NumberInput { element, range: Value::Static((0, 100)), value: Value::Static(0) }
163    }
164
165    /// Its label: the accessible name, which `new` takes. In `view!`,
166    /// `<NumberInput label="…"/>`.
167    pub fn label(mut self, label: impl IntoValue<String>) -> NumberInput {
168        self.element.prop(label.into_value(), Prop::Label);
169        self
170    }
171
172    pub fn range(mut self, min: i32, max: i32) -> NumberInput {
173        self.range = Value::Static((min, max));
174        self
175    }
176
177    /// A range that changes: `(min, max)`.
178    pub fn range_with(mut self, range: impl IntoValue<(i32, i32)>) -> NumberInput {
179        self.range = range.into_value();
180        self
181    }
182
183    /// What the buttons and arrow keys add or take away. Without one, the
184    /// platform's default (1 on every platform).
185    pub fn step(mut self, step: impl IntoValue<i32>) -> NumberInput {
186        let step = step.into_value();
187        let step = match step {
188            Value::Static(s) => Value::Static(Some(s.into())),
189            dynamic => Value::Dynamic(Rc::new(move || Some(dynamic.get().into()))),
190        };
191        self.element.prop(step, Prop::Step);
192        self
193    }
194
195    /// Stepped past one end of its range, it goes on from the other.
196    /// Without, it's the platform's: AppKit's stepper wraps round, the
197    /// other platforms' spin boxes stop.
198    pub fn wrap_around(mut self, wrap: impl IntoValue<bool>) -> NumberInput {
199        self.element.prop(wrap.into_value(), Prop::WrapAround);
200        self
201    }
202
203    pub fn value(mut self, value: impl IntoValue<i32>) -> NumberInput {
204        self.value = value.into_value();
205        self
206    }
207
208    /// Two-way binding, Vue's `v-model`.
209    pub fn bind(self, signal: Signal<i32>) -> NumberInput {
210        self.value(signal).on_change(move |value| signal.set(value))
211    }
212
213    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> NumberInput {
214        self.element.prop(enabled.into_value(), Prop::Enabled);
215        self
216    }
217
218    /// Raw platform settings, past the semantic ones: see [`Tweak`].
219    pub fn native(mut self, tweak: Tweak<NumberInput>) -> NumberInput {
220        tweak.apply(&mut self.element);
221        self
222    }
223
224    /// Called with the new number when the user steps it or finishes
225    /// typing one.
226    pub fn on_change(mut self, handler: impl Fn(i32) + 'static) -> NumberInput {
227        self.element.on(move |event| {
228            if let UiEvent::Changed(EventValue::Number(value)) = event {
229                // Backends report whole numbers in range; `as` saturates.
230                handler(value.round() as i32);
231            }
232        });
233        self
234    }
235}
236
237impl Slider {
238    /// `<Slider a11y_label="Volume" bind=volume/>`
239    #[doc(hidden)]
240    pub fn __tag() -> Slider {
241        Slider {
242            element: Element::new(WidgetKind::Slider),
243            range: Value::Static((0.0, 100.0)),
244            value: Value::Static(0.0),
245        }
246    }
247}
248
249impl NumberInput {
250    /// `<NumberInput a11y_label="Copies" bind=copies/>`
251    #[doc(hidden)]
252    pub fn __tag() -> NumberInput {
253        NumberInput {
254            element: Element::new(WidgetKind::NumberInput),
255            range: Value::Static((0, 100)),
256            value: Value::Static(0),
257        }
258    }
259}