1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use std::ops::Range;

use accesskit::ActionData;

use crate::prelude::*;

#[derive(Debug)]
enum SliderEventInternal {
    SetThumbSize(f32, f32),
    SetRange(Range<f32>),
    SetKeyboardFraction(f32),
}

#[derive(Clone, Debug, Default, Data)]
pub struct SliderDataInternal {
    pub orientation: Orientation,
    pub size: f32,
    pub thumb_size: f32,
    pub range: Range<f32>,
    pub step: f32,
    pub keyboard_fraction: f32,
}

/// The slider control can be used to select from a continuous set of values.
///
/// The slider control consists of three main parts, a **thumb** element which can be moved between the extremes of a linear **track**,
/// and an **active** element which fills the slider to indicate the current value.
///
/// The slider orientation is determined by its dimensions. If the slider width is greater than the height then the thumb
/// moves horizontally, whereas if the slider height is greater than the width the thumb moves vertically.
///
/// # Examples
///
/// ## Basic Slider
/// In the following example, a slider is bound to a value. The `on_changing` callback is used to send an event to mutate the
/// bound value when the slider thumb is moved, or if the track is clicked on.
/// ```
/// # use vizia_core::prelude::*;
/// # use vizia_derive::*;
/// # let mut cx = &mut Context::default();
/// # #[derive(Lens, Default)]
/// # pub struct AppData {
/// #     value: f32,
/// # }
/// # impl Model for AppData {}
/// # AppData::default().build(cx);
/// Slider::new(cx, AppData::value)
///     .on_changing(|cx, value| {
///         debug!("Slider on_changing: {}", value);
///     });
/// ```
///
/// ## Slider with Label
/// ```
/// # use vizia_core::prelude::*;
/// # use vizia_derive::*;
/// # let mut cx = &mut Context::default();
/// # #[derive(Lens, Default)]
/// # pub struct AppData {
/// #     value: f32,
/// # }
/// # impl Model for AppData {}
/// # AppData::default().build(cx);
/// HStack::new(cx, |cx|{
///     Slider::new(cx, AppData::value)
///         .on_changing(|cx, value| {
///             debug!("Slider on_changing: {}", value);
///         });
///     Label::new(cx, AppData::value.map(|val| format!("{:.2}", val)));
/// });
/// ```
#[derive(Lens)]
pub struct Slider<L: Lens> {
    lens: L,
    is_dragging: bool,
    internal: SliderDataInternal,
    on_changing: Option<Box<dyn Fn(&mut EventContext, f32)>>,
}

impl<L> Slider<L>
where
    L: Lens<Target = f32>,
{
    /// Creates a new slider bound to the value targeted by the lens.
    ///
    /// # Example
    /// ```
    /// # use vizia_core::prelude::*;
    /// # use vizia_derive::*;
    /// # let mut cx = &mut Context::default();
    /// # #[derive(Lens, Default)]
    /// # pub struct AppData {
    /// #     value: f32,
    /// # }
    /// # impl Model for AppData {}
    /// # AppData::default().build(cx);
    /// Slider::new(cx, AppData::value)
    ///     .on_changing(|cx, value| {
    ///         debug!("Slider on_changing: {}", value);
    ///     });
    /// ```
    pub fn new(cx: &mut Context, lens: L) -> Handle<Self> {
        Self {
            lens,
            is_dragging: false,

            internal: SliderDataInternal {
                orientation: Orientation::Horizontal,
                thumb_size: 0.0,
                size: 0.0,
                range: 0.0..1.0,
                step: 0.01,
                keyboard_fraction: 0.1,
            },

            on_changing: None,
        }
        .build(cx, move |cx| {
            Binding::new(cx, Slider::<L>::internal, move |cx, slider_data| {
                ZStack::new(cx, move |cx| {
                    let slider_data = slider_data.get(cx);
                    let thumb_size = slider_data.thumb_size;
                    let orientation = slider_data.orientation;
                    let size = slider_data.size;
                    let range = slider_data.range;

                    // Active track
                    Element::new(cx).class("active").bind(lens, move |handle, value| {
                        let val = value.get(&handle);

                        let normal_val = (val - range.start) / (range.end - range.start);
                        let min = thumb_size / size;
                        let max = 1.0;
                        let dx = min + normal_val * (max - min);

                        if orientation == Orientation::Horizontal {
                            handle
                                .height(Stretch(1.0))
                                .left(Pixels(0.0))
                                .right(Stretch(1.0))
                                .width(Percentage(dx * 100.0));
                        } else {
                            handle
                                .width(Stretch(1.0))
                                .top(Stretch(1.0))
                                .bottom(Pixels(0.0))
                                .height(Percentage(dx * 100.0));
                        }
                    });

                    // Thumb
                    Element::new(cx)
                        .class("thumb")
                        .on_geo_changed(|cx, geo| {
                            if geo.contains(GeoChanged::WIDTH_CHANGED)
                                || geo.contains(GeoChanged::HEIGHT_CHANGED)
                            {
                                let bounds = cx.bounds();
                                cx.emit(SliderEventInternal::SetThumbSize(bounds.w, bounds.h));
                            }
                        })
                        .bind(lens, move |handle, value| {
                            let val = value.get(&handle);
                            let normal_val = (val - range.start) / (range.end - range.start);
                            let px = normal_val * (1.0 - (thumb_size / size));
                            if orientation == Orientation::Horizontal {
                                handle
                                    .right(Stretch(1.0))
                                    .top(Stretch(1.0))
                                    .bottom(Stretch(1.0))
                                    .left(Percentage(100.0 * px));
                            } else {
                                handle
                                    .top(Stretch(1.0))
                                    .left(Stretch(1.0))
                                    .right(Stretch(1.0))
                                    .bottom(Percentage(100.0 * px));
                            }
                        });
                });
            });
        })
        .role(Role::Slider)
        .numeric_value(lens.map(|val| (*val as f64 * 100.0).round() / 100.0))
        .text_value(lens.map(|val| {
            let v = (*val as f64 * 100.0).round() / 100.0;
            format!("{}", v)
        }))
        .navigable(true)
    }

    pub fn custom<F>(cx: &mut Context, lens: L, content: F) -> Handle<Self>
    where
        F: FnOnce(&mut Context),
    {
        Self {
            lens,
            is_dragging: false,

            internal: SliderDataInternal {
                orientation: Orientation::Horizontal,
                thumb_size: 0.0,
                size: 0.0,
                range: 0.0..1.0,
                step: 0.01,
                keyboard_fraction: 0.1,
            },

            on_changing: None,
        }
        .build(cx, move |cx| {
            (content)(cx);
        })
        .navigable(true)
    }
}

