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)]
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 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 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 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 fn unit(self) -> f32 {
226 let (min, max) = self.bounds();
227 self.snap().unwrap_or((max - min) / PARTS)
228 }
229
230 fn snap(self) -> Option<f32> {
232 untrack(|| self.step.try_get()).filter(|step| step.is_finite() && *step > 0.0)
233 }
234
235 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 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 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 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 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 let partial = Cell::new(0.0_f32);
334 let on_wheel = move |_: &Cx, wheel: Wheel| {
335 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
391struct 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
403struct Parts {
405 style: StyleFn,
406 fill_style: StyleFn,
407 handle: Memo<Style>,
408 fraction: Memo<f32>,
409 column: bool,
411}
412
413impl Parts {
414 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 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
478fn 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}