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    use_layout_bounds: bool,
866    /// Maximum frames per second for scrolling by drag. Default is 120 FPS.
867    ///
868    /// This is used to limit the update rate of the scrollbar when it is
869    /// being dragged for some complex interactions for reducing CPU usage.
870    max_fps: usize,
871    styles: ScrollbarStyles,
872}
873
874impl Scrollbar {
875    /// Create a new scrollbar.
876    ///
877    /// This will have both vertical and horizontal scrollbars.
878    #[track_caller]
879    pub fn new<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
880        let caller = Location::caller();
881        Self {
882            id: ElementId::CodeLocation(*caller),
883            axis: ScrollbarAxis::Both,
884            placement: ScrollbarPlacement::default(),
885            mode: None,
886            scroll_handle: Rc::new(scroll_handle.clone()),
887            max_fps: 120,
888            scroll_size: None,
889            viewport_bounds: None,
890            scroll_viewport_size: None,
891            use_layout_bounds: false,
892            styles: ScrollbarStyles::default(),
893        }
894    }
895
896    /// Create with horizontal scrollbar.
897    #[track_caller]
898    pub fn horizontal<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
899        Self::new(scroll_handle).axis(ScrollbarAxis::Horizontal)
900    }
901
902    /// Create with vertical scrollbar.
903    #[track_caller]
904    pub fn vertical<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
905        Self::new(scroll_handle).axis(ScrollbarAxis::Vertical)
906    }
907
908    /// Set a specific element id, default is the [`Location::caller`].
909    ///
910    /// NOTE: In most cases, you don't need to set a specific id for scrollbar.
911    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
912        self.id = id.into();
913        self
914    }
915
916    /// Set the scrollbar show mode [`ScrollbarMode`].
917    ///
918    /// If unset, the current application theme projection is used.
919    pub fn mode(mut self, mode: ScrollbarMode) -> Self {
920        self.mode = Some(mode);
921        self
922    }
923
924    /// Set a special scroll size of the content area, default is None.
925    ///
926    /// Default will sync the `content_size` from `scroll_handle`.
927    pub fn scroll_size(mut self, scroll_size: Size<Pixels>) -> Self {
928        self.scroll_size = Some(scroll_size);
929        self
930    }
931
932    /// Override the viewport bounds that this scrollbar overlays.
933    ///
934    /// Most scroll containers should rely on the bounds reported by their
935    /// scroll handle. Custom-painted viewports, such as the text editor, can
936    /// use this when their visible bounds differ from the handle's layout
937    /// bounds.
938    pub fn viewport_bounds(mut self, bounds: Bounds<Pixels>) -> Self {
939        self.viewport_bounds = Some(bounds);
940        self
941    }
942
943    pub(crate) fn scroll_viewport_size(mut self, size: Size<Pixels>) -> Self {
944        self.scroll_viewport_size = Some(size);
945        self
946    }
947
948    /// Use the scrollbar element's layout bounds as its viewport.
949    ///
950    /// This is useful for composite widgets whose scrollbar viewport excludes
951    /// fixed headers or columns and is therefore defined by a positioned
952    /// overlay container rather than by the underlying scroll handle.
953    pub fn viewport_from_layout(mut self) -> Self {
954        self.use_layout_bounds = true;
955        self
956    }
957
958    fn resolved_viewport_bounds(&self, layout_bounds: Bounds<Pixels>) -> Bounds<Pixels> {
959        self.viewport_bounds.unwrap_or_else(|| {
960            if self.use_layout_bounds {
961                layout_bounds
962            } else {
963                self.scroll_handle.viewport_bounds()
964            }
965        })
966    }
967
968    /// Set scrollbar axis.
969    pub fn axis(mut self, axis: impl Into<ScrollbarAxis>) -> Self {
970        self.axis = axis.into();
971        self
972    }
973
974    /// Set the scrollbar placement, default is [`ScrollbarPlacement::BottomRight`].
975    ///
976    /// When both scrollbars are shown, the horizontal track ends before the
977    /// vertical one, on the vertical scrollbar's side.
978    pub fn placement(mut self, placement: ScrollbarPlacement) -> Self {
979        self.placement = placement;
980        self
981    }
982
983    pub fn styles(mut self, build: impl FnOnce(ScrollbarStyles) -> ScrollbarStyles) -> Self {
984        self.styles = build(self.styles);
985        self
986    }
987
988    /// Set maximum frames per second for scrolling by drag. Default is 120 FPS.
989    ///
990    /// If you have very high CPU usage, consider reducing this value to improve performance.
991    ///
992    /// Available values: 30..120
993    #[doc(hidden)]
994    pub fn max_fps(mut self, max_fps: usize) -> Self {
995        self.max_fps = max_fps.clamp(30, 120);
996        self
997    }
998
999    // Get the width of the scrollbar.
1000    #[doc(hidden)]
1001    pub const fn width() -> Pixels {
1002        WIDTH
1003    }
1004
1005    /// The width of a track this theme gives scrollbars without styles of their own.
1006    pub(crate) fn themed_track_width(cx: &App) -> Pixels {
1007        cx.theme().scrollbar.styles().track.width.unwrap_or(WIDTH)
1008    }
1009
1010    fn resolve_track(
1011        &self,
1012        cx: &App,
1013        state: &ScrollbarTrackStyle,
1014        global_state: &ScrollbarTrackStyle,
1015        default_border: Hsla,
1016    ) -> (Hsla, Hsla) {
1017        let theme = cx.theme();
1018        let global = theme.scrollbar.styles();
1019        (
1020            state
1021                .background
1022                .or(self.styles.track.background)
1023                .or(global_state.background)
1024                .or(global.track.background)
1025                .unwrap_or_else(gpui::transparent_black),
1026            state
1027                .border
1028                .or(self.styles.track.border)
1029                .or(global_state.border)
1030                .or(global.track.border)
1031                .unwrap_or(default_border),
1032        )
1033    }
1034
1035    fn resolve_thumb(
1036        &self,
1037        cx: &App,
1038        state: &ScrollbarThumbStyle,
1039        global_state: &ScrollbarThumbStyle,
1040        defaults: ScrollbarThumbStyle,
1041    ) -> (Background, Pixels, Pixels, Pixels, Pixels) {
1042        let theme = cx.theme();
1043        let global = theme.scrollbar.styles();
1044        (
1045            state
1046                .background
1047                .or(self.styles.thumb.background)
1048                .or(global_state.background)
1049                .or(global.thumb.background)
1050                .unwrap_or_else(|| defaults.background.unwrap()),
1051            state
1052                .width
1053                .or(self.styles.thumb.width)
1054                .or(global_state.width)
1055                .or(global.thumb.width)
1056                .unwrap_or_else(|| defaults.width.unwrap()),
1057            state
1058                .inset
1059                .or(self.styles.thumb.inset)
1060                .or(global_state.inset)
1061                .or(global.thumb.inset)
1062                .unwrap_or_else(|| defaults.inset.unwrap()),
1063            state
1064                .radius
1065                .or(self.styles.thumb.radius)
1066                .or(global_state.radius)
1067                .or(global.thumb.radius)
1068                .unwrap_or_else(|| defaults.radius.unwrap()),
1069            state
1070                .min_length
1071                .or(self.styles.thumb.min_length)
1072                .or(global_state.min_length)
1073                .or(global.thumb.min_length)
1074                .or(defaults.min_length)
1075                .unwrap_or(MIN_THUMB_SIZE),
1076        )
1077    }
1078
1079    /// The thumb colour a scrollbar falls back to when nothing has overridden
1080    /// it, taken from the active theme rather than fixed.
1081    ///
1082    /// It used to be literal black at these alphas. That reads as an ordinary
1083    /// grey thumb on a light surface and as very nearly nothing at all on a
1084    /// dark one, and no palette an application installed could change it:
1085    /// `Theme` carries `scrollbar` beside `tokens` rather than derived from
1086    /// them, so a theme swap moved every token except the ones the scrollbar
1087    /// actually paints with.
1088    ///
1089    /// `foreground` is the token that already means "ink on this surface" and
1090    /// already flips with the appearance, so on a light theme this stays within
1091    /// a hair of the old constant and on a dark one it becomes visible. An
1092    /// explicit `ScrollbarStyles` still wins: this is the bottom of the
1093    /// cascade, not a new top of it.
1094    fn thumb_default_background(cx: &App, alpha: f32) -> Background {
1095        cx.theme().tokens.colors.foreground.alpha(alpha).into()
1096    }
1097
1098    fn thumb_defaults(
1099        background: Background,
1100        width: Pixels,
1101        inset: Pixels,
1102        radius: Pixels,
1103    ) -> ScrollbarThumbStyle {
1104        ScrollbarThumbStyle {
1105            background: Some(background),
1106            width: Some(width),
1107            inset: Some(inset),
1108            radius: Some(radius),
1109            min_length: Some(MIN_THUMB_SIZE),
1110        }
1111    }
1112
1113    fn style_for_active(
1114        &self,
1115        cx: &App,
1116    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1117        let theme = cx.theme();
1118        let global = theme.scrollbar.styles();
1119        let (track, border) = self.resolve_track(
1120            cx,
1121            &self.styles.track_active,
1122            &global.track_active,
1123            gpui::transparent_black(),
1124        );
1125        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1126            cx,
1127            &self.styles.thumb_active,
1128            &global.thumb_active,
1129            Self::thumb_defaults(
1130                Self::thumb_default_background(cx, 0.55),
1131                THUMB_ACTIVE_WIDTH,
1132                THUMB_ACTIVE_INSET,
1133                THUMB_ACTIVE_RADIUS,
1134            ),
1135        );
1136        (thumb, track, border, width, inset, radius, min_length)
1137    }
1138
1139    fn style_for_hovered_thumb(
1140        &self,
1141        cx: &App,
1142    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1143        let theme = cx.theme();
1144        let global = theme.scrollbar.styles();
1145        let (track, border) = self.resolve_track(
1146            cx,
1147            &self.styles.track_active,
1148            &global.track_active,
1149            gpui::transparent_black(),
1150        );
1151        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1152            cx,
1153            &self.styles.thumb_hover,
1154            &global.thumb_hover,
1155            Self::thumb_defaults(
1156                Self::thumb_default_background(cx, 0.55),
1157                THUMB_ACTIVE_WIDTH,
1158                THUMB_ACTIVE_INSET,
1159                THUMB_ACTIVE_RADIUS,
1160            ),
1161        );
1162        (thumb, track, border, width, inset, radius, min_length)
1163    }
1164
1165    fn style_for_hovered_bar(
1166        &self,
1167        cx: &App,
1168    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1169        let theme = cx.theme();
1170        let global = theme.scrollbar.styles();
1171        let (track, border) = self.resolve_track(
1172            cx,
1173            &self.styles.track_hover,
1174            &global.track_hover,
1175            gpui::transparent_black(),
1176        );
1177        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1178            cx,
1179            &self.styles.thumb,
1180            &global.thumb,
1181            Self::thumb_defaults(
1182                Self::thumb_default_background(cx, 0.35),
1183                THUMB_WIDTH,
1184                THUMB_INSET,
1185                THUMB_RADIUS,
1186            ),
1187        );
1188        (thumb, track, border, width, inset, radius, min_length)
1189    }
1190
1191    fn style_for_normal(
1192        &self,
1193        cx: &App,
1194    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1195        let theme = cx.theme();
1196        let global = theme.scrollbar.styles();
1197
1198        let (track, border) = self.resolve_track(
1199            cx,
1200            &self.styles.track,
1201            &global.track,
1202            gpui::transparent_black(),
1203        );
1204        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1205            cx,
1206            &self.styles.thumb,
1207            &global.thumb,
1208            Self::thumb_defaults(
1209                Self::thumb_default_background(cx, 0.35),
1210                THUMB_WIDTH,
1211                THUMB_INSET,
1212                THUMB_RADIUS,
1213            ),
1214        );
1215        (thumb, track, border, width, inset, radius, min_length)
1216    }
1217}
1218
1219#[doc(hidden)]
1220pub struct PrepaintState {
1221    hitbox: Hitbox,
1222    scrollbar_state: ScrollbarState,
1223    states: Vec<AxisPrepaintState>,
1224}
1225
1226#[doc(hidden)]
1227pub struct AxisPrepaintState {
1228    axis: Axis,
1229    bar_hitbox: Hitbox,
1230    bounds: Bounds<Pixels>,
1231    radius: Pixels,
1232    bg: Hsla,
1233    border: Hsla,
1234    thumb_bounds: Bounds<Pixels>,
1235    // Bounds of thumb to be rendered.
1236    thumb_fill_bounds: Bounds<Pixels>,
1237    thumb_bg: Background,
1238    geometry: ThumbGeometry,
1239    active_geometry: ThumbGeometry,
1240    track_width: Pixels,
1241    visibility_opacity: f32,
1242    visibility_position: f32,
1243    visibility_requested: bool,
1244}
1245
1246/// The same longitudinal geometry drives painting, track clicks and dragging.
1247/// `length` excludes the inset, while `travel` excludes the full logical thumb.
1248#[derive(Clone, Copy)]
1249struct ThumbGeometry {
1250    origin: Pixels,
1251    inset: Pixels,
1252    length: Pixels,
1253    travel: Pixels,
1254    extent: Pixels,
1255}
1256
1257impl ThumbGeometry {
1258    fn new(
1259        origin: Pixels,
1260        track_size: Pixels,
1261        viewport_size: Pixels,
1262        content: Pixels,
1263        margin_end: Pixels,
1264        inset: Pixels,
1265        min_length: Pixels,
1266    ) -> Self {
1267        let track = (track_size - margin_end).max(px(0.));
1268        let logical_length = (viewport_size / content * track).max(min_length).min(track);
1269        let inset = inset.clamp(px(0.), logical_length / 2.);
1270        Self {
1271            origin,
1272            inset,
1273            length: logical_length - inset * 2.,
1274            travel: track - logical_length,
1275            extent: content - viewport_size,
1276        }
1277    }
1278
1279    fn start(self, offset: Pixels) -> Pixels {
1280        self.origin + self.inset + (-offset / self.extent).clamp(0., 1.) * self.travel
1281    }
1282
1283    fn offset(self, position: Pixels, grab: Pixels) -> Pixels {
1284        if self.travel <= px(0.) {
1285            return px(0.);
1286        }
1287        -self.extent * ((position - self.origin - self.inset - grab) / self.travel).clamp(0., 1.)
1288    }
1289
1290    fn drag_offset(
1291        self,
1292        axis: Axis,
1293        position: Point<Pixels>,
1294        grab: Point<Pixels>,
1295        mut offset: Point<Pixels>,
1296    ) -> Point<Pixels> {
1297        if self.travel <= px(0.) {
1298            return offset;
1299        }
1300        if axis.is_vertical() {
1301            offset.y = self.offset(position.y, grab.y);
1302        } else {
1303            offset.x = self.offset(position.x, grab.x);
1304        }
1305        offset
1306    }
1307}
1308
1309impl Element for Scrollbar {
1310    type RequestLayoutState = ();
1311    type PrepaintState = PrepaintState;
1312
1313    fn id(&self) -> Option<gpui::ElementId> {
1314        Some(self.id.clone())
1315    }
1316
1317    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1318        None
1319    }
1320
1321    fn request_layout(
1322        &mut self,
1323        _: Option<&GlobalElementId>,
1324        _: Option<&InspectorElementId>,
1325        window: &mut Window,
1326        cx: &mut App,
1327    ) -> (LayoutId, Self::RequestLayoutState) {
1328        let mut style = Style::default();
1329        style.position = Position::Absolute;
1330        style.flex_grow = 1.0;
1331        style.flex_shrink = 1.0;
1332        style.size.width = relative(1.).into();
1333        style.size.height = relative(1.).into();
1334
1335        (window.request_layout(style, None, cx), ())
1336    }
1337
1338    fn prepaint(
1339        &mut self,
1340        _: Option<&GlobalElementId>,
1341        _: Option<&InspectorElementId>,
1342        bounds: Bounds<Pixels>,
1343        _: &mut Self::RequestLayoutState,
1344        window: &mut Window,
1345        cx: &mut App,
1346    ) -> Self::PrepaintState {
1347        let bounds = self.resolved_viewport_bounds(bounds);
1348        let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
1349            window.insert_hitbox(bounds, HitboxBehavior::Normal)
1350        });
1351
1352        let state = window
1353            .use_state(cx, |_, _| ScrollbarState::default())
1354            .read(cx)
1355            .clone();
1356
1357        let now = Instant::now();
1358        let base_theme = cx.theme();
1359        let mode = self.mode.unwrap_or(base_theme.scrollbar.mode());
1360        let motion = base_theme.scrollbar.motion();
1361        // Always-visible scrollbars skip visibility motion but still animate
1362        // their activity width. Reduced motion snaps every channel.
1363        let reduce_motion = cx.reduce_motion();
1364        let (enter, exit) = if !mode.is_always() && !reduce_motion {
1365            (motion.enter(), motion.exit())
1366        } else {
1367            (Duration::ZERO, Duration::ZERO)
1368        };
1369        let expand = if reduce_motion {
1370            Duration::ZERO
1371        } else {
1372            motion.expand()
1373        };
1374
1375        let mut inner = state.get();
1376        let current_offset = self.scroll_handle.offset();
1377        if current_offset != inner.last_scroll_offset {
1378            inner = inner.with_last_scroll(current_offset, Some(now));
1379        }
1380
1381        let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some();
1382        let is_dragging = inner.dragged_axis.is_some();
1383        let is_currently_visible = inner.visibility.sample(now).opacity > 0.0;
1384        let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible)
1385            || wants_visible(
1386                mode,
1387                is_hovered,
1388                is_dragging,
1389                inner.last_scroll_time,
1390                motion.idle(),
1391                now,
1392            );
1393        inner.visibility.set_visible(
1394            visible,
1395            motion.entrance_for(mode, inner.hovered_on_thumb.is_some()),
1396            enter,
1397            exit,
1398            now,
1399        );
1400        let visibility = inner.visibility.sample(now);
1401        if visibility.running {
1402            window.request_animation_frame();
1403        }
1404
1405        if !is_hovered && !is_dragging {
1406            if let Some(last_time) = inner.last_scroll_time {
1407                let elapsed = now.saturating_duration_since(last_time);
1408                if elapsed < motion.idle() && !inner.idle_timer_scheduled {
1409                    inner.idle_timer_scheduled = true;
1410                    let state = state.clone();
1411                    let current_view = window.current_view();
1412                    let next_delay = motion.idle() - elapsed;
1413                    window
1414                        .spawn(cx, async move |cx| {
1415                            cx.background_executor().timer(next_delay).await;
1416                            state.set(state.get().with_idle_timer_scheduled(false));
1417                            cx.update(|_, cx| cx.notify(current_view)).ok();
1418                        })
1419                        .detach();
1420                }
1421            }
1422        }
1423        state.set(inner);
1424
1425        let mut states = vec![];
1426        let mut has_both = self.axis.is_both();
1427        let scroll_size = self
1428            .scroll_size
1429            .unwrap_or(self.scroll_handle.content_size());
1430        let scroll_viewport_size = self.scroll_viewport_size.unwrap_or(hitbox.size);
1431
1432        for axis in self.axis.all().into_iter() {
1433            let is_vertical = axis.is_vertical();
1434            let track_width = self
1435                .styles
1436                .track
1437                .width
1438                .or(cx.theme().scrollbar.styles().track.width)
1439                .unwrap_or(WIDTH);
1440            let (scroll_area_size, container_size, scroll_viewport_size, scroll_position) =
1441                if is_vertical {
1442                    (
1443                        scroll_size.height,
1444                        hitbox.size.height,
1445                        scroll_viewport_size.height,
1446                        self.scroll_handle.offset().y,
1447                    )
1448                } else {
1449                    (
1450                        scroll_size.width,
1451                        hitbox.size.width,
1452                        scroll_viewport_size.width,
1453                        self.scroll_handle.offset().x,
1454                    )
1455                };
1456
1457            // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible.
1458            let margin = if has_both && !is_vertical {
1459                track_width
1460            } else {
1461                px(0.)
1462            };
1463
1464            // Hide scrollbar, if the scroll area is smaller than the container.
1465            if scroll_area_size <= scroll_viewport_size {
1466                has_both = false;
1467                continue;
1468            }
1469
1470            let bounds = Bounds {
1471                origin: if is_vertical {
1472                    if self.placement.is_left() {
1473                        hitbox.origin
1474                    } else {
1475                        point(
1476                            hitbox.origin.x + hitbox.size.width - track_width,
1477                            hitbox.origin.y,
1478                        )
1479                    }
1480                } else if self.placement.is_top() {
1481                    hitbox.origin
1482                } else {
1483                    point(
1484                        hitbox.origin.x,
1485                        hitbox.origin.y + hitbox.size.height - track_width,
1486                    )
1487                },
1488                size: gpui::Size {
1489                    width: if is_vertical {
1490                        track_width
1491                    } else {
1492                        hitbox.size.width
1493                    },
1494                    height: if is_vertical {
1495                        hitbox.size.height
1496                    } else {
1497                        track_width
1498                    },
1499                },
1500            };
1501
1502            let is_always_to_show = mode.is_always();
1503            let is_hover_to_show = mode.is_hover();
1504            let is_hovered_on_bar = state.get().hovered_axis == Some(axis);
1505            let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis);
1506
1507            let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) =
1508                if state.get().dragged_axis == Some(axis) {
1509                    self.style_for_active(cx)
1510                } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling)
1511                    && (is_hovered_on_bar || is_hovered_on_thumb)
1512                {
1513                    if is_hovered_on_thumb {
1514                        self.style_for_hovered_thumb(cx)
1515                    } else {
1516                        self.style_for_hovered_bar(cx)
1517                    }
1518                } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) {
1519                    if is_hovered_on_thumb {
1520                        self.style_for_hovered_thumb(cx)
1521                    } else {
1522                        self.style_for_hovered_bar(cx)
1523                    }
1524                } else {
1525                    self.style_for_normal(cx)
1526                };
1527
1528            let mut width_animation = if is_vertical {
1529                state.get().vertical_width
1530            } else {
1531                state.get().horizontal_width
1532            };
1533            let (animated_width, running) = width_animation.set_target(thumb_width, expand, now);
1534            let mut updated = state.get();
1535            if is_vertical {
1536                updated.vertical_width = width_animation;
1537            } else {
1538                updated.horizontal_width = width_animation;
1539            }
1540            state.set(updated);
1541            thumb_width = animated_width;
1542            if running {
1543                window.request_animation_frame();
1544            }
1545
1546            let origin = if is_vertical {
1547                bounds.origin.y
1548            } else {
1549                bounds.origin.x
1550            };
1551            let track_origin = if !is_vertical && self.placement.is_left() {
1552                origin + margin
1553            } else {
1554                origin
1555            };
1556            let geometry = ThumbGeometry::new(
1557                track_origin,
1558                container_size,
1559                scroll_viewport_size,
1560                scroll_area_size,
1561                margin,
1562                inset,
1563                min_length,
1564            );
1565            let (_, _, _, _, active_inset, _, active_min_length) = self.style_for_active(cx);
1566            let active_geometry = ThumbGeometry::new(
1567                track_origin,
1568                container_size,
1569                scroll_viewport_size,
1570                scroll_area_size,
1571                margin,
1572                active_inset,
1573                active_min_length,
1574            );
1575            let thumb_start = geometry.start(scroll_position) - origin;
1576
1577            let thumb_length = geometry.length;
1578            let (thumb_anchor, thumb_origin) = if is_vertical {
1579                if self.placement.is_left() {
1580                    (Anchor::TopLeft, bounds.origin + point(inset, thumb_start))
1581                } else {
1582                    (
1583                        Anchor::TopRight,
1584                        bounds.top_right() + point(-inset, thumb_start),
1585                    )
1586                }
1587            } else if self.placement.is_top() {
1588                (Anchor::TopLeft, bounds.origin + point(thumb_start, inset))
1589            } else {
1590                (
1591                    Anchor::BottomLeft,
1592                    bounds.bottom_left() + point(thumb_start, -inset),
1593                )
1594            };
1595            let thumb_size = |width: Pixels| {
1596                if is_vertical {
1597                    size(width, thumb_length)
1598                } else {
1599                    size(thumb_length, width)
1600                }
1601            };
1602
1603            // The clickable area of the thumb
1604            let thumb_bounds =
1605                Bounds::from_anchor_and_size(thumb_anchor, thumb_origin, thumb_size(track_width));
1606
1607            // The actual render area of the thumb
1608            let thumb_fill_bounds =
1609                Bounds::from_anchor_and_size(thumb_anchor, thumb_origin, thumb_size(thumb_width));
1610
1611            let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
1612                window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal)
1613            });
1614
1615            states.push(AxisPrepaintState {
1616                axis,
1617                bar_hitbox,
1618                bounds,
1619                radius,
1620                bg: bar_bg,
1621                border: bar_border,
1622                thumb_bounds,
1623                thumb_fill_bounds,
1624                thumb_bg,
1625                geometry,
1626                active_geometry,
1627                track_width,
1628                visibility_opacity: visibility.opacity,
1629                visibility_position: visibility.position,
1630                visibility_requested: visible,
1631            })
1632        }
1633
1634        PrepaintState {
1635            hitbox,
1636            states,
1637            scrollbar_state: state,
1638        }
1639    }
1640
1641    fn paint(
1642        &mut self,
1643        _: Option<&GlobalElementId>,
1644        _: Option<&InspectorElementId>,
1645        _: Bounds<Pixels>,
1646        _: &mut Self::RequestLayoutState,
1647        prepaint: &mut Self::PrepaintState,
1648        window: &mut Window,
1649        cx: &mut App,
1650    ) {
1651        let scrollbar_state = &prepaint.scrollbar_state;
1652        let theme = cx.theme();
1653        let mode = self.mode.unwrap_or(theme.scrollbar.mode());
1654        let view_id = window.current_view();
1655        let hitbox_bounds = prepaint.hitbox.bounds;
1656        let is_hover_to_show = mode.is_hover();
1657
1658        window.with_content_mask(
1659            Some(ContentMask {
1660                bounds: hitbox_bounds,
1661            }),
1662            |window| {
1663                for state in prepaint.states.iter() {
1664                    let axis = state.axis;
1665                    let mut radius = state.radius;
1666                    if theme.tokens.radius.md.is_zero() {
1667                        radius = px(0.);
1668                    }
1669                    radius = clamp_thumb_radius(radius, state.thumb_fill_bounds);
1670                    let thumb_bounds = state.thumb_bounds;
1671                    let geometry = state.geometry;
1672                    let active_geometry = state.active_geometry;
1673                    let is_vertical = axis.is_vertical();
1674                    let visibility_opacity = state.visibility_opacity;
1675                    let is_visible = state.visibility_requested || visibility_opacity > 0.0;
1676                    let translation = visibility_translation(
1677                        axis,
1678                        self.placement,
1679                        state.track_width,
1680                        state.visibility_position,
1681                    );
1682                    let painted_bounds = state.bounds + translation;
1683                    let painted_thumb_bounds = state.thumb_fill_bounds + translation;
1684                    let painted_track_bg = state.bg.opacity(visibility_opacity);
1685                    let painted_border = state.border.opacity(visibility_opacity);
1686                    let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity);
1687
1688                    window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox);
1689
1690                    let paint = |cx: &mut Window| {
1691                        cx.paint_quad(fill(painted_bounds, painted_track_bg));
1692
1693                        cx.paint_quad(PaintQuad {
1694                            bounds: painted_bounds,
1695                            corner_radii: (0.).into(),
1696                            background: gpui::transparent_black().into(),
1697                            border_widths: if is_vertical {
1698                                Edges {
1699                                    top: px(0.),
1700                                    right: px(0.),
1701                                    bottom: px(0.),
1702                                    left: px(0.),
1703                                }
1704                            } else {
1705                                Edges {
1706                                    top: px(0.),
1707                                    right: px(0.),
1708                                    bottom: px(0.),
1709                                    left: px(0.),
1710                                }
1711                            },
1712                            border_color: painted_border,
1713                            border_style: BorderStyle::default(),
1714                        });
1715
1716                        cx.paint_quad(
1717                            fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius),
1718                        );
1719                    };
1720                    // GPUI Fast keeps the layer bounds to record scroll layers.
1721                    #[cfg(feature = "gpui-fast")]
1722                    window.paint_layer(hitbox_bounds, paint);
1723                    #[cfg(not(feature = "gpui-fast"))]
1724                    window.paint_layer(paint);
1725
1726                    window.on_mouse_event({
1727                        let state = scrollbar_state.clone();
1728                        let scroll_handle = self.scroll_handle.clone();
1729
1730                        move |event: &ScrollEvent, phase, _, cx| {
1731                            if phase.bubble() && hitbox_bounds.contains(&event.position) {
1732                                if scroll_handle.offset() != state.get().last_scroll_offset {
1733                                    state.set(state.get().with_last_scroll(
1734                                        scroll_handle.offset(),
1735                                        Some(Instant::now()),
1736                                    ));
1737                                    cx.notify(view_id);
1738                                }
1739                            }
1740                        }
1741                    });
1742
1743                    // A thumb follows the finger, unlike content panning. Claim
1744                    // this touch before the window turns it into wheel deltas.
1745                    window.on_mouse_event({
1746                        let state = scrollbar_state.clone();
1747                        let scroll_handle = self.scroll_handle.clone();
1748                        let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64);
1749                        move |event: &TouchDragEvent, phase, window, cx| {
1750                            if !phase.bubble() {
1751                                return;
1752                            }
1753                            if event.phase == TouchPhase::Started {
1754                                if !is_visible
1755                                    || window.default_prevented()
1756                                    || !thumb_bounds.contains(&event.start_position)
1757                                {
1758                                    return;
1759                                }
1760                                scroll_handle.start_drag();
1761                                state.set(state.get().with_drag_pos(
1762                                    axis,
1763                                    event.start_position - thumb_bounds.origin,
1764                                ));
1765                            } else if state.get().dragged_axis != Some(axis) {
1766                                return;
1767                            }
1768                            if event.phase != TouchPhase::Cancelled {
1769                                scroll_handle.set_offset(active_geometry.drag_offset(
1770                                    axis,
1771                                    event.position,
1772                                    state.get().drag_pos,
1773                                    scroll_handle.offset(),
1774                                ));
1775                            }
1776                            if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) {
1777                                scroll_handle.end_drag();
1778                                state.set(state.get().with_unset_drag_pos(Instant::now()));
1779                            }
1780                            window.prevent_default();
1781                            cx.stop_propagation();
1782                            if event.phase == TouchPhase::Moved {
1783                                state.notify_drag(
1784                                    Instant::now(),
1785                                    max_fps_duration,
1786                                    view_id,
1787                                    window,
1788                                    cx,
1789                                );
1790                            } else {
1791                                cx.notify(view_id);
1792                            }
1793                        }
1794                    });
1795
1796                    if is_visible {
1797                        window.on_mouse_event({
1798                            // The hitbox rather than the bounds, so that an
1799                            // element above the bar (a menu, a dialog) keeps
1800                            // the press.
1801                            let bar_hitbox = state.bar_hitbox.clone();
1802                            let state = scrollbar_state.clone();
1803                            let scroll_handle = self.scroll_handle.clone();
1804
1805                            move |event: &MouseDownEvent, phase, window, cx| {
1806                                if phase.bubble()
1807                                    && event.button == MouseButton::Left
1808                                    && bar_hitbox.is_hovered(window)
1809                                {
1810                                    cx.stop_propagation();
1811
1812                                    if thumb_bounds.contains(&event.position) {
1813                                        // click on the thumb bar, set the drag position
1814                                        let pos = event.position - thumb_bounds.origin;
1815
1816                                        scroll_handle.start_drag();
1817                                        state.set(state.get().with_drag_pos(axis, pos));
1818                                        // Active styling can change the inset or minimum length.
1819                                        // Keep the original grab point under the pointer on that frame.
1820                                        scroll_handle.set_offset(active_geometry.drag_offset(
1821                                            axis,
1822                                            event.position,
1823                                            pos,
1824                                            scroll_handle.offset(),
1825                                        ));
1826                                    } else {
1827                                        // click on the scrollbar, jump to the position
1828                                        // Set the thumb bar center to the click position
1829                                        let center =
1830                                            point(geometry.length / 2., geometry.length / 2.);
1831                                        scroll_handle.set_offset(geometry.drag_offset(
1832                                            axis,
1833                                            event.position,
1834                                            center,
1835                                            scroll_handle.offset(),
1836                                        ));
1837                                    }
1838
1839                                    cx.notify(view_id);
1840                                }
1841                            }
1842                        });
1843                    }
1844
1845                    window.on_mouse_event({
1846                        let bar_hitbox = state.bar_hitbox.clone();
1847                        let scroll_handle = self.scroll_handle.clone();
1848                        let state = scrollbar_state.clone();
1849                        let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64);
1850
1851                        move |event: &MouseMoveEvent, _, window, cx| {
1852                            let mut notify = false;
1853                            // When is hover to show mode or it was visible,
1854                            // we need to update the hovered state and increase the last_scroll_time.
1855                            let need_hover_to_update = is_hover_to_show || is_visible;
1856                            // Update hovered state for scrollbar
1857                            let bar_hovered = bar_hitbox.is_hovered(window);
1858                            if bar_hovered && need_hover_to_update {
1859                                let hover_changed = state.get().hovered_axis != Some(axis);
1860                                state.set(state.get().with_hovered(Some(axis), Instant::now()));
1861                                notify |= hover_changed;
1862                            } else if state.get().hovered_axis == Some(axis) {
1863                                state.set(state.get().with_hovered(None, Instant::now()));
1864                                notify = true;
1865                            }
1866
1867                            // Update hovered state for scrollbar thumb
1868                            if tracks_thumb_hover(mode, is_visible)
1869                                && bar_hovered
1870                                && thumb_bounds.contains(&event.position)
1871                            {
1872                                if state.get().hovered_on_thumb != Some(axis) {
1873                                    state.set(state.get().with_hovered_on_thumb(Some(axis)));
1874                                    notify = true;
1875                                }
1876                            } else {
1877                                if state.get().hovered_on_thumb == Some(axis) {
1878                                    state.set(state.get().with_hovered_on_thumb(None));
1879                                    notify = true;
1880                                }
1881                            }
1882
1883                            // Move thumb position on dragging
1884                            if state.get().dragged_axis == Some(axis) && event.dragging() {
1885                                // Stop the event propagation to avoid selecting text or other side effects.
1886                                cx.stop_propagation();
1887
1888                                let offset = active_geometry.drag_offset(
1889                                    axis,
1890                                    event.position,
1891                                    state.get().drag_pos,
1892                                    scroll_handle.offset(),
1893                                );
1894                                if scroll_handle.offset() != offset {
1895                                    // Coalesce rendering, never discard the newest pointer position.
1896                                    scroll_handle.set_offset(offset);
1897                                    notify = true;
1898                                }
1899                                if notify {
1900                                    state.notify_drag(
1901                                        Instant::now(),
1902                                        max_fps_duration,
1903                                        view_id,
1904                                        window,
1905                                        cx,
1906                                    );
1907                                }
1908                                return;
1909                            }
1910
1911                            if notify {
1912                                cx.notify(view_id);
1913                            }
1914                        }
1915                    });
1916
1917                    window.on_mouse_event({
1918                        let state = scrollbar_state.clone();
1919                        let scroll_handle = self.scroll_handle.clone();
1920
1921                        move |event: &MouseUpEvent, phase, _, cx| {
1922                            if phase.bubble()
1923                                && event.button == MouseButton::Left
1924                                && state.get().dragged_axis == Some(axis)
1925                            {
1926                                scroll_handle.set_offset(active_geometry.drag_offset(
1927                                    axis,
1928                                    event.position,
1929                                    state.get().drag_pos,
1930                                    scroll_handle.offset(),
1931                                ));
1932                                scroll_handle.end_drag();
1933                                state.set(state.get().with_unset_drag_pos(Instant::now()));
1934                                cx.notify(view_id);
1935                            }
1936                        }
1937                    });
1938                }
1939            },
1940        );
1941    }
1942}
1943
1944#[cfg(test)]
1945mod tests {
1946    use super::*;
1947
1948    use std::cell::{Cell, RefCell};
1949
1950    use gpui::{
1951        Context, InteractiveElement as _, Modifiers, MouseButton, ParentElement as _, Render,
1952        Styled as _, TestAppContext, VisualTestContext, div,
1953    };
1954
1955    #[test]
1956    fn thumb_radius_is_limited_by_its_actual_bounds() {
1957        let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.)));
1958        let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.)));
1959
1960        assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.));
1961        assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.));
1962        assert_eq!(
1963            clamp_thumb_radius(Pixels::ZERO, vertical_thumb),
1964            Pixels::ZERO
1965        );
1966    }
1967
1968    /// Timing standing in for what a styled layer projects. Base itself ships
1969    /// none of these; see [`motionless_base_snaps_every_transition`].
1970    const ENTER: Duration = Duration::from_millis(300);
1971    const EXIT: Duration = Duration::from_millis(500);
1972    const EXPAND: Duration = Duration::from_millis(300);
1973
1974    #[test]
1975    fn visibility_animation_uses_direction_specific_curves_and_durations() {
1976        let start = Instant::now();
1977        let mut animation = VisibilityAnimation::hidden(start);
1978
1979        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
1980        assert_eq!(animation.sample(start).opacity, 0.0);
1981        let entering = animation.sample(start + ENTER / 2).position;
1982        assert!(entering > 0.5, "ease-out must advance quickly");
1983        let entered = animation.sample(start + ENTER);
1984        assert_eq!(entered.opacity, 1.0);
1985        assert_eq!(entered.position, 1.0);
1986
1987        animation.set_visible(
1988            false,
1989            ScrollbarEntrance::SlideAndFade,
1990            ENTER,
1991            EXIT,
1992            start + ENTER,
1993        );
1994        let exiting = animation.sample(start + ENTER + EXIT / 2).opacity;
1995        assert!(exiting > 0.5, "ease-in must remain visible early in exit");
1996        assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0);
1997    }
1998
1999    #[test]
2000    fn entrance_fades_linearly_while_position_eases_out() {
2001        let start = Instant::now();
2002        let mut animation = VisibilityAnimation::hidden(start);
2003        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2004
2005        let halfway = animation.sample(start + ENTER / 2);
2006        assert!((halfway.opacity - 0.5).abs() < 0.001);
2007        assert!(halfway.position > halfway.opacity);
2008    }
2009
2010    #[test]
2011    fn fade_entrance_snaps_position_and_animates_opacity() {
2012        let start = Instant::now();
2013        let mut animation = VisibilityAnimation::hidden(start);
2014        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start);
2015
2016        let initial = animation.sample(start);
2017        assert_eq!(initial.opacity, 0.0);
2018        assert_eq!(initial.position, 1.0);
2019        let halfway = animation.sample(start + ENTER / 2);
2020        assert!((halfway.opacity - 0.5).abs() < 0.001);
2021        assert_eq!(halfway.position, 1.0);
2022    }
2023
2024    #[test]
2025    fn active_visibility_adopts_a_changed_entrance_policy() {
2026        let start = Instant::now();
2027        let halfway = start + ENTER / 2;
2028        let mut animation = VisibilityAnimation::hidden(start);
2029        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2030        let before = animation.sample(halfway);
2031
2032        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway);
2033        let after = animation.sample(halfway);
2034
2035        assert_eq!(
2036            after.opacity, before.opacity,
2037            "policy changes must not flash"
2038        );
2039        assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding");
2040    }
2041
2042    #[test]
2043    fn base_ships_no_motion_of_its_own() {
2044        let motion = ScrollbarMotion::default();
2045        assert_eq!(motion.enter(), Duration::ZERO);
2046        assert_eq!(motion.exit(), Duration::ZERO);
2047        assert_eq!(motion.expand(), Duration::ZERO);
2048        assert_eq!(motion.entrance(), ScrollbarEntrance::Fade);
2049        assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade);
2050        assert_eq!(
2051            motion.idle(),
2052            DEFAULT_IDLE,
2053            "the visibility hold is behavior, not motion, and must stay usable"
2054        );
2055    }
2056
2057    #[test]
2058    fn hover_mode_slides_only_when_the_thumb_is_hovered() {
2059        let motion = ScrollbarMotion::default()
2060            .with_entrance(ScrollbarEntrance::Fade)
2061            .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade);
2062
2063        assert_eq!(
2064            motion.entrance_for(ScrollbarMode::Hover, false),
2065            ScrollbarEntrance::Fade
2066        );
2067        assert_eq!(
2068            motion.entrance_for(ScrollbarMode::Hover, true),
2069            ScrollbarEntrance::SlideAndFade
2070        );
2071        assert_eq!(
2072            motion.entrance_for(ScrollbarMode::Scrolling, true),
2073            ScrollbarEntrance::Fade
2074        );
2075    }
2076
2077    #[test]
2078    fn hidden_scrolling_mode_does_not_track_thumb_hover() {
2079        assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false));
2080        assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true));
2081        assert!(tracks_thumb_hover(ScrollbarMode::Hover, false));
2082    }
2083
2084    #[test]
2085    fn visible_scrolling_mode_stays_visible_while_hovered() {
2086        assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false));
2087        assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true));
2088        assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false));
2089    }
2090
2091    #[test]
2092    fn motionless_base_snaps_every_transition() {
2093        let now = Instant::now();
2094        let motion = ScrollbarMotion::default();
2095        let mut visibility = VisibilityAnimation::hidden(now);
2096
2097        visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now);
2098        let shown = visibility.sample(now);
2099        assert_eq!(shown.opacity, 1.0);
2100        assert_eq!(shown.position, 1.0);
2101        assert!(!shown.running, "a motionless theme must request no frames");
2102        assert_eq!(
2103            visibility_translation(
2104                Axis::Vertical,
2105                ScrollbarPlacement::BottomRight,
2106                px(16.),
2107                shown.position
2108            ),
2109            Point::default()
2110        );
2111
2112        visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now);
2113        let hidden = visibility.sample(now);
2114        assert_eq!(hidden.opacity, 0.0);
2115        assert_eq!(hidden.position, 0.0);
2116        assert!(!hidden.running);
2117
2118        let mut width = WidthAnimation::new(now);
2119        assert_eq!(
2120            width.set_target(px(8.), motion.expand(), now),
2121            (px(8.), false)
2122        );
2123    }
2124
2125    #[test]
2126    fn a_zero_duration_settles_a_transition_already_in_flight() {
2127        let start = Instant::now();
2128        let mut animation = VisibilityAnimation::hidden(start);
2129        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2130
2131        // Reduced motion turns on midway through the entrance.
2132        let midway = start + ENTER / 2;
2133        animation.set_visible(
2134            true,
2135            ScrollbarEntrance::SlideAndFade,
2136            Duration::ZERO,
2137            Duration::ZERO,
2138            midway,
2139        );
2140        let settled = animation.sample(midway);
2141        assert_eq!(settled.opacity, 1.0);
2142        assert_eq!(settled.position, 1.0);
2143        assert!(!settled.running);
2144    }
2145
2146    #[test]
2147    fn thumb_expansion_animates_in_both_directions() {
2148        let start = Instant::now();
2149        let mut animation = WidthAnimation::new(start);
2150        assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false));
2151
2152        let (initial, running) = animation.set_target(px(8.), EXPAND, start);
2153        assert_eq!(initial, px(6.));
2154        assert!(running);
2155        let (expanded_halfway, _) = animation.sample(start + EXPAND / 2);
2156        assert!(expanded_halfway > px(7.));
2157
2158        let reversal = start + EXPAND / 2;
2159        let before = animation.sample(reversal).0;
2160        let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal);
2161        assert_eq!(after_reversal, before);
2162        assert!(running);
2163        assert_eq!(animation.sample(reversal + EXPAND).0, px(6.));
2164    }
2165
2166    #[test]
2167    fn reduced_motion_snaps_thumb_expansion() {
2168        let now = Instant::now();
2169        let mut animation = WidthAnimation::new(now);
2170        assert_eq!(
2171            animation.set_target(px(8.), Duration::ZERO, now),
2172            (px(8.), false)
2173        );
2174    }
2175
2176    #[test]
2177    fn visibility_translation_moves_toward_the_nearest_edge() {
2178        for (placement, vertical, horizontal) in [
2179            (ScrollbarPlacement::BottomRight, px(16.), px(16.)),
2180            (ScrollbarPlacement::BottomLeft, px(-16.), px(16.)),
2181            (ScrollbarPlacement::TopRight, px(16.), px(-16.)),
2182            (ScrollbarPlacement::TopLeft, px(-16.), px(-16.)),
2183        ] {
2184            assert_eq!(
2185                visibility_translation(Axis::Vertical, placement, px(16.), 0.0),
2186                point(vertical, px(0.))
2187            );
2188            assert_eq!(
2189                visibility_translation(Axis::Horizontal, placement, px(16.), 0.0),
2190                point(px(0.), horizontal)
2191            );
2192            assert_eq!(
2193                visibility_translation(Axis::Vertical, placement, px(16.), 1.0),
2194                Point::default()
2195            );
2196            assert_eq!(
2197                visibility_translation(Axis::Horizontal, placement, px(16.), 1.0),
2198                Point::default()
2199            );
2200        }
2201    }
2202
2203    #[test]
2204    fn visibility_animation_reverses_from_current_progress() {
2205        let start = Instant::now();
2206        let mut animation = VisibilityAnimation::hidden(start);
2207        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
2208        let reversal_time = start + Duration::from_millis(60);
2209        let before = animation.sample(reversal_time);
2210
2211        animation.set_visible(
2212            false,
2213            ScrollbarEntrance::SlideAndFade,
2214            ENTER,
2215            EXIT,
2216            reversal_time,
2217        );
2218        let reversed = animation.sample(reversal_time);
2219        assert_eq!(reversed.opacity, before.opacity);
2220        assert_eq!(reversed.position, before.position);
2221        let after = animation.sample(reversal_time + Duration::from_millis(10));
2222        assert!(after.opacity < before.opacity);
2223        assert!(after.position < before.position);
2224    }
2225
2226    #[test]
2227    fn always_hover_drag_and_recent_scroll_request_visibility() {
2228        let now = Instant::now();
2229        let idle = DEFAULT_IDLE;
2230        assert!(wants_visible(
2231            ScrollbarMode::Always,
2232            false,
2233            false,
2234            None,
2235            idle,
2236            now
2237        ));
2238        assert!(wants_visible(
2239            ScrollbarMode::Hover,
2240            true,
2241            false,
2242            None,
2243            idle,
2244            now
2245        ));
2246        assert!(wants_visible(
2247            ScrollbarMode::Scrolling,
2248            false,
2249            true,
2250            None,
2251            idle,
2252            now
2253        ));
2254        assert!(wants_visible(
2255            ScrollbarMode::Scrolling,
2256            false,
2257            false,
2258            Some(now - idle + Duration::from_millis(1)),
2259            idle,
2260            now,
2261        ));
2262        assert!(!wants_visible(
2263            ScrollbarMode::Scrolling,
2264            false,
2265            false,
2266            Some(now - idle),
2267            idle,
2268            now,
2269        ));
2270
2271        let mut settled = VisibilityAnimation::hidden(now - ENTER);
2272        settled.set_visible(
2273            true,
2274            ScrollbarEntrance::SlideAndFade,
2275            ENTER,
2276            EXIT,
2277            now - ENTER,
2278        );
2279        assert!(!settled.sample(now).running, "idle hold must not animate");
2280    }
2281
2282    #[test]
2283    fn leaving_hover_starts_a_fresh_idle_hold() {
2284        let entered_at = Instant::now();
2285        let left_at = entered_at + Duration::from_secs(5);
2286        let state = ScrollbarState::default().get();
2287
2288        let hovered = state.with_hovered(Some(Axis::Vertical), entered_at);
2289        assert_eq!(hovered.last_scroll_time, Some(entered_at));
2290        let left = hovered.with_hovered(None, left_at);
2291        assert_eq!(left.last_scroll_time, Some(left_at));
2292        assert!(wants_visible(
2293            ScrollbarMode::Hover,
2294            false,
2295            false,
2296            left.last_scroll_time,
2297            DEFAULT_IDLE,
2298            left_at + DEFAULT_IDLE - Duration::from_millis(1),
2299        ));
2300    }
2301
2302    #[test]
2303    fn idle_boundary_starts_the_exit_without_a_jump() {
2304        let activity = Instant::now();
2305        let exit_start = activity + DEFAULT_IDLE;
2306        let mut animation = VisibilityAnimation::hidden(activity - ENTER);
2307        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER);
2308        assert!(!wants_visible(
2309            ScrollbarMode::Scrolling,
2310            false,
2311            false,
2312            Some(activity),
2313            DEFAULT_IDLE,
2314            exit_start,
2315        ));
2316
2317        animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start);
2318        let start = animation.sample(exit_start);
2319        assert_eq!(start.opacity, 1.0);
2320        assert_eq!(start.position, 1.0);
2321        assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0);
2322    }
2323
2324    #[derive(Clone)]
2325    struct TestHandle {
2326        offset: Rc<Cell<Point<Pixels>>>,
2327        content_size: Size<Pixels>,
2328        drag_starts: Rc<Cell<usize>>,
2329        drag_ends: Rc<Cell<usize>>,
2330    }
2331
2332    impl TestHandle {
2333        fn new(content_size: Size<Pixels>) -> Self {
2334            Self {
2335                offset: Rc::new(Cell::new(Point::default())),
2336                content_size,
2337                drag_starts: Rc::new(Cell::new(0)),
2338                drag_ends: Rc::new(Cell::new(0)),
2339            }
2340        }
2341    }
2342
2343    impl ScrollbarHandle for TestHandle {
2344        fn viewport_bounds(&self) -> Bounds<Pixels> {
2345            Bounds::new(Point::default(), size(px(100.), px(100.)))
2346        }
2347
2348        fn offset(&self) -> Point<Pixels> {
2349            self.offset.get()
2350        }
2351
2352        fn set_offset(&self, offset: Point<Pixels>) {
2353            self.offset.set(offset);
2354        }
2355
2356        fn content_size(&self) -> Size<Pixels> {
2357            self.content_size
2358        }
2359
2360        fn start_drag(&self) {
2361            self.drag_starts.set(self.drag_starts.get() + 1);
2362        }
2363
2364        fn end_drag(&self) {
2365            self.drag_ends.set(self.drag_ends.get() + 1);
2366        }
2367    }
2368
2369    struct ScrollbarHarness {
2370        handle: TestHandle,
2371        axis: ScrollbarAxis,
2372        placement: ScrollbarPlacement,
2373        mode: ScrollbarMode,
2374        scroll_viewport_size: Option<Size<Pixels>>,
2375    }
2376
2377    impl Render for ScrollbarHarness {
2378        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
2379            let mut scrollbar = Scrollbar::new(&self.handle)
2380                .axis(self.axis)
2381                .placement(self.placement)
2382                .mode(self.mode);
2383            if let Some(size) = self.scroll_viewport_size {
2384                scrollbar = scrollbar.scroll_viewport_size(size);
2385            }
2386
2387            div().relative().size(px(100.)).child(scrollbar)
2388        }
2389    }
2390
2391    fn harness(
2392        cx: &mut TestAppContext,
2393        axis: ScrollbarAxis,
2394        mode: ScrollbarMode,
2395        content_size: Size<Pixels>,
2396    ) -> (&mut VisualTestContext, TestHandle) {
2397        harness_with_placement(cx, axis, ScrollbarPlacement::default(), mode, content_size)
2398    }
2399
2400    fn harness_with_placement(
2401        cx: &mut TestAppContext,
2402        axis: ScrollbarAxis,
2403        placement: ScrollbarPlacement,
2404        mode: ScrollbarMode,
2405        content_size: Size<Pixels>,
2406    ) -> (&mut VisualTestContext, TestHandle) {
2407        let handle = TestHandle::new(content_size);
2408        let (_, cx) = cx.add_window_view({
2409            let handle = handle.clone();
2410            move |_, _| ScrollbarHarness {
2411                handle,
2412                axis,
2413                placement,
2414                mode,
2415                scroll_viewport_size: None,
2416            }
2417        });
2418        cx.update(|window, cx| window.draw(cx).clear(cx));
2419        (cx, handle)
2420    }
2421
2422    #[gpui::test]
2423    fn thumb_drag_reaches_content_end_when_track_includes_padding(cx: &mut TestAppContext) {
2424        let handle = TestHandle::new(size(px(100.), px(160.)));
2425        let (_, cx) = cx.add_window_view({
2426            let handle = handle.clone();
2427            move |_, _| ScrollbarHarness {
2428                handle,
2429                axis: ScrollbarAxis::Vertical,
2430                placement: ScrollbarPlacement::default(),
2431                mode: ScrollbarMode::Always,
2432                scroll_viewport_size: Some(size(px(100.), px(80.))),
2433            }
2434        });
2435        cx.update(|window, cx| window.draw(cx).clear(cx));
2436
2437        cx.simulate_mouse_down(
2438            point(px(95.), px(20.)),
2439            MouseButton::Left,
2440            Modifiers::default(),
2441        );
2442        cx.update(|window, cx| window.draw(cx).clear(cx));
2443        cx.simulate_mouse_move(
2444            point(px(95.), px(99.)),
2445            Some(MouseButton::Left),
2446            Modifiers::default(),
2447        );
2448        cx.update(|window, cx| window.draw(cx).clear(cx));
2449        cx.simulate_mouse_up(
2450            point(px(95.), px(99.)),
2451            MouseButton::Left,
2452            Modifiers::default(),
2453        );
2454
2455        assert_eq!(handle.offset().y, px(-80.));
2456    }
2457
2458    #[test]
2459    fn explicit_viewport_bounds_override_handle_bounds() {
2460        let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.)));
2461        let scrollbar = Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.))))
2462            .viewport_bounds(expected);
2463
2464        assert_eq!(
2465            scrollbar.resolved_viewport_bounds(Bounds::default()),
2466            expected
2467        );
2468    }
2469
2470    #[test]
2471    fn layout_viewport_uses_current_element_bounds() {
2472        let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.)));
2473        let scrollbar =
2474            Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout();
2475
2476        assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected);
2477    }
2478
2479    #[test]
2480    fn typed_styles_are_fluent_and_include_geometry() {
2481        let track = gpui::hsla(0.1, 0.2, 0.3, 1.0);
2482        let border = gpui::hsla(0.2, 0.3, 0.4, 1.0);
2483        let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0);
2484        let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0);
2485        let active = gpui::hsla(0.5, 0.6, 0.7, 1.0);
2486        let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())).styles(|styles| {
2487            styles
2488                .track(|style| {
2489                    style
2490                        .width(px(14.))
2491                        .bg(track)
2492                        .border_color(border)
2493                        .when(false, |style| style.width(px(99.)))
2494                })
2495                .thumb(|style| {
2496                    style
2497                        .width(px(7.))
2498                        .inset(px(3.))
2499                        .radius(px(3.5))
2500                        .min_length(px(40.))
2501                        .bg(thumb)
2502                })
2503                .thumb_hover(|style| style.width(px(9.)).bg(hover))
2504                .thumb_active(|style| style.radius(px(4.5)).bg(active))
2505        });
2506
2507        assert_eq!(scrollbar.styles.track.background, Some(track));
2508        assert_eq!(scrollbar.styles.track.border, Some(border));
2509        assert_eq!(scrollbar.styles.track.width, Some(px(14.)));
2510        assert!(scrollbar.styles.thumb.background.is_some());
2511        assert_eq!(scrollbar.styles.thumb.width, Some(px(7.)));
2512        assert_eq!(scrollbar.styles.thumb.inset, Some(px(3.)));
2513        assert_eq!(scrollbar.styles.thumb.radius, Some(px(3.5)));
2514        assert_eq!(scrollbar.styles.thumb.min_length, Some(px(40.)));
2515        assert!(scrollbar.styles.thumb_hover.background.is_some());
2516        assert_eq!(scrollbar.styles.thumb_hover.width, Some(px(9.)));
2517        assert!(scrollbar.styles.thumb_active.background.is_some());
2518        assert_eq!(scrollbar.styles.thumb_active.radius, Some(px(4.5)));
2519    }
2520
2521    #[gpui::test]
2522    fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) {
2523        cx.update(|cx| {
2524            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()));
2525
2526            let light = gpui::hsla(0., 0., 0.04, 1.0);
2527            crate::Theme::global_mut(cx).tokens.colors.foreground = light;
2528            let (on_light, ..) = scrollbar.style_for_normal(cx);
2529
2530            let dark = gpui::hsla(0., 0., 0.98, 1.0);
2531            crate::Theme::global_mut(cx).tokens.colors.foreground = dark;
2532            let (on_dark, ..) = scrollbar.style_for_normal(cx);
2533
2534            assert_eq!(on_light, Background::from(light.alpha(0.35)));
2535            assert_eq!(on_dark, Background::from(dark.alpha(0.35)));
2536            // The point of the change: a thumb that never moved with the
2537            // palette was invisible on one of the two surfaces.
2538            assert_ne!(on_light, on_dark);
2539        });
2540    }
2541
2542    #[gpui::test]
2543    fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) {
2544        cx.update(|cx| {
2545            let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0);
2546            crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0);
2547
2548            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()))
2549                .styles(|styles| styles.thumb(|style| style.bg(chosen)));
2550            let (thumb, ..) = scrollbar.style_for_normal(cx);
2551
2552            assert_eq!(thumb, Background::from(chosen));
2553        });
2554    }
2555
2556    #[gpui::test]
2557    fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) {
2558        cx.update(|cx| {
2559            let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0);
2560            let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0);
2561            let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0);
2562
2563            crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new()
2564                .with_mode(ScrollbarMode::Always)
2565                .with_motion(ScrollbarMotion::default())
2566                .with_styles(
2567                    ScrollbarStyles::default()
2568                        .track(|style| style.width(px(13.)).bg(theme_track))
2569                        .thumb(|style| style.width(px(7.)).bg(theme_thumb)),
2570                );
2571
2572            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()))
2573                .styles(|styles| styles.thumb(|style| style.bg(instance_thumb)));
2574            let (thumb, track, _, width, _, _, _) = scrollbar.style_for_normal(cx);
2575
2576            assert_eq!(thumb, Background::from(instance_thumb));
2577            assert_eq!(track, theme_track);
2578            assert_eq!(width, px(7.));
2579            assert_eq!(cx.theme().scrollbar.styles().track.width, Some(px(13.)));
2580        });
2581    }
2582
2583    #[gpui::test]
2584    fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) {
2585        cx.update(|cx| {
2586            let handle = TestHandle::new(Size::default());
2587            let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling);
2588            let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always);
2589
2590            assert_eq!(scrolling.style_for_normal(cx).3, px(6.));
2591            assert_eq!(always.style_for_normal(cx).3, px(6.));
2592        });
2593    }
2594
2595    #[gpui::test]
2596    fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) {
2597        cx.update(|cx| {
2598            let handle = TestHandle::new(Size::default());
2599            for mode in [
2600                ScrollbarMode::Scrolling,
2601                ScrollbarMode::Hover,
2602                ScrollbarMode::Always,
2603            ] {
2604                let scrollbar = Scrollbar::new(&handle).mode(mode);
2605                assert_eq!(scrollbar.style_for_normal(cx).3, px(6.));
2606                assert_eq!(scrollbar.style_for_hovered_bar(cx).3, px(6.));
2607                assert_eq!(scrollbar.style_for_hovered_thumb(cx).3, px(8.));
2608            }
2609        });
2610    }
2611
2612    #[gpui::test]
2613    fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) {
2614        let (cx, vertical) = harness(
2615            cx,
2616            ScrollbarAxis::Vertical,
2617            ScrollbarMode::Always,
2618            size(px(100.), px(500.)),
2619        );
2620        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2621        assert!(vertical.offset().y < px(0.));
2622        assert_eq!(vertical.offset().x, px(0.));
2623    }
2624
2625    #[gpui::test]
2626    fn left_placement_puts_the_vertical_track_and_thumb_on_the_left_edge(cx: &mut TestAppContext) {
2627        let (cx, handle) = harness_with_placement(
2628            cx,
2629            ScrollbarAxis::Vertical,
2630            ScrollbarPlacement::BottomLeft,
2631            ScrollbarMode::Always,
2632            size(px(100.), px(500.)),
2633        );
2634        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2635        assert_eq!(handle.offset(), Point::default());
2636
2637        cx.simulate_mouse_down(
2638            point(px(14.), px(20.)),
2639            MouseButton::Left,
2640            Modifiers::default(),
2641        );
2642        assert_eq!(handle.drag_starts.get(), 1);
2643        assert_eq!(handle.offset(), Point::default());
2644        cx.simulate_mouse_move(
2645            point(px(14.), px(46.)),
2646            Some(MouseButton::Left),
2647            Modifiers::default(),
2648        );
2649        cx.simulate_mouse_up(
2650            point(px(14.), px(46.)),
2651            MouseButton::Left,
2652            Modifiers::default(),
2653        );
2654        assert_eq!(handle.offset(), point(px(0.), px(-200.)));
2655
2656        cx.simulate_click(point(px(5.), px(80.)), Modifiers::default());
2657        assert_eq!(handle.offset(), point(px(0.), px(-400.)));
2658    }
2659
2660    #[gpui::test]
2661    fn left_placement_starts_the_horizontal_track_after_the_vertical_one(cx: &mut TestAppContext) {
2662        let (cx, handle) = harness_with_placement(
2663            cx,
2664            ScrollbarAxis::Both,
2665            ScrollbarPlacement::BottomLeft,
2666            ScrollbarMode::Always,
2667            size(px(500.), px(500.)),
2668        );
2669        cx.simulate_click(point(px(50.), px(95.)), Modifiers::default());
2670        assert_eq!(handle.drag_starts.get(), 1);
2671        assert_eq!(handle.offset(), Point::default());
2672
2673        cx.simulate_click(point(px(99.), px(95.)), Modifiers::default());
2674        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2675    }
2676
2677    #[gpui::test]
2678    fn top_placement_puts_the_horizontal_track_and_thumb_on_the_top_edge(cx: &mut TestAppContext) {
2679        let (cx, handle) = harness_with_placement(
2680            cx,
2681            ScrollbarAxis::Horizontal,
2682            ScrollbarPlacement::TopRight,
2683            ScrollbarMode::Always,
2684            size(px(500.), px(100.)),
2685        );
2686        cx.simulate_click(point(px(80.), px(95.)), Modifiers::default());
2687        assert_eq!(handle.offset(), Point::default());
2688
2689        cx.simulate_mouse_down(
2690            point(px(20.), px(14.)),
2691            MouseButton::Left,
2692            Modifiers::default(),
2693        );
2694        assert_eq!(handle.drag_starts.get(), 1);
2695        assert_eq!(handle.offset(), Point::default());
2696        cx.simulate_mouse_move(
2697            point(px(46.), px(14.)),
2698            Some(MouseButton::Left),
2699            Modifiers::default(),
2700        );
2701        cx.simulate_mouse_up(
2702            point(px(46.), px(14.)),
2703            MouseButton::Left,
2704            Modifiers::default(),
2705        );
2706        assert_eq!(handle.offset(), point(px(-200.), px(0.)));
2707
2708        cx.simulate_click(point(px(90.), px(5.)), Modifiers::default());
2709        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2710    }
2711
2712    #[gpui::test]
2713    fn top_right_placement_ends_the_horizontal_track_before_the_vertical_one(
2714        cx: &mut TestAppContext,
2715    ) {
2716        let (cx, handle) = harness_with_placement(
2717            cx,
2718            ScrollbarAxis::Both,
2719            ScrollbarPlacement::TopRight,
2720            ScrollbarMode::Always,
2721            size(px(500.), px(500.)),
2722        );
2723        cx.simulate_click(point(px(60.), px(5.)), Modifiers::default());
2724        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2725
2726        cx.simulate_click(point(px(95.), px(90.)), Modifiers::default());
2727        assert_eq!(handle.offset(), point(px(-400.), px(-400.)));
2728        cx.simulate_click(point(px(95.), px(5.)), Modifiers::default());
2729        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2730    }
2731
2732    #[gpui::test]
2733    fn top_left_placement_starts_the_horizontal_track_after_the_vertical_one(
2734        cx: &mut TestAppContext,
2735    ) {
2736        let (cx, handle) = harness_with_placement(
2737            cx,
2738            ScrollbarAxis::Both,
2739            ScrollbarPlacement::TopLeft,
2740            ScrollbarMode::Always,
2741            size(px(500.), px(500.)),
2742        );
2743        cx.simulate_click(point(px(50.), px(5.)), Modifiers::default());
2744        assert_eq!(handle.drag_starts.get(), 1);
2745        assert_eq!(handle.offset(), Point::default());
2746
2747        cx.simulate_click(point(px(99.), px(5.)), Modifiers::default());
2748        assert_eq!(handle.offset(), point(px(-400.), px(0.)));
2749
2750        cx.simulate_click(point(px(5.), px(95.)), Modifiers::default());
2751        assert_eq!(handle.offset(), point(px(-400.), px(-400.)));
2752    }
2753
2754    #[gpui::test]
2755    fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) {
2756        let (cx, horizontal) = harness(
2757            cx,
2758            ScrollbarAxis::Horizontal,
2759            ScrollbarMode::Always,
2760            size(px(500.), px(100.)),
2761        );
2762        cx.simulate_click(point(px(80.), px(95.)), Modifiers::default());
2763        assert!(horizontal.offset().x < px(0.));
2764        assert_eq!(horizontal.offset().y, px(0.));
2765    }
2766
2767    #[gpui::test]
2768    fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) {
2769        let (cx, handle) = harness(
2770            cx,
2771            ScrollbarAxis::Both,
2772            ScrollbarMode::Always,
2773            size(px(100.), px(100.)),
2774        );
2775        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2776        assert_eq!(handle.offset(), Point::default());
2777    }
2778
2779    #[gpui::test]
2780    fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) {
2781        let (cx, handle) = harness(
2782            cx,
2783            ScrollbarAxis::Vertical,
2784            ScrollbarMode::Hover,
2785            size(px(100.), px(500.)),
2786        );
2787        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2788        assert_eq!(handle.offset(), Point::default());
2789    }
2790
2791    #[gpui::test]
2792    fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) {
2793        let (cx, handle) = harness(
2794            cx,
2795            ScrollbarAxis::Vertical,
2796            ScrollbarMode::Hover,
2797            size(px(100.), px(500.)),
2798        );
2799        cx.simulate_mouse_down(
2800            point(px(95.), px(20.)),
2801            MouseButton::Left,
2802            Modifiers::default(),
2803        );
2804        cx.simulate_mouse_move(
2805            point(px(95.), px(70.)),
2806            Some(MouseButton::Left),
2807            Modifiers::default(),
2808        );
2809        cx.simulate_mouse_up(
2810            point(px(95.), px(70.)),
2811            MouseButton::Left,
2812            Modifiers::default(),
2813        );
2814
2815        assert_eq!(handle.drag_starts.get(), 0);
2816        assert_eq!(handle.drag_ends.get(), 0);
2817        assert_eq!(handle.offset(), Point::default());
2818    }
2819
2820    /// A vertical scrollbar with an occluding element over part of it, as a
2821    /// menu or dialog would be.
2822    struct CoveredHarness {
2823        handle: TestHandle,
2824        mode: ScrollbarMode,
2825        cover: Bounds<Pixels>,
2826    }
2827
2828    impl Render for CoveredHarness {
2829        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
2830            div()
2831                .relative()
2832                .size(px(100.))
2833                .child(
2834                    Scrollbar::new(&self.handle)
2835                        .axis(ScrollbarAxis::Vertical)
2836                        .mode(self.mode),
2837                )
2838                .child(
2839                    div()
2840                        .absolute()
2841                        .left(self.cover.left())
2842                        .top(self.cover.top())
2843                        .w(self.cover.size.width)
2844                        .h(self.cover.size.height)
2845                        .occlude(),
2846                )
2847        }
2848    }
2849
2850    fn covered_harness(
2851        cx: &mut TestAppContext,
2852        mode: ScrollbarMode,
2853        cover: Bounds<Pixels>,
2854    ) -> (&mut VisualTestContext, TestHandle) {
2855        let handle = TestHandle::new(size(px(100.), px(500.)));
2856        let (_, cx) = cx.add_window_view({
2857            let handle = handle.clone();
2858            move |_, _| CoveredHarness {
2859                handle,
2860                mode,
2861                cover,
2862            }
2863        });
2864        cx.update(|window, cx| window.draw(cx).clear(cx));
2865        (cx, handle)
2866    }
2867
2868    #[gpui::test]
2869    fn a_press_on_an_element_over_the_track_is_left_to_it(cx: &mut TestAppContext) {
2870        let cover = Bounds::new(point(px(50.), px(60.)), size(px(50.), px(40.)));
2871        let (cx, handle) = covered_harness(cx, ScrollbarMode::Always, cover);
2872        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2873        assert_eq!(handle.offset(), Point::default());
2874
2875        // The track left uncovered still takes a press.
2876        cx.simulate_click(point(px(95.), px(50.)), Modifiers::default());
2877        assert!(handle.offset().y < px(0.));
2878    }
2879
2880    #[gpui::test]
2881    fn hovering_an_element_over_a_hover_scrollbar_does_not_reveal_it(cx: &mut TestAppContext) {
2882        let cover = Bounds::new(point(px(50.), px(0.)), size(px(50.), px(50.)));
2883        let (cx, handle) = covered_harness(cx, ScrollbarMode::Hover, cover);
2884        cx.simulate_mouse_move(point(px(95.), px(20.)), None, Modifiers::default());
2885        cx.run_until_parked();
2886
2887        // Uncovered, but the bar never showed, so it takes no press.
2888        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2889        assert_eq!(handle.offset(), Point::default());
2890    }
2891
2892    #[gpui::test]
2893    fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) {
2894        let (cx, handle) = harness(
2895            cx,
2896            ScrollbarAxis::Vertical,
2897            ScrollbarMode::Hover,
2898            size(px(100.), px(500.)),
2899        );
2900        // Base ships no motion, so the reveal is immediate.
2901        cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default());
2902        cx.run_until_parked();
2903
2904        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2905        assert!(handle.offset().y < px(0.));
2906    }
2907
2908    #[gpui::test]
2909    fn drag_notifications_are_throttled_and_deliver_the_latest_offset(cx: &mut TestAppContext) {
2910        let handle = TestHandle::new(size(px(100.), px(1000.)));
2911        let (view, cx) = cx.add_window_view({
2912            let handle = handle.clone();
2913            move |_, _| ScrollbarHarness {
2914                handle,
2915                axis: ScrollbarAxis::Vertical,
2916                placement: ScrollbarPlacement::default(),
2917                mode: ScrollbarMode::Always,
2918                scroll_viewport_size: None,
2919            }
2920        });
2921        cx.update(|window, cx| window.draw(cx).clear(cx));
2922        let observed = Rc::new(RefCell::new(Vec::new()));
2923        let _subscription = cx.update(|_, cx| {
2924            let observed = observed.clone();
2925            let handle = handle.clone();
2926            cx.observe(&view, move |_, _| {
2927                observed.borrow_mut().push(handle.offset().y)
2928            })
2929        });
2930        let state = ScrollbarState::default();
2931        let now = Instant::now();
2932        let interval = Duration::from_secs_f64(1. / 30.);
2933        let mut inner = state.get().with_drag_pos(Axis::Vertical, Point::default());
2934        inner.last_update = now;
2935        state.set(inner);
2936        let update = |offset, elapsed, cx: &mut VisualTestContext| {
2937            handle.set_offset(point(px(0.), px(offset)));
2938            cx.update(|window, cx| {
2939                state.notify_drag(now + elapsed, interval, view.entity_id(), window, cx)
2940            });
2941            cx.run_until_parked();
2942        };
2943        update(-10., Duration::ZERO, cx);
2944        cx.executor().advance_clock(Duration::from_millis(16));
2945        update(-20., Duration::from_millis(16), cx);
2946        update(-30., Duration::from_millis(16), cx);
2947        // Rendering at 120 Hz must not bypass the configured 30 Hz timer.
2948        cx.update(|window, cx| {
2949            window.simulate_next_frame(cx);
2950        });
2951        cx.run_until_parked();
2952        assert!(observed.borrow().is_empty());
2953        cx.executor().advance_clock(Duration::from_millis(16));
2954        cx.run_until_parked();
2955        assert!(observed.borrow().is_empty());
2956        cx.executor().advance_clock(Duration::from_millis(2));
2957        cx.run_until_parked();
2958        assert_eq!(
2959            *observed.borrow(),
2960            vec![px(-30.)],
2961            "one trailing notification must see the newest offset even when movement stops"
2962        );
2963
2964        // A second burst gets its own interval, and release invalidates its timer.
2965        let next = state.get().last_update;
2966        handle.set_offset(point(px(0.), px(-40.)));
2967        cx.update(|window, cx| state.notify_drag(next, interval, view.entity_id(), window, cx));
2968        cx.run_until_parked();
2969        state.set(state.get().with_unset_drag_pos(Instant::now()));
2970        handle.set_offset(point(px(0.), px(-50.)));
2971        cx.update(|_, cx| cx.notify(view.entity_id()));
2972        assert_eq!(*observed.borrow(), vec![px(-30.), px(-50.)]);
2973        cx.executor().advance_clock(interval);
2974        cx.run_until_parked();
2975        assert_eq!(
2976            *observed.borrow(),
2977            vec![px(-30.), px(-50.)],
2978            "release must not leave a stale trailing notification"
2979        );
2980    }
2981
2982    #[test]
2983    fn full_track_thumb_does_not_reset_the_scroll_offset() {
2984        let geometry =
2985            ThumbGeometry::new(px(20.), px(40.), px(40.), px(500.), px(0.), px(4.), px(64.));
2986        let offset = point(px(0.), px(-100.));
2987        assert_eq!(
2988            geometry.drag_offset(
2989                Axis::Vertical,
2990                point(px(0.), px(50.)),
2991                point(px(0.), px(8.)),
2992                offset
2993            ),
2994            offset
2995        );
2996    }
2997
2998    #[test]
2999    fn thumb_geometry_maps_content_viewport_to_padded_track() {
3000        let geometry =
3001            ThumbGeometry::new(px(20.), px(96.), px(80.), px(160.), px(0.), px(0.), px(0.));
3002
3003        assert_eq!(geometry.length, px(48.));
3004        assert_eq!(geometry.travel, px(48.));
3005        assert_eq!(geometry.extent, px(80.));
3006        assert_eq!(geometry.offset(px(68.), px(0.)), px(-80.));
3007
3008        let barely_overflowing =
3009            ThumbGeometry::new(px(20.), px(96.), px(80.), px(85.), px(0.), px(0.), px(0.));
3010        assert_eq!(barely_overflowing.extent, px(5.));
3011        assert!(barely_overflowing.travel > px(0.));
3012        assert_eq!(
3013            barely_overflowing.offset(px(20.) + barely_overflowing.travel, px(0.)),
3014            px(-5.)
3015        );
3016    }
3017
3018    #[gpui::test]
3019    fn repeated_touch_and_mouse_drags_keep_the_painted_grab_point(cx: &mut TestAppContext) {
3020        struct Probe {
3021            scrollbar: Scrollbar,
3022            painted: Rc<Cell<Bounds<Pixels>>>,
3023        }
3024        impl Element for Probe {
3025            type RequestLayoutState = ();
3026            type PrepaintState = PrepaintState;
3027            fn id(&self) -> Option<ElementId> {
3028                Element::id(&self.scrollbar)
3029            }
3030            fn source_location(&self) -> Option<&'static Location<'static>> {
3031                None
3032            }
3033            fn request_layout(
3034                &mut self,
3035                id: Option<&GlobalElementId>,
3036                inspector: Option<&InspectorElementId>,
3037                window: &mut Window,
3038                cx: &mut App,
3039            ) -> (LayoutId, ()) {
3040                self.scrollbar.request_layout(id, inspector, window, cx)
3041            }
3042            fn prepaint(
3043                &mut self,
3044                id: Option<&GlobalElementId>,
3045                inspector: Option<&InspectorElementId>,
3046                bounds: Bounds<Pixels>,
3047                layout: &mut (),
3048                window: &mut Window,
3049                cx: &mut App,
3050            ) -> PrepaintState {
3051                let state = self
3052                    .scrollbar
3053                    .prepaint(id, inspector, bounds, layout, window, cx);
3054                self.painted.set(state.states[0].thumb_fill_bounds);
3055                state
3056            }
3057            fn paint(
3058                &mut self,
3059                id: Option<&GlobalElementId>,
3060                inspector: Option<&InspectorElementId>,
3061                bounds: Bounds<Pixels>,
3062                layout: &mut (),
3063                state: &mut PrepaintState,
3064                window: &mut Window,
3065                cx: &mut App,
3066            ) {
3067                self.scrollbar
3068                    .paint(id, inspector, bounds, layout, state, window, cx);
3069            }
3070        }
3071        struct Root {
3072            handle: TestHandle,
3073            painted: Rc<Cell<Bounds<Pixels>>>,
3074            axis: ScrollbarAxis,
3075            viewport: Bounds<Pixels>,
3076        }
3077        impl Render for Root {
3078            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl gpui::IntoElement {
3079                div().size(px(400.)).child(Probe {
3080                    scrollbar: Scrollbar::new(&self.handle)
3081                        .axis(self.axis)
3082                        .mode(ScrollbarMode::Always)
3083                        .viewport_bounds(self.viewport)
3084                        .styles(|style| {
3085                            style
3086                                .thumb(|style| style.inset(px(6.)).min_length(px(64.)))
3087                                .thumb_active(|style| style.inset(px(3.)).min_length(px(72.)))
3088                        }),
3089                    painted: self.painted.clone(),
3090                })
3091            }
3092        }
3093        for touch in [true, false] {
3094            for vertical in [true, false] {
3095                for (origin, viewport_size, content_size) in [
3096                    (Point::default(), 200., 1000.),
3097                    (point(px(30.), px(40.)), 240., 500.),
3098                ] {
3099                    let handle = TestHandle::new(size(px(content_size), px(content_size)));
3100                    handle.set_offset(point(px(-100.), px(-100.)));
3101                    let painted = Rc::new(Cell::new(Bounds::default()));
3102                    let (_, cx) = cx.add_window_view({
3103                        let handle = handle.clone();
3104                        let painted = painted.clone();
3105                        move |_, _| Root {
3106                            handle,
3107                            painted,
3108                            axis: if vertical {
3109                                ScrollbarAxis::Vertical
3110                            } else {
3111                                ScrollbarAxis::Both
3112                            },
3113                            viewport: Bounds::new(
3114                                origin,
3115                                size(px(viewport_size), px(viewport_size)),
3116                            ),
3117                        }
3118                    });
3119                    cx.update(|window, cx| window.draw(cx).clear(cx));
3120                    let initial = painted.get();
3121                    let start = initial.center();
3122                    let grab = if vertical {
3123                        start.y - initial.origin.y
3124                    } else {
3125                        start.x - initial.origin.x
3126                    };
3127                    let axis_delta = |value| {
3128                        if vertical {
3129                            point(px(0.), px(value))
3130                        } else {
3131                            point(px(value), px(0.))
3132                        }
3133                    };
3134                    let axis_value =
3135                        |point: Point<Pixels>| if vertical { point.y } else { point.x };
3136                    let started_position = if touch { start + axis_delta(5.) } else { start };
3137                    if touch {
3138                        cx.simulate_event(TouchDragEvent {
3139                            phase: TouchPhase::Started,
3140                            start_position: start,
3141                            position: started_position,
3142                        });
3143                    } else {
3144                        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
3145                    }
3146                    cx.update(|window, cx| window.draw(cx).clear(cx));
3147                    assert!(
3148                        (axis_value(painted.get().origin) + grab - axis_value(started_position))
3149                            .abs()
3150                            < px(0.1),
3151                        "starting must preserve the grab point and first displacement"
3152                    );
3153                    let mut reference_offset = px(0.);
3154                    let mut offset_per_pixel = 0.;
3155                    for delta in [0., 24., -8., 32., -10., 8., 0.] {
3156                        let position = start + axis_delta(delta);
3157                        if touch {
3158                            cx.simulate_event(TouchDragEvent {
3159                                phase: TouchPhase::Moved,
3160                                start_position: start,
3161                                position,
3162                            });
3163                        } else {
3164                            cx.simulate_mouse_move(
3165                                position,
3166                                Some(MouseButton::Left),
3167                                Modifiers::default(),
3168                            );
3169                        }
3170                        cx.update(|window, cx| window.draw(cx).clear(cx));
3171                        if delta == 0. {
3172                            reference_offset = axis_value(handle.offset());
3173                        }
3174                        if delta == 24. {
3175                            offset_per_pixel =
3176                                (axis_value(handle.offset()) - reference_offset) / px(24.);
3177                        }
3178                        let actual = if vertical {
3179                            painted.get().origin.y + grab
3180                        } else {
3181                            painted.get().origin.x + grab
3182                        };
3183                        let expected = if vertical { position.y } else { position.x };
3184                        assert!(
3185                            (actual - expected).abs() < px(0.1),
3186                            "touch={touch} vertical={vertical} delta={delta}: painted grab {actual:?}, pointer {expected:?}"
3187                        );
3188                    }
3189                    // Release contains a final displacement without an intervening move.
3190                    let expected_offset = reference_offset + px(12.) * offset_per_pixel;
3191                    if touch {
3192                        cx.simulate_event(TouchDragEvent {
3193                            phase: TouchPhase::Ended,
3194                            start_position: start,
3195                            position: start + axis_delta(12.),
3196                        });
3197                    } else {
3198                        cx.simulate_mouse_up(
3199                            start + axis_delta(12.),
3200                            MouseButton::Left,
3201                            Modifiers::default(),
3202                        );
3203                    }
3204                    assert!(
3205                        (axis_value(handle.offset()) - expected_offset).abs() < px(0.1),
3206                        "release must flush the last displacement"
3207                    );
3208                    let released_offset = handle.offset();
3209                    cx.update(|window, cx| window.draw(cx).clear(cx));
3210                    assert_eq!(
3211                        handle.offset(),
3212                        released_offset,
3213                        "leaving active styling must not scroll"
3214                    );
3215                }
3216            }
3217        }
3218    }
3219
3220    #[gpui::test]
3221    fn touch_thumb_drag_moves_down_and_cancel_releases_handle(cx: &mut TestAppContext) {
3222        let (cx, handle) = harness(
3223            cx,
3224            ScrollbarAxis::Vertical,
3225            ScrollbarMode::Always,
3226            size(px(100.), px(500.)),
3227        );
3228        let start_position = point(px(95.), px(20.));
3229        for (phase, position) in [
3230            (TouchPhase::Started, start_position),
3231            (TouchPhase::Moved, point(px(95.), px(45.))),
3232            (TouchPhase::Cancelled, point(px(95.), px(45.))),
3233        ] {
3234            cx.simulate_event(TouchDragEvent {
3235                phase,
3236                start_position,
3237                position,
3238            });
3239        }
3240        assert!(
3241            handle.offset().y < px(0.),
3242            "thumb down must scroll toward later content"
3243        );
3244        assert_eq!(handle.offset().x, px(0.));
3245        assert_eq!(handle.drag_starts.get(), 1);
3246        assert_eq!(handle.drag_ends.get(), 1);
3247    }
3248
3249    #[gpui::test]
3250    fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) {
3251        let (cx, handle) = harness(
3252            cx,
3253            ScrollbarAxis::Vertical,
3254            ScrollbarMode::Always,
3255            size(px(100.), px(500.)),
3256        );
3257        cx.simulate_mouse_down(
3258            point(px(95.), px(20.)),
3259            MouseButton::Left,
3260            Modifiers::default(),
3261        );
3262        cx.simulate_mouse_move(
3263            point(px(95.), px(70.)),
3264            Some(MouseButton::Left),
3265            Modifiers::default(),
3266        );
3267        cx.simulate_mouse_up(
3268            point(px(95.), px(70.)),
3269            MouseButton::Left,
3270            Modifiers::default(),
3271        );
3272
3273        assert_eq!(handle.drag_starts.get(), 1);
3274        assert_eq!(handle.drag_ends.get(), 1);
3275    }
3276
3277    #[gpui::test]
3278    fn only_the_primary_button_drags_or_jumps(cx: &mut TestAppContext) {
3279        let (cx, handle) = harness(
3280            cx,
3281            ScrollbarAxis::Vertical,
3282            ScrollbarMode::Always,
3283            size(px(100.), px(500.)),
3284        );
3285        for button in [MouseButton::Right, MouseButton::Middle] {
3286            // Thumb press, then the track.
3287            for y in [px(20.), px(80.)] {
3288                cx.simulate_mouse_down(point(px(95.), y), button, Modifiers::default());
3289                cx.simulate_mouse_up(point(px(95.), y), button, Modifiers::default());
3290            }
3291        }
3292        assert_eq!(handle.drag_starts.get(), 0);
3293        assert_eq!(handle.offset(), Point::default());
3294
3295        // A secondary release does not end a primary drag.
3296        cx.simulate_mouse_down(
3297            point(px(95.), px(20.)),
3298            MouseButton::Left,
3299            Modifiers::default(),
3300        );
3301        cx.simulate_mouse_up(
3302            point(px(95.), px(20.)),
3303            MouseButton::Right,
3304            Modifiers::default(),
3305        );
3306        assert_eq!(handle.drag_ends.get(), 0);
3307        cx.simulate_mouse_up(
3308            point(px(95.), px(20.)),
3309            MouseButton::Left,
3310            Modifiers::default(),
3311        );
3312        assert_eq!(handle.drag_ends.get(), 1);
3313    }
3314}