impl<L: Lens<Target = f32>> View for Slider<L> {
    fn element(&self) -> Option<&'static str> {
        Some("slider")
    }

    fn accessibility(&self, _cx: &mut AccessContext, node: &mut AccessNode) {
        node.set_numeric_value_step(self.internal.step as f64);
        node.set_min_numeric_value(self.internal.range.start as f64);
        node.set_max_numeric_value(self.internal.range.end as f64);
    }

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.map(|slider_event_internal, _| match slider_event_internal {
            SliderEventInternal::SetThumbSize(width, height) => match self.internal.orientation {
                Orientation::Horizontal => {
                    self.internal.thumb_size = *width;
                }

                Orientation::Vertical => {
                    self.internal.thumb_size = *height;
                }
            },

            SliderEventInternal::SetRange(range) => {
                self.internal.range = range.clone();
            }

            SliderEventInternal::SetKeyboardFraction(keyboard_fraction) => {
                self.internal.keyboard_fraction = *keyboard_fraction;
            }
        });

        event.map(|window_event, _| match window_event {
            WindowEvent::GeometryChanged(_) => {
                let current = cx.current();
                let width = cx.cache.get_width(current);
                let height = cx.cache.get_height(current);

                if width >= height {
                    self.internal.orientation = Orientation::Horizontal;
                    self.internal.size = width;
                } else {
                    self.internal.orientation = Orientation::Vertical;
                    self.internal.size = height;
                }
            }

            WindowEvent::MouseDown(button) if *button == MouseButton::Left => {
                if !cx.is_disabled() {
                    self.is_dragging = true;
                    cx.capture();
                    cx.focus_with_visibility(false);
                    cx.with_current(Entity::root(), |cx| {
                        cx.set_pointer_events(false);
                    });

                    let thumb_size = self.internal.thumb_size;
                    let min = self.internal.range.start;
                    let max = self.internal.range.end;
                    let step = self.internal.step;

                    let current = cx.current();
                    let width = cx.cache.get_width(current);
                    let height = cx.cache.get_height(current);
                    let posx = cx.cache.get_posx(current);
                    let posy = cx.cache.get_posy(current);

                    let mut dx = match self.internal.orientation {
                        Orientation::Horizontal => {
                            (cx.mouse.left.pos_down.0 - posx - thumb_size / 2.0)
                                / (width - thumb_size)
                        }

                        Orientation::Vertical => {
                            (height - (cx.mouse.left.pos_down.1 - posy) - thumb_size / 2.0)
                                / (height - thumb_size)
                        }
                    };

                    dx = dx.clamp(0.0, 1.0);

                    let mut val = min + dx * (max - min);

                    val = step * (val / step).ceil();
                    val = val.clamp(min, max);

                    if let Some(callback) = self.on_changing.take() {
                        (callback)(cx, val);

                        self.on_changing = Some(callback);
                    }
                }
            }

            WindowEvent::MouseUp(button) if *button == MouseButton::Left => {
                self.is_dragging = false;
                cx.focus_with_visibility(false);
                cx.release();
                cx.with_current(Entity::root(), |cx| {
                    cx.set_pointer_events(true);
                });
            }

            WindowEvent::MouseMove(x, y) => {
                if self.is_dragging {
                    let thumb_size = self.internal.thumb_size;

                    let min = self.internal.range.start;
                    let max = self.internal.range.end;
                    let step = self.internal.step;

                    let current = cx.current();
                    let width = cx.cache.get_width(current);
                    let height = cx.cache.get_height(current);
                    let posx = cx.cache.get_posx(current);
                    let posy = cx.cache.get_posy(current);

                    let mut dx = match self.internal.orientation {
                        Orientation::Horizontal => {
                            (*x - posx - thumb_size / 2.0) / (width - thumb_size)
                        }

                        Orientation::Vertical => {
                            (height - (*y - posy) - thumb_size / 2.0) / (height - thumb_size)
                        }
                    };

                    dx = dx.clamp(0.0, 1.0);

                    let mut val = min + dx * (max - min);

                    val = step * (val / step).ceil();
                    val = val.clamp(min, max);

                    if let Some(callback) = &self.on_changing {
                        (callback)(cx, val);
                    }
                }
            }

            WindowEvent::KeyDown(Code::ArrowUp | Code::ArrowRight, _) => {
                let min = self.internal.range.start;
                let max = self.internal.range.end;
                let step = self.internal.step;
                let mut val = self.lens.get(cx) + step;
                // val = step * (val / step).ceil();
                val = val.clamp(min, max);
                if let Some(callback) = &self.on_changing {
                    (callback)(cx, val);
                }
            }

            WindowEvent::KeyDown(Code::ArrowDown | Code::ArrowLeft, _) => {
                let min = self.internal.range.start;
                let max = self.internal.range.end;
                let step = self.internal.step;
                let mut val = self.lens.get(cx) - step;
                // val = step * (val / step).ceil();
                val = val.clamp(min, max);
                if let Some(callback) = &self.on_changing {
                    (callback)(cx, val);
                }
            }

            WindowEvent::ActionRequest(action) => match action.action {
                Action::Increment => {
                    let min = self.internal.range.start;
                    let max = self.internal.range.end;
                    let step = self.internal.step;
                    let mut val = self.lens.get(cx) + step;
                    val = step * (val / step).ceil();
                    val = val.clamp(min, max);
                    if let Some(callback) = &self.on_changing {
                        (callback)(cx, val);
                    }
                }

                Action::Decrement => {
                    let min = self.internal.range.start;
                    let max = self.internal.range.end;
                    let step = self.internal.step;
                    let mut val = self.lens.get(cx) - step;
                    val = step * (val / step).ceil();
                    val = val.clamp(min, max);
                    if let Some(callback) = &self.on_changing {
                        (callback)(cx, val);
                    }
                }

                Action::SetValue => {
                    if let Some(ActionData::NumericValue(val)) = action.data {
                        let min = self.internal.range.start;
                        let max = self.internal.range.end;
                        let mut v = val as f32;
                        v = v.clamp(min, max);
                        if let Some(callback) = &self.on_changing {
                            (callback)(cx, v);
                        }
                    }
                }

                _ => {}
            },

            _ => {}
        });
    }
}

