1use crate::TestSupportExt as _;
2use std::ops::Range;
3
4use gpui::{
5 AccessibleAction, Along, AnyElement, App, AppContext as _, Axis, Bounds, Context, Div,
6 DragMoveEvent, Empty, Entity, EntityId, EventEmitter, FocusHandle, HitboxBehavior,
7 InteractiveElement, IntoElement, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent,
8 Orientation, ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString,
9 StatefulInteractiveElement, StyleRefinement, Styled, TouchDragEvent, TouchPhase, Window,
10 accesskit::ActionData, div, prelude::FluentBuilder as _, px,
11};
12
13use crate::{
14 LayoutDirection, a11y_disabled::A11yDisabledExt as _, element_ext::ElementExt,
15 geometry::AxisExt,
16};
17
18pub enum SliderEvent {
20 Change(SliderValue),
22 Release(SliderValue),
25}
26
27#[derive(Clone, Copy, Debug, PartialEq)]
34pub enum SliderValue {
35 Single(f32),
36 Range(f32, f32),
37}
38
39impl std::fmt::Display for SliderValue {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 match self {
42 SliderValue::Single(value) => write!(f, "{}", value),
43 SliderValue::Range(start, end) => write!(f, "{}..{}", start, end),
44 }
45 }
46}
47
48impl From<f32> for SliderValue {
49 fn from(value: f32) -> Self {
50 SliderValue::Single(value)
51 }
52}
53
54impl From<(f32, f32)> for SliderValue {
55 fn from(value: (f32, f32)) -> Self {
56 SliderValue::Range(value.0, value.1)
57 }
58}
59
60impl From<Range<f32>> for SliderValue {
61 fn from(value: Range<f32>) -> Self {
62 SliderValue::Range(value.start, value.end)
63 }
64}
65
66impl Default for SliderValue {
67 fn default() -> Self {
68 SliderValue::Single(0.)
69 }
70}
71
72impl SliderValue {
73 pub fn clamp(self, min: f32, max: f32) -> Self {
75 match self {
76 SliderValue::Single(value) => SliderValue::Single(value.clamp(min, max)),
77 SliderValue::Range(start, end) => {
78 SliderValue::Range(start.clamp(min, max), end.clamp(min, max))
79 }
80 }
81 }
82
83 #[inline]
85 pub fn is_single(&self) -> bool {
86 matches!(self, SliderValue::Single(_))
87 }
88
89 #[inline]
91 pub fn is_range(&self) -> bool {
92 matches!(self, SliderValue::Range(_, _))
93 }
94
95 pub fn start(&self) -> f32 {
97 match self {
98 SliderValue::Single(value) => *value,
99 SliderValue::Range(start, _) => *start,
100 }
101 }
102
103 pub fn end(&self) -> f32 {
105 match self {
106 SliderValue::Single(value) => *value,
107 SliderValue::Range(_, end) => *end,
108 }
109 }
110
111 fn set_start(&mut self, value: f32) {
112 if let SliderValue::Range(_, end) = self {
113 *self = SliderValue::Range(value.min(*end), *end);
114 } else {
115 *self = SliderValue::Single(value);
116 }
117 }
118
119 fn set_end(&mut self, value: f32) {
120 if let SliderValue::Range(start, _) = self {
121 *self = SliderValue::Range(*start, value.max(*start));
122 } else {
123 *self = SliderValue::Single(value);
124 }
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
130pub enum SliderScale {
131 #[default]
134 Linear,
135 Logarithmic,
160}
161
162impl SliderScale {
163 #[inline]
164 pub fn is_linear(&self) -> bool {
165 matches!(self, SliderScale::Linear)
166 }
167
168 #[inline]
169 pub fn is_logarithmic(&self) -> bool {
170 matches!(self, SliderScale::Logarithmic)
171 }
172}
173
174pub struct SliderState {
176 min: f32,
177 max: f32,
178 step: f32,
179 value: SliderValue,
180 percentage: Range<f32>,
182 bounds: Bounds<Pixels>,
184 scale: SliderScale,
185 dragging: bool,
188 touch_drag: Option<TouchDrag>,
190}
191
192#[derive(Clone, Copy)]
194struct TouchDrag {
195 start_position: Point<Pixels>,
197 is_start: bool,
199}
200
201impl SliderState {
202 pub fn new() -> Self {
204 Self {
205 min: 0.0,
206 max: 100.0,
207 step: 1.0,
208 value: SliderValue::default(),
209 percentage: (0.0..0.0),
210 bounds: Bounds::default(),
211 scale: SliderScale::default(),
212 dragging: false,
213 touch_drag: None,
214 }
215 }
216
217 pub fn min(mut self, min: f32) -> Self {
219 if self.scale.is_logarithmic() {
220 assert!(
221 min > 0.0,
222 "`min` must be greater than 0 for SliderScale::Logarithmic"
223 );
224 assert!(
225 min < self.max,
226 "`min` must be less than `max` for Logarithmic scale"
227 );
228 }
229 self.min = min;
230 self.update_thumb_pos();
231 self
232 }
233
234 pub fn max(mut self, max: f32) -> Self {
236 if self.scale.is_logarithmic() {
237 assert!(
238 max > self.min,
239 "`max` must be greater than `min` for Logarithmic scale"
240 );
241 }
242 self.max = max;
243 self.update_thumb_pos();
244 self
245 }
246
247 pub fn step(mut self, step: f32) -> Self {
249 self.step = step;
250 self
251 }
252
253 pub fn scale(mut self, scale: SliderScale) -> Self {
255 if scale.is_logarithmic() {
256 assert!(
257 self.min > 0.0,
258 "`min` must be greater than 0 for Logarithmic scale"
259 );
260 assert!(
261 self.max > self.min,
262 "`max` must be greater than `min` for Logarithmic scale"
263 );
264 }
265 self.scale = scale;
266 self.update_thumb_pos();
267 self
268 }
269
270 pub fn default_value(mut self, value: impl Into<SliderValue>) -> Self {
272 self.value = value.into();
273 self.update_thumb_pos();
274 self
275 }
276
277 pub fn set_value(
279 &mut self,
280 value: impl Into<SliderValue>,
281 _: &mut Window,
282 cx: &mut Context<Self>,
283 ) {
284 self.value = value.into();
285 self.update_thumb_pos();
286 cx.notify();
287 }
288
289 pub fn value(&self) -> SliderValue {
291 self.value
292 }
293
294 pub fn min_value(&self) -> f32 {
296 self.min
297 }
298
299 pub fn max_value(&self) -> f32 {
301 self.max
302 }
303
304 pub fn step_value(&self) -> f32 {
306 self.step
307 }
308
309 pub fn accessibility_step(&self) -> f32 {
313 if is_step(self.step) {
314 self.step
315 } else {
316 (self.max - self.min) / 100.
317 }
318 }
319
320 fn percentage_to_value(&self, percentage: f32) -> f32 {
323 match self.scale {
324 SliderScale::Linear => self.min + (self.max - self.min) * percentage,
325 SliderScale::Logarithmic => {
326 let base = self.max / self.min;
330 (base.powf(percentage) * self.min).clamp(self.min, self.max)
331 }
332 }
333 }
334
335 fn value_to_percentage(&self, value: f32) -> f32 {
338 match self.scale {
339 SliderScale::Linear => {
340 let range = self.max - self.min;
341 if range <= 0.0 {
342 0.0
343 } else {
344 (value - self.min) / range
345 }
346 }
347 SliderScale::Logarithmic => {
348 let base = self.max / self.min;
349 (value / self.min).log(base).clamp(0.0, 1.0)
350 }
351 }
352 }
353
354 fn update_thumb_pos(&mut self) {
355 match self.value {
356 SliderValue::Single(value) => {
357 let percentage = self.value_to_percentage(value.min(self.max).max(self.min));
358 self.percentage = 0.0..percentage;
359 }
360 SliderValue::Range(start, end) => {
361 let clamped_start = start.min(self.max).max(self.min);
364 let clamped_end = end.min(self.max).max(self.min);
365 self.percentage =
366 self.value_to_percentage(clamped_start)..self.value_to_percentage(clamped_end);
367 }
368 }
369 }
370
371 #[doc(hidden)]
373 pub fn update_value_by_position(
374 &mut self,
375 axis: Axis,
376 position: Point<Pixels>,
377 is_start: bool,
378 _: &mut Window,
379 cx: &mut Context<Self>,
380 ) {
381 self.dragging = true;
382 let bounds = self.bounds;
383 let step = self.step;
384
385 let inner_pos = self.offset_along(axis, position, cx);
386 let total_size = bounds.size.along(axis);
387 let percentage = inner_pos.clamp(px(0.), total_size) / total_size;
388
389 let percentage = if is_start {
390 percentage.clamp(0.0, self.percentage.end)
391 } else {
392 percentage.clamp(self.percentage.start, 1.0)
393 };
394
395 let value = self.percentage_to_value(percentage);
396 let value = snap_to_step(value, self.min, self.max, step);
397
398 if is_start {
399 self.value.set_start(value);
400 } else {
401 self.value.set_end(value);
402 }
403 self.update_thumb_pos();
405 cx.emit(SliderEvent::Change(self.value));
406 cx.notify();
407 }
408
409 #[doc(hidden)]
415 pub fn step_thumb(
416 &mut self,
417 start: bool,
418 delta: f32,
419 window: &mut Window,
420 cx: &mut Context<Self>,
421 ) {
422 if !steppable(self.value, self.min, self.max) {
424 return;
425 }
426 let value = step_thumb(self.value, start, delta, self.min, self.max, self.step);
427 self.commit_thumb_value(value, window, cx);
428 }
429
430 fn handle_accessibility_set_value(
431 &mut self,
432 data: Option<&ActionData>,
433 window: &mut Window,
434 cx: &mut Context<Self>,
435 ) {
436 let Some(ActionData::NumericValue(target)) = data else {
437 return;
438 };
439 if !target.is_finite() || !steppable(self.value, self.min, self.max) {
440 return;
441 }
442 let value = thumb_value_at(
443 self.value,
444 false,
445 *target as f32,
446 self.min,
447 self.max,
448 self.step,
449 );
450 self.commit_thumb_value(value, window, cx);
451 }
452
453 fn commit_thumb_value(
454 &mut self,
455 value: SliderValue,
456 window: &mut Window,
457 cx: &mut Context<Self>,
458 ) {
459 if value != self.value {
460 self.set_value(value, window, cx);
461 cx.emit(SliderEvent::Change(value));
462 cx.emit(SliderEvent::Release(value));
464 }
465 }
466
467 fn is_nearer_start(&self, axis: Axis, position: Point<Pixels>, cx: &App) -> bool {
469 let size = self.bounds.size.along(axis);
470 let along = self.offset_along(axis, position, cx);
471 let center =
472 ((self.percentage.end - self.percentage.start) / 2. + self.percentage.start) * size;
473 along < center
474 }
475
476 fn offset_along(&self, axis: Axis, position: Point<Pixels>, cx: &App) -> Pixels {
479 if axis.is_vertical() {
480 self.bounds.bottom() - position.y
481 } else if LayoutDirection::global(cx).is_rtl() {
482 self.bounds.right() - position.x
483 } else {
484 position.x - self.bounds.left()
485 }
486 }
487
488 #[doc(hidden)]
491 pub fn handle_release(&mut self, cx: &mut Context<Self>) {
492 if !self.dragging {
493 return;
494 }
495 self.dragging = false;
496 cx.emit(SliderEvent::Release(self.value));
497 }
498}
499
500const PAGE_STEPS: f32 = 10.;
502
503fn key_delta(keystroke: &Keystroke, axis: Axis, rtl: bool, step: f32, range: f32) -> Option<f32> {
506 if keystroke.modifiers.modified() {
507 return None;
508 }
509 let toward_end = if axis.is_horizontal() && rtl {
511 -step
512 } else {
513 step
514 };
515 match keystroke.key.as_str() {
516 "right" => Some(toward_end),
517 "left" => Some(-toward_end),
518 "up" => Some(step),
519 "down" => Some(-step),
520 "pageup" => Some(step * PAGE_STEPS),
521 "pagedown" => Some(-step * PAGE_STEPS),
522 "home" => Some(-range),
523 "end" => Some(range),
524 _ => None,
525 }
526}
527
528fn is_step(step: f32) -> bool {
530 step > 0. && step.is_finite()
531}
532
533fn snap_to_step(value: f32, min: f32, max: f32, step: f32) -> f32 {
536 if !is_step(step) {
537 return value;
538 }
539 (min + ((value - min) / step).round() * step)
540 .min(max)
541 .max(min)
542}
543
544fn steppable(value: SliderValue, min: f32, max: f32) -> bool {
547 let (start, end) = (value.start(), value.end());
548 min <= max && !start.is_nan() && !end.is_nan() && (!value.is_range() || start <= end)
549}
550
551fn step_thumb(
555 value: SliderValue,
556 start: bool,
557 delta: f32,
558 min: f32,
559 max: f32,
560 step: f32,
561) -> SliderValue {
562 if !steppable(value, min, max) {
563 return value;
564 }
565 let current = if start && value.is_range() {
566 value.start()
567 } else {
568 value.end()
569 };
570 thumb_value_at(value, start, current + delta, min, max, step)
571}
572
573fn thumb_value_at(
574 mut value: SliderValue,
575 start: bool,
576 target: f32,
577 min: f32,
578 max: f32,
579 step: f32,
580) -> SliderValue {
581 let next = snap_to_step(target, min, max, step).min(max).max(min);
582 if start && value.is_range() {
583 value.set_start(next);
584 } else {
585 value.set_end(next);
586 }
587 value
588}
589
590#[derive(Clone)]
591struct DragThumb((EntityId, bool));
592
593impl Render for DragThumb {
594 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
595 Empty
596 }
597}
598
599#[derive(Clone)]
600struct DragSlider(EntityId);
601
602impl Render for DragSlider {
603 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
604 Empty
605 }
606}
607
608#[derive(IntoElement)]
612pub struct Slider {
613 state: Entity<SliderState>,
614 axis: Axis,
615 disabled: bool,
616 accessibility_label: Option<SharedString>,
617 focus: Option<FocusHandle>,
618 base: Div,
619 children: Vec<AnyElement>,
620}
621
622impl Slider {
623 pub fn new(state: &Entity<SliderState>) -> Self {
624 Self {
625 state: state.clone(),
626 axis: Axis::Horizontal,
627 disabled: false,
628 accessibility_label: None,
629 focus: None,
630 base: div(),
631 children: Vec::new(),
632 }
633 }
634
635 pub fn horizontal(mut self) -> Self {
636 self.axis = Axis::Horizontal;
637 self
638 }
639
640 pub fn vertical(mut self) -> Self {
641 self.axis = Axis::Vertical;
642 self
643 }
644
645 pub fn axis(mut self, axis: Axis) -> Self {
646 self.axis = axis;
647 self
648 }
649
650 pub fn disabled(mut self, disabled: bool) -> Self {
651 self.disabled = disabled;
652 self
653 }
654
655 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
657 self.accessibility_label = Some(label.into());
658 self
659 }
660
661 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
666 self.focus = Some(focus.clone());
667 self
668 }
669}
670
671impl ParentElement for Slider {
672 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
673 self.children.extend(elements);
674 }
675}
676
677impl Styled for Slider {
678 fn style(&mut self) -> &mut StyleRefinement {
679 self.base.style()
680 }
681}
682
683impl RenderOnce for Slider {
684 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
685 let axis = self.axis;
686 let entity_id = self.state.entity_id();
687 let state = self.state.read(cx);
688 let slider_state = self.state.clone();
689
690 self.base
691 .id(("slider", entity_id))
692 .test_support()
693 .when_some(self.focus, |this, focus| this.track_focus(&focus))
694 .role(Role::Slider)
695 .when_some(self.accessibility_label, |this, label| {
696 this.aria_label(label)
697 })
698 .aria_numeric_value(state.value().end() as f64)
699 .aria_min_numeric_value(state.min_value() as f64)
700 .aria_max_numeric_value(state.max_value() as f64)
701 .aria_numeric_value_step(state.accessibility_step() as f64)
702 .aria_orientation(if axis.is_vertical() {
703 Orientation::Vertical
704 } else {
705 Orientation::Horizontal
706 })
707 .when(!self.disabled, |this| {
710 this.on_a11y_action(AccessibleAction::Increment, {
711 let state = slider_state.clone();
712 move |_, window, cx| {
713 state.update(cx, |state, cx| {
714 state.step_thumb(false, state.accessibility_step(), window, cx);
715 });
716 }
717 })
718 .on_a11y_action(AccessibleAction::Decrement, {
719 let state = slider_state.clone();
720 move |_, window, cx| {
721 state.update(cx, |state, cx| {
722 state.step_thumb(false, -state.accessibility_step(), window, cx);
723 });
724 }
725 })
726 .on_a11y_action(AccessibleAction::SetValue, {
727 let state = slider_state.clone();
728 move |data, window, cx| {
729 state.update(cx, |state, cx| {
730 state.handle_accessibility_set_value(data, window, cx);
731 });
732 }
733 })
734 .on_key_down({
736 let state = slider_state.clone();
737 move |event: &KeyDownEvent, window, cx| {
738 let rtl = LayoutDirection::global(cx).is_rtl();
739 state.update(cx, |state, cx| {
740 let step = state.accessibility_step();
741 let range = state.max - state.min;
742 let Some(delta) = key_delta(&event.keystroke, axis, rtl, step, range)
743 else {
744 return;
745 };
746 state.step_thumb(false, delta, window, cx);
747 cx.stop_propagation();
748 });
749 }
750 })
751 .on_mouse_up(
752 MouseButton::Left,
753 window.listener_for(&self.state, |state, _, _, cx| state.handle_release(cx)),
754 )
755 .on_mouse_up_out(
756 MouseButton::Left,
757 window.listener_for(&self.state, |state, _, _, cx| state.handle_release(cx)),
758 )
759 })
760 .children(self.children)
761 .a11y_disabled(self.disabled)
762 }
763}
764
765#[derive(IntoElement)]
767pub struct SliderTrack {
768 state: Entity<SliderState>,
769 axis: Axis,
770 disabled: bool,
771 base: Div,
772 children: Vec<AnyElement>,
773}
774
775impl SliderTrack {
776 pub fn new(state: &Entity<SliderState>) -> Self {
777 Self {
778 state: state.clone(),
779 axis: Axis::Horizontal,
780 disabled: false,
781 base: div(),
782 children: Vec::new(),
783 }
784 }
785
786 pub fn axis(mut self, axis: Axis) -> Self {
787 self.axis = axis;
788 self
789 }
790 pub fn disabled(mut self, disabled: bool) -> Self {
791 self.disabled = disabled;
792 self
793 }
794}
795
796impl ParentElement for SliderTrack {
797 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
798 self.children.extend(elements);
799 }
800}
801
802impl Styled for SliderTrack {
803 fn style(&mut self) -> &mut StyleRefinement {
804 self.base.style()
805 }
806}
807
808impl InteractiveElement for SliderTrack {
809 fn interactivity(&mut self) -> &mut gpui::Interactivity {
810 self.base.interactivity()
811 }
812}
813
814impl RenderOnce for SliderTrack {
815 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
816 let axis = self.axis;
817 let entity_id = self.state.entity_id();
818 let state = self.state.read(cx);
819 let is_range = state.value().is_range();
820 let touch_layer = (!self.disabled).then(|| {
824 let slider_state = self.state.clone();
825 gpui::canvas(
826 |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
827 move |_, hitbox, window, _| {
828 let slider_state = slider_state.clone();
829 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
830 if !phase.bubble() {
831 return;
832 }
833 slider_state.update(cx, |state, cx| {
834 if event.phase == TouchPhase::Started {
835 if state.touch_drag.take().is_some() {
838 state.handle_release(cx);
839 }
840 if window.default_prevented() || !hitbox.is_hovered(window) {
843 return;
844 }
845 window.prevent_default();
846 let is_start = is_range
847 && state.is_nearer_start(axis, event.start_position, cx);
848 state.touch_drag = Some(TouchDrag {
849 start_position: event.start_position,
850 is_start,
851 });
852 }
853 let Some(drag) = state.touch_drag else {
854 return;
855 };
856 if drag.start_position != event.start_position {
857 return;
858 }
859 cx.stop_propagation();
860 match event.phase {
861 TouchPhase::Started | TouchPhase::Moved => {
862 state.update_value_by_position(
863 axis,
864 event.position,
865 drag.is_start,
866 window,
867 cx,
868 );
869 }
870 TouchPhase::Ended | TouchPhase::Cancelled => {
871 state.touch_drag = None;
872 state.handle_release(cx);
873 }
874 }
875 });
876 });
877 },
878 )
879 .absolute()
880 .size_full()
881 });
882 self.base
883 .id("slider-bar-container")
884 .test_support()
885 .children(self.children)
886 .children(touch_layer)
887 .when(!self.disabled, |this| {
888 this.on_mouse_down(
889 MouseButton::Left,
890 window.listener_for(
891 &self.state,
892 move |state, event: &MouseDownEvent, window, cx| {
893 let is_start =
894 is_range && state.is_nearer_start(axis, event.position, cx);
895 state.update_value_by_position(
896 axis,
897 event.position,
898 is_start,
899 window,
900 cx,
901 );
902 },
903 ),
904 )
905 .when(!is_range, |this| {
906 this.on_drag(DragSlider(entity_id), |drag, _, _, cx| {
907 cx.stop_propagation();
908 cx.new(|_| drag.clone())
909 })
910 .on_drag_move(window.listener_for(
911 &self.state,
912 move |state, event: &DragMoveEvent<DragSlider>, window, cx| {
913 let DragSlider(id) = event.drag(cx);
914 if *id == entity_id {
915 state.update_value_by_position(
916 axis,
917 event.event.position,
918 false,
919 window,
920 cx,
921 );
922 }
923 },
924 ))
925 })
926 })
927 }
928}
929
930#[derive(IntoElement)]
932pub struct SliderIndicator {
933 state: Entity<SliderState>,
934 base: Div,
935 children: Vec<AnyElement>,
936}
937
938impl SliderIndicator {
939 pub fn new(state: &Entity<SliderState>) -> Self {
940 Self {
941 state: state.clone(),
942 base: div(),
943 children: Vec::new(),
944 }
945 }
946}
947
948impl ParentElement for SliderIndicator {
949 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
950 self.children.extend(elements);
951 }
952}
953
954impl Styled for SliderIndicator {
955 fn style(&mut self) -> &mut StyleRefinement {
956 self.base.style()
957 }
958}
959
960impl InteractiveElement for SliderIndicator {
961 fn interactivity(&mut self) -> &mut gpui::Interactivity {
962 self.base.interactivity()
963 }
964}
965
966impl StatefulInteractiveElement for SliderIndicator {}
967
968impl RenderOnce for SliderIndicator {
969 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
970 self.base
971 .id("slider-bar")
972 .children(self.children)
973 .on_prepaint({
974 let state = self.state;
975 move |bounds, _, cx| {
979 if state.read(cx).bounds != bounds {
980 state.update(cx, |state, _| state.set_bounds(bounds));
981 }
982 }
983 })
984 }
985}
986
987#[derive(IntoElement)]
989pub struct SliderThumb {
990 state: Entity<SliderState>,
991 axis: Axis,
992 start: bool,
993 disabled: bool,
994 base: Div,
995 children: Vec<AnyElement>,
996}
997
998impl SliderThumb {
999 pub fn new(state: &Entity<SliderState>) -> Self {
1000 Self {
1001 state: state.clone(),
1002 axis: Axis::Horizontal,
1003 start: false,
1004 disabled: false,
1005 base: div(),
1006 children: Vec::new(),
1007 }
1008 }
1009
1010 pub fn axis(mut self, axis: Axis) -> Self {
1011 self.axis = axis;
1012 self
1013 }
1014 pub fn start(mut self, start: bool) -> Self {
1015 self.start = start;
1016 self
1017 }
1018 pub fn disabled(mut self, disabled: bool) -> Self {
1019 self.disabled = disabled;
1020 self
1021 }
1022}
1023
1024impl ParentElement for SliderThumb {
1025 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1026 self.children.extend(elements);
1027 }
1028}
1029
1030impl Styled for SliderThumb {
1031 fn style(&mut self) -> &mut StyleRefinement {
1032 self.base.style()
1033 }
1034}
1035
1036impl InteractiveElement for SliderThumb {
1037 fn interactivity(&mut self) -> &mut gpui::Interactivity {
1038 self.base.interactivity()
1039 }
1040}
1041
1042impl StatefulInteractiveElement for SliderThumb {}
1043
1044impl RenderOnce for SliderThumb {
1045 fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
1046 let entity_id = self.state.entity_id();
1047 let axis = self.axis;
1048 let start = self.start;
1049 self.base
1050 .id(("slider-thumb", start as u32))
1051 .test_support()
1052 .children(self.children)
1053 .when(!self.disabled, |this| {
1054 this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1055 .on_drag(DragThumb((entity_id, start)), |drag, _, _, cx| {
1056 cx.stop_propagation();
1057 cx.new(|_| drag.clone())
1058 })
1059 .on_drag_move(window.listener_for(
1060 &self.state,
1061 move |state, event: &DragMoveEvent<DragThumb>, window, cx| {
1062 let DragThumb((id, start)) = event.drag(cx);
1063 if *id == entity_id {
1064 state.update_value_by_position(
1065 axis,
1066 event.event.position,
1067 *start,
1068 window,
1069 cx,
1070 );
1071 }
1072 },
1073 ))
1074 })
1075 .a11y_disabled(self.disabled)
1077 }
1078}
1079
1080impl EventEmitter<SliderEvent> for SliderState {}
1081
1082impl SliderState {
1083 #[doc(hidden)]
1084 pub fn percentage(&self) -> Range<f32> {
1085 self.percentage.clone()
1086 }
1087
1088 #[doc(hidden)]
1089 pub fn bounds(&self) -> Bounds<Pixels> {
1090 self.bounds
1091 }
1092
1093 #[doc(hidden)]
1094 pub fn set_bounds(&mut self, bounds: Bounds<Pixels>) {
1095 self.bounds = bounds;
1096 }
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101 use super::*;
1102
1103 #[test]
1104 fn legacy_value_conversions_and_clamping_are_preserved() {
1105 assert_eq!(SliderValue::from(5.), SliderValue::Single(5.));
1106 assert_eq!(SliderValue::from((2., 8.)), SliderValue::Range(2., 8.));
1107 assert_eq!(SliderValue::from(2.0..8.0), SliderValue::Range(2., 8.));
1108 assert_eq!(
1109 SliderValue::Range(-1., 12.).clamp(0., 10.),
1110 SliderValue::Range(0., 10.)
1111 );
1112 }
1113
1114 #[test]
1115 fn legacy_linear_state_keeps_percentage_and_range_ordering() {
1116 let state = SliderState::new()
1117 .min(0.)
1118 .max(200.)
1119 .default_value((50., 150.));
1120 assert_eq!(state.value(), SliderValue::Range(50., 150.));
1121 assert_eq!(state.percentage(), 0.25..0.75);
1122 }
1123
1124 #[test]
1125 fn legacy_logarithmic_state_keeps_mapping() {
1126 let state = SliderState::new()
1127 .min(1.)
1128 .max(1000.)
1129 .scale(SliderScale::Logarithmic)
1130 .default_value(10.);
1131 let percentage = state.percentage().end;
1132 assert!((percentage - (1. / 3.)).abs() < 0.0001);
1133 }
1134
1135 #[gpui::test]
1136 fn a_disabled_thumb_marks_its_node_disabled(cx: &mut gpui::TestAppContext) {
1137 struct Thumb {
1138 state: Entity<SliderState>,
1139 disabled: bool,
1140 }
1141
1142 impl Render for Thumb {
1143 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1144 SliderThumb::new(&self.state)
1145 .role(Role::Slider)
1146 .disabled(self.disabled)
1147 }
1148 }
1149
1150 for disabled in [false, true] {
1151 let (_, cx) = cx.add_window_view(|_, cx| Thumb {
1152 state: cx.new(|_| SliderState::new()),
1153 disabled,
1154 });
1155 cx.update(|window, cx| {
1156 window.draw(cx).clear(cx);
1157 let thumb = crate::test_support::snapshots(window)
1158 .into_iter()
1159 .find(|node| node.role() == Some(Role::Slider))
1160 .expect("a thumb node");
1161 assert_eq!(thumb.disabled(), disabled.then_some(true));
1162 });
1163 }
1164 }
1165
1166 #[gpui::test]
1167 fn a_slider_takes_focus_on_its_own_node(cx: &mut gpui::TestAppContext) {
1168 struct Focusable {
1169 state: Entity<SliderState>,
1170 focus: FocusHandle,
1171 }
1172
1173 impl Render for Focusable {
1174 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1175 Slider::new(&self.state).track_focus(&self.focus)
1176 }
1177 }
1178
1179 let (view, cx) = cx.add_window_view(|_, cx| Focusable {
1180 state: cx.new(|_| SliderState::new()),
1181 focus: cx.focus_handle(),
1182 });
1183 cx.update(|window, cx| {
1184 let focus = view.read(cx).focus.clone();
1185 focus.focus(window, cx);
1186 window.draw(cx).clear(cx);
1187 let slider = crate::test_support::snapshots(window)
1188 .into_iter()
1189 .find(|node| node.role() == Some(Role::Slider))
1190 .expect("a slider node");
1191 assert_eq!(slider.focused(), Some(true));
1192 });
1193 }
1194
1195 #[test]
1196 fn keys_map_to_steps() {
1197 let key = |key: &'static str, axis, rtl| {
1198 key_delta(&Keystroke::parse(key).unwrap(), axis, rtl, 5., 100.)
1199 };
1200 for axis in [Axis::Horizontal, Axis::Vertical] {
1201 assert_eq!(key("right", axis, false), Some(5.));
1202 assert_eq!(key("left", axis, false), Some(-5.));
1203 assert_eq!(key("up", axis, false), Some(5.));
1204 assert_eq!(key("down", axis, false), Some(-5.));
1205 assert_eq!(key("pageup", axis, false), Some(50.));
1206 assert_eq!(key("pagedown", axis, false), Some(-50.));
1207 assert_eq!(key("home", axis, false), Some(-100.));
1208 assert_eq!(key("end", axis, false), Some(100.));
1209 assert_eq!(key("a", axis, false), None);
1210 assert_eq!(key("ctrl-right", axis, false), None);
1211 assert_eq!(key("shift-home", axis, false), None);
1212 }
1213 assert_eq!(key("right", Axis::Horizontal, true), Some(-5.));
1215 assert_eq!(key("left", Axis::Horizontal, true), Some(5.));
1216 assert_eq!(key("up", Axis::Horizontal, true), Some(5.));
1217 assert_eq!(key("right", Axis::Vertical, true), Some(5.));
1218 }
1219
1220 #[gpui::test]
1221 fn a_focused_slider_steps_on_keys_and_reports_each_step(cx: &mut gpui::TestAppContext) {
1222 struct Focusable {
1223 state: Entity<SliderState>,
1224 focus: FocusHandle,
1225 disabled: bool,
1226 }
1227
1228 impl Render for Focusable {
1229 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1230 Slider::new(&self.state)
1231 .track_focus(&self.focus)
1232 .disabled(self.disabled)
1233 }
1234 }
1235
1236 let (view, cx) = cx.add_window_view(|_, cx| Focusable {
1237 state: cx.new(|_| SliderState::new().step(5.).default_value(50.)),
1238 focus: cx.focus_handle(),
1239 disabled: false,
1240 });
1241 let state = view.read_with(cx, |view, _| view.state.clone());
1242 let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1243 cx.update(|window, cx| {
1244 let events = events.clone();
1245 cx.subscribe(&state, move |_, event: &SliderEvent, _| {
1246 events.borrow_mut().push(match event {
1247 SliderEvent::Change(value) => ("change", value.end()),
1248 SliderEvent::Release(value) => ("release", value.end()),
1249 });
1250 })
1251 .detach();
1252 view.read(cx).focus.clone().focus(window, cx);
1253 window.draw(cx).clear(cx);
1254 });
1255
1256 for (key, value) in [
1257 ("right", 55.),
1258 ("left", 50.),
1259 ("up", 55.),
1260 ("down", 50.),
1261 ("pageup", 100.),
1262 ("pagedown", 50.),
1263 ("home", 0.),
1264 ("end", 100.),
1265 ] {
1266 cx.simulate_keystrokes(key);
1267 assert_eq!(
1268 std::mem::take(&mut *events.borrow_mut()),
1269 [("change", value), ("release", value)],
1270 "{key}"
1271 );
1272 }
1273 cx.simulate_keystrokes("end ctrl-left");
1275 view.update(cx, |view, cx| {
1276 view.disabled = true;
1277 cx.notify();
1278 });
1279 cx.simulate_keystrokes("home");
1280 assert!(events.borrow().is_empty());
1281 assert_eq!(state.read_with(cx, |state, _| state.value().end()), 100.);
1282 }
1283
1284 #[test]
1285 fn min_can_be_set_above_the_default_max_before_max() {
1286 let state = SliderState::new().min(150.).max(200.).default_value(175.);
1287 assert_eq!(state.value(), SliderValue::Single(175.));
1288 assert_eq!(state.percentage(), 0.0..0.5);
1289
1290 let state = SliderState::new()
1291 .default_value((160., 180.))
1292 .min(150.)
1293 .max(200.);
1294 assert_eq!(state.percentage(), 0.2..0.6);
1295 }
1296
1297 #[test]
1298 fn dragging_snaps_from_min() {
1299 assert_eq!(snap_to_step(9.4, 3., 100., 5.), 8.);
1301 assert_eq!(snap_to_step(11., 3., 100., 5.), 13.);
1302 assert_eq!(snap_to_step(99., 3., 100., 5.), 98.);
1304 assert_eq!(snap_to_step(100., 0., 99., 10.), 99.);
1305 assert_eq!(snap_to_step(42.5, 0., 100., 0.), 42.5);
1307 assert_eq!(snap_to_step(42.5, 0., 100., -5.), 42.5);
1308 assert_eq!(snap_to_step(42.5, 0., 100., f32::NAN), 42.5);
1309 assert_eq!(snap_to_step(42.5, 0., 100., f32::INFINITY), 42.5);
1310 }
1311
1312 #[test]
1313 fn accessibility_steps_move_only_the_stepped_thumb() {
1314 assert_eq!(
1315 step_thumb(SliderValue::Range(20., 60.), false, 1., 0., 100., 1.),
1316 SliderValue::Range(20., 61.)
1317 );
1318 assert_eq!(
1319 step_thumb(SliderValue::Range(20., 20.), false, -1., 0., 100., 1.),
1320 SliderValue::Range(20., 20.),
1321 "the end never passes the start"
1322 );
1323 assert_eq!(
1324 step_thumb(SliderValue::Single(99.5), false, 1., 0., 100., 1.),
1325 SliderValue::Single(100.)
1326 );
1327 assert_eq!(
1328 step_thumb(SliderValue::Range(20., 60.), true, -1., 0., 100., 1.),
1329 SliderValue::Range(19., 60.)
1330 );
1331 assert_eq!(
1332 step_thumb(SliderValue::Range(60., 60.), true, 1., 0., 100., 1.),
1333 SliderValue::Range(60., 60.),
1334 "the start never passes the end"
1335 );
1336 }
1337
1338 #[test]
1339 fn accessibility_steps_land_on_the_step_grid() {
1340 assert_eq!(
1341 step_thumb(SliderValue::Single(33.), false, 10., 0., 100., 10.),
1342 SliderValue::Single(40.)
1343 );
1344 assert_eq!(
1345 step_thumb(SliderValue::Single(33.), false, -10., 0., 100., 10.),
1346 SliderValue::Single(20.)
1347 );
1348 assert_eq!(
1349 step_thumb(SliderValue::Single(33.), false, 0.5, 0., 100., 0.),
1350 SliderValue::Single(33.5),
1351 "a continuous slider does not snap"
1352 );
1353 }
1354
1355 #[test]
1356 fn a_continuous_slider_steps_by_a_hundredth_of_its_range() {
1357 for step in [0., -1., f32::NAN] {
1358 let state = SliderState::new().min(0.).max(200.).step(step);
1359 assert_eq!(state.accessibility_step(), 2., "step {step}");
1360 }
1361 assert_eq!(SliderState::new().step(5.).accessibility_step(), 5.);
1362 }
1363
1364 #[test]
1365 fn stepping_leaves_an_invalid_value_or_range_alone() {
1366 let nan = step_thumb(SliderValue::Single(f32::NAN), false, 1., 0., 100., 1.);
1367 assert!(nan.end().is_nan(), "a NaN value does not jump to max");
1368 assert_eq!(
1369 step_thumb(SliderValue::Single(50.), false, 1., 100., 0., 1.),
1370 SliderValue::Single(50.),
1371 "min above max"
1372 );
1373 assert_eq!(
1374 step_thumb(SliderValue::Range(60., 20.), true, 1., 0., 100., 1.),
1375 SliderValue::Range(60., 20.),
1376 "a reversed range"
1377 );
1378 }
1379
1380 struct Holder(Entity<SliderState>);
1381
1382 impl Render for Holder {
1383 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1384 div()
1385 }
1386 }
1387
1388 fn sized(
1390 state: SliderState,
1391 cx: &mut gpui::TestAppContext,
1392 ) -> (Entity<SliderState>, &mut gpui::VisualTestContext) {
1393 let (holder, cx) = cx.add_window_view(|_, cx| Holder(cx.new(|_| state)));
1394 let state = holder.read_with(cx, |holder, _| holder.0.clone());
1395 state.update(cx, |state, _| {
1396 state.set_bounds(Bounds::new(
1397 gpui::point(px(0.), px(0.)),
1398 gpui::size(px(100.), px(10.)),
1399 ));
1400 });
1401 (state, cx)
1402 }
1403
1404 fn drag(state: &Entity<SliderState>, x: f32, start: bool, cx: &mut gpui::VisualTestContext) {
1405 state.update_in(cx, |state, window, cx| {
1406 let position = gpui::point(px(x), px(0.));
1407 state.update_value_by_position(Axis::Horizontal, position, start, window, cx);
1408 })
1409 }
1410
1411 #[gpui::test]
1412 fn a_drag_snaps_to_steps_counted_from_min(cx: &mut gpui::TestAppContext) {
1413 let (state, cx) = sized(SliderState::new().min(3.).max(103.).step(5.), cx);
1414 drag(&state, 6., false, cx);
1416 assert_eq!(
1417 state.read_with(cx, |state, _| state.value()),
1418 SliderValue::Single(8.)
1419 );
1420 }
1421
1422 #[gpui::test]
1423 fn a_right_to_left_slider_grows_from_the_right(cx: &mut gpui::TestAppContext) {
1424 let (state, cx) = sized(SliderState::new().step(25.), cx);
1425 cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
1426 drag(&state, 30., false, cx);
1428 assert_eq!(
1429 state.read_with(cx, |state, _| state.value()),
1430 SliderValue::Single(75.)
1431 );
1432
1433 state.update_in(cx, |state, window, cx| {
1434 state.set_value((25., 75.), window, cx);
1435 });
1436 let nearer_start = state.read_with(cx, |state, cx| {
1438 state.is_nearer_start(Axis::Horizontal, gpui::point(px(80.), px(0.)), cx)
1439 });
1440 assert!(nearer_start);
1441 }
1442
1443 #[gpui::test]
1444 fn a_dropped_thumb_stands_at_its_value(cx: &mut gpui::TestAppContext) {
1445 let (state, cx) = sized(SliderState::new().step(25.), cx);
1446 drag(&state, 30., false, cx);
1447 state.read_with(cx, |state, _| {
1448 assert_eq!(state.value(), SliderValue::Single(25.));
1449 assert_eq!(state.percentage(), 0.0..0.25);
1450 });
1451
1452 state.update_in(cx, |state, window, cx| {
1453 state.set_value((25., 75.), window, cx);
1454 });
1455 drag(&state, 40., true, cx);
1456 drag(&state, 60., false, cx);
1457 state.read_with(cx, |state, _| {
1458 assert_eq!(state.value(), SliderValue::Range(50., 50.));
1459 assert_eq!(state.percentage(), 0.5..0.5);
1460 });
1461 }
1462
1463 #[gpui::test]
1464 fn a_zero_step_drags_continuously(cx: &mut gpui::TestAppContext) {
1465 for step in [0., -5., f32::NAN, f32::INFINITY] {
1466 let (state, cx) = sized(SliderState::new().step(step), cx);
1467 drag(&state, 30., false, cx);
1468 state.read_with(cx, |state, _| {
1469 let value = state.value().end();
1470 assert!((value - 30.).abs() < 1e-3, "step {step}: {value}");
1471 assert!((state.percentage().end - 0.3).abs() < 1e-5, "step {step}");
1472 });
1473 }
1474 }
1475
1476 #[gpui::test]
1477 fn an_accessibility_step_reports_a_change_then_a_release(cx: &mut gpui::TestAppContext) {
1478 let (state, cx) = sized(SliderState::new().default_value(99.), cx);
1479 let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1480 cx.update(|_, cx| {
1481 let events = events.clone();
1482 cx.subscribe(&state, move |_, event: &SliderEvent, _| {
1483 events.borrow_mut().push(match event {
1484 SliderEvent::Change(value) => ("change", value.end()),
1485 SliderEvent::Release(value) => ("release", value.end()),
1486 });
1487 })
1488 .detach();
1489 });
1490 let step = |delta: f32, cx: &mut gpui::VisualTestContext| {
1491 state.update_in(cx, |state, window, cx| {
1492 state.step_thumb(false, delta, window, cx)
1493 })
1494 };
1495 step(1., cx);
1496 assert_eq!(&*events.borrow(), &[("change", 100.), ("release", 100.)]);
1497 assert_eq!(state.read_with(cx, |state, _| state.value().end()), 100.);
1498 step(1., cx);
1500 assert_eq!(events.borrow().len(), 2);
1501 step(-1., cx);
1502 assert_eq!(events.borrow()[2..], [("change", 99.), ("release", 99.)]);
1503 }
1504
1505 #[gpui::test]
1506 fn accessibility_set_value_moves_the_reported_thumb(cx: &mut gpui::TestAppContext) {
1507 let (state, cx) = sized(SliderState::new().step(5.).default_value((20., 60.)), cx);
1508 let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1509 cx.update(|_, cx| {
1510 let events = events.clone();
1511 cx.subscribe(&state, move |_, event: &SliderEvent, _| {
1512 events.borrow_mut().push(match event {
1513 SliderEvent::Change(value) => ("change", *value),
1514 SliderEvent::Release(value) => ("release", *value),
1515 });
1516 })
1517 .detach();
1518 });
1519 let set = |target, cx: &mut gpui::VisualTestContext| {
1520 state.update_in(cx, |state, window, cx| {
1521 state.handle_accessibility_set_value(
1522 Some(&ActionData::NumericValue(target)),
1523 window,
1524 cx,
1525 );
1526 });
1527 };
1528 set(72., cx);
1529 set(72., cx);
1530 set(f64::NAN, cx);
1531 set(10., cx);
1532 assert_eq!(
1533 &*events.borrow(),
1534 &[
1535 ("change", SliderValue::Range(20., 70.)),
1536 ("release", SliderValue::Range(20., 70.)),
1537 ("change", SliderValue::Range(20., 20.)),
1538 ("release", SliderValue::Range(20., 20.)),
1539 ]
1540 );
1541 }
1542
1543 #[gpui::test]
1544 fn an_accessibility_step_leaves_an_invalid_value_alone(cx: &mut gpui::TestAppContext) {
1545 let cases = [
1546 SliderState::new().default_value(f32::NAN),
1547 SliderState::new().default_value((60., 20.)),
1548 ];
1549 for state in cases {
1550 let (state, cx) = sized(state, cx);
1551 let before = state.read_with(cx, |state, _| state.value());
1552 let changes = std::rc::Rc::new(std::cell::Cell::new(0));
1553 cx.update(|_, cx| {
1554 let changes = changes.clone();
1555 cx.subscribe(&state, move |_, _: &SliderEvent, _| {
1556 changes.set(changes.get() + 1)
1557 })
1558 .detach();
1559 });
1560 for start in [false, true] {
1561 state.update_in(cx, |state, window, cx| {
1562 state.step_thumb(start, 1., window, cx)
1563 });
1564 }
1565 let after = state.read_with(cx, |state, _| state.value());
1566 assert_eq!(
1567 (after.start().to_bits(), after.end().to_bits()),
1568 (before.start().to_bits(), before.end().to_bits()),
1569 "{before:?} became {after:?}"
1570 );
1571 assert_eq!(changes.get(), 0, "{before:?} reported a change");
1572 }
1573 }
1574
1575 #[gpui::test]
1576 fn an_accessibility_step_keeps_a_range(cx: &mut gpui::TestAppContext) {
1577 let (state, cx) = sized(SliderState::new().default_value((20., 60.)), cx);
1578 let step = |start: bool, delta: f32, cx: &mut gpui::VisualTestContext| {
1579 state.update_in(cx, |state, window, cx| {
1580 state.step_thumb(start, delta, window, cx)
1581 });
1582 state.read_with(cx, |state, _| state.value())
1583 };
1584 assert_eq!(step(false, 1., cx), SliderValue::Range(20., 61.));
1585 assert_eq!(step(true, 5., cx), SliderValue::Range(25., 61.));
1586 assert_eq!(
1587 step(true, 100., cx),
1588 SliderValue::Range(61., 61.),
1589 "a thumb stops at the other"
1590 );
1591 }
1592
1593 #[gpui::test]
1594 fn a_continuous_slider_reports_a_usable_step(cx: &mut gpui::TestAppContext) {
1595 use gpui::{Element as _, accesskit, canvas};
1596 use std::{cell::Cell, rc::Rc};
1597
1598 struct Probe(Rc<Cell<Option<f64>>>);
1599
1600 impl Render for Probe {
1601 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1602 let reported = self.0.clone();
1603 canvas(
1604 move |_, window, cx| {
1605 let state = cx.new(|_| SliderState::new().step(0.));
1606 let element = Slider::new(&state).render(window, cx).into_element();
1607 let mut node = accesskit::Node::new(Role::Slider);
1608 element.write_a11y_info(&mut node);
1609 reported.set(node.numeric_value_step());
1610 },
1611 |_, _, _, _| {},
1612 )
1613 }
1614 }
1615
1616 let reported = Rc::new(Cell::new(None));
1617 let (_, cx) = cx.add_window_view({
1618 let reported = reported.clone();
1619 move |_, _| Probe(reported)
1620 });
1621 cx.update(|window, cx| window.draw(cx).clear(cx));
1622 assert_eq!(reported.get(), Some(1.), "a hundredth of 0..100");
1623 }
1624
1625 #[test]
1626 #[should_panic(expected = "`min` must be greater than 0")]
1627 fn legacy_logarithmic_validation_is_preserved() {
1628 let _ = SliderState::new().scale(SliderScale::Logarithmic);
1629 }
1630
1631 #[cfg(feature = "gpui-fast")]
1633 mod retained {
1634 use std::{cell::Cell, rc::Rc};
1635
1636 use gpui::{
1637 AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
1638 TestAppContext, Window, div, px,
1639 };
1640
1641 use super::super::{SliderIndicator, SliderState};
1642
1643 struct Readout {
1645 state: Entity<SliderState>,
1646 renders: Rc<Cell<usize>>,
1647 }
1648
1649 impl Render for Readout {
1650 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1651 self.renders.set(self.renders.get() + 1);
1652 div().child(self.state.read(cx).value().to_string())
1653 }
1654 }
1655
1656 struct Bar {
1658 state: Entity<SliderState>,
1659 }
1660
1661 impl Render for Bar {
1662 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1663 div()
1664 .w(px(120.))
1665 .h(px(24.))
1666 .child(SliderIndicator::new(&self.state).size_full())
1667 }
1668 }
1669
1670 struct Pair {
1672 bar: Entity<Bar>,
1673 readout: Entity<Readout>,
1674 }
1675
1676 impl Render for Pair {
1677 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1678 div()
1679 .flex()
1680 .child(self.bar.clone())
1681 .child(self.readout.clone())
1682 }
1683 }
1684
1685 #[gpui::test]
1689 fn drawing_a_slider_again_leaves_its_readers_retained(cx: &mut TestAppContext) {
1690 let renders = Rc::new(Cell::new(0));
1691 let (view, cx) = cx.add_window_view({
1692 let renders = renders.clone();
1693 move |_, cx| {
1694 let state = cx.new(|_| SliderState::new());
1695 Pair {
1696 bar: cx.new(|_| Bar {
1697 state: state.clone(),
1698 }),
1699 readout: cx.new(|_| Readout { state, renders }),
1700 }
1701 }
1702 });
1703 cx.update(|window, cx| window.draw(cx).clear(cx));
1704 cx.update(|window, cx| window.draw(cx).clear(cx));
1705 let rendered = renders.get();
1706 for _ in 0..3 {
1707 view.update(cx, |pair, cx| pair.bar.update(cx, |_, cx| cx.notify()));
1708 cx.update(|window, cx| window.draw(cx).clear(cx));
1709 }
1710 cx.update(|window, cx| window.draw(cx).clear(cx));
1711 assert_eq!(renders.get(), rendered, "the readout was built again");
1712 }
1713 }
1714}