1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 Along, AnyElement, App, AppContext, AvailableSpace, Axis, Bounds, DragMoveEvent, ElementId,
5 Entity, FocusHandle, HitboxBehavior, InteractiveElement, IntoElement, MouseButton,
6 ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString,
7 StatefulInteractiveElement, Styled, TouchDragEvent, TouchPhase, Window, canvas, div, point,
8 prelude::FluentBuilder, px, relative,
9};
10use gpui_base::{
11 AxisExt, TestSupportExt,
12 slider::{Slider as BaseSlider, SliderIndicator},
13};
14use gpui_material_foundation::{
15 DragCapture, RangeThumb, animate, color, range_semantics, shape_text, value_label,
16 window_material_theme,
17};
18use gpui_material_theme::{ColorRole, Direction, TypeRole, TypographyEmphasis};
19
20use crate::ControlSize;
21
22pub use gpui_base::slider::{SliderEvent, SliderScale, SliderState, SliderValue};
23
24#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum SliderKind {
26 #[default]
27 Standard,
28 Centered,
29}
30
31#[derive(IntoElement)]
34pub struct Slider {
35 id: ElementId,
36 name: SharedString,
37 state: Entity<SliderState>,
38 kind: SliderKind,
39 axis: Axis,
40 size: ControlSize,
41 disabled: bool,
42 icon: Option<AnyElement>,
43 tick_intervals: u16,
44 range_end_name: Option<SharedString>,
45}
46
47impl Slider {
48 pub fn new(
49 id: impl Into<ElementId>,
50 name: impl Into<SharedString>,
51 state: &Entity<SliderState>,
52 ) -> Self {
53 Self {
54 id: id.into(),
55 name: name.into(),
56 state: state.clone(),
57 kind: SliderKind::Standard,
58 axis: Axis::Horizontal,
59 size: ControlSize::ExtraSmall,
60 disabled: false,
61 icon: None,
62 tick_intervals: 0,
63 range_end_name: None,
64 }
65 }
66
67 pub fn range(
69 id: impl Into<ElementId>,
70 start_name: impl Into<SharedString>,
71 end_name: impl Into<SharedString>,
72 state: &Entity<SliderState>,
73 ) -> Self {
74 let mut slider = Self::new(id, start_name, state);
75 slider.range_end_name = Some(end_name.into());
76 slider
77 }
78
79 pub fn kind(mut self, kind: SliderKind) -> Self {
80 self.kind = kind;
81 self
82 }
83
84 pub fn axis(mut self, axis: Axis) -> Self {
85 self.axis = axis;
86 self
87 }
88
89 pub fn size(mut self, size: ControlSize) -> Self {
91 self.size = size;
92 self
93 }
94
95 pub fn disabled(mut self, disabled: bool) -> Self {
96 self.disabled = disabled;
97 self
98 }
99
100 pub fn tick_intervals(mut self, intervals: u16) -> Self {
103 self.tick_intervals = intervals;
104 self
105 }
106
107 pub fn icon(mut self, icon: impl IntoElement) -> Self {
108 self.icon = Some(icon.into_any_element());
109 self
110 }
111}
112
113#[derive(Default)]
114struct Gesture {
115 thumb: Option<RangeThumb>,
116 origin: Option<Point<Pixels>>,
117 capture: Option<DragCapture>,
118}
119
120struct SliderDrag(Entity<SliderState>);
121
122impl Render for SliderDrag {
123 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
124 div()
125 }
126}
127
128#[derive(Clone, Copy)]
129struct Geometry {
130 axis: Axis,
131 direction: Direction,
132}
133
134impl Geometry {
135 fn reversed(self) -> bool {
136 self.axis.is_horizontal() && self.direction == Direction::Rtl
137 }
138
139 fn position(self, bounds: Bounds<Pixels>, pointer: Point<Pixels>) -> Point<Pixels> {
140 if self.reversed() {
141 point(bounds.left() + (bounds.right() - pointer.x), pointer.y)
142 } else {
143 pointer
144 }
145 }
146
147 fn fraction(self, bounds: Bounds<Pixels>, pointer: Point<Pixels>) -> f32 {
148 let pointer = self.position(bounds, pointer);
149 if self.axis.is_horizontal() {
150 (pointer.x - bounds.left()) / bounds.size.width
151 } else {
152 (bounds.bottom() - pointer.y) / bounds.size.height
153 }
154 }
155
156 fn point_at(self, bounds: Bounds<Pixels>, offset: Pixels) -> Point<Pixels> {
157 if self.axis.is_vertical() {
158 point(bounds.center().x, bounds.bottom() - offset)
159 } else if self.reversed() {
160 point(bounds.right() - offset, bounds.center().y)
161 } else {
162 point(bounds.left() + offset, bounds.center().y)
163 }
164 }
165
166 fn track_corners(self, start: Pixels, end: Pixels) -> gpui::Corners<Pixels> {
167 let (left, right) = if self.reversed() {
168 (end, start)
169 } else {
170 (start, end)
171 };
172 gpui::Corners {
173 top_left: if self.axis.is_vertical() { end } else { left },
174 top_right: if self.axis.is_vertical() { end } else { right },
175 bottom_left: if self.axis.is_vertical() { start } else { left },
176 bottom_right: if self.axis.is_vertical() {
177 start
178 } else {
179 right
180 },
181 }
182 }
183
184 fn place(self, element: gpui::Div, position: f32) -> gpui::Div {
185 if self.axis.is_vertical() {
186 element.bottom(relative(position))
187 } else if self.reversed() {
188 element.right(relative(position))
189 } else {
190 element.left(relative(position))
191 }
192 }
193}
194
195impl RenderOnce for Slider {
196 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
197 let ([start_focus, end_focus], gesture) = window
198 .use_keyed_state(
199 ElementId::from((self.id.clone(), "slider-state")),
200 cx,
201 |_, cx| {
202 (
203 [cx.focus_handle(), cx.focus_handle()],
204 Rc::new(RefCell::new(Gesture::default())),
205 )
206 },
207 )
208 .read(cx)
209 .clone();
210 let geometry = Geometry {
211 axis: self.axis,
212 direction: window_material_theme(window, cx).layout.direction,
213 };
214 let horizontal = self.axis.is_horizontal();
215 let state = self.state.read(cx);
216 let value = state.value();
217 let percentage = state.percentage();
218 let tick_count = self.tick_intervals;
219 let start = percentage.start;
220 let end = percentage.end;
221 let range = value.is_range();
222 let centered = self.kind == SliderKind::Centered && !range;
223 let center = if centered { 0.5 } else { start };
224 let (thickness, thumb_extent, track_radius, icon_size): (f32, f32, f32, Option<f32>) =
226 match self.size {
227 ControlSize::ExtraSmall => (16., 44., 8., None),
228 ControlSize::Small => (24., 44., 8., None),
229 ControlSize::Medium => (40., 52., 12., Some(24.)),
230 ControlSize::Large => (56., 68., 16., Some(24.)),
231 ControlSize::ExtraLarge => (96., 108., 28., Some(32.)),
232 };
233 let target = thumb_extent.max(48.);
234 let colors = window_material_theme(window, cx).colors.clone();
235 let resolve = |role| color(colors.color(role));
236 let disabled = resolve(ColorRole::OnSurface);
237 let active = if self.disabled {
238 disabled.opacity(0.38)
239 } else {
240 resolve(ColorRole::Primary)
241 };
242 let inactive = if self.disabled {
243 disabled.opacity(0.12)
244 } else {
245 resolve(ColorRole::SecondaryContainer)
246 };
247 let ring = resolve(ColorRole::Secondary);
248
249 let active_icon = resolve(ColorRole::OnPrimary);
250 let inactive_icon = resolve(ColorRole::OnSecondaryContainer);
251 let disabled_icon = resolve(ColorRole::OnSurface).opacity(0.38);
252 let disabled_control = self.disabled;
253 let dragging = gesture.borrow().thumb;
254 let reduced = cx.reduce_motion();
255 let scheme = window_material_theme(window, cx).motion;
256 let resize = scheme.spec(
257 gpui_material_theme::MotionKind::Spatial,
258 gpui_material_theme::MotionSpeed::Fast,
259 reduced,
260 );
261 let reveal = scheme.spec(
262 gpui_material_theme::MotionKind::Effects,
263 gpui_material_theme::MotionSpeed::Fast,
264 reduced,
265 );
266 let width = |which, window: &mut Window, cx: &mut App| {
267 px(animate(
268 (
269 self.id.clone(),
270 if which == RangeThumb::Start {
271 "start-width"
272 } else {
273 "end-width"
274 },
275 ),
276 if dragging == Some(which) { 2. } else { 4. },
277 resize,
278 window,
279 cx,
280 )
281 .clamp(2., 4.))
282 };
283 let start_width = if range {
284 width(RangeThumb::Start, window, cx)
285 } else {
286 px(4.)
287 };
288 let end_width = width(RangeThumb::End, window, cx);
289 let handle_width = |which| {
290 if which == RangeThumb::Start {
291 start_width
292 } else {
293 end_width
294 }
295 };
296 let label_opacity = |which, focus: &FocusHandle, window: &mut Window, cx: &mut App| {
297 let visible = !self.disabled
298 && (dragging == Some(which)
299 || focus.is_focused(window) && window.last_input_was_keyboard());
300 animate(
301 (
302 self.id.clone(),
303 if which == RangeThumb::Start {
304 "start-label"
305 } else {
306 "end-label"
307 },
308 ),
309 f32::from(visible),
310 reveal,
311 window,
312 cx,
313 )
314 .clamp(0., 1.)
315 };
316 let start_label = if range {
317 label_opacity(RangeThumb::Start, &start_focus, window, cx)
318 } else {
319 0.
320 };
321 let end_label = label_opacity(RangeThumb::End, &end_focus, window, cx);
322 let end_gap = px(6.) + handle_width(RangeThumb::End) / 2.;
324 let center_gap = if range {
325 px(6.) + handle_width(RangeThumb::Start) / 2.
326 } else if centered {
327 px(6.)
328 } else {
329 px(0.)
330 };
331 let (first, last) = if center <= end {
332 ((center, center_gap), (end, end_gap))
333 } else {
334 ((end, end_gap), (center, center_gap))
335 };
336 let segments = move |length| track_segments(length, first, last);
337 let track_icon = self.icon.zip(icon_size).map(|(icon, side)| {
338 canvas(
339 move |bounds, window, cx| {
340 let side = px(side);
341 let length = bounds.size.along(geometry.axis);
342 let (offset, active) = segments(length)
343 .into_iter()
344 .find_map(|segment| segment.icon_position(side, px(track_radius)))?;
345 let foreground = if disabled_control {
346 disabled_icon
347 } else if active {
348 active_icon
349 } else {
350 inactive_icon
351 };
352 let origin = geometry.point_at(bounds, offset) - point(side / 2., side / 2.);
353 let mut icon = div()
354 .size(side)
355 .flex()
356 .items_center()
357 .justify_center()
358 .text_size(side)
359 .line_height(side)
360 .text_color(foreground)
361 .child(icon)
362 .into_any_element();
363 let space = gpui::size(
364 AvailableSpace::Definite(side),
365 AvailableSpace::Definite(side),
366 );
367 icon.prepaint_as_root(origin, space, window, cx);
368 Some(icon)
369 },
370 |_, icon, window, cx| {
371 if let Some(mut icon) = icon {
372 icon.paint(window, cx);
373 }
374 },
375 )
376 .absolute()
377 .inset_0()
378 .size_full()
379 });
380 let track = SliderIndicator::new(&self.state)
381 .relative()
382 .size_full()
383 .child(
384 canvas(
385 |_, _, _| (),
386 move |bounds, _, window, _| {
387 let length = bounds.size.along(geometry.axis);
388 let track_segments = segments(length);
389 let draw_indicator = |offset, tint, window: &mut Window| {
390 let center = geometry.point_at(bounds, offset);
391 let radius = px(2.);
392 window.paint_quad(gpui::quad(
393 Bounds::from_corners(
394 center - point(radius, radius),
395 center + point(radius, radius),
396 ),
397 radius,
398 tint,
399 px(0.),
400 gpui::transparent_black(),
401 gpui::BorderStyle::Solid,
402 ));
403 };
404 for segment in track_segments {
405 if segment.end <= segment.start {
406 continue;
407 }
408 let a = geometry.point_at(bounds, segment.start);
409 let b = geometry.point_at(bounds, segment.end);
410 let half = px(thickness / 2.);
411 let rect = if horizontal {
412 Bounds::from_corners(
413 point(a.x.min(b.x), a.y - half),
414 point(a.x.max(b.x), b.y + half),
415 )
416 } else {
417 Bounds::from_corners(
418 point(a.x - half, a.y.min(b.y)),
419 point(a.x + half, a.y.max(b.y)),
420 )
421 };
422 let tint = if segment.active { active } else { inactive };
423 let (start_corner, end_corner) = segment.corners(px(track_radius));
424 window.paint_quad(gpui::quad(
425 rect,
426 geometry.track_corners(start_corner, end_corner),
427 tint,
428 px(0.),
429 gpui::transparent_black(),
430 gpui::BorderStyle::Solid,
431 ));
432 if !segment.active {
434 let radius = px(track_radius);
435 if segment.outer_start
436 && segment.start + radius + px(2.) <= segment.end
437 {
438 draw_indicator(segment.start + radius, active, window);
439 }
440 if segment.outer_end
441 && segment.end - radius - px(2.) >= segment.start
442 {
443 draw_indicator(segment.end - radius, active, window);
444 }
445 }
446 }
447 if tick_count >= 2 {
448 let spacing = f32::from(length) / f32::from(tick_count);
451 if spacing >= 6. {
452 for index in 1..tick_count {
453 let offset =
454 length * (f32::from(index) / f32::from(tick_count));
455 if let Some(segment) = track_segments.iter().find(|segment| {
456 segment.start + px(2.) <= offset
457 && offset <= segment.end - px(2.)
458 }) {
459 let tint = if disabled_control {
460 disabled_icon
461 } else if segment.active {
462 active_icon
463 } else {
464 inactive_icon
465 };
466 let on_endpoint = !segment.active
467 && (segment.outer_start
468 && (offset - segment.start - px(track_radius))
469 .abs()
470 < px(4.)
471 || segment.outer_end
472 && (segment.end - px(track_radius) - offset)
473 .abs()
474 < px(4.));
475 if !on_endpoint {
476 draw_indicator(offset, tint, window);
477 }
478 }
479 }
480 }
481 }
482 },
483 )
484 .absolute()
485 .inset_0()
486 .size_full(),
487 )
488 .children(track_icon);
489 let thumb = |which, position, name, focus: &FocusHandle| {
490 let keyboard_state = self.state.clone();
491 let handle_width = handle_width(which);
492 let half_handle = handle_width / 2.;
493 let (width, height) = if horizontal {
494 (handle_width, px(thumb_extent))
495 } else {
496 (px(thumb_extent), handle_width)
497 };
498 let opacity = if which == RangeThumb::Start {
499 start_label
500 } else {
501 end_label
502 };
503 let label = (opacity > 0.).then(|| {
504 let text =
505 value_label(&self.state, which, cx, |value| format!("{value:.2}").into());
506 let theme = window_material_theme(window, cx);
507 let foreground = resolve(ColorRole::InverseOnSurface).opacity(opacity);
508 let background = resolve(ColorRole::InverseSurface).opacity(opacity);
509 let line = shape_text(
510 text,
511 TypeRole::LabelLarge.style(TypographyEmphasis::Baseline),
512 &theme.typography,
513 1.,
514 foreground,
515 window,
516 cx,
517 )
518 .expect("numeric slider label");
519 canvas(
520 |_, _, _| (),
521 move |thumb, _, window, cx| {
522 let size = gpui::size(
523 (line.line().width.ceil() + px(16.)).max(px(48.)),
524 line.line_height().max(px(44.)),
525 );
526 let visible = window.content_mask().bounds;
527 if !visible.contains(&thumb.center()) {
528 return;
529 }
530 let origin = value_label_origin(
531 thumb,
532 size,
533 visible,
534 horizontal,
535 geometry.direction,
536 );
537 let bounds = Bounds::new(origin, size);
538 window.paint_quad(gpui::quad(
539 bounds,
540 px(6.),
541 background,
542 px(0.),
543 background,
544 gpui::BorderStyle::Solid,
545 ));
546 let _ = line.paint(
547 origin
548 + point(
549 (size.width - line.line().width) / 2.,
550 (size.height - line.line_height()) / 2.,
551 ),
552 gpui::TextAlign::Left,
553 None,
554 window,
555 cx,
556 );
557 },
558 )
559 .absolute()
560 .inset_0()
561 .size_full()
562 });
563 let element = geometry
564 .place(
565 div()
566 .absolute()
567 .when(horizontal, |thumb| {
568 thumb
569 .top((px(target) - height) / 2.)
570 .ml(-half_handle)
571 .when(geometry.reversed(), |thumb| {
572 thumb.ml(px(0.)).mr(-half_handle)
573 })
574 })
575 .when(!horizontal, |thumb| {
576 thumb.left((px(target) - width) / 2.).mb(-half_handle)
577 }),
578 position,
579 )
580 .id(ElementId::from((
581 self.id.clone(),
582 if which == RangeThumb::Start {
583 "start"
584 } else {
585 "end"
586 },
587 )))
588 .when(!self.disabled, |thumb| thumb.role(Role::Slider))
589 .when(!self.disabled, |thumb| thumb.aria_label(name))
590 .w(width)
591 .h(height)
592 .rounded_full()
593 .bg(active)
594 .focus_visible(move |style| style.bg(ring))
595 .children(label);
596
597 let element = if self.disabled {
598 element
599 } else {
600 range_semantics(element, &self.state, which, self.axis, cx).capture_key_down(
601 move |event, window, cx| {
602 let sign = match event.keystroke.key.as_str() {
603 "left" if geometry.reversed() => 1.,
604 "right" if geometry.reversed() => -1.,
605 _ => return,
606 };
607 keyboard_state.update(cx, |state, cx| {
608 state.step_thumb(
609 which == RangeThumb::Start,
610 sign * state.accessibility_step(),
611 window,
612 cx,
613 );
614 });
615 cx.stop_propagation();
616 },
617 )
618 };
619 element.test_support().when(!self.disabled, |thumb| {
620 thumb.track_focus(&focus.clone().tab_stop(true))
621 })
622 };
623 let disabled_name = self.range_end_name.as_ref().map_or_else(
624 || self.name.clone(),
625 |end| format!("{} – {end}", self.name).into(),
626 );
627 let track_and_handles = div()
630 .relative()
631 .size_full()
632 .child(track)
633 .when(range, |root| {
634 root.child(thumb(
635 RangeThumb::Start,
636 start,
637 self.name.clone(),
638 &start_focus,
639 ))
640 })
641 .child(thumb(
642 RangeThumb::End,
643 end,
644 self.range_end_name.unwrap_or(self.name),
645 &end_focus,
646 ));
647 let root = div()
648 .id(self.id.clone())
649 .relative()
650 .when(horizontal, |root| root.w_full().h(px(target)).px_2())
651 .when(!horizontal, |root| root.w(px(target)).h(px(200.)).py_2())
652 .child(track_and_handles);
653 if self.disabled || !window.is_window_active() && gesture.borrow().thumb.is_some() {
654 if gesture.borrow().thumb.is_some() {
655 let state = self.state.clone();
656 let gesture = gesture.clone();
657 window.defer(cx, move |window, cx| {
658 finish(&state, &gesture, window, cx, true)
659 });
660 }
661 return if self.disabled {
662 BaseSlider::new(&self.state)
663 .axis(self.axis)
664 .disabled(true)
665 .accessibility_label(disabled_name)
666 .child(root)
667 .into_any_element()
668 } else {
669 root.into_any_element()
670 };
671 }
672
673 let touch = gesture.clone();
674 let touch_state = self.state.clone();
675 let touch_focus = [start_focus.clone(), end_focus.clone()];
676 let touch_layer = canvas(
677 |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
678 move |_, hitbox, window, _| {
679 let gesture = touch.clone();
680 let state = touch_state.clone();
681 let focus = touch_focus.clone();
682 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
683 if !phase.bubble() {
684 return;
685 }
686 if event.phase == TouchPhase::Started {
687 if window.default_prevented()
688 || !hitbox.is_hovered_at(event.start_position, window)
689 {
690 return;
691 }
692 let bounds = state.read(cx).bounds();
693 if bounds.size.along(geometry.axis) <= px(0.) {
694 return;
695 }
696 let fraction = geometry.fraction(bounds, event.start_position);
697 let current = state.read(cx).percentage();
698 let which = if range && current.start == current.end {
699 choose_thumb(
700 true,
701 fraction,
702 fraction,
703 geometry.fraction(bounds, event.position),
704 )
705 } else {
706 choose_thumb(range, current.start, current.end, fraction)
707 };
708 window.prevent_default();
709 let mut gesture = gesture.borrow_mut();
710 gesture.origin = Some(event.start_position);
711 gesture.thumb = Some(which);
712 focus[usize::from(which == RangeThumb::End)].focus(window, cx);
713 }
714 let which = {
715 let gesture = gesture.borrow();
716 if gesture.origin != Some(event.start_position) || gesture.capture.is_some()
717 {
718 return;
719 }
720 let Some(which) = gesture.thumb else {
721 return;
722 };
723 which
724 };
725 match event.phase {
726 TouchPhase::Started | TouchPhase::Moved => {
727 update(&state, geometry, which, event.position, window, cx);
728 }
729 TouchPhase::Ended | TouchPhase::Cancelled => {
730 finish(&state, &gesture, window, cx, false);
731 }
732 }
733 cx.stop_propagation();
734 });
735 },
736 )
737 .absolute()
738 .inset_0()
739 .size_full();
740 let down = gesture.clone();
741 let begin = gesture.clone();
742 let drag = gesture.clone();
743 let release = gesture.clone();
744 let release_out = gesture.clone();
745 let scroll = gesture.clone();
746 let escape = gesture;
747 let down_state = self.state.clone();
748 let begin_state = self.state.clone();
749 let drag_state = self.state.clone();
750 let drag_source = self.state.clone();
751 let drag_focus = [start_focus.clone(), end_focus.clone()];
752 let release_state = self.state.clone();
753 let outside_state = self.state.clone();
754 let escape_state = self.state;
755 root.child(touch_layer)
756 .on_mouse_down(MouseButton::Left, move |event, window, cx| {
757 let bounds = down_state.read(cx).bounds();
758 if bounds.size.along(geometry.axis) <= px(0.) {
759 return;
760 }
761 let fraction = geometry.fraction(bounds, event.position);
762 let which = choose_thumb(range, start, end, fraction);
763 {
764 let mut down = down.borrow_mut();
765 down.thumb = Some(which);
766 down.origin = Some(event.position);
767 }
768 if which == RangeThumb::Start {
769 start_focus.focus(window, cx);
770 } else {
771 end_focus.focus(window, cx);
772 }
773 update(&down_state, geometry, which, event.position, window, cx);
774 })
775 .on_drag(SliderDrag(drag_source), move |payload, _, window, cx| {
776 let gesture = Rc::downgrade(&begin);
777 let state = begin_state.clone();
778 begin.borrow_mut().capture =
779 Some(DragCapture::watch(window, cx, move |window, cx| {
780 if let Some(gesture) = gesture.upgrade() {
781 finish(&state, &gesture, window, cx, false);
782 }
783 }));
784 cx.stop_propagation();
785 cx.new(|_| SliderDrag(payload.0.clone()))
786 })
787 .on_drag_move(move |event: &DragMoveEvent<SliderDrag>, window, cx| {
788 if event.drag(cx).0.entity_id() != drag_state.entity_id() {
789 return;
790 }
791 let mut gesture = drag.borrow_mut();
792 let Some(mut which) = gesture.thumb else {
793 return;
794 };
795 if range
796 && start == end
797 && let Some(origin) = gesture.origin.take()
798 {
799 let bounds = drag_state.read(cx).bounds();
800 which = if geometry.fraction(bounds, event.event.position)
801 < geometry.fraction(bounds, origin)
802 {
803 RangeThumb::Start
804 } else {
805 RangeThumb::End
806 };
807 gesture.thumb = Some(which);
808 drag_focus[usize::from(which == RangeThumb::End)].focus(window, cx);
809 }
810 update(
811 &drag_state,
812 geometry,
813 which,
814 event.event.position,
815 window,
816 cx,
817 );
818 cx.stop_propagation();
819 })
820 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
821 finish(&release_state, &release, window, cx, false)
822 })
823 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
824 finish(&outside_state, &release_out, window, cx, false)
825 })
826 .capture_key_down(move |event, window, cx| {
827 if event.keystroke.key == "escape" && escape.borrow().thumb.is_some() {
828 finish(&escape_state, &escape, window, cx, true);
829 cx.stop_propagation();
830 }
831 })
832 .on_scroll(move |_, _, cx| {
833 if scroll.borrow().thumb.is_some() {
835 cx.stop_propagation();
836 }
837 })
838 .into_any_element()
839 }
840}
841
842fn value_label_origin(
843 thumb: Bounds<Pixels>,
844 label: gpui::Size<Pixels>,
845 visible: Bounds<Pixels>,
846 horizontal: bool,
847 direction: Direction,
848) -> Point<Pixels> {
849 let gap = px(12.);
850 let x = if horizontal {
851 thumb.center().x - label.width / 2.
852 } else if direction == Direction::Ltr && thumb.right() + gap + label.width <= visible.right()
853 || thumb.left() - gap - label.width < visible.left()
854 {
855 thumb.right() + gap
856 } else {
857 thumb.left() - gap - label.width
858 };
859 let y = if horizontal && thumb.top() - gap - label.height >= visible.top() {
860 thumb.top() - gap - label.height
861 } else if horizontal {
862 thumb.bottom() + gap
863 } else {
864 thumb.center().y - label.height / 2.
865 };
866 point(
867 x.clamp(
868 visible.left(),
869 (visible.right() - label.width).max(visible.left()),
870 ),
871 y.clamp(
872 visible.top(),
873 (visible.bottom() - label.height).max(visible.top()),
874 ),
875 )
876}
877
878#[derive(Clone, Copy)]
879struct TrackSegment {
880 start: Pixels,
881 end: Pixels,
882 outer_start: bool,
883 outer_end: bool,
884 active: bool,
885}
886
887impl TrackSegment {
888 fn corners(self, outer: Pixels) -> (Pixels, Pixels) {
889 let limit = (self.end - self.start).max(px(0.)) / 2.;
890 let radius = |outside| if outside { outer } else { px(2.) }.min(limit);
891 (radius(self.outer_start), radius(self.outer_end))
892 }
893
894 fn icon_position(self, side: Pixels, outer: Pixels) -> Option<(Pixels, bool)> {
895 let (start, end) = self.corners(outer);
896 let start = start.max(px(4.));
897 let end = end.max(px(4.));
898 (self.end - self.start >= start + side + end)
899 .then_some((self.start + start + side / 2., self.active))
900 }
901}
902
903fn track_segments(
904 length: Pixels,
905 (first, first_gap): (f32, Pixels),
906 (last, last_gap): (f32, Pixels),
907) -> [TrackSegment; 3] {
908 let first = length * first;
909 let last = length * last;
910 [
911 TrackSegment {
912 start: px(0.),
913 end: (first - first_gap).min(last - last_gap),
914 outer_start: true,
915 outer_end: false,
916 active: false,
917 },
918 TrackSegment {
919 start: first + first_gap,
920 end: last - last_gap,
921 outer_start: first_gap == px(0.),
922 outer_end: last_gap == px(0.),
923 active: true,
924 },
925 TrackSegment {
926 start: (last + last_gap).max(first + first_gap),
927 end: length,
928 outer_start: false,
929 outer_end: true,
930 active: false,
931 },
932 ]
933}
934
935fn choose_thumb(range: bool, start: f32, end: f32, fraction: f32) -> RangeThumb {
936 if range && fraction < (start + end) / 2. {
937 RangeThumb::Start
938 } else {
939 RangeThumb::End
940 }
941}
942
943fn update(
944 state: &Entity<SliderState>,
945 geometry: Geometry,
946 thumb: RangeThumb,
947 pointer: Point<Pixels>,
948 window: &mut Window,
949 cx: &mut App,
950) {
951 state.update(cx, |state, cx| {
952 let position = geometry.position(state.bounds(), pointer);
953 state.update_value_by_position(
954 geometry.axis,
955 position,
956 thumb == RangeThumb::Start,
957 window,
958 cx,
959 );
960 });
961}
962
963fn finish(
964 state: &Entity<SliderState>,
965 gesture: &RefCell<Gesture>,
966 window: &mut Window,
967 cx: &mut App,
968 cancel: bool,
969) {
970 let mut gesture = gesture.borrow_mut();
971 if gesture.thumb.take().is_none() {
972 return;
973 }
974 if let Some(capture) = gesture.capture.take()
975 && cancel
976 {
977 capture.cancel(window, cx);
978 }
979 gesture.origin = None;
980 state.update(cx, |state, cx| state.handle_release(cx));
981 window.refresh();
982}
983
984#[cfg(test)]
985mod tests {
986 use super::*;
987
988 #[test]
989 fn value_labels_keep_material_gap_and_flip_inside_the_viewport() {
990 let visible = Bounds::new(point(px(0.), px(0.)), gpui::size(px(200.), px(200.)));
991 let label = gpui::size(px(48.), px(44.));
992 let thumb = Bounds::new(point(px(98.), px(100.)), gpui::size(px(4.), px(44.)));
993 let above = value_label_origin(thumb, label, visible, true, Direction::Ltr);
994 assert_eq!(above, point(px(76.), px(44.)));
995 assert_eq!(thumb.top() - above.y - label.height, px(12.));
996
997 let top = Bounds::new(point(px(0.), px(0.)), thumb.size);
998 let below = value_label_origin(top, label, visible, true, Direction::Rtl);
999 assert_eq!(below, point(px(0.), px(56.)));
1000 let vertical = value_label_origin(thumb, label, visible, false, Direction::Rtl);
1001 assert_eq!(vertical.x + label.width + px(12.), thumb.left());
1002 }
1003
1004 #[test]
1005 fn track_segments_stop_the_same_distance_from_each_handle() {
1006 for percentage in [0.1, 0.5, 0.9] {
1007 let length = px(200.);
1008 let center = length * percentage;
1009 let [_, active, inactive] = track_segments(length, (0., px(0.)), (percentage, px(8.)));
1010 assert_eq!(center - active.end, px(8.));
1011 assert_eq!(inactive.start - center, px(8.));
1012 assert_eq!(active.corners(px(12.)).1, px(2.));
1013 assert_eq!(inactive.corners(px(12.)).0, px(2.));
1014 }
1015
1016 let [before, active, after] = track_segments(px(200.), (0.5, px(7.)), (0.5, px(8.)));
1017 assert_eq!(before.end, px(92.));
1018 assert_eq!(after.start, px(108.));
1019 assert!(active.end < active.start);
1020 }
1021}