impl<L: Lens> Handle<'_, Slider<L>> {
    /// Sets the callback triggered when the slider value is changing (dragging).
    ///
    /// Takes a closure which triggers when the slider value is changing,
    /// either by pressing the track or dragging the thumb along the track.
    ///
    /// # Example
    ///
    /// ```
    /// # use vizia_core::prelude::*;
    /// # use vizia_derive::*;
    /// # let mut cx = &mut Context::default();
    /// # #[derive(Lens, Default)]
    /// # pub struct AppData {
    /// #     value: f32,
    /// # }
    /// # impl Model for AppData {}
    /// # AppData::default().build(cx);
    /// Slider::new(cx, AppData::value)
    ///     .on_changing(|cx, value| {
    ///         debug!("Slider on_changing: {}", value);
    ///     });
    /// ```
    pub fn on_changing<F>(self, callback: F) -> Self
    where
        F: 'static + Fn(&mut EventContext, f32),
    {
        self.modify(|slider| slider.on_changing = Some(Box::new(callback)))
    }

    /// Sets the range of the slider.
    ///
    /// If the bound data is outside of the range then the slider will clip to min/max of the range.
    ///
    /// # Example
    /// ```
    /// # use vizia_core::prelude::*;
    /// # use vizia_derive::*;
    /// # let mut cx = &mut Context::default();
    /// # #[derive(Lens, Default)]
    /// # pub struct AppData {
    /// #     value: f32,
    /// # }
    /// # impl Model for AppData {}
    /// # AppData::default().build(cx);
    /// Slider::new(cx, AppData::value)
    ///     .range(-20.0..50.0)
    ///     .on_changing(|cx, value| {
    ///         debug!("Slider on_changing: {}", value);
    ///     });
    /// ```
    pub fn range(self, range: Range<f32>) -> Self {
        self.cx.emit_to(self.entity, SliderEventInternal::SetRange(range));

        self
    }

    pub fn step(self, step: f32) -> Self {
        self.modify(|slider: &mut Slider<L>| slider.internal.step = step)
    }

    /// Sets the fraction of a slider that a press of an arrow key will change.
    ///
    /// # Example
    /// ```
    /// # use vizia_core::prelude::*;
    /// # use vizia_derive::*;
    /// # let mut cx = &mut Context::default();
    /// # #[derive(Lens, Default)]
    /// # pub struct AppData {
    /// #     value: f32,
    /// # }
    /// # impl Model for AppData {}
    /// # AppData::default().build(cx);
    /// Slider::new(cx, AppData::value)
    ///     .keyboard_fraction(0.05)
    ///     .on_changing(|cx, value| {
    ///         debug!("Slider on_changing: {}", value);
    ///     });
    /// ```
    pub fn keyboard_fraction(self, keyboard_fraction: f32) -> Self {
        self.cx.emit_to(self.entity, SliderEventInternal::SetKeyboardFraction(keyboard_fraction));

        self
    }
}

