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 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
73const TRACK: (f32, f32) = (120.0, 4.0);
75
76const HANDLE: f32 = 16.0;
78
79const PARTS: f32 = 20.0;
82
83impl Slider {
84 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 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 pub fn step(mut self, step: impl IntoProp<f32>) -> Slider {
116 self.props.step = Some(step.into_prop());
117 self
118 }
119
120 pub fn limit(mut self, max: impl IntoProp<Option<f32>>) -> Slider {
129 self.props.limit = Some(max.into_prop());
130 self
131 }
132
133 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 pub fn vertical(mut self, vertical: impl IntoProp<bool>) -> Slider {
146 self.props.vertical = Some(vertical.into_prop());
147 self
148 }
149
150 pub fn enabled(mut self, enabled: impl IntoProp<bool>) -> Slider {
153 self.props.enabled = Some(enabled.into_prop());
154 self
155 }
156
157 pub fn style(mut self, style: impl IntoProp<Style>) -> Slider {
159 self.props.style = Some(style.into_prop());
160 self
161 }
162
163 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 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 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 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#[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 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 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 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 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 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 fn snap(self) -> Option<f32> {
283 untrack(|| self.step.try_get()).filter(|step| step.is_finite() && *step > 0.0)
284 }
285
286 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 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 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 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 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 let partial = Cell::new(0.0_f32);
390 let on_wheel = move |_: &Cx, wheel: Wheel| {
391 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
447struct 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
459struct Parts {
461 style: StyleFn,
462 fill_style: StyleFn,
463 handle: Memo<Style>,
464 fraction: Memo<f32>,
465 column: bool,
467}
468
469impl Parts {
470 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 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
534fn 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}