1use 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
18type StyleFn = Rc<dyn Fn() -> Style>;
20
21pub 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
71const TRACK: (f32, f32) = (120.0, 4.0);
73
74const HANDLE: f32 = 16.0;
76
77const PARTS: f32 = 20.0;
80
81impl Slider {
82 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 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 pub fn step(mut self, step: impl IntoProp<f32>) -> Slider {
112 self.props.step = Some(step.into_prop());
113 self
114 }
115
116 pub fn vertical(mut self, vertical: impl IntoProp<bool>) -> Slider {
118 self.props.vertical = Some(vertical.into_prop());
119 self
120 }
121
122 pub fn enabled(mut self, enabled: impl IntoProp<bool>) -> Slider {
125 self.props.enabled = Some(enabled.into_prop());
126 self
127 }
128
129 pub fn style(mut self, style: impl IntoProp<Style>) -> Slider {
131 self.props.style = Some(style.into_prop());
132 self
133 }
134
135 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 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 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 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#[derive(Clone, Copy)]
183struct Range {
184 value: Signal<f32>,
185 min: Memo<f32>,
186 max: Memo<f32>,
187 step: Memo<f32>,
188}
189
190impl Range {
191 fn bounds(self) -> (f32, f32) {
194 let number = |n: f32| if n.is_nan() { 0.0 } else { n };
195 let min = number(self.min.get());
196 (min, number(self.max.get()).max(min))
197 }
198
199 fn fraction(self) -> f32 {
201 let (min, max) = self.bounds();
202 let value = self.value.get();
203 if max > min && !value.is_nan() {
204 ((value - min) / (max - min)).clamp(0.0, 1.0)
205 } else {
206 0.0
207 }
208 }
209
210 fn unit(self) -> f32 {
212 let (min, max) = self.bounds();
213 self.snap().unwrap_or((max - min) / PARTS)
214 }
215
216 fn snap(self) -> Option<f32> {
218 untrack(|| self.step.try_get()).filter(|step| step.is_finite() && *step > 0.0)
219 }
220
221 fn now(self) -> f32 {
223 untrack(|| {
224 let (min, _) = self.bounds();
225 self.value.try_get().filter(|v| !v.is_nan()).unwrap_or(min)
226 })
227 }
228
229 fn write(self, value: f32) {
231 untrack(|| {
232 let (min, max) = self.bounds();
233 let mut value = if value.is_nan() { min } else { value };
234 if let Some(step) = self.snap() {
235 value = min + ((value - min) / step).round() * step;
236 }
237 let value = value.max(min).min(max);
238 if self.value.try_get() != Some(value) {
239 self.value.try_set(value);
240 }
241 });
242 }
243
244 fn write_fraction(self, t: f32) {
246 let (min, max) = untrack(|| self.bounds());
247 self.write(min + t.clamp(0.0, 1.0) * (max - min));
248 }
249}
250
251fn build(cx: &Cx, props: SliderProps) -> Button {
252 let SliderProps {
253 value,
254 min,
255 max,
256 step,
257 vertical,
258 enabled,
259 style,
260 fill_style,
261 handle_style,
262 dragging,
263 } = props;
264 let range = Range {
265 value,
266 min: cx.memo(shared_or(min, 0.0)),
267 max: cx.memo(shared_or(max, 1.0)),
268 step: cx.memo(shared_or(step, 0.0)),
269 };
270 if let Some(dragging) = dragging {
271 cx.signal(LetGo(dragging));
273 }
274 let vertical = cx.memo(shared_or(vertical, false));
275 let style = shared_style(style);
276 let fill_style = shared_style(fill_style);
277 let handle = {
278 let handle_style = shared_style(handle_style);
279 cx.memo(move || {
280 Style::new()
281 .width(HANDLE)
282 .height(HANDLE)
283 .merge(handle_style())
284 .shrink(0.0)
285 })
286 };
287 let fraction = cx.memo(move || range.fraction());
288
289 let on_drag = move |_: &Cx, drag: Drag| {
290 if let Some(dragging) = dragging {
291 let held = drag.phase != DragPhase::End;
292 if untrack(|| dragging.try_get()) != Some(held) {
293 dragging.try_set(held);
294 }
295 }
296 if drag.phase == DragPhase::End {
297 return;
298 }
299 let vertical = untrack(|| vertical.get());
300 let handle = untrack(|| handle.get());
301 let (at, length, size) = if vertical {
302 (drag.position.y, drag.size.height, handle.height)
303 } else {
304 (drag.position.x, drag.size.width, handle.width)
305 };
306 let size = size.unwrap_or(HANDLE).max(0.0);
307 let travel = length - size;
309 let t = if travel > 0.0 {
310 (at - size / 2.0) / travel
311 } else if length > 0.0 {
312 at / length
313 } else {
314 0.0
315 };
316 range.write_fraction(if vertical { 1.0 - t } else { t });
317 };
318 let partial = Cell::new(0.0_f32);
320 let on_wheel = move |_: &Cx, wheel: Wheel| {
321 let notches = wheel.x.notches - wheel.y.notches;
323 let steps = if notches != 0.0 {
324 notches
325 } else {
326 (wheel.x.pixels - wheel.y.pixels) / PIXELS_PER_STEP
327 };
328 if !steps.is_finite() {
329 return;
330 }
331 let unit = untrack(|| range.unit());
332 if range.snap().is_some() {
333 let total = partial.get() + steps;
334 let whole = total.trunc();
335 partial.set(total - whole);
336 if whole != 0.0 {
337 range.write(range.now() + whole * unit);
338 }
339 } else if steps != 0.0 {
340 range.write(range.now() + steps * unit);
341 }
342 if wheel.x.stop || wheel.y.stop {
343 partial.set(0.0);
344 }
345 };
346 let on_key = move |_: &Cx, event: &KeyEvent| {
347 let steps = match event.key {
348 Key::Left | Key::Down => -1.0,
349 Key::Right | Key::Up => 1.0,
350 _ => return false,
351 };
352 range.write(range.now() + steps * untrack(|| range.unit()));
353 true
354 };
355
356 let body = |column: bool| {
357 let parts = Parts {
358 style: Rc::clone(&style),
359 fill_style: Rc::clone(&fill_style),
360 handle,
361 fraction,
362 column,
363 };
364 parts.area().visible(move || vertical.get() == column)
365 };
366 let mut button = Button::new(Stack::new().child(body(false)).child(body(true)))
367 .on_drag(on_drag)
368 .on_wheel(on_wheel)
369 .on_key(on_key);
370 if let Some(enabled) = enabled {
371 button = button.enabled(enabled);
372 }
373 button
374}
375
376struct LetGo(Signal<bool>);
379
380impl Drop for LetGo {
381 fn drop(&mut self) {
382 if untrack(|| self.0.try_get()) == Some(true) {
383 self.0.try_set(false);
384 }
385 }
386}
387
388struct Parts {
390 style: StyleFn,
391 fill_style: StyleFn,
392 handle: Memo<Style>,
393 fraction: Memo<f32>,
394 column: bool,
396}
397
398impl Parts {
399 fn area(self) -> Stack {
401 let Parts {
402 style,
403 fill_style,
404 handle,
405 fraction,
406 column,
407 } = self;
408 let (along, across) = TRACK;
409 let size = if column {
410 Style::new().width(across).height(along)
411 } else {
412 Style::new().width(along).height(across)
413 };
414 let half = move || {
415 let handle = handle.get();
416 let size = if column { handle.height } else { handle.width };
417 size.unwrap_or(HANDLE).max(0.0) / 2.0
418 };
419 let fill = Stack::new().style(move || fill_style().basis(half()).grow(fraction.get()));
422 let rest = Stack::new().style(move || Style::new().basis(half()).grow(1.0 - fraction.get()));
423 let track_style = move || {
424 size
425 .align_self(Align::Center)
426 .justify_self(Align::Center)
427 .merge(style())
428 };
429 let before = Stack::new().style(move || Style::new().basis(0.0).grow(fraction.get()));
430 let after = Stack::new().style(move || Style::new().basis(0.0).grow(1.0 - fraction.get()));
431 let knob = Stack::new().style(move || handle.get());
432 if column {
433 Stack::new()
434 .child(
435 Column::new()
436 .reverse(true)
437 .style(track_style)
438 .child(fill)
439 .child(rest),
440 )
441 .child(
442 Column::new()
443 .reverse(true)
444 .align(Align::Center)
445 .child(before)
446 .child(knob)
447 .child(after),
448 )
449 } else {
450 Stack::new()
451 .child(Row::new().style(track_style).child(fill).child(rest))
452 .child(
453 Row::new()
454 .align(Align::Center)
455 .child(before)
456 .child(knob)
457 .child(after),
458 )
459 }
460 }
461}
462
463fn shared_or<T: Clone + 'static>(prop: Option<Prop<T>>, default: T) -> impl FnMut() -> T + 'static {
465 let prop = prop.map(Prop::shared);
466 move || prop.as_ref().map_or_else(|| default.clone(), |prop| prop())
467}
468
469fn shared_style(prop: Option<Prop<Style>>) -> StyleFn {
470 match prop {
471 Some(prop) => prop.shared(),
472 None => Rc::new(Style::new),
473 }
474}