enum NamedSliderEvent {
    Change(f32),
}

#[derive(Lens)]
pub struct NamedSlider {
    on_changing: Option<Box<dyn Fn(&mut EventContext, f32)>>,
}

impl NamedSlider {
    pub fn new<L, T>(cx: &mut Context, lens: L, name: impl Res<T>) -> Handle<Self>
    where
        L: Lens<Target = f32>,
        T: ToString,
    {
        let name = name.get(cx).to_string();
        Self { on_changing: None }
            .build(cx, move |cx| {
                Binding::new(cx, lens, move |cx, lens| {
                    Textbox::new(cx, lens.map(|v| format!("{:.2}", v))).on_submit(|cx, txt, _| {
                        if let Ok(val) = txt.parse() {
                            cx.emit(NamedSliderEvent::Change(val));
                        }
                    });
                });
                Slider::custom(cx, lens, move |cx| {
                    Binding::new(cx, Slider::<L>::internal, move |cx, slider_data| {
                        ZStack::new(cx, |cx| {
                            let slider_data = slider_data.get(cx);
                            let thumb_size = slider_data.thumb_size;
                            let size = slider_data.size;
                            let range = slider_data.range;

                            // Active track
                            Element::new(cx).class("active").bind(lens, move |handle, value| {
                                let val = value.get(&handle);
                                let normal_val = (val - range.start) / (range.end - range.start);
                                let min = thumb_size / size;
                                let max = 1.0;
                                let dx = min + normal_val * (max - min);

                                handle
                                    .height(Stretch(1.0))
                                    .left(Pixels(0.0))
                                    .right(Stretch(1.0))
                                    .width(Percentage(dx * 100.0));
                            });

                            Label::new(cx, &name);
                        });
                    })
                })
                .on_changing(|cx, v| cx.emit(NamedSliderEvent::Change(v)));
            })
            .layout_type(LayoutType::Row)
    }
}

impl View for NamedSlider {
    fn element(&self) -> Option<&'static str> {
        Some("namedslider")
    }

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.map(|e, _| match e {
            NamedSliderEvent::Change(v) => {
                if let Some(callback) = self.on_changing.take() {
                    (callback)(cx, *v);

                    self.on_changing = Some(callback);
                }
            }
        })
    }
}

impl Handle<'_, NamedSlider> {
    pub fn on_changing<F>(self, callback: F) -> Self
    where
        F: 'static + Fn(&mut EventContext, f32),
    {
        self.modify(|slider| slider.on_changing = Some(Box::new(callback)))
    }

    pub fn range(self, range: Range<f32>) -> Self {
        self.cx.emit_custom(
            Event::new(SliderEventInternal::SetRange(range))
                .target(self.entity())
                .origin(self.entity())
                .propagate(Propagation::Subtree),
        );

        self
    }

    pub fn keyboard_fraction(self, keyboard_fraction: f32) -> Self {
        self.cx.emit_custom(
            Event::new(SliderEventInternal::SetKeyboardFraction(keyboard_fraction))
                .origin(self.entity())
                .propagate(Propagation::Subtree),
        );

        self
    }
}