Skip to main content

gpui_material_components/
slider.rs

1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4    Along, AnyElement, App, AppContext, AvailableSpace, Axis, Bounds, DragMoveEvent, ElementId,
5    Entity, FocusHandle, HitboxBehavior, Hsla, InteractiveElement, IntoElement, MouseButton,
6    ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString, Size,
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, InteractionSource, InteractionState, InteractionTracker, animate, color,
16    range_semantics, shape_text, 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};
23pub use gpui_material_foundation::RangeThumb;
24
25/// Optional track dimensions in logical pixels.
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct SliderTrackStyle {
28    pub thickness: Option<Pixels>,
29    pub outer_radius: Option<Pixels>,
30    pub inner_radius: Option<Pixels>,
31    pub thumb_gap: Option<Pixels>,
32}
33
34/// Optional dimensions and colors for one handle.
35#[derive(Clone, Copy, Debug, Default, PartialEq)]
36pub struct SliderThumbStyle {
37    /// The first dimension lies along the slider axis, the second across it.
38    pub size: Option<Size<Pixels>>,
39    /// The dimension along the slider axis while the handle is pressed.
40    pub pressed_width: Option<Pixels>,
41    pub color: Option<Hsla>,
42    pub disabled_color: Option<Hsla>,
43    pub focused_color: Option<Hsla>,
44}
45
46/// Optional slider colors. Unspecified fields use the window theme.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct SliderColors {
49    pub thumb: Option<Hsla>,
50    pub active_track: Option<Hsla>,
51    pub inactive_track: Option<Hsla>,
52    pub active_tick: Option<Hsla>,
53    pub inactive_tick: Option<Hsla>,
54    pub disabled_thumb: Option<Hsla>,
55    pub disabled_active_track: Option<Hsla>,
56    pub disabled_inactive_track: Option<Hsla>,
57    pub disabled_active_tick: Option<Hsla>,
58    pub disabled_inactive_tick: Option<Hsla>,
59}
60
61/// The window position and default paint of a track tick or stop.
62#[derive(Clone, Copy, Debug, PartialEq)]
63#[non_exhaustive]
64pub struct SliderMarker {
65    pub center: Point<Pixels>,
66    pub diameter: Pixels,
67    pub color: Hsla,
68}
69
70type DrawMarker = Box<dyn Fn(SliderMarker, &mut Window, &mut App)>;
71type FormatValue = Box<dyn Fn(f32) -> SharedString>;
72
73#[derive(Default)]
74struct ThumbOptions {
75    style: SliderThumbStyle,
76    content: Option<AnyElement>,
77    source: Option<Entity<InteractionSource>>,
78}
79
80fn thumb_index(which: RangeThumb) -> usize {
81    usize::from(which == RangeThumb::End)
82}
83
84fn thumb_id(id: &ElementId, which: RangeThumb) -> ElementId {
85    (
86        id.clone(),
87        if which == RangeThumb::Start {
88            "start"
89        } else {
90            "end"
91        },
92    )
93        .into()
94}
95
96#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
97pub enum SliderKind {
98    #[default]
99    Standard,
100    Centered,
101}
102
103/// An Expressive slider. Base owns the value and step grid. The caller retains
104/// the state entity and observes its SliderEvent notifications.
105#[derive(IntoElement)]
106pub struct Slider {
107    id: ElementId,
108    name: SharedString,
109    state: Entity<SliderState>,
110    kind: SliderKind,
111    axis: Axis,
112    reverse_vertical: bool,
113    size: ControlSize,
114    disabled: bool,
115    icon: Option<AnyElement>,
116    tick_intervals: u16,
117    range_end_name: Option<SharedString>,
118    track_style: SliderTrackStyle,
119    track: Option<AnyElement>,
120    thumbs: [ThumbOptions; 2],
121    colors: SliderColors,
122    draw_tick: Option<DrawMarker>,
123    draw_stop: Option<DrawMarker>,
124    show_stop_indicators: bool,
125    value_indicator: bool,
126    format_value: Option<FormatValue>,
127}
128
129impl Slider {
130    pub fn new(
131        id: impl Into<ElementId>,
132        name: impl Into<SharedString>,
133        state: &Entity<SliderState>,
134    ) -> Self {
135        Self {
136            id: id.into(),
137            name: name.into(),
138            state: state.clone(),
139            kind: SliderKind::Standard,
140            axis: Axis::Horizontal,
141            reverse_vertical: false,
142            size: ControlSize::ExtraSmall,
143            disabled: false,
144            icon: None,
145            tick_intervals: 0,
146            range_end_name: None,
147            track_style: SliderTrackStyle::default(),
148            track: None,
149            thumbs: Default::default(),
150            colors: SliderColors::default(),
151            draw_tick: None,
152            draw_stop: None,
153            show_stop_indicators: true,
154            value_indicator: true,
155            format_value: None,
156        }
157    }
158
159    /// Supplies the two accessible names of a slider with a Base range value.
160    pub fn range(
161        id: impl Into<ElementId>,
162        start_name: impl Into<SharedString>,
163        end_name: impl Into<SharedString>,
164        state: &Entity<SliderState>,
165    ) -> Self {
166        let mut slider = Self::new(id, start_name, state);
167        slider.range_end_name = Some(end_name.into());
168        slider
169    }
170
171    pub fn kind(mut self, kind: SliderKind) -> Self {
172        self.kind = kind;
173        self
174    }
175
176    pub fn axis(mut self, axis: Axis) -> Self {
177        self.axis = axis;
178        self
179    }
180
181    /// Increases vertical sliders from top to bottom. Horizontal sliders follow the window direction.
182    pub fn reverse_vertical(mut self, reverse: bool) -> Self {
183        self.reverse_vertical = reverse;
184        self
185    }
186
187    /// Selects the expressive track size. ExtraSmall (16 dp) is the default.
188    pub fn size(mut self, size: ControlSize) -> Self {
189        self.size = size;
190        self
191    }
192
193    pub fn disabled(mut self, disabled: bool) -> Self {
194        self.disabled = disabled;
195        self
196    }
197
198    /// Draws equally spaced ticks in the visual range without changing the Base value scale.
199    /// Pass the number of intervals, including the two endpoints.
200    pub fn tick_intervals(mut self, intervals: u16) -> Self {
201        self.tick_intervals = intervals;
202        self
203    }
204
205    pub fn icon(mut self, icon: impl IntoElement) -> Self {
206        self.icon = Some(icon.into_any_element());
207        self
208    }
209
210    /// Replaces the built-in track, icon, and marker artwork. The slider retains its input region.
211    pub fn track(mut self, element: impl IntoElement) -> Self {
212        self.track = Some(element.into_any_element());
213        self
214    }
215
216    /// Sets the built-in track dimensions. Thickness also sizes a custom track's slot.
217    pub fn track_style(mut self, style: SliderTrackStyle) -> Self {
218        self.track_style = style;
219        self
220    }
221
222    /// Replaces the handle artwork. Use `RangeThumb::End` for a single value.
223    pub fn thumb(mut self, which: RangeThumb, element: impl IntoElement) -> Self {
224        self.thumbs[thumb_index(which)].content = Some(element.into_any_element());
225        self
226    }
227
228    /// Sets per-handle size and colors. Use `RangeThumb::End` for a single value.
229    pub fn thumb_style(mut self, which: RangeThumb, style: SliderThumbStyle) -> Self {
230        self.thumbs[thumb_index(which)].style = style;
231        self
232    }
233
234    pub fn colors(mut self, colors: SliderColors) -> Self {
235        self.colors = colors;
236        self
237    }
238
239    /// Observes one handle under the slider ID paired with `"start"` or `"end"`.
240    pub fn interaction_source(
241        mut self,
242        which: RangeThumb,
243        source: &Entity<InteractionSource>,
244    ) -> Self {
245        self.thumbs[thumb_index(which)].source = Some(source.clone());
246        self
247    }
248
249    /// Replaces the default dot painter for visual ticks.
250    pub fn draw_ticks(
251        mut self,
252        draw: impl Fn(SliderMarker, &mut Window, &mut App) + 'static,
253    ) -> Self {
254        self.draw_tick = Some(Box::new(draw));
255        self
256    }
257
258    /// Replaces the default dot painter for track stops.
259    pub fn draw_stop_indicators(
260        mut self,
261        draw: impl Fn(SliderMarker, &mut Window, &mut App) + 'static,
262    ) -> Self {
263        self.draw_stop = Some(Box::new(draw));
264        self
265    }
266
267    pub fn show_stop_indicators(mut self, show: bool) -> Self {
268        self.show_stop_indicators = show;
269        self
270    }
271
272    /// Enables the value indicator during dragging and keyboard focus. It is enabled by default.
273    pub fn value_indicator(mut self, show: bool) -> Self {
274        self.value_indicator = show;
275        self
276    }
277
278    /// Formats the current value of the handle whose indicator is visible.
279    pub fn format_value(mut self, format: impl Fn(f32) -> SharedString + 'static) -> Self {
280        self.format_value = Some(Box::new(format));
281        self
282    }
283}
284
285#[derive(Default)]
286struct Gesture {
287    thumb: Option<RangeThumb>,
288    origin: Option<Point<Pixels>>,
289    capture: Option<DragCapture>,
290    dragged: bool,
291    disabled: bool,
292    feedback: [ThumbFeedback; 2],
293}
294
295#[derive(Default)]
296struct ThumbFeedback {
297    focus: Option<FocusHandle>,
298    tracker: Option<InteractionTracker>,
299    hovered: bool,
300}
301
302impl Gesture {
303    fn record(&self, window: &Window, cx: &mut App) {
304        for (which, feedback) in [RangeThumb::Start, RangeThumb::End]
305            .into_iter()
306            .zip(&self.feedback)
307        {
308            let Some(tracker) = &feedback.tracker else {
309                continue;
310            };
311            let mut snapshot = InteractionState::default();
312            snapshot.disabled = self.disabled;
313            if !self.disabled && window.is_window_active() {
314                snapshot.hovered = feedback.hovered;
315                snapshot.focus_visible = window.last_input_was_keyboard()
316                    && feedback
317                        .focus
318                        .as_ref()
319                        .is_some_and(|focus| focus.is_focused(window));
320                snapshot.pressed = self.thumb == Some(which);
321                snapshot.dragged = snapshot.pressed && self.dragged;
322            }
323            tracker.record(snapshot, cx);
324        }
325    }
326}
327
328struct SliderDrag(Entity<SliderState>);
329
330impl Render for SliderDrag {
331    fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
332        div()
333    }
334}
335
336#[derive(Clone, Copy)]
337struct Geometry {
338    axis: Axis,
339    direction: Direction,
340    reverse_vertical: bool,
341}
342
343impl Geometry {
344    fn reversed(self) -> bool {
345        if self.axis.is_horizontal() {
346            self.direction == Direction::Rtl
347        } else {
348            self.reverse_vertical
349        }
350    }
351
352    fn position(self, bounds: Bounds<Pixels>, pointer: Point<Pixels>) -> Point<Pixels> {
353        if !self.reversed() {
354            pointer
355        } else if self.axis.is_horizontal() {
356            point(bounds.left() + (bounds.right() - pointer.x), pointer.y)
357        } else {
358            point(pointer.x, bounds.top() + (bounds.bottom() - pointer.y))
359        }
360    }
361
362    fn fraction(self, bounds: Bounds<Pixels>, pointer: Point<Pixels>) -> f32 {
363        let pointer = self.position(bounds, pointer);
364        if self.axis.is_horizontal() {
365            (pointer.x - bounds.left()) / bounds.size.width
366        } else {
367            (bounds.bottom() - pointer.y) / bounds.size.height
368        }
369    }
370
371    fn point_at(self, bounds: Bounds<Pixels>, offset: Pixels) -> Point<Pixels> {
372        if self.axis.is_vertical() && self.reversed() {
373            point(bounds.center().x, bounds.top() + offset)
374        } else if self.axis.is_vertical() {
375            point(bounds.center().x, bounds.bottom() - offset)
376        } else if self.reversed() {
377            point(bounds.right() - offset, bounds.center().y)
378        } else {
379            point(bounds.left() + offset, bounds.center().y)
380        }
381    }
382
383    fn track_corners(self, start: Pixels, end: Pixels) -> gpui::Corners<Pixels> {
384        let (left, right) = if self.reversed() {
385            (end, start)
386        } else {
387            (start, end)
388        };
389        gpui::Corners {
390            top_left: if self.axis.is_vertical() { right } else { left },
391            top_right: right,
392            bottom_left: left,
393            bottom_right: if self.axis.is_vertical() { left } else { right },
394        }
395    }
396
397    fn place(self, element: gpui::Div, position: f32) -> gpui::Div {
398        if self.axis.is_vertical() && self.reversed() {
399            element.top(relative(position))
400        } else if self.axis.is_vertical() {
401            element.bottom(relative(position))
402        } else if self.reversed() {
403            element.right(relative(position))
404        } else {
405            element.left(relative(position))
406        }
407    }
408
409    fn reversed_key_delta(self, key: &str) -> Option<f32> {
410        if !self.reversed() {
411            return None;
412        }
413        match (self.axis, key) {
414            (Axis::Horizontal, "left") | (Axis::Vertical, "down") => Some(1.),
415            (Axis::Horizontal, "right") | (Axis::Vertical, "up") => Some(-1.),
416            _ => None,
417        }
418    }
419
420    fn choose_at(
421        self,
422        range: bool,
423        values: std::ops::Range<f32>,
424        handle_sizes: [Size<Pixels>; 2],
425        bounds: Bounds<Pixels>,
426        pointer: Point<Pixels>,
427    ) -> RangeThumb {
428        let fraction = self.fraction(bounds, pointer);
429        if range && values.start != values.end {
430            let hit = |position, handle: Size<Pixels>| {
431                let center = self.point_at(bounds, bounds.size.along(self.axis) * position);
432                let offset = pointer - center;
433                let (along, across) = if self.axis.is_horizontal() {
434                    (offset.x, offset.y)
435                } else {
436                    (offset.y, offset.x)
437                };
438                along.abs() <= handle.width / 2. && across.abs() <= handle.height / 2.
439            };
440            match (
441                hit(values.start, handle_sizes[0]),
442                hit(values.end, handle_sizes[1]),
443            ) {
444                (true, false) => return RangeThumb::Start,
445                (false, true) => return RangeThumb::End,
446                _ => {}
447            }
448        }
449        choose_thumb(range, values.start, values.end, fraction)
450    }
451}
452
453fn dimension(value: Option<Pixels>, default: f32, zero_allowed: bool) -> Pixels {
454    value
455        .filter(|value| {
456            f32::from(*value).is_finite() && (*value > px(0.) || zero_allowed && *value == px(0.))
457        })
458        .unwrap_or(px(default))
459}
460
461impl RenderOnce for Slider {
462    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
463        let ([start_focus, end_focus], gesture) = window
464            .use_keyed_state(
465                ElementId::from((self.id.clone(), "slider-state")),
466                cx,
467                |_, cx| {
468                    (
469                        [cx.focus_handle(), cx.focus_handle()],
470                        Rc::new(RefCell::new(Gesture::default())),
471                    )
472                },
473            )
474            .read(cx)
475            .clone();
476        let geometry = Geometry {
477            axis: self.axis,
478            direction: window_material_theme(window, cx).layout.direction,
479            reverse_vertical: self.reverse_vertical,
480        };
481        let horizontal = self.axis.is_horizontal();
482        let state = self.state.read(cx);
483        let value = state.value();
484        let percentage = state.percentage();
485        let tick_count = self.tick_intervals;
486        let start = percentage.start;
487        let end = percentage.end;
488        let range = value.is_range();
489        let centered = self.kind == SliderKind::Centered && !range;
490        let center = if centered { 0.5 } else { start };
491        let focus_handles = [&start_focus, &end_focus];
492        {
493            let mut gesture = gesture.borrow_mut();
494            gesture.disabled = self.disabled;
495            for which in [RangeThumb::Start, RangeThumb::End] {
496                let index = thumb_index(which);
497                let feedback = &mut gesture.feedback[index];
498                feedback.focus = Some(focus_handles[index].clone());
499                feedback.tracker = self.thumbs[index]
500                    .source
501                    .as_ref()
502                    .filter(|_| range || which == RangeThumb::End)
503                    .map(|source| {
504                        InteractionSource::track(source, &thumb_id(&self.id, which), window, cx)
505                    });
506                if self.disabled
507                    || !window.is_window_active()
508                    || !range && which == RangeThumb::Start
509                {
510                    feedback.hovered = false;
511                }
512            }
513            gesture.record(window, cx);
514        }
515        // Material slider specs, expressive track and handle sizes.
516        let (thickness, thumb_extent, track_radius, icon_size): (f32, f32, f32, Option<f32>) =
517            match self.size {
518                ControlSize::ExtraSmall => (16., 44., 8., None),
519                ControlSize::Small => (24., 44., 8., None),
520                ControlSize::Medium => (40., 52., 12., Some(24.)),
521                ControlSize::Large => (56., 68., 16., Some(24.)),
522                ControlSize::ExtraLarge => (96., 108., 28., Some(32.)),
523            };
524        let [start_content, end_content] = self.thumbs.each_mut().map(|thumb| thumb.content.take());
525        let thickness = dimension(self.track_style.thickness, thickness, false);
526        let track_radius =
527            dimension(self.track_style.outer_radius, track_radius, true).min(thickness / 2.);
528        let inner_radius = dimension(self.track_style.inner_radius, 2., true).min(thickness / 2.);
529        let thumb_gap = dimension(self.track_style.thumb_gap, 6., true);
530        let cross_extent = |which| {
531            dimension(
532                self.thumbs[thumb_index(which)]
533                    .style
534                    .size
535                    .map(|size| size.height),
536                thumb_extent,
537                false,
538            )
539        };
540        let target = thickness.max(cross_extent(RangeThumb::End)).max(px(48.));
541        let target = if range {
542            target.max(cross_extent(RangeThumb::Start))
543        } else {
544            target
545        };
546        let colors = window_material_theme(window, cx).colors.clone();
547        let resolve = |role| color(colors.color(role));
548        let disabled = resolve(ColorRole::OnSurface);
549        let (active, inactive, active_tick, inactive_tick, thumb_color) = if self.disabled {
550            (
551                self.colors
552                    .disabled_active_track
553                    .unwrap_or_else(|| disabled.opacity(0.38)),
554                self.colors
555                    .disabled_inactive_track
556                    .unwrap_or_else(|| disabled.opacity(0.12)),
557                self.colors
558                    .disabled_active_tick
559                    .unwrap_or_else(|| disabled.opacity(0.38)),
560                self.colors
561                    .disabled_inactive_tick
562                    .unwrap_or_else(|| disabled.opacity(0.38)),
563                self.colors
564                    .disabled_thumb
565                    .unwrap_or_else(|| disabled.opacity(0.38)),
566            )
567        } else {
568            (
569                self.colors
570                    .active_track
571                    .unwrap_or_else(|| resolve(ColorRole::Primary)),
572                self.colors
573                    .inactive_track
574                    .unwrap_or_else(|| resolve(ColorRole::SecondaryContainer)),
575                self.colors
576                    .active_tick
577                    .unwrap_or_else(|| resolve(ColorRole::OnPrimary)),
578                self.colors
579                    .inactive_tick
580                    .unwrap_or_else(|| resolve(ColorRole::OnSecondaryContainer)),
581                self.colors
582                    .thumb
583                    .unwrap_or_else(|| resolve(ColorRole::Primary)),
584            )
585        };
586        let ring = resolve(ColorRole::Secondary);
587
588        let active_icon = resolve(ColorRole::OnPrimary);
589        let inactive_icon = resolve(ColorRole::OnSecondaryContainer);
590        let disabled_icon = resolve(ColorRole::OnSurface).opacity(0.38);
591        let disabled_control = self.disabled;
592        let dragging = gesture
593            .borrow()
594            .thumb
595            .filter(|_| !self.disabled && window.is_window_active());
596        let reduced = cx.reduce_motion();
597        let scheme = window_material_theme(window, cx).motion;
598        let resize = scheme.spec(
599            gpui_material_theme::MotionKind::Spatial,
600            gpui_material_theme::MotionSpeed::Fast,
601            reduced,
602        );
603        let reveal = scheme.spec(
604            gpui_material_theme::MotionKind::Effects,
605            gpui_material_theme::MotionSpeed::Fast,
606            reduced,
607        );
608        let rest_width = |which| {
609            dimension(
610                self.thumbs[thumb_index(which)]
611                    .style
612                    .size
613                    .map(|size| size.width),
614                4.,
615                false,
616            )
617        };
618        let pressed_width = |which| {
619            dimension(
620                self.thumbs[thumb_index(which)].style.pressed_width,
621                2.,
622                false,
623            )
624        };
625        let width = |which, window: &mut Window, cx: &mut App| {
626            let rest = f32::from(rest_width(which));
627            let pressed = f32::from(pressed_width(which));
628            px(animate(
629                (
630                    self.id.clone(),
631                    if which == RangeThumb::Start {
632                        "start-width"
633                    } else {
634                        "end-width"
635                    },
636                ),
637                if dragging == Some(which) {
638                    pressed
639                } else {
640                    rest
641                },
642                resize,
643                window,
644                cx,
645            )
646            .clamp(rest.min(pressed), rest.max(pressed)))
647        };
648        let start_width = if range {
649            width(RangeThumb::Start, window, cx)
650        } else {
651            px(4.)
652        };
653        let end_width = width(RangeThumb::End, window, cx);
654        let handle_sizes = [
655            gpui::size(start_width, cross_extent(RangeThumb::Start)),
656            gpui::size(end_width, cross_extent(RangeThumb::End)),
657        ];
658        let handle_width = |which| {
659            if which == RangeThumb::Start {
660                start_width
661            } else {
662                end_width
663            }
664        };
665        let axis_padding = |which| rest_width(which).max(pressed_width(which)) / 2.;
666        let padding = px(8.).max(axis_padding(RangeThumb::End));
667        let padding = if range {
668            padding.max(axis_padding(RangeThumb::Start))
669        } else {
670            padding
671        };
672        let label_opacity = |which, focus: &FocusHandle, window: &mut Window, cx: &mut App| {
673            if !self.value_indicator || self.disabled {
674                return 0.;
675            }
676            let visible = window.is_window_active()
677                && (dragging == Some(which)
678                    || dragging.is_none()
679                        && focus.is_focused(window)
680                        && window.last_input_was_keyboard());
681            animate(
682                (
683                    self.id.clone(),
684                    if which == RangeThumb::Start {
685                        "start-label"
686                    } else {
687                        "end-label"
688                    },
689                ),
690                f32::from(visible),
691                reveal,
692                window,
693                cx,
694            )
695            .clamp(0., 1.)
696        };
697        let start_label = if range {
698            label_opacity(RangeThumb::Start, &start_focus, window, cx)
699        } else {
700            0.
701        };
702        let end_label = label_opacity(RangeThumb::End, &end_focus, window, cx);
703        // Expressive tracks leave 6 dp between a handle's edge and each adjacent segment.
704        let end_gap = thumb_gap + handle_width(RangeThumb::End) / 2.;
705        let center_gap = if range {
706            thumb_gap + handle_width(RangeThumb::Start) / 2.
707        } else if centered {
708            thumb_gap
709        } else {
710            px(0.)
711        };
712        let (first, last) = if center <= end {
713            ((center, center_gap), (end, end_gap))
714        } else {
715            ((end, end_gap), (center, center_gap))
716        };
717        let segments = move |length| track_segments(length, first, last);
718        let track_icon = self.icon.zip(icon_size).map(|(icon, side)| {
719            canvas(
720                move |bounds, window, cx| {
721                    let side = px(side);
722                    let length = bounds.size.along(geometry.axis);
723                    let (offset, active) = segments(length).into_iter().find_map(|segment| {
724                        segment.icon_position(side, track_radius, inner_radius)
725                    })?;
726                    let foreground = if disabled_control {
727                        disabled_icon
728                    } else if active {
729                        active_icon
730                    } else {
731                        inactive_icon
732                    };
733                    let origin = geometry.point_at(bounds, offset) - point(side / 2., side / 2.);
734                    let mut icon = div()
735                        .size(side)
736                        .flex()
737                        .items_center()
738                        .justify_center()
739                        .text_size(side)
740                        .line_height(side)
741                        .text_color(foreground)
742                        .child(icon)
743                        .into_any_element();
744                    let space = gpui::size(
745                        AvailableSpace::Definite(side),
746                        AvailableSpace::Definite(side),
747                    );
748                    icon.prepaint_as_root(origin, space, window, cx);
749                    Some(icon)
750                },
751                |_, icon, window, cx| {
752                    if let Some(mut icon) = icon {
753                        icon.paint(window, cx);
754                    }
755                },
756            )
757            .absolute()
758            .inset_0()
759            .size_full()
760        });
761        let track_artwork = if let Some(custom) = self.track.take() {
762            div()
763                .absolute()
764                .when(horizontal, |track| {
765                    track.w_full().h(thickness).top((target - thickness) / 2.)
766                })
767                .when(!horizontal, |track| {
768                    track.h_full().w(thickness).left((target - thickness) / 2.)
769                })
770                .child(custom)
771                .into_any_element()
772        } else {
773            let show_stops = self.show_stop_indicators;
774            let draw_tick = self.draw_tick.take();
775            let draw_stop = self.draw_stop.take();
776            div()
777                .absolute()
778                .inset_0()
779                .child(
780                    canvas(
781                        |_, _, _| (),
782                        move |bounds, _, window, cx| {
783                            let length = bounds.size.along(geometry.axis);
784                            let track_segments = segments(length);
785                            let stop_offset = track_radius.max(px(2.));
786                            let marker = |offset, color| SliderMarker {
787                                center: geometry.point_at(bounds, offset),
788                                diameter: px(4.),
789                                color,
790                            };
791                            for segment in track_segments {
792                                if segment.end <= segment.start {
793                                    continue;
794                                }
795                                let a = geometry.point_at(bounds, segment.start);
796                                let b = geometry.point_at(bounds, segment.end);
797                                let half = thickness / 2.;
798                                let rect = if horizontal {
799                                    Bounds::from_corners(
800                                        point(a.x.min(b.x), a.y - half),
801                                        point(a.x.max(b.x), b.y + half),
802                                    )
803                                } else {
804                                    Bounds::from_corners(
805                                        point(a.x - half, a.y.min(b.y)),
806                                        point(a.x + half, a.y.max(b.y)),
807                                    )
808                                };
809                                let tint = if segment.active { active } else { inactive };
810                                let (start_corner, end_corner) =
811                                    segment.corners(track_radius, inner_radius);
812                                window.paint_quad(gpui::quad(
813                                    rect,
814                                    geometry.track_corners(start_corner, end_corner),
815                                    tint,
816                                    px(0.),
817                                    gpui::transparent_black(),
818                                    gpui::BorderStyle::Solid,
819                                ));
820                                // The stop indicator marks the outer edge of each inactive segment.
821                                if show_stops && !segment.active {
822                                    if segment.outer_start
823                                        && segment.start + stop_offset + px(2.) <= segment.end
824                                    {
825                                        draw_marker(
826                                            draw_stop.as_ref(),
827                                            marker(segment.start + stop_offset, active),
828                                            window,
829                                            cx,
830                                        );
831                                    }
832                                    if segment.outer_end
833                                        && segment.end - stop_offset - px(2.) >= segment.start
834                                    {
835                                        draw_marker(
836                                            draw_stop.as_ref(),
837                                            marker(segment.end - stop_offset, active),
838                                            window,
839                                            cx,
840                                        );
841                                    }
842                                }
843                            }
844                            if tick_count >= 2 {
845                                // Skip ticks when they would visually merge instead of iterating every
846                                // possible value on a fine-grained scale.
847                                let spacing = f32::from(length) / f32::from(tick_count);
848                                if spacing >= 6. {
849                                    for index in 1..tick_count {
850                                        let offset =
851                                            length * (f32::from(index) / f32::from(tick_count));
852                                        if let Some(segment) =
853                                            track_segments.iter().find(|segment| {
854                                                segment.start + px(2.) <= offset
855                                                    && offset <= segment.end - px(2.)
856                                            })
857                                        {
858                                            let tint = if segment.active {
859                                                active_tick
860                                            } else {
861                                                inactive_tick
862                                            };
863                                            let on_endpoint = show_stops
864                                                && !segment.active
865                                                && (segment.outer_start
866                                                    && (offset - segment.start - stop_offset)
867                                                        .abs()
868                                                        < px(4.)
869                                                    || segment.outer_end
870                                                        && (segment.end - stop_offset - offset)
871                                                            .abs()
872                                                            < px(4.));
873                                            if !on_endpoint {
874                                                draw_marker(
875                                                    draw_tick.as_ref(),
876                                                    marker(offset, tint),
877                                                    window,
878                                                    cx,
879                                                );
880                                            }
881                                        }
882                                    }
883                                }
884                            }
885                        },
886                    )
887                    .absolute()
888                    .inset_0()
889                    .size_full(),
890                )
891                .children(track_icon)
892                .into_any_element()
893        };
894        let track = SliderIndicator::new(&self.state)
895            .relative()
896            .size_full()
897            .child(track_artwork);
898        let thumb = |which, position, name, focus: &FocusHandle, content: Option<AnyElement>| {
899            let keyboard_state = self.state.clone();
900            let handle_width = handle_width(which);
901            let half_handle = handle_width / 2.;
902            let cross = cross_extent(which);
903            let (width, height) = if horizontal {
904                (handle_width, cross)
905            } else {
906                (cross, handle_width)
907            };
908            let style = self.thumbs[thumb_index(which)].style;
909            let tint = if self.disabled {
910                style.disabled_color
911            } else {
912                style.color
913            }
914            .unwrap_or(thumb_color);
915            let focus_color = style.focused_color.unwrap_or(ring);
916            let opacity = if which == RangeThumb::Start {
917                start_label
918            } else {
919                end_label
920            };
921            let label = (opacity > 0.)
922                .then(|| {
923                    let numeric_value = if which == RangeThumb::Start {
924                        value.start()
925                    } else {
926                        value.end()
927                    };
928                    let text = self.format_value.as_ref().map_or_else(
929                        || format!("{numeric_value:.2}").into(),
930                        |format| format(numeric_value),
931                    );
932                    let theme = window_material_theme(window, cx);
933                    let foreground = resolve(ColorRole::InverseOnSurface).opacity(opacity);
934                    let background = resolve(ColorRole::InverseSurface).opacity(opacity);
935                    let line = shape_text(
936                        text,
937                        TypeRole::LabelLarge.style(TypographyEmphasis::Baseline),
938                        &theme.typography,
939                        1.,
940                        foreground,
941                        window,
942                        cx,
943                    )?;
944                    Some(
945                        canvas(
946                            |_, _, _| (),
947                            move |thumb, _, window, cx| {
948                                let size = gpui::size(
949                                    (line.line().width.ceil() + px(16.)).max(px(48.)),
950                                    line.line_height().max(px(44.)),
951                                );
952                                let visible = window.content_mask().bounds;
953                                if !visible.contains(&thumb.center()) {
954                                    return;
955                                }
956                                let origin = value_label_origin(
957                                    thumb,
958                                    size,
959                                    visible,
960                                    horizontal,
961                                    geometry.direction,
962                                );
963                                let bounds = Bounds::new(origin, size);
964                                window.paint_quad(gpui::quad(
965                                    bounds,
966                                    px(6.),
967                                    background,
968                                    px(0.),
969                                    background,
970                                    gpui::BorderStyle::Solid,
971                                ));
972                                let _ = line.paint(
973                                    origin
974                                        + point(
975                                            (size.width - line.line().width) / 2.,
976                                            (size.height - line.line_height()) / 2.,
977                                        ),
978                                    gpui::TextAlign::Left,
979                                    None,
980                                    window,
981                                    cx,
982                                );
983                            },
984                        )
985                        .absolute()
986                        .inset_0()
987                        .size_full(),
988                    )
989                })
990                .flatten();
991            let custom = content.is_some();
992            let element = geometry
993                .place(
994                    div()
995                        .absolute()
996                        .when(horizontal, |thumb| {
997                            thumb
998                                .top((target - height) / 2.)
999                                .ml(-half_handle)
1000                                .when(geometry.reversed(), |thumb| {
1001                                    thumb.ml(px(0.)).mr(-half_handle)
1002                                })
1003                        })
1004                        .when(!horizontal, |thumb| {
1005                            thumb.left((target - width) / 2.).when_else(
1006                                geometry.reversed(),
1007                                |thumb| thumb.mt(-half_handle),
1008                                |thumb| thumb.mb(-half_handle),
1009                            )
1010                        }),
1011                    position,
1012                )
1013                .id(thumb_id(&self.id, which))
1014                .when(!self.disabled, |thumb| thumb.role(Role::Slider))
1015                .when(!self.disabled, |thumb| thumb.aria_label(name))
1016                .w(width)
1017                .h(height)
1018                .when_else(
1019                    custom,
1020                    |thumb| {
1021                        thumb
1022                            .text_color(tint)
1023                            .focus_visible(move |style| style.border_1().border_color(focus_color))
1024                            .children(content.map(|art| div().size_full().child(art)))
1025                    },
1026                    |thumb| {
1027                        thumb
1028                            .rounded_full()
1029                            .bg(tint)
1030                            .focus_visible(move |style| style.bg(focus_color))
1031                    },
1032                )
1033                .children(label);
1034
1035            let element = if self.disabled {
1036                element
1037            } else {
1038                let hover = gesture.clone();
1039                range_semantics(element, &self.state, which, self.axis, cx)
1040                    .capture_key_down(move |event, window, cx| {
1041                        let Some(sign) = geometry.reversed_key_delta(&event.keystroke.key) else {
1042                            return;
1043                        };
1044                        keyboard_state.update(cx, |state, cx| {
1045                            state.step_thumb(
1046                                which == RangeThumb::Start,
1047                                sign * state.accessibility_step(),
1048                                window,
1049                                cx,
1050                            );
1051                        });
1052                        cx.stop_propagation();
1053                    })
1054                    .on_hover(move |hovered, window, cx| {
1055                        let mut hover = hover.borrow_mut();
1056                        hover.feedback[thumb_index(which)].hovered = *hovered;
1057                        hover.record(window, cx);
1058                    })
1059            };
1060            element.test_support().when(!self.disabled, |thumb| {
1061                thumb.track_focus(&focus.clone().tab_stop(true))
1062            })
1063        };
1064        let disabled_name = self.range_end_name.as_ref().map_or_else(
1065            || self.name.clone(),
1066            |end| format!("{} – {end}", self.name).into(),
1067        );
1068        // The indicator records these bounds for Base input. Absolute thumbs are children
1069        // of the same unpadded coordinate space, so percentages use those bounds as well.
1070        let track_and_handles = div()
1071            .relative()
1072            .size_full()
1073            .child(track)
1074            .when(range, |root| {
1075                root.child(thumb(
1076                    RangeThumb::Start,
1077                    start,
1078                    self.name.clone(),
1079                    &start_focus,
1080                    start_content,
1081                ))
1082            })
1083            .child(thumb(
1084                RangeThumb::End,
1085                end,
1086                self.range_end_name.unwrap_or(self.name),
1087                &end_focus,
1088                end_content,
1089            ));
1090        let root = div()
1091            .id(self.id.clone())
1092            .relative()
1093            .when(horizontal, |root| root.w_full().h(target).px(padding))
1094            .when(!horizontal, |root| root.w(target).h(px(200.)).py(padding))
1095            .child(track_and_handles);
1096        let active_thumb = gesture.borrow().thumb;
1097        let inactive = !window.is_window_active();
1098        if active_thumb
1099            .is_some_and(|which| self.disabled || inactive || !range && which == RangeThumb::Start)
1100        {
1101            let state = self.state.clone();
1102            let gesture = gesture.clone();
1103            window.defer(cx, move |window, cx| {
1104                finish(&state, &gesture, window, cx, true)
1105            });
1106        }
1107        if self.disabled || inactive && active_thumb.is_some() {
1108            return if self.disabled {
1109                BaseSlider::new(&self.state)
1110                    .axis(self.axis)
1111                    .disabled(true)
1112                    .accessibility_label(disabled_name)
1113                    .child(root)
1114                    .into_any_element()
1115            } else {
1116                root.into_any_element()
1117            };
1118        }
1119
1120        let touch = gesture.clone();
1121        let touch_state = self.state.clone();
1122        let touch_focus = [start_focus.clone(), end_focus.clone()];
1123        let touch_layer = canvas(
1124            |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
1125            move |_, hitbox, window, _| {
1126                let gesture = touch.clone();
1127                let state = touch_state.clone();
1128                let focus = touch_focus.clone();
1129                window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
1130                    if !phase.bubble() {
1131                        return;
1132                    }
1133                    if event.phase == TouchPhase::Started {
1134                        if window.default_prevented()
1135                            || !hitbox.is_hovered_at(event.start_position, window)
1136                        {
1137                            return;
1138                        }
1139                        let bounds = state.read(cx).bounds();
1140                        if bounds.size.along(geometry.axis) <= px(0.) {
1141                            return;
1142                        }
1143                        let current = state.read(cx).percentage();
1144                        let which = if range && current.start == current.end {
1145                            let fraction = geometry.fraction(bounds, event.start_position);
1146                            choose_thumb(
1147                                true,
1148                                fraction,
1149                                fraction,
1150                                geometry.fraction(bounds, event.position),
1151                            )
1152                        } else {
1153                            geometry.choose_at(
1154                                range,
1155                                current,
1156                                handle_sizes,
1157                                bounds,
1158                                event.start_position,
1159                            )
1160                        };
1161                        window.prevent_default();
1162                        {
1163                            let mut gesture = gesture.borrow_mut();
1164                            gesture.origin = Some(event.start_position);
1165                            gesture.thumb = Some(which);
1166                        }
1167                        focus[thumb_index(which)].focus(window, cx);
1168                    }
1169                    let which = {
1170                        let gesture = gesture.borrow();
1171                        if gesture.origin != Some(event.start_position) || gesture.capture.is_some()
1172                        {
1173                            return;
1174                        }
1175                        let Some(which) = gesture.thumb else {
1176                            return;
1177                        };
1178                        which
1179                    };
1180                    match event.phase {
1181                        TouchPhase::Started | TouchPhase::Moved => {
1182                            {
1183                                let mut gesture = gesture.borrow_mut();
1184                                gesture.dragged = event.position != event.start_position;
1185                                gesture.record(window, cx);
1186                            }
1187                            update(&state, geometry, which, event.position, window, cx);
1188                        }
1189                        TouchPhase::Ended | TouchPhase::Cancelled => {
1190                            finish(&state, &gesture, window, cx, false);
1191                        }
1192                    }
1193                    cx.stop_propagation();
1194                });
1195            },
1196        )
1197        .absolute()
1198        .inset_0()
1199        .size_full();
1200        let down = gesture.clone();
1201        let begin = gesture.clone();
1202        let drag = gesture.clone();
1203        let release = gesture.clone();
1204        let release_out = gesture.clone();
1205        let scroll = gesture.clone();
1206        let escape = gesture;
1207        let down_state = self.state.clone();
1208        let begin_state = self.state.clone();
1209        let drag_state = self.state.clone();
1210        let drag_source = self.state.clone();
1211        let drag_focus = [start_focus.clone(), end_focus.clone()];
1212        let release_state = self.state.clone();
1213        let outside_state = self.state.clone();
1214        let escape_state = self.state;
1215        root.child(touch_layer)
1216            .on_mouse_down(MouseButton::Left, move |event, window, cx| {
1217                let bounds = down_state.read(cx).bounds();
1218                if bounds.size.along(geometry.axis) <= px(0.) {
1219                    return;
1220                }
1221                let which = geometry.choose_at(
1222                    range,
1223                    down_state.read(cx).percentage(),
1224                    handle_sizes,
1225                    bounds,
1226                    event.position,
1227                );
1228                {
1229                    let mut down = down.borrow_mut();
1230                    down.thumb = Some(which);
1231                    down.origin = Some(event.position);
1232                }
1233                if which == RangeThumb::Start {
1234                    start_focus.focus(window, cx);
1235                } else {
1236                    end_focus.focus(window, cx);
1237                }
1238                down.borrow().record(window, cx);
1239                update(&down_state, geometry, which, event.position, window, cx);
1240            })
1241            .on_drag(SliderDrag(drag_source), move |payload, _, window, cx| {
1242                let gesture = Rc::downgrade(&begin);
1243                let state = begin_state.clone();
1244                begin.borrow_mut().capture =
1245                    Some(DragCapture::watch(window, cx, move |window, cx| {
1246                        if let Some(gesture) = gesture.upgrade() {
1247                            finish(&state, &gesture, window, cx, false);
1248                        }
1249                    }));
1250                {
1251                    let mut begin = begin.borrow_mut();
1252                    begin.dragged = true;
1253                    begin.record(window, cx);
1254                }
1255                cx.stop_propagation();
1256                cx.new(|_| SliderDrag(payload.0.clone()))
1257            })
1258            .on_drag_move(move |event: &DragMoveEvent<SliderDrag>, window, cx| {
1259                if event.drag(cx).0.entity_id() != drag_state.entity_id() {
1260                    return;
1261                }
1262                let mut gesture = drag.borrow_mut();
1263                let Some(mut which) = gesture.thumb else {
1264                    return;
1265                };
1266                if range
1267                    && start == end
1268                    && let Some(origin) = gesture.origin.take()
1269                {
1270                    let bounds = drag_state.read(cx).bounds();
1271                    which = if geometry.fraction(bounds, event.event.position)
1272                        < geometry.fraction(bounds, origin)
1273                    {
1274                        RangeThumb::Start
1275                    } else {
1276                        RangeThumb::End
1277                    };
1278                    gesture.thumb = Some(which);
1279                    drag_focus[thumb_index(which)].focus(window, cx);
1280                }
1281                gesture.record(window, cx);
1282                update(
1283                    &drag_state,
1284                    geometry,
1285                    which,
1286                    event.event.position,
1287                    window,
1288                    cx,
1289                );
1290                cx.stop_propagation();
1291            })
1292            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
1293                finish(&release_state, &release, window, cx, false)
1294            })
1295            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
1296                finish(&outside_state, &release_out, window, cx, false)
1297            })
1298            .capture_key_down(move |event, window, cx| {
1299                if event.keystroke.key == "escape" && escape.borrow().thumb.is_some() {
1300                    finish(&escape_state, &escape, window, cx, true);
1301                    cx.stop_propagation();
1302                }
1303            })
1304            .on_scroll(move |_, _, cx| {
1305                // Wheel events over the active range gesture stay with it.
1306                if scroll.borrow().thumb.is_some() {
1307                    cx.stop_propagation();
1308                }
1309            })
1310            .into_any_element()
1311    }
1312}
1313
1314fn draw_marker(draw: Option<&DrawMarker>, marker: SliderMarker, window: &mut Window, cx: &mut App) {
1315    if let Some(draw) = draw {
1316        draw(marker, window, cx);
1317    } else {
1318        let radius = marker.diameter / 2.;
1319        let offset = point(radius, radius);
1320        window.paint_quad(gpui::quad(
1321            Bounds::from_corners(marker.center - offset, marker.center + offset),
1322            radius,
1323            marker.color,
1324            px(0.),
1325            gpui::transparent_black(),
1326            gpui::BorderStyle::Solid,
1327        ));
1328    }
1329}
1330
1331fn value_label_origin(
1332    thumb: Bounds<Pixels>,
1333    label: gpui::Size<Pixels>,
1334    visible: Bounds<Pixels>,
1335    horizontal: bool,
1336    direction: Direction,
1337) -> Point<Pixels> {
1338    let gap = px(12.);
1339    let x = if horizontal {
1340        thumb.center().x - label.width / 2.
1341    } else if direction == Direction::Ltr && thumb.right() + gap + label.width <= visible.right()
1342        || thumb.left() - gap - label.width < visible.left()
1343    {
1344        thumb.right() + gap
1345    } else {
1346        thumb.left() - gap - label.width
1347    };
1348    let y = if horizontal && thumb.top() - gap - label.height >= visible.top() {
1349        thumb.top() - gap - label.height
1350    } else if horizontal {
1351        thumb.bottom() + gap
1352    } else {
1353        thumb.center().y - label.height / 2.
1354    };
1355    point(
1356        x.clamp(
1357            visible.left(),
1358            (visible.right() - label.width).max(visible.left()),
1359        ),
1360        y.clamp(
1361            visible.top(),
1362            (visible.bottom() - label.height).max(visible.top()),
1363        ),
1364    )
1365}
1366
1367#[derive(Clone, Copy)]
1368struct TrackSegment {
1369    start: Pixels,
1370    end: Pixels,
1371    outer_start: bool,
1372    outer_end: bool,
1373    active: bool,
1374}
1375
1376impl TrackSegment {
1377    fn corners(self, outer: Pixels, inner: Pixels) -> (Pixels, Pixels) {
1378        let limit = (self.end - self.start).max(px(0.)) / 2.;
1379        let radius = |outside| if outside { outer } else { inner }.min(limit);
1380        (radius(self.outer_start), radius(self.outer_end))
1381    }
1382
1383    fn icon_position(self, side: Pixels, outer: Pixels, inner: Pixels) -> Option<(Pixels, bool)> {
1384        let (start, end) = self.corners(outer, inner);
1385        let start = start.max(px(4.));
1386        let end = end.max(px(4.));
1387        (self.end - self.start >= start + side + end)
1388            .then_some((self.start + start + side / 2., self.active))
1389    }
1390}
1391
1392fn track_segments(
1393    length: Pixels,
1394    (first, first_gap): (f32, Pixels),
1395    (last, last_gap): (f32, Pixels),
1396) -> [TrackSegment; 3] {
1397    let first = length * first;
1398    let last = length * last;
1399    [
1400        TrackSegment {
1401            start: px(0.),
1402            end: (first - first_gap).min(last - last_gap),
1403            outer_start: true,
1404            outer_end: false,
1405            active: false,
1406        },
1407        TrackSegment {
1408            start: first + first_gap,
1409            end: last - last_gap,
1410            outer_start: first == px(0.) && first_gap == px(0.),
1411            outer_end: last == length && last_gap == px(0.),
1412            active: true,
1413        },
1414        TrackSegment {
1415            start: (last + last_gap).max(first + first_gap),
1416            end: length,
1417            outer_start: false,
1418            outer_end: true,
1419            active: false,
1420        },
1421    ]
1422}
1423
1424fn choose_thumb(range: bool, start: f32, end: f32, fraction: f32) -> RangeThumb {
1425    if range && fraction < (start + end) / 2. {
1426        RangeThumb::Start
1427    } else {
1428        RangeThumb::End
1429    }
1430}
1431
1432fn update(
1433    state: &Entity<SliderState>,
1434    geometry: Geometry,
1435    thumb: RangeThumb,
1436    pointer: Point<Pixels>,
1437    window: &mut Window,
1438    cx: &mut App,
1439) {
1440    state.update(cx, |state, cx| {
1441        let bounds = state.bounds();
1442        if bounds.size.along(geometry.axis) <= px(0.) {
1443            return;
1444        }
1445        let position = geometry.position(bounds, pointer);
1446        state.update_value_by_position(
1447            geometry.axis,
1448            position,
1449            thumb == RangeThumb::Start,
1450            window,
1451            cx,
1452        );
1453    });
1454}
1455
1456fn finish(
1457    state: &Entity<SliderState>,
1458    gesture: &RefCell<Gesture>,
1459    window: &mut Window,
1460    cx: &mut App,
1461    cancel: bool,
1462) {
1463    let capture = {
1464        let mut gesture = gesture.borrow_mut();
1465        if gesture.thumb.take().is_none() {
1466            return;
1467        }
1468        gesture.origin = None;
1469        gesture.dragged = false;
1470        gesture.record(window, cx);
1471        gesture.capture.take()
1472    };
1473    if let Some(capture) = capture
1474        && cancel
1475    {
1476        capture.cancel(window, cx);
1477    }
1478    state.update(cx, |state, cx| state.handle_release(cx));
1479    window.refresh();
1480}
1481
1482#[cfg(test)]
1483mod tests {
1484    use super::*;
1485
1486    #[test]
1487    fn value_labels_keep_material_gap_and_flip_inside_the_viewport() {
1488        let visible = Bounds::new(point(px(0.), px(0.)), gpui::size(px(200.), px(200.)));
1489        let label = gpui::size(px(48.), px(44.));
1490        let thumb = Bounds::new(point(px(98.), px(100.)), gpui::size(px(4.), px(44.)));
1491        let above = value_label_origin(thumb, label, visible, true, Direction::Ltr);
1492        assert_eq!(above, point(px(76.), px(44.)));
1493        assert_eq!(thumb.top() - above.y - label.height, px(12.));
1494
1495        let top = Bounds::new(point(px(0.), px(0.)), thumb.size);
1496        let below = value_label_origin(top, label, visible, true, Direction::Rtl);
1497        assert_eq!(below, point(px(0.), px(56.)));
1498        let vertical = value_label_origin(thumb, label, visible, false, Direction::Rtl);
1499        assert_eq!(vertical.x + label.width + px(12.), thumb.left());
1500    }
1501
1502    #[test]
1503    fn track_segments_stop_the_same_distance_from_each_handle() {
1504        for percentage in [0.1, 0.5, 0.9] {
1505            let length = px(200.);
1506            let center = length * percentage;
1507            let [_, active, inactive] = track_segments(length, (0., px(0.)), (percentage, px(8.)));
1508            assert_eq!(center - active.end, px(8.));
1509            assert_eq!(inactive.start - center, px(8.));
1510            assert_eq!(active.corners(px(12.), px(2.)).1, px(2.));
1511            assert_eq!(inactive.corners(px(12.), px(2.)).0, px(2.));
1512        }
1513
1514        let [before, active, after] = track_segments(px(200.), (0.5, px(7.)), (0.5, px(8.)));
1515        assert_eq!(before.end, px(92.));
1516        assert_eq!(after.start, px(108.));
1517        assert!(active.end < active.start);
1518    }
1519}