Skip to main content

gpui_base/
scrollbar.rs

1use std::{cell::Cell, ops::Deref, panic::Location, rc::Rc};
2
3use instant::{Duration, Instant};
4
5use crate::{
6    AxisExt,
7    animation::{ease_in_cubic, ease_out_cubic},
8    theme::ActiveTheme as _,
9};
10use gpui::{
11    Anchor, App, Axis, Background, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element,
12    ElementId, EntityId, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IsZero,
13    LayoutId, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
14    Pixels, Point, Position, ScrollEvent, ScrollHandle, Size, Style, TouchDragEvent, TouchPhase,
15    UniformListScrollHandle, Window, fill, point, prelude::FluentBuilder, px, relative, size,
16};
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19
20/// The width of the scrollbar (THUMB_ACTIVE_INSET * 2 + THUMB_ACTIVE_WIDTH)
21const WIDTH: Pixels = px(4. * 2. + 8.);
22const MIN_THUMB_SIZE: Pixels = px(48.);
23
24const THUMB_WIDTH: Pixels = px(6.);
25const THUMB_RADIUS: Pixels = Pixels::ZERO;
26const THUMB_INSET: Pixels = px(4.);
27
28const THUMB_ACTIVE_WIDTH: Pixels = px(8.);
29const THUMB_ACTIVE_RADIUS: Pixels = Pixels::ZERO;
30const THUMB_ACTIVE_INSET: Pixels = px(4.);
31
32/// How long visibility is held after the last activity, when the styled layer
33/// projects no [`ScrollbarMotion`] of its own.
34///
35/// This is a visibility hold rather than motion: without it [`ScrollbarMode::Scrolling`]
36/// could never reveal the scrollbar.
37const DEFAULT_IDLE: Duration = Duration::from_secs(2);
38
39fn clamp_thumb_radius(radius: Pixels, bounds: Bounds<Pixels>) -> Pixels {
40    radius
41        .min(bounds.size.width / 2.)
42        .min(bounds.size.height / 2.)
43}
44
45/// Scrollbar show mode.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash, Default, JsonSchema)]
47pub enum ScrollbarMode {
48    /// Show scrollbar when scrolling, will fade out after idle.
49    #[default]
50    Scrolling,
51    /// Show scrollbar on hover.
52    Hover,
53    /// Always show scrollbar.
54    Always,
55}
56
57impl ScrollbarMode {
58    fn is_hover(&self) -> bool {
59        matches!(self, Self::Hover)
60    }
61
62    fn is_always(&self) -> bool {
63        matches!(self, Self::Always)
64    }
65}
66
67/// A trait for scroll handles that can get and set offset.
68pub trait ScrollbarHandle: 'static {
69    /// Bounds of the viewport the scrollbar overlays.
70    fn viewport_bounds(&self) -> Bounds<Pixels>;
71    /// Get the current offset of the scroll handle.
72    fn offset(&self) -> Point<Pixels>;
73    /// Set the offset of the scroll handle.
74    fn set_offset(&self, offset: Point<Pixels>);
75    /// The full size of the content, including padding.
76    fn content_size(&self) -> Size<Pixels>;
77    /// Called when start dragging the scrollbar thumb.
78    fn start_drag(&self) {}
79    /// Called when end dragging the scrollbar thumb.
80    fn end_drag(&self) {}
81}
82
83impl ScrollbarHandle for ScrollHandle {
84    fn viewport_bounds(&self) -> Bounds<Pixels> {
85        self.bounds()
86    }
87
88    fn offset(&self) -> Point<Pixels> {
89        self.offset()
90    }
91
92    fn set_offset(&self, offset: Point<Pixels>) {
93        self.set_offset(offset);
94    }
95
96    fn content_size(&self) -> Size<Pixels> {
97        (self.max_offset() + self.bounds().size.into()).into()
98    }
99}
100
101impl ScrollbarHandle for UniformListScrollHandle {
102    fn viewport_bounds(&self) -> Bounds<Pixels> {
103        self.0.borrow().base_handle.bounds()
104    }
105
106    fn offset(&self) -> Point<Pixels> {
107        self.0.borrow().base_handle.offset()
108    }
109
110    fn set_offset(&self, offset: Point<Pixels>) {
111        self.0.borrow_mut().base_handle.set_offset(offset)
112    }
113
114    fn content_size(&self) -> Size<Pixels> {
115        let base_handle = &self.0.borrow().base_handle;
116        (base_handle.max_offset() + base_handle.bounds().size.into()).into()
117    }
118}
119
120impl ScrollbarHandle for ListState {
121    fn viewport_bounds(&self) -> Bounds<Pixels> {
122        ListState::viewport_bounds(self)
123    }
124
125    fn offset(&self) -> Point<Pixels> {
126        self.scroll_px_offset_for_scrollbar()
127    }
128
129    fn set_offset(&self, offset: Point<Pixels>) {
130        self.set_offset_from_scrollbar(offset);
131    }
132
133    fn content_size(&self) -> Size<Pixels> {
134        self.viewport_bounds().size + self.max_offset_for_scrollbar().into()
135    }
136
137    fn start_drag(&self) {
138        self.scrollbar_drag_started();
139    }
140
141    fn end_drag(&self) {
142        self.scrollbar_drag_ended();
143    }
144}
145
146#[doc(hidden)]
147#[derive(Debug, Clone)]
148struct ScrollbarState(Rc<Cell<ScrollbarStateInner>>);
149
150#[doc(hidden)]
151#[derive(Debug, Clone, Copy)]
152struct ScrollbarStateInner {
153    hovered_axis: Option<Axis>,
154    hovered_on_thumb: Option<Axis>,
155    dragged_axis: Option<Axis>,
156    drag_pos: Point<Pixels>,
157    last_scroll_offset: Point<Pixels>,
158    last_scroll_time: Option<Instant>,
159    // Last update offset
160    last_update: Instant,
161    drag_update_scheduled: bool,
162    drag_update_generation: u64,
163    idle_timer_scheduled: bool,
164    visibility: VisibilityAnimation,
165    vertical_width: WidthAnimation,
166    horizontal_width: WidthAnimation,
167}
168
169impl Default for ScrollbarState {
170    fn default() -> Self {
171        let now = Instant::now();
172        Self(Rc::new(Cell::new(ScrollbarStateInner {
173            hovered_axis: None,
174            hovered_on_thumb: None,
175            dragged_axis: None,
176            drag_pos: point(px(0.), px(0.)),
177            last_scroll_offset: point(px(0.), px(0.)),
178            last_scroll_time: None,
179            last_update: now,
180            drag_update_scheduled: false,
181            drag_update_generation: 0,
182            idle_timer_scheduled: false,
183            visibility: VisibilityAnimation::hidden(now),
184            vertical_width: WidthAnimation::new(now),
185            horizontal_width: WidthAnimation::new(now),
186        })))
187    }
188}
189
190#[derive(Debug, Clone, Copy)]
191struct ScalarTransition<T> {
192    from: T,
193    target: T,
194    started_at: Instant,
195    duration: Duration,
196}
197
198impl<T: Copy + PartialEq> ScalarTransition<T> {
199    fn settled(value: T, now: Instant) -> Self {
200        Self {
201            from: value,
202            target: value,
203            started_at: now,
204            duration: Duration::ZERO,
205        }
206    }
207
208    fn sample(&self, now: Instant, interpolate: impl FnOnce(T, T, f32) -> T) -> (T, bool) {
209        if self.from == self.target || self.duration.is_zero() {
210            return (self.target, false);
211        }
212        let linear = now.saturating_duration_since(self.started_at).as_secs_f32()
213            / self.duration.as_secs_f32();
214        if linear >= 1.0 {
215            (self.target, false)
216        } else {
217            (
218                interpolate(self.from, self.target, linear.clamp(0.0, 1.0)),
219                true,
220            )
221        }
222    }
223
224    fn start(&mut self, from: T, target: T, duration: Duration, now: Instant) {
225        self.from = from;
226        self.target = target;
227        self.started_at = now;
228        self.duration = duration;
229    }
230
231    fn settle(&mut self, target: T, now: Instant) {
232        self.start(target, target, Duration::ZERO, now);
233    }
234}
235
236#[derive(Debug, Clone, Copy)]
237struct WidthAnimation {
238    transition: ScalarTransition<Pixels>,
239    initialized: bool,
240}
241
242impl WidthAnimation {
243    fn new(now: Instant) -> Self {
244        Self {
245            transition: ScalarTransition::settled(Pixels::ZERO, now),
246            initialized: false,
247        }
248    }
249
250    fn sample(&self, now: Instant) -> (Pixels, bool) {
251        self.transition.sample(now, |from, target, linear| {
252            from + (target - from) * ease_out_cubic(linear)
253        })
254    }
255
256    /// Move toward `target` over `duration`. A zero duration adopts the target
257    /// immediately, which is how reduced motion and a motionless theme arrive here.
258    fn set_target(&mut self, target: Pixels, duration: Duration, now: Instant) -> (Pixels, bool) {
259        if duration.is_zero() || !self.initialized {
260            self.transition.settle(target, now);
261            self.initialized = true;
262        } else if self.transition.target != target {
263            let from = self.sample(now).0;
264            self.transition.start(from, target, duration, now);
265        }
266        self.sample(now)
267    }
268}
269
270/// How a scrollbar becomes visible.
271///
272/// The styled layer chooses the choreography; Base only plays it.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
274pub enum ScrollbarEntrance {
275    /// Fade in without moving.
276    #[default]
277    Fade,
278    /// Slide in from the nearest edge while fading.
279    SlideAndFade,
280}
281
282/// Motion tokens used by [`Scrollbar`].
283///
284/// Base installs no motion of its own: every transition duration defaults to
285/// zero, so visibility and thumb width snap. Product timing belongs to the
286/// styled layer, which projects it through [`crate::ScrollbarTheme`].
287#[derive(Debug, Clone, Copy, PartialEq)]
288pub struct ScrollbarMotion {
289    idle: Duration,
290    enter: Duration,
291    exit: Duration,
292    expand: Duration,
293    entrance: ScrollbarEntrance,
294    thumb_hover_entrance: ScrollbarEntrance,
295}
296
297impl Default for ScrollbarMotion {
298    fn default() -> Self {
299        Self {
300            idle: DEFAULT_IDLE,
301            enter: Duration::ZERO,
302            exit: Duration::ZERO,
303            expand: Duration::ZERO,
304            entrance: ScrollbarEntrance::Fade,
305            thumb_hover_entrance: ScrollbarEntrance::Fade,
306        }
307    }
308}
309
310impl ScrollbarMotion {
311    /// How long visibility is held after the last scroll, drag, or hover.
312    pub fn with_idle(mut self, idle: Duration) -> Self {
313        self.idle = idle;
314        self
315    }
316
317    /// How long the scrollbar takes to become fully visible.
318    pub fn with_enter(mut self, enter: Duration) -> Self {
319        self.enter = enter;
320        self
321    }
322
323    /// How long the scrollbar takes to fade away once the idle hold expires.
324    pub fn with_exit(mut self, exit: Duration) -> Self {
325        self.exit = exit;
326        self
327    }
328
329    /// How long the thumb takes to reach a new width.
330    pub fn with_expand(mut self, expand: Duration) -> Self {
331        self.expand = expand;
332        self
333    }
334
335    /// Which entrance choreography to play.
336    pub fn with_entrance(mut self, entrance: ScrollbarEntrance) -> Self {
337        self.entrance = entrance;
338        self
339    }
340
341    /// Which entrance choreography to play when hover reveals the thumb.
342    pub fn with_thumb_hover_entrance(mut self, entrance: ScrollbarEntrance) -> Self {
343        self.thumb_hover_entrance = entrance;
344        self
345    }
346
347    pub fn idle(&self) -> Duration {
348        self.idle
349    }
350
351    pub fn enter(&self) -> Duration {
352        self.enter
353    }
354
355    pub fn exit(&self) -> Duration {
356        self.exit
357    }
358
359    pub fn expand(&self) -> Duration {
360        self.expand
361    }
362
363    pub fn entrance(&self) -> ScrollbarEntrance {
364        self.entrance
365    }
366
367    pub fn thumb_hover_entrance(&self) -> ScrollbarEntrance {
368        self.thumb_hover_entrance
369    }
370
371    fn entrance_for(&self, mode: ScrollbarMode, thumb_hovered: bool) -> ScrollbarEntrance {
372        if mode.is_hover() && thumb_hovered {
373            self.thumb_hover_entrance
374        } else {
375            self.entrance
376        }
377    }
378}
379
380#[derive(Debug, Clone, Copy)]
381struct VisibilityAnimation {
382    opacity: ScalarTransition<f32>,
383    position: ScalarTransition<f32>,
384    entrance: ScrollbarEntrance,
385}
386
387#[derive(Debug, Clone, Copy)]
388struct VisibilitySample {
389    opacity: f32,
390    position: f32,
391    running: bool,
392}
393
394impl VisibilityAnimation {
395    fn hidden(now: Instant) -> Self {
396        Self {
397            opacity: ScalarTransition::settled(0.0, now),
398            position: ScalarTransition::settled(0.0, now),
399            entrance: ScrollbarEntrance::Fade,
400        }
401    }
402
403    fn sample(&self, now: Instant) -> VisibilitySample {
404        let entering =
405            self.opacity.target > self.opacity.from || self.position.target > self.position.from;
406        let (opacity, opacity_running) = self.opacity.sample(now, |from, target, linear| {
407            let factor = if entering {
408                linear
409            } else {
410                ease_in_cubic(linear)
411            };
412            from + (target - from) * factor
413        });
414        let (position, position_running) = self.position.sample(now, |from, target, linear| {
415            let factor = if entering {
416                ease_out_cubic(linear)
417            } else {
418                ease_in_cubic(linear)
419            };
420            from + (target - from) * factor
421        });
422
423        VisibilitySample {
424            opacity,
425            position,
426            running: opacity_running || position_running,
427        }
428    }
429
430    /// Reverse or start a transition toward `visible`.
431    ///
432    /// The leg runs for `enter` or `exit` scaled by the distance still to cover,
433    /// so an interrupted transition keeps its speed instead of restarting.
434    fn set_visible(
435        &mut self,
436        visible: bool,
437        entrance: ScrollbarEntrance,
438        enter: Duration,
439        exit: Duration,
440        now: Instant,
441    ) {
442        let target = if visible { 1.0 } else { 0.0 };
443        let full_duration = if visible { enter } else { exit };
444        if full_duration.is_zero() {
445            // A motionless policy — reduced motion, an always-visible scrollbar,
446            // or a theme that projects no motion — adopts the target outright,
447            // even if a transition was in flight when the policy changed.
448            self.opacity.settle(target, now);
449            self.position.settle(target, now);
450            self.entrance = entrance;
451            return;
452        }
453        if self.opacity.target == target
454            && self.position.target == target
455            && self.entrance == entrance
456        {
457            return;
458        }
459
460        let sample = self.sample(now);
461        let from_position = if visible && entrance == ScrollbarEntrance::Fade {
462            1.0
463        } else {
464            sample.position
465        };
466        let distance = (target - sample.opacity)
467            .abs()
468            .max((target - from_position).abs());
469        let duration = full_duration.mul_f32(distance);
470        self.opacity.start(sample.opacity, target, duration, now);
471        self.position.start(from_position, target, duration, now);
472        self.entrance = entrance;
473    }
474}
475
476fn visibility_translation(
477    axis: Axis,
478    placement: ScrollbarPlacement,
479    track_width: Pixels,
480    progress: f32,
481) -> Point<Pixels> {
482    let offset = track_width * (1.0 - progress.clamp(0.0, 1.0));
483    if axis.is_vertical() {
484        if placement.is_left() {
485            point(-offset, px(0.))
486        } else {
487            point(offset, px(0.))
488        }
489    } else if placement.is_top() {
490        point(px(0.), -offset)
491    } else {
492        point(px(0.), offset)
493    }
494}
495
496fn wants_visible(
497    mode: ScrollbarMode,
498    is_hovered: bool,
499    is_dragging: bool,
500    last_scroll_time: Option<Instant>,
501    idle: Duration,
502    now: Instant,
503) -> bool {
504    mode.is_always()
505        || is_dragging
506        || (mode.is_hover() && is_hovered)
507        || last_scroll_time.is_some_and(|last| now.saturating_duration_since(last) < idle)
508}
509
510fn tracks_thumb_hover(mode: ScrollbarMode, is_visible: bool) -> bool {
511    mode.is_hover() || is_visible
512}
513
514fn hover_keeps_visible(mode: ScrollbarMode, is_hovered: bool, is_currently_visible: bool) -> bool {
515    is_hovered && (mode.is_hover() || (mode == ScrollbarMode::Scrolling && is_currently_visible))
516}
517
518impl Deref for ScrollbarState {
519    type Target = Rc<Cell<ScrollbarStateInner>>;
520
521    fn deref(&self) -> &Self::Target {
522        &self.0
523    }
524}
525
526impl ScrollbarState {
527    fn notify_drag(
528        &self,
529        now: Instant,
530        interval: Duration,
531        view: EntityId,
532        window: &mut Window,
533        cx: &mut App,
534    ) {
535        let mut inner = self.get();
536        if inner.drag_update_scheduled {
537            return;
538        }
539        let elapsed = now.saturating_duration_since(inner.last_update);
540        if elapsed >= interval {
541            self.set(inner.with_last_update(now));
542            cx.notify(view);
543            return;
544        }
545        inner.drag_update_scheduled = true;
546        self.set(inner);
547        let generation = inner.drag_update_generation;
548        let delay = interval - elapsed;
549        let state = self.clone();
550        window
551            .spawn(cx, async move |cx| {
552                cx.background_executor().timer(delay).await;
553                let mut inner = state.get();
554                // A release or new drag supersedes the pending trailing update.
555                if !inner.drag_update_scheduled || inner.drag_update_generation != generation {
556                    return;
557                }
558                inner.drag_update_scheduled = false;
559                inner.last_update = Instant::now();
560                state.set(inner);
561                cx.update(|_, cx| cx.notify(view)).ok();
562            })
563            .detach();
564    }
565}
566
567impl ScrollbarStateInner {
568    fn with_drag_pos(&self, axis: Axis, pos: Point<Pixels>) -> Self {
569        let mut state = *self;
570        if axis.is_vertical() {
571            state.drag_pos.y = pos.y;
572        } else {
573            state.drag_pos.x = pos.x;
574        }
575
576        state.dragged_axis = Some(axis);
577        state.last_update = Instant::now();
578        state.drag_update_scheduled = false;
579        state.drag_update_generation = state.drag_update_generation.wrapping_add(1);
580        state
581    }
582
583    fn with_unset_drag_pos(&self, now: Instant) -> Self {
584        let mut state = *self;
585        state.dragged_axis = None;
586        state.drag_update_scheduled = false;
587        state.drag_update_generation = state.drag_update_generation.wrapping_add(1);
588        state.last_scroll_time = Some(now);
589        state
590    }
591
592    fn with_hovered(&self, axis: Option<Axis>, now: Instant) -> Self {
593        let mut state = *self;
594        state.hovered_axis = axis;
595        state.last_scroll_time = Some(now);
596        state
597    }
598
599    fn with_hovered_on_thumb(&self, axis: Option<Axis>) -> Self {
600        let mut state = *self;
601        state.hovered_on_thumb = axis;
602        if self.is_scrollbar_visible() {
603            if axis.is_some() {
604                state.last_scroll_time = Some(Instant::now());
605            }
606        }
607        state
608    }
609
610    fn with_last_scroll(
611        &self,
612        last_scroll_offset: Point<Pixels>,
613        last_scroll_time: Option<Instant>,
614    ) -> Self {
615        let mut state = *self;
616        state.last_scroll_offset = last_scroll_offset;
617        state.last_scroll_time = last_scroll_time;
618        state
619    }
620
621    fn with_last_update(&self, t: Instant) -> Self {
622        let mut state = *self;
623        state.last_update = t;
624        state
625    }
626
627    fn with_idle_timer_scheduled(&self, scheduled: bool) -> Self {
628        let mut state = *self;
629        state.idle_timer_scheduled = scheduled;
630        state
631    }
632
633    fn is_scrollbar_visible(&self) -> bool {
634        self.dragged_axis.is_some() || self.visibility.sample(Instant::now()).opacity > 0.0
635    }
636}
637
638/// Scrollbar axis.
639#[derive(Debug, Clone, Copy, PartialEq, Eq)]
640pub enum ScrollbarAxis {
641    /// Vertical scrollbar.
642    Vertical,
643    /// Horizontal scrollbar.
644    Horizontal,
645    /// Show both vertical and horizontal scrollbars.
646    Both,
647}
648
649/// Where the scrollbars sit in the viewport.
650///
651/// A single-axis scrollbar uses only the part of the placement for its axis.
652#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
653pub enum ScrollbarPlacement {
654    /// Vertical scrollbar on the right, horizontal scrollbar at the bottom.
655    #[default]
656    BottomRight,
657    /// Vertical scrollbar on the left, horizontal scrollbar at the bottom.
658    BottomLeft,
659    /// Vertical scrollbar on the right, horizontal scrollbar at the top.
660    TopRight,
661    /// Vertical scrollbar on the left, horizontal scrollbar at the top.
662    TopLeft,
663}
664
665impl ScrollbarPlacement {
666    /// Return true if the vertical scrollbar is on the left.
667    #[inline]
668    pub fn is_left(&self) -> bool {
669        matches!(self, Self::BottomLeft | Self::TopLeft)
670    }
671
672    /// Return true if the horizontal scrollbar is at the top.
673    #[inline]
674    pub fn is_top(&self) -> bool {
675        matches!(self, Self::TopRight | Self::TopLeft)
676    }
677}
678
679/// Paint-only styles for a scrollbar track.
680#[derive(Clone, Default)]
681pub struct ScrollbarTrackStyle {
682    background: Option<Hsla>,
683    border: Option<Hsla>,
684    width: Option<Pixels>,
685}
686
687impl ScrollbarTrackStyle {
688    pub fn bg(mut self, background: Hsla) -> Self {
689        self.background = Some(background);
690        self
691    }
692
693    pub fn border_color(mut self, border: Hsla) -> Self {
694        self.border = Some(border);
695        self
696    }
697
698    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
699        self.width = Some(width.into());
700        self
701    }
702}
703
704impl FluentBuilder for ScrollbarTrackStyle {}
705
706/// Paint-only styles for a scrollbar thumb.
707#[derive(Clone, Default)]
708pub struct ScrollbarThumbStyle {
709    background: Option<Background>,
710    width: Option<Pixels>,
711    inset: Option<Pixels>,
712    radius: Option<Pixels>,
713    min_length: Option<Pixels>,
714}
715
716impl ScrollbarThumbStyle {
717    pub fn bg(mut self, background: impl Into<Background>) -> Self {
718        self.background = Some(background.into());
719        self
720    }
721
722    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
723        self.width = Some(width.into());
724        self
725    }
726
727    pub fn inset(mut self, inset: impl Into<Pixels>) -> Self {
728        self.inset = Some(inset.into());
729        self
730    }
731
732    pub fn radius(mut self, radius: impl Into<Pixels>) -> Self {
733        self.radius = Some(radius.into());
734        self
735    }
736
737    pub fn min_length(mut self, min_length: impl Into<Pixels>) -> Self {
738        self.min_length = Some(min_length.into());
739        self
740    }
741}
742
743impl FluentBuilder for ScrollbarThumbStyle {}
744
745/// Typed paint styles supported by [`Scrollbar`].
746#[derive(Clone, Default)]
747pub struct ScrollbarStyles {
748    track: ScrollbarTrackStyle,
749    track_hover: ScrollbarTrackStyle,
750    track_active: ScrollbarTrackStyle,
751    thumb: ScrollbarThumbStyle,
752    thumb_hover: ScrollbarThumbStyle,
753    thumb_active: ScrollbarThumbStyle,
754}
755
756impl ScrollbarStyles {
757    pub fn track(mut self, build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle) -> Self {
758        self.track = build(self.track);
759        self
760    }
761
762    pub fn track_hover(
763        mut self,
764        build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle,
765    ) -> Self {
766        self.track_hover = build(self.track_hover);
767        self
768    }
769
770    pub fn track_active(
771        mut self,
772        build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle,
773    ) -> Self {
774        self.track_active = build(self.track_active);
775        self
776    }
777
778    pub fn thumb(mut self, build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle) -> Self {
779        self.thumb = build(self.thumb);
780        self
781    }
782
783    pub fn thumb_hover(
784        mut self,
785        build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle,
786    ) -> Self {
787        self.thumb_hover = build(self.thumb_hover);
788        self
789    }
790
791    pub fn thumb_active(
792        mut self,
793        build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle,
794    ) -> Self {
795        self.thumb_active = build(self.thumb_active);
796        self
797    }
798}
799
800impl FluentBuilder for ScrollbarStyles {}
801
802impl From<Axis> for ScrollbarAxis {
803    fn from(axis: Axis) -> Self {
804        match axis {
805            Axis::Vertical => Self::Vertical,
806            Axis::Horizontal => Self::Horizontal,
807        }
808    }
809}
810
811impl ScrollbarAxis {
812    /// Return true if the scrollbar axis is vertical.
813    #[inline]
814    pub fn is_vertical(&self) -> bool {
815        matches!(self, Self::Vertical)
816    }
817
818    /// Return true if the scrollbar axis is horizontal.
819    #[inline]
820    pub fn is_horizontal(&self) -> bool {
821        matches!(self, Self::Horizontal)
822    }
823
824    /// Return true if the scrollbar axis is both vertical and horizontal.
825    #[inline]
826    pub fn is_both(&self) -> bool {
827        matches!(self, Self::Both)
828    }
829
830    /// Return true if the scrollbar has vertical axis.
831    #[inline]
832    pub fn has_vertical(&self) -> bool {
833        matches!(self, Self::Vertical | Self::Both)
834    }
835
836    /// Return true if the scrollbar has horizontal axis.
837    #[inline]
838    pub fn has_horizontal(&self) -> bool {
839        matches!(self, Self::Horizontal | Self::Both)
840    }
841
842    #[inline]
843    fn all(&self) -> Vec<Axis> {
844        match self {
845            Self::Vertical => vec![Axis::Vertical],
846            Self::Horizontal => vec![Axis::Horizontal],
847            // This should keep Horizontal first, Vertical is the primary axis
848            // if Vertical not need display, then Horizontal will not keep right margin.
849            Self::Both => vec![Axis::Horizontal, Axis::Vertical],
850        }
851    }
852}
853
854/// Scrollbar control for scroll-area or a uniform-list.
855pub struct Scrollbar {
856    pub(crate) id: ElementId,
857    axis: ScrollbarAxis,
858    placement: ScrollbarPlacement,
859    mode: Option<ScrollbarMode>,
860    scroll_handle: Rc<dyn ScrollbarHandle>,
861    scroll_size: Option<Size<Pixels>>,
862    viewport_bounds: Option<Bounds<Pixels>>,
863    // Scroll range may use a smaller viewport than the padded track bounds.
864    scroll_viewport_size: Option<Size<Pixels>>,
865    horizontal_viewport_bounds: Option<Bounds<Pixels>>,
866    use_layout_bounds: bool,
867    /// Maximum frames per second for scrolling by drag. Default is 120 FPS.
868    ///
869    /// This is used to limit the update rate of the scrollbar when it is
870    /// being dragged for some complex interactions for reducing CPU usage.
871    max_fps: usize,
872    styles: ScrollbarStyles,
873}
874
875impl Scrollbar {
876    /// Create a new scrollbar.
877    ///
878    /// This will have both vertical and horizontal scrollbars.
879    #[track_caller]
880    pub fn new<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
881        let caller = Location::caller();
882        Self {
883            id: ElementId::CodeLocation(*caller),
884            axis: ScrollbarAxis::Both,
885            placement: ScrollbarPlacement::default(),
886            mode: None,
887            scroll_handle: Rc::new(scroll_handle.clone()),
888            max_fps: 120,
889            scroll_size: None,
890            viewport_bounds: None,
891            scroll_viewport_size: None,
892            horizontal_viewport_bounds: None,
893            use_layout_bounds: false,
894            styles: ScrollbarStyles::default(),
895        }
896    }
897
898    /// Create with horizontal scrollbar.
899    #[track_caller]
900    pub fn horizontal<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
901        Self::new(scroll_handle).axis(ScrollbarAxis::Horizontal)
902    }
903
904    /// Create with vertical scrollbar.
905    #[track_caller]
906    pub fn vertical<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
907        Self::new(scroll_handle).axis(ScrollbarAxis::Vertical)
908    }
909
910    /// Set a specific element id, default is the [`Location::caller`].
911    ///
912    /// NOTE: In most cases, you don't need to set a specific id for scrollbar.
913    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
914        self.id = id.into();
915        self
916    }
917
918    /// Editors can exclude a fixed gutter from horizontal scrolling while the
919    /// vertical track stays at the outside edge of the full viewport.
920    pub(crate) fn horizontal_viewport_bounds(mut self, bounds: Bounds<Pixels>) -> Self {
921        self.horizontal_viewport_bounds = Some(bounds);
922        self
923    }
924
925    /// Set the scrollbar show mode [`ScrollbarMode`].
926    ///
927    /// If unset, the current application theme projection is used.
928    pub fn mode(mut self, mode: ScrollbarMode) -> Self {
929        self.mode = Some(mode);
930        self
931    }
932
933    /// Set a special scroll size of the content area, default is None.
934    ///
935    /// Default will sync the `content_size` from `scroll_handle`.
936    pub fn scroll_size(mut self, scroll_size: Size<Pixels>) -> Self {
937        self.scroll_size = Some(scroll_size);
938        self
939    }
940
941    /// Override the viewport bounds that this scrollbar overlays.
942    ///
943    /// Most scroll containers should rely on the bounds reported by their
944    /// scroll handle. Custom-painted viewports, such as the text editor, can
945    /// use this when their visible bounds differ from the handle's layout
946    /// bounds.
947    pub fn viewport_bounds(mut self, bounds: Bounds<Pixels>) -> Self {
948        self.viewport_bounds = Some(bounds);
949        self
950    }
951
952    pub(crate) fn scroll_viewport_size(mut self, size: Size<Pixels>) -> Self {
953        self.scroll_viewport_size = Some(size);
954        self
955    }
956
957    /// Use the scrollbar element's layout bounds as its viewport.
958    ///
959    /// This is useful for composite widgets whose scrollbar viewport excludes
960    /// fixed headers or columns and is therefore defined by a positioned
961    /// overlay container rather than by the underlying scroll handle.
962    pub fn viewport_from_layout(mut self) -> Self {
963        self.use_layout_bounds = true;
964        self
965    }
966
967    fn resolved_viewport_bounds(&self, layout_bounds: Bounds<Pixels>) -> Bounds<Pixels> {
968        self.viewport_bounds.unwrap_or_else(|| {
969            if self.use_layout_bounds {
970                layout_bounds
971            } else {
972                self.scroll_handle.viewport_bounds()
973            }
974        })
975    }
976
977    /// Set scrollbar axis.
978    pub fn axis(mut self, axis: impl Into<ScrollbarAxis>) -> Self {
979        self.axis = axis.into();
980        self
981    }
982
983    /// Set the scrollbar placement, default is [`ScrollbarPlacement::BottomRight`].
984    ///
985    /// When both scrollbars are shown, the horizontal track ends before the
986    /// vertical one, on the vertical scrollbar's side.
987    pub fn placement(mut self, placement: ScrollbarPlacement) -> Self {
988        self.placement = placement;
989        self
990    }
991
992    pub fn styles(mut self, build: impl FnOnce(ScrollbarStyles) -> ScrollbarStyles) -> Self {
993        self.styles = build(self.styles);
994        self
995    }
996
997    /// Set maximum frames per second for scrolling by drag. Default is 120 FPS.
998    ///
999    /// If you have very high CPU usage, consider reducing this value to improve performance.
1000    ///
1001    /// Available values: 30..120
1002    #[doc(hidden)]
1003    pub fn max_fps(mut self, max_fps: usize) -> Self {
1004        self.max_fps = max_fps.clamp(30, 120);
1005        self
1006    }
1007
1008    // Get the width of the scrollbar.
1009    #[doc(hidden)]
1010    pub const fn width() -> Pixels {
1011        WIDTH
1012    }
1013
1014    /// The width of a track this theme gives scrollbars without styles of their own.
1015    pub(crate) fn themed_track_width(cx: &App) -> Pixels {
1016        cx.theme().scrollbar.styles().track.width.unwrap_or(WIDTH)
1017    }
1018
1019    fn track_width(&self, cx: &App) -> Pixels {
1020        self.styles
1021            .track
1022            .width
1023            .or(cx.theme().scrollbar.styles().track.width)
1024            .unwrap_or(WIDTH)
1025    }
1026
1027    /// The width the scrollbar takes from the edge it sits on: its track, or
1028    /// its active thumb where that reaches further.
1029    pub(crate) fn full_width(&self, cx: &App) -> Pixels {
1030        let (_, _, _, width, inset, _, _) = self.style_for_active(cx);
1031        self.track_width(cx).max(inset + width)
1032    }
1033
1034    fn resolve_track(
1035        &self,
1036        cx: &App,
1037        state: &ScrollbarTrackStyle,
1038        global_state: &ScrollbarTrackStyle,
1039        default_border: Hsla,
1040    ) -> (Hsla, Hsla) {
1041        let theme = cx.theme();
1042        let global = theme.scrollbar.styles();
1043        (
1044            state
1045                .background
1046                .or(self.styles.track.background)
1047                .or(global_state.background)
1048                .or(global.track.background)
1049                .unwrap_or_else(gpui::transparent_black),
1050            state
1051                .border
1052                .or(self.styles.track.border)
1053                .or(global_state.border)
1054                .or(global.track.border)
1055                .unwrap_or(default_border),
1056        )
1057    }
1058
1059    fn resolve_thumb(
1060        &self,
1061        cx: &App,
1062        state: &ScrollbarThumbStyle,
1063        global_state: &ScrollbarThumbStyle,
1064        defaults: ScrollbarThumbStyle,
1065    ) -> (Background, Pixels, Pixels, Pixels, Pixels) {
1066        let theme = cx.theme();
1067        let global = theme.scrollbar.styles();
1068        (
1069            state
1070                .background
1071                .or(self.styles.thumb.background)
1072                .or(global_state.background)
1073                .or(global.thumb.background)
1074                .unwrap_or_else(|| defaults.background.unwrap()),
1075            state
1076                .width
1077                .or(self.styles.thumb.width)
1078                .or(global_state.width)
1079                .or(global.thumb.width)
1080                .unwrap_or_else(|| defaults.width.unwrap()),
1081            state
1082                .inset
1083                .or(self.styles.thumb.inset)
1084                .or(global_state.inset)
1085                .or(global.thumb.inset)
1086                .unwrap_or_else(|| defaults.inset.unwrap()),
1087            state
1088                .radius
1089                .or(self.styles.thumb.radius)
1090                .or(global_state.radius)
1091                .or(global.thumb.radius)
1092                .unwrap_or_else(|| defaults.radius.unwrap()),
1093            state
1094                .min_length
1095                .or(self.styles.thumb.min_length)
1096                .or(global_state.min_length)
1097                .or(global.thumb.min_length)
1098                .or(defaults.min_length)
1099                .unwrap_or(MIN_THUMB_SIZE),
1100        )
1101    }
1102
1103    /// The thumb colour a scrollbar falls back to when nothing has overridden
1104    /// it, taken from the active theme rather than fixed.
1105    ///
1106    /// It used to be literal black at these alphas. That reads as an ordinary
1107    /// grey thumb on a light surface and as very nearly nothing at all on a
1108    /// dark one, and no palette an application installed could change it:
1109    /// `Theme` carries `scrollbar` beside `tokens` rather than derived from
1110    /// them, so a theme swap moved every token except the ones the scrollbar
1111    /// actually paints with.
1112    ///
1113    /// `foreground` is the token that already means "ink on this surface" and
1114    /// already flips with the appearance, so on a light theme this stays within
1115    /// a hair of the old constant and on a dark one it becomes visible. An
1116    /// explicit `ScrollbarStyles` still wins: this is the bottom of the
1117    /// cascade, not a new top of it.
1118    fn thumb_default_background(cx: &App, alpha: f32) -> Background {
1119        cx.theme().tokens.colors.foreground.alpha(alpha).into()
1120    }
1121
1122    fn thumb_defaults(
1123        background: Background,
1124        width: Pixels,
1125        inset: Pixels,
1126        radius: Pixels,
1127    ) -> ScrollbarThumbStyle {
1128        ScrollbarThumbStyle {
1129            background: Some(background),
1130            width: Some(width),
1131            inset: Some(inset),
1132            radius: Some(radius),
1133            min_length: Some(MIN_THUMB_SIZE),
1134        }
1135    }
1136
1137    fn style_for_active(
1138        &self,
1139        cx: &App,
1140    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1141        let theme = cx.theme();
1142        let global = theme.scrollbar.styles();
1143        let (track, border) = self.resolve_track(
1144            cx,
1145            &self.styles.track_active,
1146            &global.track_active,
1147            gpui::transparent_black(),
1148        );
1149        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1150            cx,
1151            &self.styles.thumb_active,
1152            &global.thumb_active,
1153            Self::thumb_defaults(
1154                Self::thumb_default_background(cx, 0.55),
1155                THUMB_ACTIVE_WIDTH,
1156                THUMB_ACTIVE_INSET,
1157                THUMB_ACTIVE_RADIUS,
1158            ),
1159        );
1160        (thumb, track, border, width, inset, radius, min_length)
1161    }
1162
1163    fn style_for_hovered_thumb(
1164        &self,
1165        cx: &App,
1166    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1167        let theme = cx.theme();
1168        let global = theme.scrollbar.styles();
1169        let (track, border) = self.resolve_track(
1170            cx,
1171            &self.styles.track_active,
1172            &global.track_active,
1173            gpui::transparent_black(),
1174        );
1175        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1176            cx,
1177            &self.styles.thumb_hover,
1178            &global.thumb_hover,
1179            Self::thumb_defaults(
1180                Self::thumb_default_background(cx, 0.55),
1181                THUMB_ACTIVE_WIDTH,
1182                THUMB_ACTIVE_INSET,
1183                THUMB_ACTIVE_RADIUS,
1184            ),
1185        );
1186        (thumb, track, border, width, inset, radius, min_length)
1187    }
1188
1189    fn style_for_hovered_bar(
1190        &self,
1191        cx: &App,
1192    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1193        let theme = cx.theme();
1194        let global = theme.scrollbar.styles();
1195        let (track, border) = self.resolve_track(
1196            cx,
1197            &self.styles.track_hover,
1198            &global.track_hover,
1199            gpui::transparent_black(),
1200        );
1201        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1202            cx,
1203            &self.styles.thumb,
1204            &global.thumb,
1205            Self::thumb_defaults(
1206                Self::thumb_default_background(cx, 0.35),
1207                THUMB_WIDTH,
1208                THUMB_INSET,
1209                THUMB_RADIUS,
1210            ),
1211        );
1212        (thumb, track, border, width, inset, radius, min_length)
1213    }
1214
1215    fn style_for_normal(
1216        &self,
1217        cx: &App,
1218    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1219        let theme = cx.theme();
1220        let global = theme.scrollbar.styles();
1221
1222        let (track, border) = self.resolve_track(
1223            cx,
1224            &self.styles.track,
1225            &global.track,
1226            gpui::transparent_black(),
1227        );
1228        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1229            cx,
1230            &self.styles.thumb,
1231            &global.thumb,
1232            Self::thumb_defaults(
1233                Self::thumb_default_background(cx, 0.35),
1234                THUMB_WIDTH,
1235                THUMB_INSET,
1236                THUMB_RADIUS,
1237            ),
1238        );
1239        (thumb, track, border, width, inset, radius, min_length)
1240    }
1241}
1242
1243#[doc(hidden)]
1244pub struct PrepaintState {
1245    hitbox: Hitbox,
1246    scrollbar_state: ScrollbarState,
1247    states: Vec<AxisPrepaintState>,
1248}
1249
1250#[doc(hidden)]
1251pub struct AxisPrepaintState {
1252    axis: Axis,
1253    bar_hitbox: Hitbox,
1254    bounds: Bounds<Pixels>,
1255    radius: Pixels,
1256    bg: Hsla,
1257    border: Hsla,
1258    thumb_bounds: Bounds<Pixels>,
1259    // Bounds of thumb to be rendered.
1260    thumb_fill_bounds: Bounds<Pixels>,
1261    thumb_bg: Background,
1262    geometry: ThumbGeometry,
1263    active_geometry: ThumbGeometry,
1264    track_width: Pixels,
1265    visibility_opacity: f32,
1266    visibility_position: f32,
1267    visibility_requested: bool,
1268}
1269
1270/// The same longitudinal geometry drives painting, track clicks and dragging.
1271/// `length` excludes the inset, while `travel` excludes the full logical thumb.
1272#[derive(Clone, Copy)]
1273struct ThumbGeometry {
1274    origin: Pixels,
1275    inset: Pixels,
1276    length: Pixels,
1277    travel: Pixels,
1278    extent: Pixels,
1279}
1280
1281impl ThumbGeometry {
1282    fn new(
1283        origin: Pixels,
1284        track_size: Pixels,
1285        viewport_size: Pixels,
1286        content: Pixels,
1287        margin_end: Pixels,
1288        inset: Pixels,
1289        min_length: Pixels,
1290    ) -> Self {
1291        let track = (track_size - margin_end).max(px(0.));
1292        let logical_length = (viewport_size / content * track).max(min_length).min(track);
1293        let inset = inset.clamp(px(0.), logical_length / 2.);
1294        Self {
1295            origin,
1296            inset,
1297            length: logical_length - inset * 2.,
1298            travel: track - logical_length,
1299            extent: content - viewport_size,
1300        }
1301    }
1302
1303    fn start(self, offset: Pixels) -> Pixels {
1304        self.origin + self.inset + (-offset / self.extent).clamp(0., 1.) * self.travel
1305    }
1306
1307    fn offset(self, position: Pixels, grab: Pixels) -> Pixels {
1308        if self.travel <= px(0.) {
1309            return px(0.);
1310        }
1311        -self.extent * ((position - self.origin - self.inset - grab) / self.travel).clamp(0., 1.)
1312    }
1313
1314    fn drag_offset(
1315        self,
1316        axis: Axis,
1317        position: Point<Pixels>,
1318        grab: Point<Pixels>,
1319        mut offset: Point<Pixels>,
1320    ) -> Point<Pixels> {
1321        if self.travel <= px(0.) {
1322            return offset;
1323        }
1324        if axis.is_vertical() {
1325            offset.y = self.offset(position.y, grab.y);
1326        } else {
1327            offset.x = self.offset(position.x, grab.x);
1328        }
1329        offset
1330    }
1331}
1332
1333impl Element for Scrollbar {
1334    type RequestLayoutState = ();
1335    type PrepaintState = PrepaintState;
1336
1337    fn id(&self) -> Option<gpui::ElementId> {
1338        Some(self.id.clone())
1339    }
1340
1341    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1342        None
1343    }
1344
1345    fn request_layout(
1346        &mut self,
1347        _: Option<&GlobalElementId>,
1348        _: Option<&InspectorElementId>,
1349        window: &mut Window,
1350        cx: &mut App,
1351    ) -> (LayoutId, Self::RequestLayoutState) {
1352        let mut style = Style::default();
1353        style.position = Position::Absolute;
1354        style.flex_grow = 1.0;
1355        style.flex_shrink = 1.0;
1356        style.size.width = relative(1.).into();
1357        style.size.height = relative(1.).into();
1358
1359        (window.request_layout(style, None, cx), ())
1360    }
1361
1362    fn prepaint(
1363        &mut self,
1364        _: Option<&GlobalElementId>,
1365        _: Option<&InspectorElementId>,
1366        bounds: Bounds<Pixels>,
1367        _: &mut Self::RequestLayoutState,
1368        window: &mut Window,
1369        cx: &mut App,
1370    ) -> Self::PrepaintState {
1371        let bounds = self.resolved_viewport_bounds(bounds);
1372        let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
1373            window.insert_hitbox(bounds, HitboxBehavior::Normal)
1374        });
1375
1376        let state = window
1377            .use_state(cx, |_, _| ScrollbarState::default())
1378            .read(cx)
1379            .clone();
1380
1381        let now = Instant::now();
1382        let base_theme = cx.theme();
1383        let mode = self.mode.unwrap_or(base_theme.scrollbar.mode());
1384        let motion = base_theme.scrollbar.motion();
1385        // Always-visible scrollbars skip visibility motion but still animate
1386        // their activity width. Reduced motion snaps every channel.
1387        let reduce_motion = cx.reduce_motion();
1388        let (enter, exit) = if !mode.is_always() && !reduce_motion {
1389            (motion.enter(), motion.exit())
1390        } else {
1391            (Duration::ZERO, Duration::ZERO)
1392        };
1393        let expand = if reduce_motion {
1394            Duration::ZERO
1395        } else {
1396            motion.expand()
1397        };
1398
1399        let mut inner = state.get();
1400        let current_offset = self.scroll_handle.offset();
1401        if current_offset != inner.last_scroll_offset {
1402            inner = inner.with_last_scroll(current_offset, Some(now));
1403        }
1404
1405        let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some();
1406        let is_dragging = inner.dragged_axis.is_some();
1407        let is_currently_visible = inner.visibility.sample(now).opacity > 0.0;
1408        let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible)
1409            || wants_visible(
1410                mode,
1411                is_hovered,
1412                is_dragging,
1413                inner.last_scroll_time,
1414                motion.idle(),
1415                now,
1416            );
1417        inner.visibility.set_visible(
1418            visible,
1419            motion.entrance_for(mode, inner.hovered_on_thumb.is_some()),
1420            enter,
1421            exit,
1422            now,
1423        );
1424        let visibility = inner.visibility.sample(now);
1425        if visibility.running {
1426            window.request_animation_frame();
1427        }
1428
1429        if !is_hovered && !is_dragging {
1430            if let Some(last_time) = inner.last_scroll_time {
1431                let elapsed = now.saturating_duration_since(last_time);
1432                if elapsed < motion.idle() && !inner.idle_timer_scheduled {
1433                    inner.idle_timer_scheduled = true;
1434                    let state = state.clone();
1435                    let current_view = window.current_view();
1436                    let next_delay = motion.idle() - elapsed;
1437                    window
1438                        .spawn(cx, async move |cx| {
1439                            cx.background_executor().timer(next_delay).await;
1440                            state.set(state.get().with_idle_timer_scheduled(false));
1441                            cx.update(|_, cx| cx.notify(current_view)).ok();
1442                        })
1443                        .detach();
1444                }
1445            }
1446        }
1447        state.set(inner);
1448
1449        let mut states = vec![];
1450        let mut has_both = self.axis.is_both();
1451        let scroll_size = self
1452            .scroll_size
1453            .unwrap_or(self.scroll_handle.content_size());
1454        let scroll_viewport_size = self.scroll_viewport_size.unwrap_or(hitbox.size);
1455
1456        for axis in self.axis.all().into_iter() {
1457            let is_vertical = axis.is_vertical();
1458            let viewport = if is_vertical {
1459                hitbox.bounds
1460            } else {
1461                self.horizontal_viewport_bounds.unwrap_or(hitbox.bounds)
1462            };
1463            let track_width = self.track_width(cx);
1464            let (scroll_area_size, container_size, scroll_viewport_size, scroll_position) =
1465                if is_vertical {
1466                    (
1467                        scroll_size.height,
1468                        viewport.size.height,
1469                        scroll_viewport_size.height,
1470                        self.scroll_handle.offset().y,
1471                    )
1472                } else {
1473                    let excluded = hitbox.size.width - viewport.size.width;
1474                    (
1475                        scroll_size.width - excluded,
1476                        viewport.size.width,
1477                        scroll_viewport_size.width - excluded,
1478                        self.scroll_handle.offset().x,
1479                    )
1480                };
1481
1482            // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible.
1483            let margin = if has_both && !is_vertical {
1484                track_width
1485            } else {
1486                px(0.)
1487            };
1488
1489            // Hide scrollbar, if the scroll area is smaller than the container.
1490            if scroll_area_size <= scroll_viewport_size {
1491                has_both = false;
1492                continue;
1493            }
1494
1495            let bounds = Bounds {
1496                origin: if is_vertical {
1497                    if self.placement.is_left() {
1498                        viewport.origin
1499                    } else {
1500                        point(
1501                            viewport.origin.x + viewport.size.width - track_width,
1502                            viewport.origin.y,
1503                        )
1504                    }
1505                } else if self.placement.is_top() {
1506                    viewport.origin
1507                } else {
1508                    point(
1509                        viewport.origin.x,
1510                        viewport.origin.y + viewport.size.height - track_width,
1511                    )
1512                },
1513                size: gpui::Size {
1514                    width: if is_vertical {
1515                        track_width
1516                    } else {
1517                        viewport.size.width
1518                    },
1519                    height: if is_vertical {
1520                        viewport.size.height
1521                    } else {
1522                        track_width
1523                    },
1524                },
1525            };
1526
1527            let is_always_to_show = mode.is_always();
1528            let is_hover_to_show = mode.is_hover();
1529            let is_hovered_on_bar = state.get().hovered_axis == Some(axis);
1530            let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis);
1531
1532            let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) =
1533                if state.get().dragged_axis == Some(axis) {
1534                    self.style_for_active(cx)
1535                } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling)
1536                    && (is_hovered_on_bar || is_hovered_on_thumb)
1537                {
1538                    if is_hovered_on_thumb {
1539                        self.style_for_hovered_thumb(cx)
1540                    } else {
1541                        self.style_for_hovered_bar(cx)
1542                    }
1543                } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) {
1544                    if is_hovered_on_thumb {
1545                        self.style_for_hovered_thumb(cx)
1546                    } else {
1547                        self.style_for_hovered_bar(cx)
1548                    }
1549                } else {
1550                    self.style_for_normal(cx)
1551                };
1552
1553            let mut width_animation = if is_vertical {
1554                state.get().vertical_width
1555            } else {
1556                state.get().horizontal_width
1557            };
1558            let (animated_width, running) = width_animation.set_target(thumb_width, expand, now);
1559            let mut updated = state.get();
1560            if is_vertical {
1561                updated.vertical_width = width_animation;
1562            } else {
1563                updated.horizontal_width = width_animation;
1564            }
1565            state.set(updated);
1566            thumb_width = animated_width;
1567            if running {
1568                window.request_animation_frame();
1569            }
1570
1571            let origin = if is_vertical {
1572                bounds.origin.y
1573            } else {
1574                bounds.origin.x
1575            };
1576            let track_origin = if !is_vertical && self.placement.is_left() {
1577                origin + margin
1578            } else {
1579                origin
1580            };
1581            let geometry = ThumbGeometry::new(
1582                track_origin,
1583                container_size,
1584                scroll_viewport_size,
1585                scroll_area_size,
1586                margin,
1587                inset,
1588                min_length,
1589            );
1590            let (_, _, _, _, active_inset, _, active_min_length) = self.style_for_active(cx);
1591            let active_geometry = ThumbGeometry::new(
1592                track_origin,
1593                container_size,
1594                scroll_viewport_size,
1595                scroll_area_size,
1596                margin,
1597                active_inset,
1598                active_min_length,
1599            );
1600            let thumb_start = geometry.start(scroll_position) - origin;
1601
1602            let thumb_length = geometry.length;
1603            let (thumb_anchor, thumb_origin) = if is_vertical {
1604                if self.placement.is_left() {
1605                    (Anchor::TopLeft, bounds.origin + point(inset, thumb_start))
1606                } else {
1607                    (
1608                        Anchor::TopRight,
1609                        bounds.top_right() + point(-inset, thumb_start),
1610                    )
1611                }
1612            } else if self.placement.is_top() {
1613                (Anchor::TopLeft, bounds.origin + point(thumb_start, inset))
1614            } else {
1615                (
1616                    Anchor::BottomLeft,
1617                    bounds.bottom_left() + point(thumb_start, -inset),
1618                )
1619            };
1620            let thumb_size = |width: Pixels| {
1621                if is_vertical {
1622                    size(width, thumb_length)
1623                } else {
1624                    size(thumb_length, width)
1625                }
1626            };
1627
1628            // The clickable area of the thumb
1629            let thumb_bounds =
1630                Bounds::from_anchor_and_size(thumb_anchor, thumb_origin, thumb_size(track_width));
1631
1632            // The actual render area of the thumb
1633            let thumb_fill_bounds =
1634                Bounds::from_anchor_and_size(thumb_anchor, thumb_origin, thumb_size(thumb_width));
1635
1636            let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
1637                window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal)
1638            });
1639
1640            states.push(AxisPrepaintState {
1641                axis,
1642                bar_hitbox,
1643                bounds,
1644                radius,
1645                bg: bar_bg,
1646                border: bar_border,
1647                thumb_bounds,
1648                thumb_fill_bounds,
1649                thumb_bg,
1650                geometry,
1651                active_geometry,
1652                track_width,
1653                visibility_opacity: visibility.opacity,
1654                visibility_position: visibility.position,
1655                visibility_requested: visible,
1656            })
1657        }
1658
1659        PrepaintState {
1660            hitbox,
1661            states,
1662            scrollbar_state: state,
1663        }
1664    }
1665
1666    fn paint(
1667        &mut self,
1668        _: Option<&GlobalElementId>,
1669        _: Option<&InspectorElementId>,
1670        _: Bounds<Pixels>,
1671        _: &mut Self::RequestLayoutState,
1672        prepaint: &mut Self::PrepaintState,
1673        window: &mut Window,
1674        cx: &mut App,
1675    ) {
1676        let scrollbar_state = &prepaint.scrollbar_state;
1677        let theme = cx.theme();
1678        let mode = self.mode.unwrap_or(theme.scrollbar.mode());
1679        let view_id = window.current_view();
1680        let hitbox_bounds = prepaint.hitbox.bounds;
1681        let is_hover_to_show = mode.is_hover();
1682
1683        window.with_content_mask(
1684            Some(ContentMask {
1685                bounds: hitbox_bounds,
1686            }),
1687            |window| {
1688                for state in prepaint.states.iter() {
1689                    let axis = state.axis;
1690                    let mut radius = state.radius;
1691                    if theme.tokens.radius.md.is_zero() {
1692                        radius = px(0.);
1693                    }
1694                    radius = clamp_thumb_radius(radius, state.thumb_fill_bounds);
1695                    let thumb_bounds = state.thumb_bounds;
1696                    let geometry = state.geometry;
1697                    let active_geometry = state.active_geometry;
1698                    let is_vertical = axis.is_vertical();
1699                    let visibility_opacity = state.visibility_opacity;
1700                    let is_visible = state.visibility_requested || visibility_opacity > 0.0;
1701                    let translation = visibility_translation(
1702                        axis,
1703                        self.placement,
1704                        state.track_width,
1705                        state.visibility_position,
1706                    );
1707                    let painted_bounds = state.bounds + translation;
1708                    let painted_thumb_bounds = state.thumb_fill_bounds + translation;
1709                    let painted_track_bg = state.bg.opacity(visibility_opacity);
1710                    let painted_border = state.border.opacity(visibility_opacity);
1711                    let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity);
1712
1713                    window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox);
1714
1715                    let paint = |cx: &mut Window| {
1716                        cx.paint_quad(fill(painted_bounds, painted_track_bg));
1717
1718                        cx.paint_quad(PaintQuad {
1719                            bounds: painted_bounds,
1720                            corner_radii: (0.).into(),
1721                            background: gpui::transparent_black().into(),
1722                            border_widths: if is_vertical {
1723                                Edges {
1724                                    top: px(0.),
1725                                    right: px(0.),
1726                                    bottom: px(0.),
1727                                    left: px(0.),
1728                                }
1729                            } else {
1730                                Edges {
1731                                    top: px(0.),
1732                                    right: px(0.),
1733                                    bottom: px(0.),
1734                                    left: px(0.),
1735                                }
1736                            },
1737                            border_color: painted_border,
1738                            border_style: BorderStyle::default(),
1739                        });
1740
1741                        cx.paint_quad(
1742                            fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius),
1743                        );
1744                    };
1745                    // GPUI Fast keeps the layer bounds to record scroll layers.
1746                    #[cfg(feature = "gpui-fast")]
1747                    window.paint_layer(hitbox_bounds, paint);
1748                    #[cfg(not(feature = "gpui-fast"))]
1749                    window.paint_layer(paint);
1750
1751                    window.on_mouse_event({
1752                        let state = scrollbar_state.clone();
1753                        let scroll_handle = self.scroll_handle.clone();
1754
1755                        move |event: &ScrollEvent, phase, _, cx| {
1756                            if phase.bubble() && hitbox_bounds.contains(&event.position) {
1757                                if scroll_handle.offset() != state.get().last_scroll_offset {
1758                                    state.set(state.get().with_last_scroll(
1759                                        scroll_handle.offset(),
1760                                        Some(Instant::now()),
1761                                    ));
1762                                    cx.notify(view_id);
1763                                }
1764                            }
1765                        }
1766                    });
1767
1768                    // A thumb follows the finger, unlike content panning. Claim
1769                    // this touch before the window turns it into wheel deltas.
1770                    window.on_mouse_event({
1771                        let state = scrollbar_state.clone();
1772                        let scroll_handle = self.scroll_handle.clone();
1773                        let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64);
1774                        move |event: &TouchDragEvent, phase, window, cx| {
1775                            if !phase.bubble() {
1776                                return;
1777                            }
1778                            if event.phase == TouchPhase::Started {
1779                                if !is_visible
1780                                    || window.default_prevented()
1781                                    || !thumb_bounds.contains(&event.start_position)
1782                                {
1783                                    return;
1784                                }
1785                                scroll_handle.start_drag();
1786                                state.set(state.get().with_drag_pos(
1787                                    axis,
1788                                    event.start_position - thumb_bounds.origin,
1789                                ));
1790                            } else if state.get().dragged_axis != Some(axis) {
1791                                return;
1792                            }
1793                            if event.phase != TouchPhase::Cancelled {
1794                                scroll_handle.set_offset(active_geometry.drag_offset(
1795                                    axis,
1796                                    event.position,
1797                                    state.get().drag_pos,
1798                                    scroll_handle.offset(),
1799                                ));
1800                            }
1801                            if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) {
1802                                scroll_handle.end_drag();
1803                                state.set(state.get().with_unset_drag_pos(Instant::now()));
1804                            }
1805                            window.prevent_default();
1806                            cx.stop_propagation();
1807                            if event.phase == TouchPhase::Moved {
1808                                state.notify_drag(
1809                                    Instant::now(),
1810                                    max_fps_duration,
1811                                    view_id,
1812                                    window,
1813                                    cx,
1814                                );
1815                            } else {
1816                                cx.notify(view_id);
1817                            }
1818                        }
1819                    });
1820
1821                    if is_visible {
1822                        window.on_mouse_event({
1823                            // The hitbox rather than the bounds, so that an
1824                            // element above the bar (a menu, a dialog) keeps
1825                            // the press.
1826                            let bar_hitbox = state.bar_hitbox.clone();
1827                            let state = scrollbar_state.clone();
1828                            let scroll_handle = self.scroll_handle.clone();
1829
1830                            move |event: &MouseDownEvent, phase, window, cx| {
1831                                if phase.bubble()
1832                                    && event.button == MouseButton::Left
1833                                    && bar_hitbox.is_hovered(window)
1834                                {
1835                                    cx.stop_propagation();
1836
1837                                    if thumb_bounds.contains(&event.position) {
1838                                        // click on the thumb bar, set the drag position
1839                                        let pos = event.position - thumb_bounds.origin;
1840
1841                                        scroll_handle.start_drag();
1842                                        state.set(state.get().with_drag_pos(axis, pos));
1843                                        // Active styling can change the inset or minimum length.
1844                                        // Keep the original grab point under the pointer on that frame.
1845                                        scroll_handle.set_offset(active_geometry.drag_offset(
1846                                            axis,
1847                                            event.position,
1848                                            pos,
1849                                            scroll_handle.offset(),
1850                                        ));
1851                                    } else {
1852                                        // click on the scrollbar, jump to the position
1853                                        // Set the thumb bar center to the click position
1854                                        let center =
1855                                            point(geometry.length / 2., geometry.length / 2.);
1856                                        scroll_handle.set_offset(geometry.drag_offset(
1857                                            axis,
1858                                            event.position,
1859                                            center,
1860                                            scroll_handle.offset(),
1861                                        ));
1862                                    }
1863
1864                                    cx.notify(view_id);
1865                                }
1866                            }
1867                        });
1868                    }
1869
1870                    window.on_mouse_event({
1871                        let bar_hitbox = state.bar_hitbox.clone();
1872                        let scroll_handle = self.scroll_handle.clone();
1873                        let state = scrollbar_state.clone();
1874                        let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64);
1875
1876                        move |event: &MouseMoveEvent, _, window, cx| {
1877                            let mut notify = false;
1878                            // When is hover to show mode or it was visible,
1879                            // we need to update the hovered state and increase the last_scroll_time.
1880                            let need_hover_to_update = is_hover_to_show || is_visible;
1881                            // Update hovered state for scrollbar
1882                            let bar_hovered = bar_hitbox.is_hovered(window);
1883                            if bar_hovered && need_hover_to_update {
1884                                let hover_changed = state.get().hovered_axis != Some(axis);
1885                                state.set(state.get().with_hovered(Some(axis), Instant::now()));
1886                                notify |= hover_changed;
1887                            } else if state.get().hovered_axis == Some(axis) {
1888                                state.set(state.get().with_hovered(None, Instant::now()));
1889                                notify = true;
1890                            }
1891
1892                            // Update hovered state for scrollbar thumb
1893                            if tracks_thumb_hover(mode, is_visible)
1894                                && bar_hovered
1895                                && thumb_bounds.contains(&event.position)
1896                            {
1897                                if state.get().hovered_on_thumb != Some(axis) {
1898                                    state.set(state.get().with_hovered_on_thumb(Some(axis)));
1899                                    notify = true;
1900                                }
1901                            } else {
1902                                if state.get().hovered_on_thumb == Some(axis) {
1903                                    state.set(state.get().with_hovered_on_thumb(None));
1904                                    notify = true;
1905                                }
1906                            }
1907
1908                            // Move thumb position on dragging
1909                            if state.get().dragged_axis == Some(axis) && event.dragging() {
1910                                // Stop the event propagation to avoid selecting text or other side effects.
1911                                cx.stop_propagation();
1912
1913                                let offset = active_geometry.drag_offset(
1914                                    axis,
1915                                    event.position,
1916                                    state.get().drag_pos,
1917                                    scroll_handle.offset(),
1918                                );
1919                                if scroll_handle.offset() != offset {
1920                                    // Coalesce rendering, never discard the newest pointer position.
1921                                    scroll_handle.set_offset(offset);
1922                                    notify = true;
1923                                }
1924                                if notify {
1925                                    state.notify_drag(
1926                                        Instant::now(),
1927                                        max_fps_duration,
1928                                        view_id,
1929                                        window,
1930                                        cx,
1931                                    );
1932                                }
1933                                return;
1934                            }
1935
1936                            if notify {
1937                                cx.notify(view_id);
1938                            }
1939                        }
1940                    });
1941
1942                    window.on_mouse_event({
1943                        let state = scrollbar_state.clone();
1944                        let scroll_handle = self.scroll_handle.clone();
1945
1946                        move |event: &MouseUpEvent, phase, _, cx| {
1947                            if phase.bubble()
1948                                && event.button == MouseButton::Left
1949                                && state.get().dragged_axis == Some(axis)
1950                            {
1951                                scroll_handle.set_offset(active_geometry.drag_offset(
1952                                    axis,
1953                                    event.position,
1954                                    state.get().drag_pos,
1955                                    scroll_handle.offset(),
1956                                ));
1957                                scroll_handle.end_drag();
1958                                state.set(state.get().with_unset_drag_pos(Instant::now()));
1959                                cx.notify(view_id);
1960                            }
1961                        }
1962                    });
1963                }
1964            },
1965        );
1966    }
1967}
1968
1969#[cfg(test)]
1970mod tests {
1971    use super::*;
1972
1973    use std::cell::{Cell, RefCell};
1974
1975    use gpui::{
1976        Context, InteractiveElement as _, Modifiers, MouseButton, ParentElement as _, Render,
1977        Styled as _, TestAppContext, VisualTestContext, div,
1978    };
1979
1980    #[test]
1981    fn thumb_radius_is_limited_by_its_actual_bounds() {
1982        let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.)));
1983        let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.)));
1984
1985        assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.));
1986        assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.));
1987        assert_eq!(
1988            clamp_thumb_radius(Pixels::ZERO, vertical_thumb),
1989            Pixels::ZERO
1990        );
1991    }
1992
1993    /// Timing standing in for what a styled layer projects. Base itself ships
1994    /// none of these; see [`motionless_base_snaps_every_transition`].
1995    const ENTER: Duration = Duration::from_millis(300);
1996    const EXIT: Duration = Duration::from_millis(500);
1997    const EXPAND: Duration = Duration::from_millis(300);
1998
1999    #[test]
2000    fn visibility_animation_uses_direction_specific_curves_and_durations() {
2001        let start = Instant::now();
2002        let mut animation = VisibilityAnimation::hidden(start);
2003
2004        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2005        assert_eq!(animation.sample(start).opacity, 0.0);
2006        let entering = animation.sample(start + ENTER / 2).position;
2007        assert!(entering > 0.5, "ease-out must advance quickly");
2008        let entered = animation.sample(start + ENTER);
2009        assert_eq!(entered.opacity, 1.0);
2010        assert_eq!(entered.position, 1.0);
2011
2012        animation.set_visible(
2013            false,
2014            ScrollbarEntrance::SlideAndFade,
2015            ENTER,
2016            EXIT,
2017            start + ENTER,
2018        );
2019        let exiting = animation.sample(start + ENTER + EXIT / 2).opacity;
2020        assert!(exiting > 0.5, "ease-in must remain visible early in exit");
2021        assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0);
2022    }
2023
2024    #[test]
2025    fn entrance_fades_linearly_while_position_eases_out() {
2026        let start = Instant::now();
2027        let mut animation = VisibilityAnimation::hidden(start);
2028        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2029
2030        let halfway = animation.sample(start + ENTER / 2);
2031        assert!((halfway.opacity - 0.5).abs() < 0.001);
2032        assert!(halfway.position > halfway.opacity);
2033    }
2034
2035    #[test]
2036    fn fade_entrance_snaps_position_and_animates_opacity() {
2037        let start = Instant::now();
2038        let mut animation = VisibilityAnimation::hidden(start);
2039        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start);
2040
2041        let initial = animation.sample(start);
2042        assert_eq!(initial.opacity, 0.0);
2043        assert_eq!(initial.position, 1.0);
2044        let halfway = animation.sample(start + ENTER / 2);
2045        assert!((halfway.opacity - 0.5).abs() < 0.001);
2046        assert_eq!(halfway.position, 1.0);
2047    }
2048
2049    #[test]
2050    fn active_visibility_adopts_a_changed_entrance_policy() {
2051        let start = Instant::now();
2052        let halfway = start + ENTER / 2;
2053        let mut animation = VisibilityAnimation::hidden(start);
2054        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2055        let before = animation.sample(halfway);
2056
2057        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway);
2058        let after = animation.sample(halfway);
2059
2060        assert_eq!(
2061            after.opacity, before.opacity,
2062            "policy changes must not flash"
2063        );
2064        assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding");
2065    }
2066
2067    #[test]
2068    fn base_ships_no_motion_of_its_own() {
2069        let motion = ScrollbarMotion::default();
2070        assert_eq!(motion.enter(), Duration::ZERO);
2071        assert_eq!(motion.exit(), Duration::ZERO);
2072        assert_eq!(motion.expand(), Duration::ZERO);
2073        assert_eq!(motion.entrance(), ScrollbarEntrance::Fade);
2074        assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade);
2075        assert_eq!(
2076            motion.idle(),
2077            DEFAULT_IDLE,
2078            "the visibility hold is behavior, not motion, and must stay usable"
2079        );
2080    }
2081
2082    #[test]
2083    fn hover_mode_slides_only_when_the_thumb_is_hovered() {
2084        let motion = ScrollbarMotion::default()
2085            .with_entrance(ScrollbarEntrance::Fade)
2086            .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade);
2087
2088        assert_eq!(
2089            motion.entrance_for(ScrollbarMode::Hover, false),
2090            ScrollbarEntrance::Fade
2091        );
2092        assert_eq!(
2093            motion.entrance_for(ScrollbarMode::Hover, true),
2094            ScrollbarEntrance::SlideAndFade
2095        );
2096        assert_eq!(
2097            motion.entrance_for(ScrollbarMode::Scrolling, true),
2098            ScrollbarEntrance::Fade
2099        );
2100    }
2101
2102    #[test]
2103    fn hidden_scrolling_mode_does_not_track_thumb_hover() {
2104        assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false));
2105        assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true));
2106        assert!(tracks_thumb_hover(ScrollbarMode::Hover, false));
2107    }
2108
2109    #[test]
2110    fn visible_scrolling_mode_stays_visible_while_hovered() {
2111        assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false));
2112        assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true));
2113        assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false));
2114    }
2115
2116    #[test]
2117    fn motionless_base_snaps_every_transition() {
2118        let now = Instant::now();
2119        let motion = ScrollbarMotion::default();
2120        let mut visibility = VisibilityAnimation::hidden(now);
2121
2122        visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now);
2123        let shown = visibility.sample(now);
2124        assert_eq!(shown.opacity, 1.0);
2125        assert_eq!(shown.position, 1.0);
2126        assert!(!shown.running, "a motionless theme must request no frames");
2127        assert_eq!(
2128            visibility_translation(
2129                Axis::Vertical,
2130                ScrollbarPlacement::BottomRight,
2131                px(16.),
2132                shown.position
2133            ),
2134            Point::default()
2135        );
2136
2137        visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now);
2138        let hidden = visibility.sample(now);
2139        assert_eq!(hidden.opacity, 0.0);
2140        assert_eq!(hidden.position, 0.0);
2141        assert!(!hidden.running);
2142
2143        let mut width = WidthAnimation::new(now);
2144        assert_eq!(
2145            width.set_target(px(8.), motion.expand(), now),
2146            (px(8.), false)
2147        );
2148    }
2149
2150    #[test]
2151    fn a_zero_duration_settles_a_transition_already_in_flight() {
2152        let start = Instant::now();
2153        let mut animation = VisibilityAnimation::hidden(start);
2154        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2155
2156        // Reduced motion turns on midway through the entrance.
2157        let midway = start + ENTER / 2;
2158        animation.set_visible(
2159            true,
2160            ScrollbarEntrance::SlideAndFade,
2161            Duration::ZERO,
2162            Duration::ZERO,
2163            midway,
2164        );
2165        let settled = animation.sample(midway);
2166        assert_eq!(settled.opacity, 1.0);
2167        assert_eq!(settled.position, 1.0);
2168        assert!(!settled.running);
2169    }
2170
2171    #[test]
2172    fn thumb_expansion_animates_in_both_directions() {
2173        let start = Instant::now();
2174        let mut animation = WidthAnimation::new(start);
2175        assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false));
2176
2177        let (initial, running) = animation.set_target(px(8.), EXPAND, start);
2178        assert_eq!(initial, px(6.));
2179        assert!(running);
2180        let (expanded_halfway, _) = animation.sample(start + EXPAND / 2);
2181        assert!(expanded_halfway > px(7.));
2182
2183        let reversal = start + EXPAND / 2;
2184        let before = animation.sample(reversal).0;
2185        let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal);
2186        assert_eq!(after_reversal, before);
2187        assert!(running);
2188        assert_eq!(animation.sample(reversal + EXPAND).0, px(6.));
2189    }
2190
2191    #[test]
2192    fn reduced_motion_snaps_thumb_expansion() {
2193        let now = Instant::now();
2194        let mut animation = WidthAnimation::new(now);
2195        assert_eq!(
2196            animation.set_target(px(8.), Duration::ZERO, now),
2197            (px(8.), false)
2198        );
2199    }
2200
2201    #[test]
2202    fn visibility_translation_moves_toward_the_nearest_edge() {
2203        for (placement, vertical, horizontal) in [
2204            (ScrollbarPlacement::BottomRight, px(16.), px(16.)),
2205            (ScrollbarPlacement::BottomLeft, px(-16.), px(16.)),
2206            (ScrollbarPlacement::TopRight, px(16.), px(-16.)),
2207            (ScrollbarPlacement::TopLeft, px(-16.), px(-16.)),
2208        ] {
2209            assert_eq!(
2210                visibility_translation(Axis::Vertical, placement, px(16.), 0.0),
2211                point(vertical, px(0.))
2212            );
2213            assert_eq!(
2214                visibility_translation(Axis::Horizontal, placement, px(16.), 0.0),
2215                point(px(0.), horizontal)
2216            );
2217            assert_eq!(
2218                visibility_translation(Axis::Vertical, placement, px(16.), 1.0),
2219                Point::default()
2220            );
2221            assert_eq!(
2222                visibility_translation(Axis::Horizontal, placement, px(16.), 1.0),
2223                Point::default()
2224            );
2225        }
2226    }
2227
2228    #[test]
2229    fn visibility_animation_reverses_from_current_progress() {
2230        let start = Instant::now();
2231        let mut animation = VisibilityAnimation::hidden(start);
2232        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2233        let reversal_time = start + Duration::from_millis(60);
2234        let before = animation.sample(reversal_time);
2235
2236        animation.set_visible(
2237            false,
2238            ScrollbarEntrance::SlideAndFade,
2239            ENTER,
2240            EXIT,
2241            reversal_time,
2242        );
2243        let reversed = animation.sample(reversal_time);
2244        assert_eq!(reversed.opacity, before.opacity);
2245        assert_eq!(reversed.position, before.position);
2246        let after = animation.sample(reversal_time + Duration::from_millis(10));
2247        assert!(after.opacity < before.opacity);
2248        assert!(after.position < before.position);
2249    }
2250
2251    #[test]
2252    fn always_hover_drag_and_recent_scroll_request_visibility() {
2253        let now = Instant::now();
2254        let idle = DEFAULT_IDLE;
2255        assert!(wants_visible(
2256            ScrollbarMode::Always,
2257            false,
2258            false,
2259            None,
2260            idle,
2261            now
2262        ));
2263        assert!(wants_visible(
2264            ScrollbarMode::Hover,
2265            true,
2266            false,
2267            None,
2268            idle,
2269            now
2270        ));
2271        assert!(wants_visible(
2272            ScrollbarMode::Scrolling,
2273            false,
2274            true,
2275            None,
2276            idle,
2277            now
2278        ));
2279        assert!(wants_visible(
2280            ScrollbarMode::Scrolling,
2281            false,
2282            false,
2283            Some(now - idle + Duration::from_millis(1)),
2284            idle,
2285            now,
2286        ));
2287        assert!(!wants_visible(
2288            ScrollbarMode::Scrolling,
2289            false,
2290            false,
2291            Some(now - idle),
2292            idle,
2293            now,
2294        ));
2295
2296        let mut settled = VisibilityAnimation::hidden(now - ENTER);
2297        settled.set_visible(
2298            true,
2299            ScrollbarEntrance::SlideAndFade,
2300            ENTER,
2301            EXIT,
2302            now - ENTER,
2303        );
2304        assert!(!settled.sample(now).running, "idle hold must not animate");
2305    }
2306
2307    #[test]
2308    fn leaving_hover_starts_a_fresh_idle_hold() {
2309        let entered_at = Instant::now();
2310        let left_at = entered_at + Duration::from_secs(5);
2311        let state = ScrollbarState::default().get();
2312
2313        let hovered = state.with_hovered(Some(Axis::Vertical), entered_at);
2314        assert_eq!(hovered.last_scroll_time, Some(entered_at));
2315        let left = hovered.with_hovered(None, left_at);
2316        assert_eq!(left.last_scroll_time, Some(left_at));
2317        assert!(wants_visible(
2318            ScrollbarMode::Hover,
2319            false,
2320            false,
2321            left.last_scroll_time,
2322            DEFAULT_IDLE,
2323            left_at + DEFAULT_IDLE - Duration::from_millis(1),
2324        ));
2325    }
2326
2327    #[test]
2328    fn idle_boundary_starts_the_exit_without_a_jump() {
2329        let activity = Instant::now();
2330        let exit_start = activity + DEFAULT_IDLE;
2331        let mut animation = VisibilityAnimation::hidden(activity - ENTER);
2332        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER);
2333        assert!(!wants_visible(
2334            ScrollbarMode::Scrolling,
2335            false,
2336            false,
2337            Some(activity),
2338            DEFAULT_IDLE,
2339            exit_start,
2340        ));
2341
2342        animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start);
2343        let start = animation.sample(exit_start);
2344        assert_eq!(start.opacity, 1.0);
2345        assert_eq!(start.position, 1.0);
2346        assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0);
2347    }
2348
2349    #[derive(Clone)]
2350    struct TestHandle {
2351        offset: Rc<Cell<Point<Pixels>>>,
2352        content_size: Size<Pixels>,
2353        drag_starts: Rc<Cell<usize>>,
2354        drag_ends: Rc<Cell<usize>>,
2355    }
2356
2357    impl TestHandle {
2358        fn new(content_size: Size<Pixels>) -> Self {
2359            Self {
2360                offset: Rc::new(Cell::new(Point::default())),
2361                content_size,
2362                drag_starts: Rc::new(Cell::new(0)),
2363                drag_ends: Rc::new(Cell::new(0)),
2364            }
2365        }
2366    }
2367
2368    impl ScrollbarHandle for TestHandle {
2369        fn viewport_bounds(&self) -> Bounds<Pixels> {
2370            Bounds::new(Point::default(), size(px(100.), px(100.)))
2371        }
2372
2373        fn offset(&self) -> Point<Pixels> {
2374            self.offset.get()
2375        }
2376
2377        fn set_offset(&self, offset: Point<Pixels>) {
2378            self.offset.set(offset);
2379        }
2380
2381        fn content_size(&self) -> Size<Pixels> {
2382            self.content_size
2383        }
2384
2385        fn start_drag(&self) {
2386            self.drag_starts.set(self.drag_starts.get() + 1);
2387        }
2388
2389        fn end_drag(&self) {
2390            self.drag_ends.set(self.drag_ends.get() + 1);
2391        }
2392    }
2393
2394    struct ScrollbarHarness {
2395        handle: TestHandle,
2396        axis: ScrollbarAxis,
2397        placement: ScrollbarPlacement,
2398        mode: ScrollbarMode,
2399        scroll_viewport_size: Option<Size<Pixels>>,
2400    }
2401
2402    impl Render for ScrollbarHarness {
2403        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
2404            let mut scrollbar = Scrollbar::new(&self.handle)
2405                .axis(self.axis)
2406                .placement(self.placement)
2407                .mode(self.mode);
2408            if let Some(size) = self.scroll_viewport_size {
2409                scrollbar = scrollbar.scroll_viewport_size(size);
2410            }
2411
2412            div().relative().size(px(100.)).child(scrollbar)
2413        }
2414    }
2415
2416    fn harness(
2417        cx: &mut TestAppContext,
2418        axis: ScrollbarAxis,
2419        mode: ScrollbarMode,
2420        content_size: Size<Pixels>,
2421    ) -> (&mut VisualTestContext, TestHandle) {
2422        harness_with_placement(cx, axis, ScrollbarPlacement::default(), mode, content_size)
2423    }
2424
2425    fn harness_with_placement(
2426        cx: &mut TestAppContext,
2427        axis: ScrollbarAxis,
2428        placement: ScrollbarPlacement,
2429        mode: ScrollbarMode,
2430        content_size: Size<Pixels>,
2431    ) -> (&mut VisualTestContext, TestHandle) {
2432        let handle = TestHandle::new(content_size);
2433        let (_, cx) = cx.add_window_view({
2434            let handle = handle.clone();
2435            move |_, _| ScrollbarHarness {
2436                handle,
2437                axis,
2438                placement,
2439                mode,
2440                scroll_viewport_size: None,
2441            }
2442        });
2443        cx.update(|window, cx| window.draw(cx).clear(cx));
2444        (cx, handle)
2445    }
2446
2447    #[gpui::test]
2448    fn thumb_drag_reaches_content_end_when_track_includes_padding(cx: &mut TestAppContext) {
2449        let handle = TestHandle::new(size(px(100.), px(160.)));
2450        let (_, cx) = cx.add_window_view({
2451            let handle = handle.clone();
2452            move |_, _| ScrollbarHarness {
2453                handle,
2454                axis: ScrollbarAxis::Vertical,
2455                placement: ScrollbarPlacement::default(),
2456                mode: ScrollbarMode::Always,
2457                scroll_viewport_size: Some(size(px(100.), px(80.))),
2458            }
2459        });
2460        cx.update(|window, cx| window.draw(cx).clear(cx));
2461
2462        cx.simulate_mouse_down(
2463            point(px(95.), px(20.)),
2464            MouseButton::Left,
2465            Modifiers::default(),
2466        );
2467        cx.update(|window, cx| window.draw(cx).clear(cx));
2468        cx.simulate_mouse_move(
2469            point(px(95.), px(99.)),
2470            Some(MouseButton::Left),
2471            Modifiers::default(),
2472        );
2473        cx.update(|window, cx| window.draw(cx).clear(cx));
2474        cx.simulate_mouse_up(
2475            point(px(95.), px(99.)),
2476            MouseButton::Left,
2477            Modifiers::default(),
2478        );
2479
2480        assert_eq!(handle.offset().y, px(-80.));
2481    }
2482
2483    #[test]
2484    fn explicit_viewport_bounds_override_handle_bounds() {
2485        let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.)));
2486        let scrollbar = Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.))))
2487            .viewport_bounds(expected);
2488
2489        assert_eq!(
2490            scrollbar.resolved_viewport_bounds(Bounds::default()),
2491            expected
2492        );
2493    }
2494
2495    #[test]
2496    fn layout_viewport_uses_current_element_bounds() {
2497        let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.)));
2498        let scrollbar =
2499            Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout();
2500
2501        assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected);
2502    }
2503
2504    #[test]
2505    fn typed_styles_are_fluent_and_include_geometry() {
2506        let track = gpui::hsla(0.1, 0.2, 0.3, 1.0);
2507        let border = gpui::hsla(0.2, 0.3, 0.4, 1.0);
2508        let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0);
2509        let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0);
2510        let active = gpui::hsla(0.5, 0.6, 0.7, 1.0);
2511        let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())).styles(|styles| {
2512            styles
2513                .track(|style| {
2514                    style
2515                        .width(px(14.))
2516                        .bg(track)
2517                        .border_color(border)
2518                        .when(false, |style| style.width(px(99.)))
2519                })
2520                .thumb(|style| {
2521                    style
2522                        .width(px(7.))
2523                        .inset(px(3.))
2524                        .radius(px(3.5))
2525                        .min_length(px(40.))
2526                        .bg(thumb)
2527                })
2528                .thumb_hover(|style| style.width(px(9.)).bg(hover))
2529                .thumb_active(|style| style.radius(px(4.5)).bg(active))
2530        });
2531
2532        assert_eq!(scrollbar.styles.track.background, Some(track));
2533        assert_eq!(scrollbar.styles.track.border, Some(border));
2534        assert_eq!(scrollbar.styles.track.width, Some(px(14.)));
2535        assert!(scrollbar.styles.thumb.background.is_some());
2536        assert_eq!(scrollbar.styles.thumb.width, Some(px(7.)));
2537        assert_eq!(scrollbar.styles.thumb.inset, Some(px(3.)));
2538        assert_eq!(scrollbar.styles.thumb.radius, Some(px(3.5)));
2539        assert_eq!(scrollbar.styles.thumb.min_length, Some(px(40.)));
2540        assert!(scrollbar.styles.thumb_hover.background.is_some());
2541        assert_eq!(scrollbar.styles.thumb_hover.width, Some(px(9.)));
2542        assert!(scrollbar.styles.thumb_active.background.is_some());
2543        assert_eq!(scrollbar.styles.thumb_active.radius, Some(px(4.5)));
2544    }
2545
2546    #[gpui::test]
2547    fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) {
2548        cx.update(|cx| {
2549            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()));
2550
2551            let light = gpui::hsla(0., 0., 0.04, 1.0);
2552            crate::Theme::global_mut(cx).tokens.colors.foreground = light;
2553            let (on_light, ..) = scrollbar.style_for_normal(cx);
2554
2555            let dark = gpui::hsla(0., 0., 0.98, 1.0);
2556            crate::Theme::global_mut(cx).tokens.colors.foreground = dark;
2557            let (on_dark, ..) = scrollbar.style_for_normal(cx);
2558
2559            assert_eq!(on_light, Background::from(light.alpha(0.35)));
2560            assert_eq!(on_dark, Background::from(dark.alpha(0.35)));
2561            // The point of the change: a thumb that never moved with the
2562            // palette was invisible on one of the two surfaces.
2563            assert_ne!(on_light, on_dark);
2564        });
2565    }
2566
2567    #[gpui::test]
2568    fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) {
2569        cx.update(|cx| {
2570            let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0);
2571            crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0);
2572
2573            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()))
2574                .styles(|styles| styles.thumb(|style| style.bg(chosen)));
2575            let (thumb, ..) = scrollbar.style_for_normal(cx);
2576
2577            assert_eq!(thumb, Background::from(chosen));
2578        });
2579    }
2580
2581    #[gpui::test]
2582    fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) {
2583        cx.update(|cx| {
2584            let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0);
2585            let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0);
2586            let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0);
2587
2588            crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new()
2589                .with_mode(ScrollbarMode::Always)
2590                .with_motion(ScrollbarMotion::default())
2591                .with_styles(
2592                    ScrollbarStyles::default()
2593                        .track(|style| style.width(px(13.)).bg(theme_track))
2594                        .thumb(|style| style.width(px(7.)).bg(theme_thumb)),
2595                );
2596
2597            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()))
2598                .styles(|styles| styles.thumb(|style| style.bg(instance_thumb)));
2599            let (thumb, track, _, width, _, _, _) = scrollbar.style_for_normal(cx);
2600
2601            assert_eq!(thumb, Background::from(instance_thumb));
2602            assert_eq!(track, theme_track);
2603            assert_eq!(width, px(7.));
2604            assert_eq!(cx.theme().scrollbar.styles().track.width, Some(px(13.)));
2605        });
2606    }
2607
2608    #[gpui::test]
2609    fn the_full_width_is_the_track_or_an_active_thumb_reaching_further(cx: &mut TestAppContext) {
2610        cx.update(|cx| {
2611            let scrollbar = Scrollbar::vertical(&TestHandle::new(Size::default()));
2612            assert_eq!(scrollbar.full_width(cx), Scrollbar::width());
2613
2614            crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new()
2615                .with_styles(ScrollbarStyles::default().track(|style| style.width(px(24.))));
2616            assert_eq!(scrollbar.full_width(cx), px(24.));
2617
2618            crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new().with_styles(
2619                ScrollbarStyles::default().thumb_active(|style| style.width(px(20.)).inset(px(4.))),
2620            );
2621            assert_eq!(scrollbar.full_width(cx), px(24.));
2622        });
2623    }
2624
2625    #[gpui::test]
2626    fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) {
2627        cx.update(|cx| {
2628            let handle = TestHandle::new(Size::default());
2629            let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling);
2630            let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always);
2631
2632            assert_eq!(scrolling.style_for_normal(cx).3, px(6.));
2633            assert_eq!(always.style_for_normal(cx).3, px(6.));
2634        });
2635    }
2636
2637    #[gpui::test]
2638    fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) {
2639        cx.update(|cx| {
2640            let handle = TestHandle::new(Size::default());
2641            for mode in [
2642                ScrollbarMode::Scrolling,
2643                ScrollbarMode::Hover,
2644                ScrollbarMode::Always,
2645            ] {
2646                let scrollbar = Scrollbar::new(&handle).mode(mode);
2647                assert_eq!(scrollbar.style_for_normal(cx).3, px(6.));
2648                assert_eq!(scrollbar.style_for_hovered_bar(cx).3, px(6.));
2649                assert_eq!(scrollbar.style_for_hovered_thumb(cx).3, px(8.));
2650            }
2651        });
2652    }
2653
2654    #[gpui::test]
2655    fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) {
2656        let (cx, vertical) = harness(
2657            cx,
2658            ScrollbarAxis::Vertical,
2659            ScrollbarMode::Always,
2660            size(px(100.), px(500.)),
2661        );
2662        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2663        assert!(vertical.offset().y < px(0.));
2664        assert_eq!(vertical.offset().x, px(0.));
2665    }
2666
2667    #[gpui::test]
2668    fn horizontal_viewport_excludes_fixed_content_without_changing_scroll_extent(
2669        cx: &mut TestAppContext,
2670    ) {
2671        struct FixedGutterHarness(TestHandle);
2672        impl Render for FixedGutterHarness {
2673            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
2674                div().relative().size(px(100.)).child(
2675                    Scrollbar::new(&self.0)
2676                        .mode(ScrollbarMode::Always)
2677                        .placement(ScrollbarPlacement::BottomLeft)
2678                        .horizontal_viewport_bounds(Bounds::new(
2679                            Point::default(),
2680                            size(px(70.), px(100.)),
2681                        )),
2682                )
2683            }
2684        }
2685        let handle = TestHandle::new(size(px(500.), px(500.)));
2686        let (_, cx) = cx.add_window_view(|_, _| FixedGutterHarness(handle.clone()));
2687        cx.update(|window, cx| window.draw(cx).clear(cx));
2688        cx.simulate_click(point(px(90.), px(95.)), Modifiers::default());
2689        assert_eq!(
2690            handle.offset(),
2691            Point::default(),
2692            "fixed gutter must not be a horizontal track"
2693        );
2694        cx.simulate_click(point(px(69.), px(95.)), Modifiers::default());
2695        assert_eq!(
2696            handle.offset(),
2697            point(px(-400.), px(0.)),
2698            "cropping the track must preserve the horizontal range"
2699        );
2700        cx.simulate_click(point(px(5.), px(80.)), Modifiers::default());
2701        assert_eq!(
2702            handle.offset(),
2703            point(px(-400.), px(-400.)),
2704            "vertical range must use the full viewport"
2705        );
2706    }
2707
2708    #[gpui::test]
2709    fn left_placement_puts_the_vertical_track_and_thumb_on_the_left_edge(cx: &mut TestAppContext) {
2710        let (cx, handle) = harness_with_placement(
2711            cx,
2712            ScrollbarAxis::Vertical,
2713            ScrollbarPlacement::BottomLeft,
2714            ScrollbarMode::Always,
2715            size(px(100.), px(500.)),
2716        );
2717        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2718        assert_eq!(handle.offset(), Point::default());
2719
2720        cx.simulate_mouse_down(
2721            point(px(14.), px(20.)),
2722            MouseButton::Left,
2723            Modifiers::default(),
2724        );
2725        assert_eq!(handle.drag_starts.get(), 1);
2726        assert_eq!(handle.offset(), Point::default());
2727        cx.simulate_mouse_move(
2728            point(px(14.), px(46.)),
2729            Some(MouseButton::Left),
2730            Modifiers::default(),
2731        );
2732        cx.simulate_mouse_up(
2733            point(px(14.), px(46.)),
2734            MouseButton::Left,
2735            Modifiers::default(),
2736        );
2737        assert_eq!(handle.offset(), point(px(0.), px(-200.)));
2738
2739        cx.simulate_click(point(px(5.), px(80.)), Modifiers::default());
2740        assert_eq!(handle.offset(), point(px(0.), px(-400.)));
2741    }
2742
2743    #[gpui::test]
2744    fn left_placement_starts_the_horizontal_track_after_the_vertical_one(cx: &mut TestAppContext) {
2745        let (cx, handle) = harness_with_placement(
2746            cx,
2747            ScrollbarAxis::Both,
2748            ScrollbarPlacement::BottomLeft,
2749            ScrollbarMode::Always,
2750            size(px(500.), px(500.)),
2751        );
2752        cx.simulate_click(point(px(50.), px(95.)), Modifiers::default());
2753        assert_eq!(handle.drag_starts.get(), 1);
2754        assert_eq!(handle.offset(), Point::default());
2755
2756        cx.simulate_click(point(px(99.), px(95.)), Modifiers::default());
2757        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2758    }
2759
2760    #[gpui::test]
2761    fn top_placement_puts_the_horizontal_track_and_thumb_on_the_top_edge(cx: &mut TestAppContext) {
2762        let (cx, handle) = harness_with_placement(
2763            cx,
2764            ScrollbarAxis::Horizontal,
2765            ScrollbarPlacement::TopRight,
2766            ScrollbarMode::Always,
2767            size(px(500.), px(100.)),
2768        );
2769        cx.simulate_click(point(px(80.), px(95.)), Modifiers::default());
2770        assert_eq!(handle.offset(), Point::default());
2771
2772        cx.simulate_mouse_down(
2773            point(px(20.), px(14.)),
2774            MouseButton::Left,
2775            Modifiers::default(),
2776        );
2777        assert_eq!(handle.drag_starts.get(), 1);
2778        assert_eq!(handle.offset(), Point::default());
2779        cx.simulate_mouse_move(
2780            point(px(46.), px(14.)),
2781            Some(MouseButton::Left),
2782            Modifiers::default(),
2783        );
2784        cx.simulate_mouse_up(
2785            point(px(46.), px(14.)),
2786            MouseButton::Left,
2787            Modifiers::default(),
2788        );
2789        assert_eq!(handle.offset(), point(px(-200.), px(0.)));
2790
2791        cx.simulate_click(point(px(90.), px(5.)), Modifiers::default());
2792        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2793    }
2794
2795    #[gpui::test]
2796    fn top_right_placement_ends_the_horizontal_track_before_the_vertical_one(
2797        cx: &mut TestAppContext,
2798    ) {
2799        let (cx, handle) = harness_with_placement(
2800            cx,
2801            ScrollbarAxis::Both,
2802            ScrollbarPlacement::TopRight,
2803            ScrollbarMode::Always,
2804            size(px(500.), px(500.)),
2805        );
2806        cx.simulate_click(point(px(60.), px(5.)), Modifiers::default());
2807        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2808
2809        cx.simulate_click(point(px(95.), px(90.)), Modifiers::default());
2810        assert_eq!(handle.offset(), point(px(-400.), px(-400.)));
2811        cx.simulate_click(point(px(95.), px(5.)), Modifiers::default());
2812        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2813    }
2814
2815    #[gpui::test]
2816    fn top_left_placement_starts_the_horizontal_track_after_the_vertical_one(
2817        cx: &mut TestAppContext,
2818    ) {
2819        let (cx, handle) = harness_with_placement(
2820            cx,
2821            ScrollbarAxis::Both,
2822            ScrollbarPlacement::TopLeft,
2823            ScrollbarMode::Always,
2824            size(px(500.), px(500.)),
2825        );
2826        cx.simulate_click(point(px(50.), px(5.)), Modifiers::default());
2827        assert_eq!(handle.drag_starts.get(), 1);
2828        assert_eq!(handle.offset(), Point::default());
2829
2830        cx.simulate_click(point(px(99.), px(5.)), Modifiers::default());
2831        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2832
2833        cx.simulate_click(point(px(5.), px(95.)), Modifiers::default());
2834        assert_eq!(handle.offset(), point(px(-400.), px(-400.)));
2835    }
2836
2837    #[gpui::test]
2838    fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) {
2839        let (cx, horizontal) = harness(
2840            cx,
2841            ScrollbarAxis::Horizontal,
2842            ScrollbarMode::Always,
2843            size(px(500.), px(100.)),
2844        );
2845        cx.simulate_click(point(px(80.), px(95.)), Modifiers::default());
2846        assert!(horizontal.offset().x < px(0.));
2847        assert_eq!(horizontal.offset().y, px(0.));
2848    }
2849
2850    #[gpui::test]
2851    fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) {
2852        let (cx, handle) = harness(
2853            cx,
2854            ScrollbarAxis::Both,
2855            ScrollbarMode::Always,
2856            size(px(100.), px(100.)),
2857        );
2858        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2859        assert_eq!(handle.offset(), Point::default());
2860    }
2861
2862    #[gpui::test]
2863    fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) {
2864        let (cx, handle) = harness(
2865            cx,
2866            ScrollbarAxis::Vertical,
2867            ScrollbarMode::Hover,
2868            size(px(100.), px(500.)),
2869        );
2870        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2871        assert_eq!(handle.offset(), Point::default());
2872    }
2873
2874    #[gpui::test]
2875    fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) {
2876        let (cx, handle) = harness(
2877            cx,
2878            ScrollbarAxis::Vertical,
2879            ScrollbarMode::Hover,
2880            size(px(100.), px(500.)),
2881        );
2882        cx.simulate_mouse_down(
2883            point(px(95.), px(20.)),
2884            MouseButton::Left,
2885            Modifiers::default(),
2886        );
2887        cx.simulate_mouse_move(
2888            point(px(95.), px(70.)),
2889            Some(MouseButton::Left),
2890            Modifiers::default(),
2891        );
2892        cx.simulate_mouse_up(
2893            point(px(95.), px(70.)),
2894            MouseButton::Left,
2895            Modifiers::default(),
2896        );
2897
2898        assert_eq!(handle.drag_starts.get(), 0);
2899        assert_eq!(handle.drag_ends.get(), 0);
2900        assert_eq!(handle.offset(), Point::default());
2901    }
2902
2903    /// A vertical scrollbar with an occluding element over part of it, as a
2904    /// menu or dialog would be.
2905    struct CoveredHarness {
2906        handle: TestHandle,
2907        mode: ScrollbarMode,
2908        cover: Bounds<Pixels>,
2909    }
2910
2911    impl Render for CoveredHarness {
2912        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
2913            div()
2914                .relative()
2915                .size(px(100.))
2916                .child(
2917                    Scrollbar::new(&self.handle)
2918                        .axis(ScrollbarAxis::Vertical)
2919                        .mode(self.mode),
2920                )
2921                .child(
2922                    div()
2923                        .absolute()
2924                        .left(self.cover.left())
2925                        .top(self.cover.top())
2926                        .w(self.cover.size.width)
2927                        .h(self.cover.size.height)
2928                        .occlude(),
2929                )
2930        }
2931    }
2932
2933    fn covered_harness(
2934        cx: &mut TestAppContext,
2935        mode: ScrollbarMode,
2936        cover: Bounds<Pixels>,
2937    ) -> (&mut VisualTestContext, TestHandle) {
2938        let handle = TestHandle::new(size(px(100.), px(500.)));
2939        let (_, cx) = cx.add_window_view({
2940            let handle = handle.clone();
2941            move |_, _| CoveredHarness {
2942                handle,
2943                mode,
2944                cover,
2945            }
2946        });
2947        cx.update(|window, cx| window.draw(cx).clear(cx));
2948        (cx, handle)
2949    }
2950
2951    #[gpui::test]
2952    fn a_press_on_an_element_over_the_track_is_left_to_it(cx: &mut TestAppContext) {
2953        let cover = Bounds::new(point(px(50.), px(60.)), size(px(50.), px(40.)));
2954        let (cx, handle) = covered_harness(cx, ScrollbarMode::Always, cover);
2955        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2956        assert_eq!(handle.offset(), Point::default());
2957
2958        // The track left uncovered still takes a press.
2959        cx.simulate_click(point(px(95.), px(50.)), Modifiers::default());
2960        assert!(handle.offset().y < px(0.));
2961    }
2962
2963    #[gpui::test]
2964    fn hovering_an_element_over_a_hover_scrollbar_does_not_reveal_it(cx: &mut TestAppContext) {
2965        let cover = Bounds::new(point(px(50.), px(0.)), size(px(50.), px(50.)));
2966        let (cx, handle) = covered_harness(cx, ScrollbarMode::Hover, cover);
2967        cx.simulate_mouse_move(point(px(95.), px(20.)), None, Modifiers::default());
2968        cx.run_until_parked();
2969
2970        // Uncovered, but the bar never showed, so it takes no press.
2971        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2972        assert_eq!(handle.offset(), Point::default());
2973    }
2974
2975    #[gpui::test]
2976    fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) {
2977        let (cx, handle) = harness(
2978            cx,
2979            ScrollbarAxis::Vertical,
2980            ScrollbarMode::Hover,
2981            size(px(100.), px(500.)),
2982        );
2983        // Base ships no motion, so the reveal is immediate.
2984        cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default());
2985        cx.run_until_parked();
2986
2987        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2988        assert!(handle.offset().y < px(0.));
2989    }
2990
2991    #[gpui::test]
2992    fn drag_notifications_are_throttled_and_deliver_the_latest_offset(cx: &mut TestAppContext) {
2993        let handle = TestHandle::new(size(px(100.), px(1000.)));
2994        let (view, cx) = cx.add_window_view({
2995            let handle = handle.clone();
2996            move |_, _| ScrollbarHarness {
2997                handle,
2998                axis: ScrollbarAxis::Vertical,
2999                placement: ScrollbarPlacement::default(),
3000                mode: ScrollbarMode::Always,
3001                scroll_viewport_size: None,
3002            }
3003        });
3004        cx.update(|window, cx| window.draw(cx).clear(cx));
3005        let observed = Rc::new(RefCell::new(Vec::new()));
3006        let _subscription = cx.update(|_, cx| {
3007            let observed = observed.clone();
3008            let handle = handle.clone();
3009            cx.observe(&view, move |_, _| {
3010                observed.borrow_mut().push(handle.offset().y)
3011            })
3012        });
3013        let state = ScrollbarState::default();
3014        let now = Instant::now();
3015        let interval = Duration::from_secs_f64(1. / 30.);
3016        let mut inner = state.get().with_drag_pos(Axis::Vertical, Point::default());
3017        inner.last_update = now;
3018        state.set(inner);
3019        let update = |offset, elapsed, cx: &mut VisualTestContext| {
3020            handle.set_offset(point(px(0.), px(offset)));
3021            cx.update(|window, cx| {
3022                state.notify_drag(now + elapsed, interval, view.entity_id(), window, cx)
3023            });
3024            cx.run_until_parked();
3025        };
3026        update(-10., Duration::ZERO, cx);
3027        cx.executor().advance_clock(Duration::from_millis(16));
3028        update(-20., Duration::from_millis(16), cx);
3029        update(-30., Duration::from_millis(16), cx);
3030        // Rendering at 120 Hz must not bypass the configured 30 Hz timer.
3031        cx.update(|window, cx| {
3032            window.simulate_next_frame(cx);
3033        });
3034        cx.run_until_parked();
3035        assert!(observed.borrow().is_empty());
3036        cx.executor().advance_clock(Duration::from_millis(16));
3037        cx.run_until_parked();
3038        assert!(observed.borrow().is_empty());
3039        cx.executor().advance_clock(Duration::from_millis(2));
3040        cx.run_until_parked();
3041        assert_eq!(
3042            *observed.borrow(),
3043            vec![px(-30.)],
3044            "one trailing notification must see the newest offset even when movement stops"
3045        );
3046
3047        // A second burst gets its own interval, and release invalidates its timer.
3048        let next = state.get().last_update;
3049        handle.set_offset(point(px(0.), px(-40.)));
3050        cx.update(|window, cx| state.notify_drag(next, interval, view.entity_id(), window, cx));
3051        cx.run_until_parked();
3052        state.set(state.get().with_unset_drag_pos(Instant::now()));
3053        handle.set_offset(point(px(0.), px(-50.)));
3054        cx.update(|_, cx| cx.notify(view.entity_id()));
3055        assert_eq!(*observed.borrow(), vec![px(-30.), px(-50.)]);
3056        cx.executor().advance_clock(interval);
3057        cx.run_until_parked();
3058        assert_eq!(
3059            *observed.borrow(),
3060            vec![px(-30.), px(-50.)],
3061            "release must not leave a stale trailing notification"
3062        );
3063    }
3064
3065    #[test]
3066    fn full_track_thumb_does_not_reset_the_scroll_offset() {
3067        let geometry =
3068            ThumbGeometry::new(px(20.), px(40.), px(40.), px(500.), px(0.), px(4.), px(64.));
3069        let offset = point(px(0.), px(-100.));
3070        assert_eq!(
3071            geometry.drag_offset(
3072                Axis::Vertical,
3073                point(px(0.), px(50.)),
3074                point(px(0.), px(8.)),
3075                offset
3076            ),
3077            offset
3078        );
3079    }
3080
3081    #[test]
3082    fn thumb_geometry_maps_content_viewport_to_padded_track() {
3083        let geometry =
3084            ThumbGeometry::new(px(20.), px(96.), px(80.), px(160.), px(0.), px(0.), px(0.));
3085
3086        assert_eq!(geometry.length, px(48.));
3087        assert_eq!(geometry.travel, px(48.));
3088        assert_eq!(geometry.extent, px(80.));
3089        assert_eq!(geometry.offset(px(68.), px(0.)), px(-80.));
3090
3091        let barely_overflowing =
3092            ThumbGeometry::new(px(20.), px(96.), px(80.), px(85.), px(0.), px(0.), px(0.));
3093        assert_eq!(barely_overflowing.extent, px(5.));
3094        assert!(barely_overflowing.travel > px(0.));
3095        assert_eq!(
3096            barely_overflowing.offset(px(20.) + barely_overflowing.travel, px(0.)),
3097            px(-5.)
3098        );
3099    }
3100
3101    #[gpui::test]
3102    fn repeated_touch_and_mouse_drags_keep_the_painted_grab_point(cx: &mut TestAppContext) {
3103        struct Probe {
3104            scrollbar: Scrollbar,
3105            painted: Rc<Cell<Bounds<Pixels>>>,
3106        }
3107        impl Element for Probe {
3108            type RequestLayoutState = ();
3109            type PrepaintState = PrepaintState;
3110            fn id(&self) -> Option<ElementId> {
3111                Element::id(&self.scrollbar)
3112            }
3113            fn source_location(&self) -> Option<&'static Location<'static>> {
3114                None
3115            }
3116            fn request_layout(
3117                &mut self,
3118                id: Option<&GlobalElementId>,
3119                inspector: Option<&InspectorElementId>,
3120                window: &mut Window,
3121                cx: &mut App,
3122            ) -> (LayoutId, ()) {
3123                self.scrollbar.request_layout(id, inspector, window, cx)
3124            }
3125            fn prepaint(
3126                &mut self,
3127                id: Option<&GlobalElementId>,
3128                inspector: Option<&InspectorElementId>,
3129                bounds: Bounds<Pixels>,
3130                layout: &mut (),
3131                window: &mut Window,
3132                cx: &mut App,
3133            ) -> PrepaintState {
3134                let state = self
3135                    .scrollbar
3136                    .prepaint(id, inspector, bounds, layout, window, cx);
3137                self.painted.set(state.states[0].thumb_fill_bounds);
3138                state
3139            }
3140            fn paint(
3141                &mut self,
3142                id: Option<&GlobalElementId>,
3143                inspector: Option<&InspectorElementId>,
3144                bounds: Bounds<Pixels>,
3145                layout: &mut (),
3146                state: &mut PrepaintState,
3147                window: &mut Window,
3148                cx: &mut App,
3149            ) {
3150                self.scrollbar
3151                    .paint(id, inspector, bounds, layout, state, window, cx);
3152            }
3153        }
3154        struct Root {
3155            handle: TestHandle,
3156            painted: Rc<Cell<Bounds<Pixels>>>,
3157            axis: ScrollbarAxis,
3158            viewport: Bounds<Pixels>,
3159        }
3160        impl Render for Root {
3161            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
3162                div().size(px(400.)).child(Probe {
3163                    scrollbar: Scrollbar::new(&self.handle)
3164                        .axis(self.axis)
3165                        .mode(ScrollbarMode::Always)
3166                        .viewport_bounds(self.viewport)
3167                        .styles(|style| {
3168                            style
3169                                .thumb(|style| style.inset(px(6.)).min_length(px(64.)))
3170                                .thumb_active(|style| style.inset(px(3.)).min_length(px(72.)))
3171                        }),
3172                    painted: self.painted.clone(),
3173                })
3174            }
3175        }
3176        for touch in [true, false] {
3177            for vertical in [true, false] {
3178                for (origin, viewport_size, content_size) in [
3179                    (Point::default(), 200., 1000.),
3180                    (point(px(30.), px(40.)), 240., 500.),
3181                ] {
3182                    let handle = TestHandle::new(size(px(content_size), px(content_size)));
3183                    handle.set_offset(point(px(-100.), px(-100.)));
3184                    let painted = Rc::new(Cell::new(Bounds::default()));
3185                    let (_, cx) = cx.add_window_view({
3186                        let handle = handle.clone();
3187                        let painted = painted.clone();
3188                        move |_, _| Root {
3189                            handle,
3190                            painted,
3191                            axis: if vertical {
3192                                ScrollbarAxis::Vertical
3193                            } else {
3194                                ScrollbarAxis::Both
3195                            },
3196                            viewport: Bounds::new(
3197                                origin,
3198                                size(px(viewport_size), px(viewport_size)),
3199                            ),
3200                        }
3201                    });
3202                    cx.update(|window, cx| window.draw(cx).clear(cx));
3203                    let initial = painted.get();
3204                    let start = initial.center();
3205                    let grab = if vertical {
3206                        start.y - initial.origin.y
3207                    } else {
3208                        start.x - initial.origin.x
3209                    };
3210                    let axis_delta = |value| {
3211                        if vertical {
3212                            point(px(0.), px(value))
3213                        } else {
3214                            point(px(value), px(0.))
3215                        }
3216                    };
3217                    let axis_value =
3218                        |point: Point<Pixels>| if vertical { point.y } else { point.x };
3219                    let started_position = if touch { start + axis_delta(5.) } else { start };
3220                    if touch {
3221                        cx.simulate_event(TouchDragEvent {
3222                            phase: TouchPhase::Started,
3223                            start_position: start,
3224                            position: started_position,
3225                        });
3226                    } else {
3227                        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
3228                    }
3229                    cx.update(|window, cx| window.draw(cx).clear(cx));
3230                    assert!(
3231                        (axis_value(painted.get().origin) + grab - axis_value(started_position))
3232                            .abs()
3233                            < px(0.1),
3234                        "starting must preserve the grab point and first displacement"
3235                    );
3236                    let mut reference_offset = px(0.);
3237                    let mut offset_per_pixel = 0.;
3238                    for delta in [0., 24., -8., 32., -10., 8., 0.] {
3239                        let position = start + axis_delta(delta);
3240                        if touch {
3241                            cx.simulate_event(TouchDragEvent {
3242                                phase: TouchPhase::Moved,
3243                                start_position: start,
3244                                position,
3245                            });
3246                        } else {
3247                            cx.simulate_mouse_move(
3248                                position,
3249                                Some(MouseButton::Left),
3250                                Modifiers::default(),
3251                            );
3252                        }
3253                        cx.update(|window, cx| window.draw(cx).clear(cx));
3254                        if delta == 0. {
3255                            reference_offset = axis_value(handle.offset());
3256                        }
3257                        if delta == 24. {
3258                            offset_per_pixel =
3259                                (axis_value(handle.offset()) - reference_offset) / px(24.);
3260                        }
3261                        let actual = if vertical {
3262                            painted.get().origin.y + grab
3263                        } else {
3264                            painted.get().origin.x + grab
3265                        };
3266                        let expected = if vertical { position.y } else { position.x };
3267                        assert!(
3268                            (actual - expected).abs() < px(0.1),
3269                            "touch={touch} vertical={vertical} delta={delta}: painted grab {actual:?}, pointer {expected:?}"
3270                        );
3271                    }
3272                    // Release contains a final displacement without an intervening move.
3273                    let expected_offset = reference_offset + px(12.) * offset_per_pixel;
3274                    if touch {
3275                        cx.simulate_event(TouchDragEvent {
3276                            phase: TouchPhase::Ended,
3277                            start_position: start,
3278                            position: start + axis_delta(12.),
3279                        });
3280                    } else {
3281                        cx.simulate_mouse_up(
3282                            start + axis_delta(12.),
3283                            MouseButton::Left,
3284                            Modifiers::default(),
3285                        );
3286                    }
3287                    assert!(
3288                        (axis_value(handle.offset()) - expected_offset).abs() < px(0.1),
3289                        "release must flush the last displacement"
3290                    );
3291                    let released_offset = handle.offset();
3292                    cx.update(|window, cx| window.draw(cx).clear(cx));
3293                    assert_eq!(
3294                        handle.offset(),
3295                        released_offset,
3296                        "leaving active styling must not scroll"
3297                    );
3298                }
3299            }
3300        }
3301    }
3302
3303    #[gpui::test]
3304    fn touch_thumb_drag_moves_down_and_cancel_releases_handle(cx: &mut TestAppContext) {
3305        let (cx, handle) = harness(
3306            cx,
3307            ScrollbarAxis::Vertical,
3308            ScrollbarMode::Always,
3309            size(px(100.), px(500.)),
3310        );
3311        let start_position = point(px(95.), px(20.));
3312        for (phase, position) in [
3313            (TouchPhase::Started, start_position),
3314            (TouchPhase::Moved, point(px(95.), px(45.))),
3315            (TouchPhase::Cancelled, point(px(95.), px(45.))),
3316        ] {
3317            cx.simulate_event(TouchDragEvent {
3318                phase,
3319                start_position,
3320                position,
3321            });
3322        }
3323        assert!(
3324            handle.offset().y < px(0.),
3325            "thumb down must scroll toward later content"
3326        );
3327        assert_eq!(handle.offset().x, px(0.));
3328        assert_eq!(handle.drag_starts.get(), 1);
3329        assert_eq!(handle.drag_ends.get(), 1);
3330    }
3331
3332    #[gpui::test]
3333    fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) {
3334        let (cx, handle) = harness(
3335            cx,
3336            ScrollbarAxis::Vertical,
3337            ScrollbarMode::Always,
3338            size(px(100.), px(500.)),
3339        );
3340        cx.simulate_mouse_down(
3341            point(px(95.), px(20.)),
3342            MouseButton::Left,
3343            Modifiers::default(),
3344        );
3345        cx.simulate_mouse_move(
3346            point(px(95.), px(70.)),
3347            Some(MouseButton::Left),
3348            Modifiers::default(),
3349        );
3350        cx.simulate_mouse_up(
3351            point(px(95.), px(70.)),
3352            MouseButton::Left,
3353            Modifiers::default(),
3354        );
3355
3356        assert_eq!(handle.drag_starts.get(), 1);
3357        assert_eq!(handle.drag_ends.get(), 1);
3358    }
3359
3360    #[gpui::test]
3361    fn only_the_primary_button_drags_or_jumps(cx: &mut TestAppContext) {
3362        let (cx, handle) = harness(
3363            cx,
3364            ScrollbarAxis::Vertical,
3365            ScrollbarMode::Always,
3366            size(px(100.), px(500.)),
3367        );
3368        for button in [MouseButton::Right, MouseButton::Middle] {
3369            // Thumb press, then the track.
3370            for y in [px(20.), px(80.)] {
3371                cx.simulate_mouse_down(point(px(95.), y), button, Modifiers::default());
3372                cx.simulate_mouse_up(point(px(95.), y), button, Modifiers::default());
3373            }
3374        }
3375        assert_eq!(handle.drag_starts.get(), 0);
3376        assert_eq!(handle.offset(), Point::default());
3377
3378        // A secondary release does not end a primary drag.
3379        cx.simulate_mouse_down(
3380            point(px(95.), px(20.)),
3381            MouseButton::Left,
3382            Modifiers::default(),
3383        );
3384        cx.simulate_mouse_up(
3385            point(px(95.), px(20.)),
3386            MouseButton::Right,
3387            Modifiers::default(),
3388        );
3389        assert_eq!(handle.drag_ends.get(), 0);
3390        cx.simulate_mouse_up(
3391            point(px(95.), px(20.)),
3392            MouseButton::Left,
3393            Modifiers::default(),
3394        );
3395        assert_eq!(handle.drag_ends.get(), 1);
3396    }
3397}