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
use std::ops::Range;
use crate::prelude::*;
use accesskit::ActionData;
/// Internal events for the slider view.
pub(crate) enum SliderEvent {
Increment,
Decrement,
SetMin,
SetMax,
ResetDefault,
}
/// 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 a **range** element which fills the slider to indicate the current value.
///
/// # Examples
///
/// ## Basic Slider
/// In the following example, a slider reads from a value source. The `on_change` callback is used
/// to update that value when the slider thumb is moved, or if the track is clicked on.
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// Slider::new(cx, value)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// ```
///
/// ## Slider with Label
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// HStack::new(cx, |cx|{
/// Slider::new(cx, value)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// Label::new(cx, value.map(|val| format!("{:.2}", val)));
/// });
/// ```
pub struct Slider<S> {
value: S,
is_dragging: bool,
/// The orientation of the slider.
orientation: Signal<Orientation>,
/// The range of the slider.
range: Signal<Range<f32>>,
/// The step of the slider.
step: Signal<f32>,
/// The value that the slider resets to when double-clicking the thumb.
default_value: Signal<f32>,
on_change: Option<Box<dyn Fn(&mut EventContext, f32)>>,
}
impl<S> Slider<S>
where
S: SignalGet<f32> + SignalMap<f32> + Copy + 'static,
{
/// Creates a new slider from the provided value source.
///
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// Slider::new(cx, value)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// ```
pub fn new(cx: &mut Context, value: S) -> Handle<Self> {
let range = Signal::new(0.0..1.0);
let orientation = Signal::new(Orientation::Horizontal);
let step = Signal::new(0.01);
let default_value = Signal::new(value.get());
Self { value, is_dragging: false, orientation, range, step, default_value, on_change: None }
.build(cx, move |cx| {
Keymap::from(vec![
(
KeyChord::new(Modifiers::empty(), Code::ArrowUp),
KeymapEntry::new("Increment", |cx| cx.emit(SliderEvent::Increment)),
),
(
KeyChord::new(Modifiers::empty(), Code::ArrowRight),
KeymapEntry::new("Increment", |cx| cx.emit(SliderEvent::Increment)),
),
(
KeyChord::new(Modifiers::empty(), Code::ArrowDown),
KeymapEntry::new("Decrement", |cx| cx.emit(SliderEvent::Decrement)),
),
(
KeyChord::new(Modifiers::empty(), Code::ArrowLeft),
KeymapEntry::new("Decrement", |cx| cx.emit(SliderEvent::Decrement)),
),
(
KeyChord::new(Modifiers::empty(), Code::Home),
KeymapEntry::new("Set Min", |cx| cx.emit(SliderEvent::SetMin)),
),
(
KeyChord::new(Modifiers::empty(), Code::End),
KeymapEntry::new("Set Max", |cx| cx.emit(SliderEvent::SetMax)),
),
])
.build(cx);
// Track
HStack::new(cx, move |cx| {
let active_normalized = Memo::new(move |_| {
let active_range = range.get();
let val = value.get().clamp(active_range.start, active_range.end);
(val - active_range.start) / (active_range.end - active_range.start)
});
let active_width = Memo::new(move |_| {
let normal_val = active_normalized.get();
if orientation.get() == Orientation::Horizontal {
Percentage(normal_val * 100.0)
} else {
Stretch(1.0)
}
});
let active_height = Memo::new(move |_| {
let normal_val = active_normalized.get();
if orientation.get() == Orientation::Horizontal {
Stretch(1.0)
} else {
Percentage(normal_val * 100.0)
}
});
// Range track
VStack::new(cx, move |cx| {
let dir = cx.environment().direction;
let thumb_translate: Memo<Translate> = Memo::new(move |_| {
let thumb_range = range.get();
let val = value.get().clamp(thumb_range.start, thumb_range.end);
let normal_val =
(val - thumb_range.start) / (thumb_range.end - thumb_range.start);
// Todo: Find a way to react to local direction rather than global direction.
// Currently not possible because local direction is a style property
// that gets resolved after bindings.
// Ideally we need a way to do the translation in css which means changing
// a css variable in rust code that gets used in the stylesheet to do the translation
// rather than doing it here in code.
let is_rtl = dir.get() == Direction::RightToLeft;
if orientation.get() == Orientation::Horizontal {
if is_rtl {
(Percentage(-100.0 * (1.0 - normal_val)), Pixels(0.0)).into()
} else {
(Percentage(100.0 * (1.0 - normal_val)), Pixels(0.0)).into()
}
} else {
(Pixels(0.0), Percentage(-100.0 * (1.0 - normal_val))).into()
}
});
// Thumb
Element::new(cx).class("thumb").translate(thumb_translate);
})
.class("range")
.width(active_width)
.height(active_height)
.layout_type(orientation.map(|o| {
if *o == Orientation::Horizontal {
LayoutType::Row
} else {
LayoutType::Column
}
}))
.alignment(orientation.map(|o| {
if *o == Orientation::Horizontal {
Alignment::Right
} else {
Alignment::TopCenter
}
}));
})
.class("track");
})
.orientation(orientation)
.role(Role::Slider)
.numeric_value(value.map(|v| (*v as f64 * 100.0).round() / 100.0))
.text_value(value.map(|v| format!("{}", (*v as f64 * 100.0).round() / 100.0)))
.navigable(true)
}
}
impl<S> View for Slider<S>
where
S: SignalGet<f32> + 'static,
{
fn element(&self) -> Option<&'static str> {
Some("slider")
}
fn accessibility(&self, _cx: &mut AccessContext, node: &mut AccessNode) {
node.set_numeric_value_step(self.step.get() as f64);
node.set_min_numeric_value(self.range.get().start as f64);
node.set_max_numeric_value(self.range.get().end as f64);
}
fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
event.map(|slider_event, _| match slider_event {
SliderEvent::Increment => {
let min = self.range.get().start;
let max = self.range.get().end;
let step = self.step.get();
let mut val = self.value.get() + step;
val = val.clamp(min, max);
if let Some(callback) = &self.on_change {
(callback)(cx, val);
}
}
SliderEvent::Decrement => {
let min = self.range.get().start;
let max = self.range.get().end;
let step = self.step.get();
let mut val = self.value.get() - step;
val = val.clamp(min, max);
if let Some(callback) = &self.on_change {
(callback)(cx, val);
}
}
SliderEvent::SetMin => {
if let Some(callback) = &self.on_change {
(callback)(cx, self.range.get().start);
}
}
SliderEvent::SetMax => {
if let Some(callback) = &self.on_change {
(callback)(cx, self.range.get().end);
}
}
SliderEvent::ResetDefault => {
let min = self.range.get().start;
let max = self.range.get().end;
let val = self.default_value.get().clamp(min, max);
if let Some(callback) = &self.on_change {
(callback)(cx, val);
}
}
});
event.map(|window_event, meta| match window_event {
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 = cx.get_entities_by_class("thumb").first().copied().unwrap();
let thumb_size = match self.orientation.get() {
Orientation::Horizontal => cx.cache.get_width(thumb),
Orientation::Vertical => cx.cache.get_height(thumb),
};
let min = self.range.get().start;
let max = self.range.get().end;
let step = self.step.get();
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 is_rtl = matches!(
cx.style.direction.get(current).copied(),
Some(Direction::RightToLeft)
);
let mut dx = match self.orientation.get() {
Orientation::Horizontal => {
let raw_dx = (cx.mouse.left.pos_down.0 - posx - thumb_size / 2.0)
/ (width - thumb_size);
if is_rtl { 1.0 - raw_dx } else { raw_dx }
}
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_change.take() {
(callback)(cx, val);
self.on_change = 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 = cx.get_entities_by_class("thumb").first().copied().unwrap();
let thumb_size = match self.orientation.get() {
Orientation::Horizontal => cx.cache.get_width(thumb),
Orientation::Vertical => cx.cache.get_height(thumb),
};
let min = self.range.get().start;
let max = self.range.get().end;
let step = self.step.get();
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 is_rtl = matches!(
cx.style.direction.get(current).copied(),
Some(Direction::RightToLeft)
);
let mut dx = match self.orientation.get() {
Orientation::Horizontal => {
let raw_dx = (*x - posx - thumb_size / 2.0) / (width - thumb_size);
if is_rtl { 1.0 - raw_dx } else { raw_dx }
}
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_change {
(callback)(cx, val);
}
}
}
WindowEvent::MouseDoubleClick(button) if *button == MouseButton::Left => {
let is_thumb_target = cx
.get_entities_by_class("thumb")
.first()
.copied()
.map(|thumb| thumb == meta.target)
.unwrap_or(false);
if is_thumb_target {
cx.focus_with_visibility(false);
cx.release();
cx.with_current(Entity::root(), |cx| {
cx.set_pointer_events(true);
});
self.is_dragging = false;
cx.emit(SliderEvent::ResetDefault);
}
}
WindowEvent::ActionRequest(action) => match action.action {
Action::Increment => {
let min = self.range.get().start;
let max = self.range.get().end;
let step = self.step.get();
let mut val = self.value.get() + step;
val = step * (val / step).ceil();
val = val.clamp(min, max);
if let Some(callback) = &self.on_change {
(callback)(cx, val);
}
}
Action::Decrement => {
let min = self.range.get().start;
let max = self.range.get().end;
let step = self.step.get();
let mut val = self.value.get() - step;
val = step * (val / step).ceil();
val = val.clamp(min, max);
if let Some(callback) = &self.on_change {
(callback)(cx, val);
}
}
Action::SetValue => {
if let Some(ActionData::NumericValue(val)) = action.data {
let min = self.range.get().start;
let max = self.range.get().end;
let mut v = val as f32;
v = v.clamp(min, max);
if let Some(callback) = &self.on_change {
(callback)(cx, v);
}
}
}
_ => {}
},
_ => {}
});
}
}
pub trait SliderModifiers: Sized {
/// Sets the callback triggered when the slider value is changed.
///
/// Takes a closure which triggers when the slider value is changed,
/// either by pressing the track or dragging the thumb along the track.
///
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// Slider::new(cx, value)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// ```
fn on_change<F>(self, callback: F) -> Self
where
F: 'static + Fn(&mut EventContext, f32);
/// Sets the range of the slider.
///
/// If the source value is outside of the range then the slider will clip to min/max of the range.
///
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// Slider::new(cx, value)
/// .range(-20.0..50.0)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// ```
fn range<U: Into<Range<f32>> + Clone + 'static>(self, range: impl Res<U> + 'static) -> Self;
/// Sets the orientation of the slider to vertical.
///
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// Slider::new(cx, value)
/// .vertical(true)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// ```
fn vertical<U: Into<bool> + Clone + 'static>(self, vertical: impl Res<U> + 'static) -> Self;
/// Set the step value for the slider.
///
/// ```
/// # use vizia_core::prelude::*;
///
/// # let mut cx = &mut Context::default();
/// # #[derive(Default)]
/// # pub struct AppData {
/// # value: f32,
/// # }
/// # impl Model for AppData {}
/// # let value = Signal::new(0.5);
/// Slider::new(cx, value)
/// .step(0.1_f32)
/// .on_change(|cx, value| {
/// let _ = (cx, value);
/// });
/// ```
fn step<U: Into<f32> + Clone + 'static>(self, step: impl Res<U> + 'static) -> Self;
/// Sets the value that the slider resets to when the thumb is double-clicked.
fn default_value<U: Into<f32> + Clone + 'static>(
self,
default_value: impl Res<U> + 'static,
) -> Self;
}
impl<S> SliderModifiers for Handle<'_, Slider<S>>
where
S: SignalGet<f32> + 'static,
{
fn on_change<F>(self, callback: F) -> Self
where
F: 'static + Fn(&mut EventContext, f32),
{
self.modify(|slider| slider.on_change = Some(Box::new(callback)))
}
fn range<U: Into<Range<f32>> + Clone + 'static>(self, range: impl Res<U> + 'static) -> Self {
let range = range.to_signal(self.cx);
self.bind(range, move |handle| {
let range = range.get();
let range = range.into();
handle.modify(|slider| {
slider.range.set(range);
});
})
}
fn vertical<U: Into<bool> + Clone + 'static>(self, vertical: impl Res<U> + 'static) -> Self {
let vertical = vertical.to_signal(self.cx);
self.bind(vertical, move |handle| {
let vertical = vertical.get().into();
let orientation =
if vertical { Orientation::Vertical } else { Orientation::Horizontal };
handle.modify(|slider| {
slider.orientation.set(orientation);
});
})
}
fn step<U: Into<f32> + Clone + 'static>(self, step: impl Res<U> + 'static) -> Self {
let step = step.to_signal(self.cx);
self.bind(step, move |handle| {
let step = step.get();
let step = step.into();
handle.modify(|slider| {
slider.step.set(step);
});
})
}
fn default_value<U: Into<f32> + Clone + 'static>(
self,
default_value: impl Res<U> + 'static,
) -> Self {
let default_value = default_value.to_signal(self.cx);
self.bind(default_value, move |handle| {
let default_value = default_value.get().into();
handle.modify(|slider| {
slider.default_value.set(default_value);
});
})
}
}