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, ColorExt as _, ContentMask, CursorStyle,
12    Edges, Element, ElementId, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId,
13    IntoElement, IsZero, LayoutId, ListState, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
14    PaintQuad, Pixels, Point, Position, ScrollHandle, ScrollWheelEvent, Size, Style,
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    idle_timer_scheduled: bool,
162    visibility: VisibilityAnimation,
163    vertical_width: WidthAnimation,
164    horizontal_width: WidthAnimation,
165}
166
167impl Default for ScrollbarState {
168    fn default() -> Self {
169        let now = Instant::now();
170        Self(Rc::new(Cell::new(ScrollbarStateInner {
171            hovered_axis: None,
172            hovered_on_thumb: None,
173            dragged_axis: None,
174            drag_pos: point(px(0.), px(0.)),
175            last_scroll_offset: point(px(0.), px(0.)),
176            last_scroll_time: None,
177            last_update: now,
178            idle_timer_scheduled: false,
179            visibility: VisibilityAnimation::hidden(now),
180            vertical_width: WidthAnimation::new(now),
181            horizontal_width: WidthAnimation::new(now),
182        })))
183    }
184}
185
186#[derive(Debug, Clone, Copy)]
187struct ScalarTransition<T> {
188    from: T,
189    target: T,
190    started_at: Instant,
191    duration: Duration,
192}
193
194impl<T: Copy + PartialEq> ScalarTransition<T> {
195    fn settled(value: T, now: Instant) -> Self {
196        Self {
197            from: value,
198            target: value,
199            started_at: now,
200            duration: Duration::ZERO,
201        }
202    }
203
204    fn sample(&self, now: Instant, interpolate: impl FnOnce(T, T, f32) -> T) -> (T, bool) {
205        if self.from == self.target || self.duration.is_zero() {
206            return (self.target, false);
207        }
208        let linear = now.saturating_duration_since(self.started_at).as_secs_f32()
209            / self.duration.as_secs_f32();
210        if linear >= 1.0 {
211            (self.target, false)
212        } else {
213            (
214                interpolate(self.from, self.target, linear.clamp(0.0, 1.0)),
215                true,
216            )
217        }
218    }
219
220    fn start(&mut self, from: T, target: T, duration: Duration, now: Instant) {
221        self.from = from;
222        self.target = target;
223        self.started_at = now;
224        self.duration = duration;
225    }
226
227    fn settle(&mut self, target: T, now: Instant) {
228        self.start(target, target, Duration::ZERO, now);
229    }
230}
231
232#[derive(Debug, Clone, Copy)]
233struct WidthAnimation {
234    transition: ScalarTransition<Pixels>,
235    initialized: bool,
236}
237
238impl WidthAnimation {
239    fn new(now: Instant) -> Self {
240        Self {
241            transition: ScalarTransition::settled(Pixels::ZERO, now),
242            initialized: false,
243        }
244    }
245
246    fn sample(&self, now: Instant) -> (Pixels, bool) {
247        self.transition.sample(now, |from, target, linear| {
248            from + (target - from) * ease_out_cubic(linear)
249        })
250    }
251
252    /// Move toward `target` over `duration`. A zero duration adopts the target
253    /// immediately, which is how reduced motion and a motionless theme arrive here.
254    fn set_target(&mut self, target: Pixels, duration: Duration, now: Instant) -> (Pixels, bool) {
255        if duration.is_zero() || !self.initialized {
256            self.transition.settle(target, now);
257            self.initialized = true;
258        } else if self.transition.target != target {
259            let from = self.sample(now).0;
260            self.transition.start(from, target, duration, now);
261        }
262        self.sample(now)
263    }
264}
265
266/// How a scrollbar becomes visible.
267///
268/// The styled layer chooses the choreography; Base only plays it.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
270pub enum ScrollbarEntrance {
271    /// Fade in without moving.
272    #[default]
273    Fade,
274    /// Slide in from the nearest edge while fading.
275    SlideAndFade,
276}
277
278/// Motion tokens used by [`Scrollbar`].
279///
280/// Base installs no motion of its own: every transition duration defaults to
281/// zero, so visibility and thumb width snap. Product timing belongs to the
282/// styled layer, which projects it through [`crate::ScrollbarTheme`].
283#[derive(Debug, Clone, Copy, PartialEq)]
284pub struct ScrollbarMotion {
285    idle: Duration,
286    enter: Duration,
287    exit: Duration,
288    expand: Duration,
289    entrance: ScrollbarEntrance,
290    thumb_hover_entrance: ScrollbarEntrance,
291}
292
293impl Default for ScrollbarMotion {
294    fn default() -> Self {
295        Self {
296            idle: DEFAULT_IDLE,
297            enter: Duration::ZERO,
298            exit: Duration::ZERO,
299            expand: Duration::ZERO,
300            entrance: ScrollbarEntrance::Fade,
301            thumb_hover_entrance: ScrollbarEntrance::Fade,
302        }
303    }
304}
305
306impl ScrollbarMotion {
307    /// How long visibility is held after the last scroll, drag, or hover.
308    pub fn with_idle(mut self, idle: Duration) -> Self {
309        self.idle = idle;
310        self
311    }
312
313    /// How long the scrollbar takes to become fully visible.
314    pub fn with_enter(mut self, enter: Duration) -> Self {
315        self.enter = enter;
316        self
317    }
318
319    /// How long the scrollbar takes to fade away once the idle hold expires.
320    pub fn with_exit(mut self, exit: Duration) -> Self {
321        self.exit = exit;
322        self
323    }
324
325    /// How long the thumb takes to reach a new width.
326    pub fn with_expand(mut self, expand: Duration) -> Self {
327        self.expand = expand;
328        self
329    }
330
331    /// Which entrance choreography to play.
332    pub fn with_entrance(mut self, entrance: ScrollbarEntrance) -> Self {
333        self.entrance = entrance;
334        self
335    }
336
337    /// Which entrance choreography to play when hover reveals the thumb.
338    pub fn with_thumb_hover_entrance(mut self, entrance: ScrollbarEntrance) -> Self {
339        self.thumb_hover_entrance = entrance;
340        self
341    }
342
343    pub fn idle(&self) -> Duration {
344        self.idle
345    }
346
347    pub fn enter(&self) -> Duration {
348        self.enter
349    }
350
351    pub fn exit(&self) -> Duration {
352        self.exit
353    }
354
355    pub fn expand(&self) -> Duration {
356        self.expand
357    }
358
359    pub fn entrance(&self) -> ScrollbarEntrance {
360        self.entrance
361    }
362
363    pub fn thumb_hover_entrance(&self) -> ScrollbarEntrance {
364        self.thumb_hover_entrance
365    }
366
367    fn entrance_for(&self, mode: ScrollbarMode, thumb_hovered: bool) -> ScrollbarEntrance {
368        if mode.is_hover() && thumb_hovered {
369            self.thumb_hover_entrance
370        } else {
371            self.entrance
372        }
373    }
374}
375
376#[derive(Debug, Clone, Copy)]
377struct VisibilityAnimation {
378    opacity: ScalarTransition<f32>,
379    position: ScalarTransition<f32>,
380    entrance: ScrollbarEntrance,
381}
382
383#[derive(Debug, Clone, Copy)]
384struct VisibilitySample {
385    opacity: f32,
386    position: f32,
387    running: bool,
388}
389
390impl VisibilityAnimation {
391    fn hidden(now: Instant) -> Self {
392        Self {
393            opacity: ScalarTransition::settled(0.0, now),
394            position: ScalarTransition::settled(0.0, now),
395            entrance: ScrollbarEntrance::Fade,
396        }
397    }
398
399    fn sample(&self, now: Instant) -> VisibilitySample {
400        let entering =
401            self.opacity.target > self.opacity.from || self.position.target > self.position.from;
402        let (opacity, opacity_running) = self.opacity.sample(now, |from, target, linear| {
403            let factor = if entering {
404                linear
405            } else {
406                ease_in_cubic(linear)
407            };
408            from + (target - from) * factor
409        });
410        let (position, position_running) = self.position.sample(now, |from, target, linear| {
411            let factor = if entering {
412                ease_out_cubic(linear)
413            } else {
414                ease_in_cubic(linear)
415            };
416            from + (target - from) * factor
417        });
418
419        VisibilitySample {
420            opacity,
421            position,
422            running: opacity_running || position_running,
423        }
424    }
425
426    /// Reverse or start a transition toward `visible`.
427    ///
428    /// The leg runs for `enter` or `exit` scaled by the distance still to cover,
429    /// so an interrupted transition keeps its speed instead of restarting.
430    fn set_visible(
431        &mut self,
432        visible: bool,
433        entrance: ScrollbarEntrance,
434        enter: Duration,
435        exit: Duration,
436        now: Instant,
437    ) {
438        let target = if visible { 1.0 } else { 0.0 };
439        let full_duration = if visible { enter } else { exit };
440        if full_duration.is_zero() {
441            // A motionless policy — reduced motion, an always-visible scrollbar,
442            // or a theme that projects no motion — adopts the target outright,
443            // even if a transition was in flight when the policy changed.
444            self.opacity.settle(target, now);
445            self.position.settle(target, now);
446            self.entrance = entrance;
447            return;
448        }
449        if self.opacity.target == target
450            && self.position.target == target
451            && self.entrance == entrance
452        {
453            return;
454        }
455
456        let sample = self.sample(now);
457        let from_position = if visible && entrance == ScrollbarEntrance::Fade {
458            1.0
459        } else {
460            sample.position
461        };
462        let distance = (target - sample.opacity)
463            .abs()
464            .max((target - from_position).abs());
465        let duration = full_duration.mul_f32(distance);
466        self.opacity.start(sample.opacity, target, duration, now);
467        self.position.start(from_position, target, duration, now);
468        self.entrance = entrance;
469    }
470}
471
472fn visibility_translation(axis: Axis, track_width: Pixels, progress: f32) -> Point<Pixels> {
473    let offset = track_width * (1.0 - progress.clamp(0.0, 1.0));
474    if axis.is_vertical() {
475        point(offset, px(0.))
476    } else {
477        point(px(0.), offset)
478    }
479}
480
481fn wants_visible(
482    mode: ScrollbarMode,
483    is_hovered: bool,
484    is_dragging: bool,
485    last_scroll_time: Option<Instant>,
486    idle: Duration,
487    now: Instant,
488) -> bool {
489    mode.is_always()
490        || is_dragging
491        || (mode.is_hover() && is_hovered)
492        || last_scroll_time.is_some_and(|last| now.saturating_duration_since(last) < idle)
493}
494
495fn tracks_thumb_hover(mode: ScrollbarMode, is_visible: bool) -> bool {
496    mode.is_hover() || is_visible
497}
498
499fn hover_keeps_visible(mode: ScrollbarMode, is_hovered: bool, is_currently_visible: bool) -> bool {
500    is_hovered && (mode.is_hover() || (mode == ScrollbarMode::Scrolling && is_currently_visible))
501}
502
503impl Deref for ScrollbarState {
504    type Target = Rc<Cell<ScrollbarStateInner>>;
505
506    fn deref(&self) -> &Self::Target {
507        &self.0
508    }
509}
510
511impl ScrollbarStateInner {
512    fn with_drag_pos(&self, axis: Axis, pos: Point<Pixels>) -> Self {
513        let mut state = *self;
514        if axis.is_vertical() {
515            state.drag_pos.y = pos.y;
516        } else {
517            state.drag_pos.x = pos.x;
518        }
519
520        state.dragged_axis = Some(axis);
521        state
522    }
523
524    fn with_unset_drag_pos(&self, now: Instant) -> Self {
525        let mut state = *self;
526        state.dragged_axis = None;
527        state.last_scroll_time = Some(now);
528        state
529    }
530
531    fn with_hovered(&self, axis: Option<Axis>, now: Instant) -> Self {
532        let mut state = *self;
533        state.hovered_axis = axis;
534        state.last_scroll_time = Some(now);
535        state
536    }
537
538    fn with_hovered_on_thumb(&self, axis: Option<Axis>) -> Self {
539        let mut state = *self;
540        state.hovered_on_thumb = axis;
541        if self.is_scrollbar_visible() {
542            if axis.is_some() {
543                state.last_scroll_time = Some(Instant::now());
544            }
545        }
546        state
547    }
548
549    fn with_last_scroll(
550        &self,
551        last_scroll_offset: Point<Pixels>,
552        last_scroll_time: Option<Instant>,
553    ) -> Self {
554        let mut state = *self;
555        state.last_scroll_offset = last_scroll_offset;
556        state.last_scroll_time = last_scroll_time;
557        state
558    }
559
560    fn with_last_update(&self, t: Instant) -> Self {
561        let mut state = *self;
562        state.last_update = t;
563        state
564    }
565
566    fn with_idle_timer_scheduled(&self, scheduled: bool) -> Self {
567        let mut state = *self;
568        state.idle_timer_scheduled = scheduled;
569        state
570    }
571
572    fn is_scrollbar_visible(&self) -> bool {
573        self.dragged_axis.is_some() || self.visibility.sample(Instant::now()).opacity > 0.0
574    }
575}
576
577/// Scrollbar axis.
578#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579pub enum ScrollbarAxis {
580    /// Vertical scrollbar.
581    Vertical,
582    /// Horizontal scrollbar.
583    Horizontal,
584    /// Show both vertical and horizontal scrollbars.
585    Both,
586}
587
588/// Paint-only styles for a scrollbar track.
589#[derive(Clone, Default)]
590pub struct ScrollbarTrackStyle {
591    background: Option<Hsla>,
592    border: Option<Hsla>,
593    width: Option<Pixels>,
594}
595
596impl ScrollbarTrackStyle {
597    pub fn bg(mut self, background: Hsla) -> Self {
598        self.background = Some(background);
599        self
600    }
601
602    pub fn border_color(mut self, border: Hsla) -> Self {
603        self.border = Some(border);
604        self
605    }
606
607    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
608        self.width = Some(width.into());
609        self
610    }
611}
612
613impl FluentBuilder for ScrollbarTrackStyle {}
614
615/// Paint-only styles for a scrollbar thumb.
616#[derive(Clone, Default)]
617pub struct ScrollbarThumbStyle {
618    background: Option<Background>,
619    width: Option<Pixels>,
620    inset: Option<Pixels>,
621    radius: Option<Pixels>,
622    min_length: Option<Pixels>,
623}
624
625impl ScrollbarThumbStyle {
626    pub fn bg(mut self, background: impl Into<Background>) -> Self {
627        self.background = Some(background.into());
628        self
629    }
630
631    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
632        self.width = Some(width.into());
633        self
634    }
635
636    pub fn inset(mut self, inset: impl Into<Pixels>) -> Self {
637        self.inset = Some(inset.into());
638        self
639    }
640
641    pub fn radius(mut self, radius: impl Into<Pixels>) -> Self {
642        self.radius = Some(radius.into());
643        self
644    }
645
646    pub fn min_length(mut self, min_length: impl Into<Pixels>) -> Self {
647        self.min_length = Some(min_length.into());
648        self
649    }
650}
651
652impl FluentBuilder for ScrollbarThumbStyle {}
653
654/// Typed paint styles supported by [`Scrollbar`].
655#[derive(Clone, Default)]
656pub struct ScrollbarStyles {
657    track: ScrollbarTrackStyle,
658    track_hover: ScrollbarTrackStyle,
659    track_active: ScrollbarTrackStyle,
660    thumb: ScrollbarThumbStyle,
661    thumb_hover: ScrollbarThumbStyle,
662    thumb_active: ScrollbarThumbStyle,
663}
664
665impl ScrollbarStyles {
666    pub fn track(mut self, build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle) -> Self {
667        self.track = build(self.track);
668        self
669    }
670
671    pub fn track_hover(
672        mut self,
673        build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle,
674    ) -> Self {
675        self.track_hover = build(self.track_hover);
676        self
677    }
678
679    pub fn track_active(
680        mut self,
681        build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle,
682    ) -> Self {
683        self.track_active = build(self.track_active);
684        self
685    }
686
687    pub fn thumb(mut self, build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle) -> Self {
688        self.thumb = build(self.thumb);
689        self
690    }
691
692    pub fn thumb_hover(
693        mut self,
694        build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle,
695    ) -> Self {
696        self.thumb_hover = build(self.thumb_hover);
697        self
698    }
699
700    pub fn thumb_active(
701        mut self,
702        build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle,
703    ) -> Self {
704        self.thumb_active = build(self.thumb_active);
705        self
706    }
707}
708
709impl FluentBuilder for ScrollbarStyles {}
710
711impl From<Axis> for ScrollbarAxis {
712    fn from(axis: Axis) -> Self {
713        match axis {
714            Axis::Vertical => Self::Vertical,
715            Axis::Horizontal => Self::Horizontal,
716        }
717    }
718}
719
720impl ScrollbarAxis {
721    /// Return true if the scrollbar axis is vertical.
722    #[inline]
723    pub fn is_vertical(&self) -> bool {
724        matches!(self, Self::Vertical)
725    }
726
727    /// Return true if the scrollbar axis is horizontal.
728    #[inline]
729    pub fn is_horizontal(&self) -> bool {
730        matches!(self, Self::Horizontal)
731    }
732
733    /// Return true if the scrollbar axis is both vertical and horizontal.
734    #[inline]
735    pub fn is_both(&self) -> bool {
736        matches!(self, Self::Both)
737    }
738
739    /// Return true if the scrollbar has vertical axis.
740    #[inline]
741    pub fn has_vertical(&self) -> bool {
742        matches!(self, Self::Vertical | Self::Both)
743    }
744
745    /// Return true if the scrollbar has horizontal axis.
746    #[inline]
747    pub fn has_horizontal(&self) -> bool {
748        matches!(self, Self::Horizontal | Self::Both)
749    }
750
751    #[inline]
752    fn all(&self) -> Vec<Axis> {
753        match self {
754            Self::Vertical => vec![Axis::Vertical],
755            Self::Horizontal => vec![Axis::Horizontal],
756            // This should keep Horizontal first, Vertical is the primary axis
757            // if Vertical not need display, then Horizontal will not keep right margin.
758            Self::Both => vec![Axis::Horizontal, Axis::Vertical],
759        }
760    }
761}
762
763/// Scrollbar control for scroll-area or a uniform-list.
764pub struct Scrollbar {
765    pub(crate) id: ElementId,
766    axis: ScrollbarAxis,
767    mode: Option<ScrollbarMode>,
768    scroll_handle: Rc<dyn ScrollbarHandle>,
769    scroll_size: Option<Size<Pixels>>,
770    viewport_bounds: Option<Bounds<Pixels>>,
771    use_layout_bounds: bool,
772    /// Maximum frames per second for scrolling by drag. Default is 120 FPS.
773    ///
774    /// This is used to limit the update rate of the scrollbar when it is
775    /// being dragged for some complex interactions for reducing CPU usage.
776    max_fps: usize,
777    styles: ScrollbarStyles,
778}
779
780impl Scrollbar {
781    /// Create a new scrollbar.
782    ///
783    /// This will have both vertical and horizontal scrollbars.
784    #[track_caller]
785    pub fn new<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
786        let caller = Location::caller();
787        Self {
788            id: ElementId::CodeLocation(*caller),
789            axis: ScrollbarAxis::Both,
790            mode: None,
791            scroll_handle: Rc::new(scroll_handle.clone()),
792            max_fps: 120,
793            scroll_size: None,
794            viewport_bounds: None,
795            use_layout_bounds: false,
796            styles: ScrollbarStyles::default(),
797        }
798    }
799
800    /// Create with horizontal scrollbar.
801    #[track_caller]
802    pub fn horizontal<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
803        Self::new(scroll_handle).axis(ScrollbarAxis::Horizontal)
804    }
805
806    /// Create with vertical scrollbar.
807    #[track_caller]
808    pub fn vertical<H: ScrollbarHandle + Clone>(scroll_handle: &H) -> Self {
809        Self::new(scroll_handle).axis(ScrollbarAxis::Vertical)
810    }
811
812    /// Set a specific element id, default is the [`Location::caller`].
813    ///
814    /// NOTE: In most cases, you don't need to set a specific id for scrollbar.
815    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
816        self.id = id.into();
817        self
818    }
819
820    /// Set the scrollbar show mode [`ScrollbarMode`].
821    ///
822    /// If unset, the current application theme projection is used.
823    pub fn mode(mut self, mode: ScrollbarMode) -> Self {
824        self.mode = Some(mode);
825        self
826    }
827
828    /// Set a special scroll size of the content area, default is None.
829    ///
830    /// Default will sync the `content_size` from `scroll_handle`.
831    pub fn scroll_size(mut self, scroll_size: Size<Pixels>) -> Self {
832        self.scroll_size = Some(scroll_size);
833        self
834    }
835
836    /// Override the viewport bounds that this scrollbar overlays.
837    ///
838    /// Most scroll containers should rely on the bounds reported by their
839    /// scroll handle. Custom-painted viewports, such as the text editor, can
840    /// use this when their visible bounds differ from the handle's layout
841    /// bounds.
842    pub fn viewport_bounds(mut self, bounds: Bounds<Pixels>) -> Self {
843        self.viewport_bounds = Some(bounds);
844        self
845    }
846
847    /// Use the scrollbar element's layout bounds as its viewport.
848    ///
849    /// This is useful for composite widgets whose scrollbar viewport excludes
850    /// fixed headers or columns and is therefore defined by a positioned
851    /// overlay container rather than by the underlying scroll handle.
852    pub fn viewport_from_layout(mut self) -> Self {
853        self.use_layout_bounds = true;
854        self
855    }
856
857    fn resolved_viewport_bounds(&self, layout_bounds: Bounds<Pixels>) -> Bounds<Pixels> {
858        self.viewport_bounds.unwrap_or_else(|| {
859            if self.use_layout_bounds {
860                layout_bounds
861            } else {
862                self.scroll_handle.viewport_bounds()
863            }
864        })
865    }
866
867    /// Set scrollbar axis.
868    pub fn axis(mut self, axis: impl Into<ScrollbarAxis>) -> Self {
869        self.axis = axis.into();
870        self
871    }
872
873    pub fn styles(mut self, build: impl FnOnce(ScrollbarStyles) -> ScrollbarStyles) -> Self {
874        self.styles = build(self.styles);
875        self
876    }
877
878    /// Set maximum frames per second for scrolling by drag. Default is 120 FPS.
879    ///
880    /// If you have very high CPU usage, consider reducing this value to improve performance.
881    ///
882    /// Available values: 30..120
883    #[doc(hidden)]
884    pub fn max_fps(mut self, max_fps: usize) -> Self {
885        self.max_fps = max_fps.clamp(30, 120);
886        self
887    }
888
889    // Get the width of the scrollbar.
890    #[doc(hidden)]
891    pub const fn width() -> Pixels {
892        WIDTH
893    }
894
895    fn resolve_track(
896        &self,
897        cx: &App,
898        state: &ScrollbarTrackStyle,
899        global_state: &ScrollbarTrackStyle,
900        default_border: Hsla,
901    ) -> (Hsla, Hsla) {
902        let theme = cx.theme();
903        let global = theme.scrollbar.styles();
904        (
905            state
906                .background
907                .or(self.styles.track.background)
908                .or(global_state.background)
909                .or(global.track.background)
910                .unwrap_or_else(gpui::transparent_black),
911            state
912                .border
913                .or(self.styles.track.border)
914                .or(global_state.border)
915                .or(global.track.border)
916                .unwrap_or(default_border),
917        )
918    }
919
920    fn resolve_thumb(
921        &self,
922        cx: &App,
923        state: &ScrollbarThumbStyle,
924        global_state: &ScrollbarThumbStyle,
925        defaults: ScrollbarThumbStyle,
926    ) -> (Background, Pixels, Pixels, Pixels, Pixels) {
927        let theme = cx.theme();
928        let global = theme.scrollbar.styles();
929        (
930            state
931                .background
932                .or(self.styles.thumb.background)
933                .or(global_state.background)
934                .or(global.thumb.background)
935                .unwrap_or_else(|| defaults.background.unwrap()),
936            state
937                .width
938                .or(self.styles.thumb.width)
939                .or(global_state.width)
940                .or(global.thumb.width)
941                .unwrap_or_else(|| defaults.width.unwrap()),
942            state
943                .inset
944                .or(self.styles.thumb.inset)
945                .or(global_state.inset)
946                .or(global.thumb.inset)
947                .unwrap_or_else(|| defaults.inset.unwrap()),
948            state
949                .radius
950                .or(self.styles.thumb.radius)
951                .or(global_state.radius)
952                .or(global.thumb.radius)
953                .unwrap_or_else(|| defaults.radius.unwrap()),
954            state
955                .min_length
956                .or(self.styles.thumb.min_length)
957                .or(global_state.min_length)
958                .or(global.thumb.min_length)
959                .or(defaults.min_length)
960                .unwrap_or(MIN_THUMB_SIZE),
961        )
962    }
963
964    /// The thumb colour a scrollbar falls back to when nothing has overridden
965    /// it, taken from the active theme rather than fixed.
966    ///
967    /// It used to be literal black at these alphas. That reads as an ordinary
968    /// grey thumb on a light surface and as very nearly nothing at all on a
969    /// dark one, and no palette an application installed could change it:
970    /// `Theme` carries `scrollbar` beside `tokens` rather than derived from
971    /// them, so a theme swap moved every token except the ones the scrollbar
972    /// actually paints with.
973    ///
974    /// `foreground` is the token that already means "ink on this surface" and
975    /// already flips with the appearance, so on a light theme this stays within
976    /// a hair of the old constant and on a dark one it becomes visible. An
977    /// explicit `ScrollbarStyles` still wins: this is the bottom of the
978    /// cascade, not a new top of it.
979    fn thumb_default_background(cx: &App, alpha: f32) -> Background {
980        let mut color = cx.theme().tokens.colors.foreground;
981        color.alpha = alpha.clamp(0., 1.);
982        color.into()
983    }
984
985    fn thumb_defaults(
986        background: Background,
987        width: Pixels,
988        inset: Pixels,
989        radius: Pixels,
990    ) -> ScrollbarThumbStyle {
991        ScrollbarThumbStyle {
992            background: Some(background),
993            width: Some(width),
994            inset: Some(inset),
995            radius: Some(radius),
996            min_length: Some(MIN_THUMB_SIZE),
997        }
998    }
999
1000    fn style_for_active(
1001        &self,
1002        cx: &App,
1003    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1004        let theme = cx.theme();
1005        let global = theme.scrollbar.styles();
1006        let (track, border) = self.resolve_track(
1007            cx,
1008            &self.styles.track_active,
1009            &global.track_active,
1010            gpui::transparent_black(),
1011        );
1012        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1013            cx,
1014            &self.styles.thumb_active,
1015            &global.thumb_active,
1016            Self::thumb_defaults(
1017                Self::thumb_default_background(cx, 0.55),
1018                THUMB_ACTIVE_WIDTH,
1019                THUMB_ACTIVE_INSET,
1020                THUMB_ACTIVE_RADIUS,
1021            ),
1022        );
1023        (thumb, track, border, width, inset, radius, min_length)
1024    }
1025
1026    fn style_for_hovered_thumb(
1027        &self,
1028        cx: &App,
1029    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1030        let theme = cx.theme();
1031        let global = theme.scrollbar.styles();
1032        let (track, border) = self.resolve_track(
1033            cx,
1034            &self.styles.track_active,
1035            &global.track_active,
1036            gpui::transparent_black(),
1037        );
1038        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1039            cx,
1040            &self.styles.thumb_hover,
1041            &global.thumb_hover,
1042            Self::thumb_defaults(
1043                Self::thumb_default_background(cx, 0.55),
1044                THUMB_ACTIVE_WIDTH,
1045                THUMB_ACTIVE_INSET,
1046                THUMB_ACTIVE_RADIUS,
1047            ),
1048        );
1049        (thumb, track, border, width, inset, radius, min_length)
1050    }
1051
1052    fn style_for_hovered_bar(
1053        &self,
1054        cx: &App,
1055    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1056        let theme = cx.theme();
1057        let global = theme.scrollbar.styles();
1058        let (track, border) = self.resolve_track(
1059            cx,
1060            &self.styles.track_hover,
1061            &global.track_hover,
1062            gpui::transparent_black(),
1063        );
1064        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1065            cx,
1066            &self.styles.thumb,
1067            &global.thumb,
1068            Self::thumb_defaults(
1069                Self::thumb_default_background(cx, 0.35),
1070                THUMB_WIDTH,
1071                THUMB_INSET,
1072                THUMB_RADIUS,
1073            ),
1074        );
1075        (thumb, track, border, width, inset, radius, min_length)
1076    }
1077
1078    fn style_for_normal(
1079        &self,
1080        cx: &App,
1081    ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) {
1082        let theme = cx.theme();
1083        let global = theme.scrollbar.styles();
1084
1085        let (track, border) = self.resolve_track(
1086            cx,
1087            &self.styles.track,
1088            &global.track,
1089            gpui::transparent_black(),
1090        );
1091        let (thumb, width, inset, radius, min_length) = self.resolve_thumb(
1092            cx,
1093            &self.styles.thumb,
1094            &global.thumb,
1095            Self::thumb_defaults(
1096                Self::thumb_default_background(cx, 0.35),
1097                THUMB_WIDTH,
1098                THUMB_INSET,
1099                THUMB_RADIUS,
1100            ),
1101        );
1102        (thumb, track, border, width, inset, radius, min_length)
1103    }
1104}
1105
1106impl IntoElement for Scrollbar {
1107    type Element = Self;
1108
1109    fn into_element(self) -> Self::Element {
1110        self
1111    }
1112}
1113
1114#[doc(hidden)]
1115pub struct PrepaintState {
1116    hitbox: Hitbox,
1117    scrollbar_state: ScrollbarState,
1118    states: Vec<AxisPrepaintState>,
1119}
1120
1121#[doc(hidden)]
1122pub struct AxisPrepaintState {
1123    axis: Axis,
1124    bar_hitbox: Hitbox,
1125    bounds: Bounds<Pixels>,
1126    radius: Pixels,
1127    bg: Hsla,
1128    border: Hsla,
1129    thumb_bounds: Bounds<Pixels>,
1130    // Bounds of thumb to be rendered.
1131    thumb_fill_bounds: Bounds<Pixels>,
1132    thumb_bg: Background,
1133    scroll_size: Pixels,
1134    container_size: Pixels,
1135    thumb_size: Pixels,
1136    margin_end: Pixels,
1137    track_width: Pixels,
1138    visibility_opacity: f32,
1139    visibility_position: f32,
1140    visibility_requested: bool,
1141}
1142
1143impl Element for Scrollbar {
1144    type RequestLayoutState = ();
1145    type PrepaintState = PrepaintState;
1146
1147    fn id(&self) -> Option<gpui::ElementId> {
1148        Some(self.id.clone())
1149    }
1150
1151    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1152        None
1153    }
1154
1155    fn request_layout(
1156        &mut self,
1157        _: Option<&GlobalElementId>,
1158        _: Option<&InspectorElementId>,
1159        window: &mut Window,
1160        cx: &mut App,
1161    ) -> (LayoutId, Self::RequestLayoutState) {
1162        let mut style = Style::default();
1163        style.position = Position::Absolute;
1164        style.flex_grow = 1.0;
1165        style.flex_shrink = 1.0;
1166        style.size.width = relative(1.).into();
1167        style.size.height = relative(1.).into();
1168
1169        (window.request_layout(style, None, cx), ())
1170    }
1171
1172    fn prepaint(
1173        &mut self,
1174        _: Option<&GlobalElementId>,
1175        _: Option<&InspectorElementId>,
1176        bounds: Bounds<Pixels>,
1177        _: &mut Self::RequestLayoutState,
1178        window: &mut Window,
1179        cx: &mut App,
1180    ) -> Self::PrepaintState {
1181        let bounds = self.resolved_viewport_bounds(bounds);
1182        let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
1183            window.insert_hitbox(bounds, HitboxBehavior::Normal)
1184        });
1185
1186        let state = window
1187            .use_state(cx, |_, _| ScrollbarState::default())
1188            .read(cx)
1189            .clone();
1190
1191        let now = Instant::now();
1192        let base_theme = cx.theme();
1193        let mode = self.mode.unwrap_or(base_theme.scrollbar.mode());
1194        let motion = base_theme.scrollbar.motion();
1195        // Always-visible scrollbars skip visibility motion but still animate
1196        // their activity width. Reduced motion snaps every channel.
1197        let reduce_motion = cx.reduce_motion();
1198        let (enter, exit) = if !mode.is_always() && !reduce_motion {
1199            (motion.enter(), motion.exit())
1200        } else {
1201            (Duration::ZERO, Duration::ZERO)
1202        };
1203        let expand = if reduce_motion {
1204            Duration::ZERO
1205        } else {
1206            motion.expand()
1207        };
1208
1209        let mut inner = state.get();
1210        let current_offset = self.scroll_handle.offset();
1211        if current_offset != inner.last_scroll_offset {
1212            inner = inner.with_last_scroll(current_offset, Some(now));
1213        }
1214
1215        let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some();
1216        let is_dragging = inner.dragged_axis.is_some();
1217        let is_currently_visible = inner.visibility.sample(now).opacity > 0.0;
1218        let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible)
1219            || wants_visible(
1220                mode,
1221                is_hovered,
1222                is_dragging,
1223                inner.last_scroll_time,
1224                motion.idle(),
1225                now,
1226            );
1227        inner.visibility.set_visible(
1228            visible,
1229            motion.entrance_for(mode, inner.hovered_on_thumb.is_some()),
1230            enter,
1231            exit,
1232            now,
1233        );
1234        let visibility = inner.visibility.sample(now);
1235        if visibility.running {
1236            window.request_animation_frame();
1237        }
1238
1239        if !is_hovered && !is_dragging {
1240            if let Some(last_time) = inner.last_scroll_time {
1241                let elapsed = now.saturating_duration_since(last_time);
1242                if elapsed < motion.idle() && !inner.idle_timer_scheduled {
1243                    inner.idle_timer_scheduled = true;
1244                    let state = state.clone();
1245                    let current_view = window.current_view();
1246                    let next_delay = motion.idle() - elapsed;
1247                    window
1248                        .spawn(cx, async move |cx| {
1249                            cx.background_executor().timer(next_delay).await;
1250                            state.set(state.get().with_idle_timer_scheduled(false));
1251                            cx.update(|_, cx| cx.notify(current_view)).ok();
1252                        })
1253                        .detach();
1254                }
1255            }
1256        }
1257        state.set(inner);
1258
1259        let mut states = vec![];
1260        let mut has_both = self.axis.is_both();
1261        let scroll_size = self
1262            .scroll_size
1263            .unwrap_or(self.scroll_handle.content_size());
1264
1265        for axis in self.axis.all().into_iter() {
1266            let is_vertical = axis.is_vertical();
1267            let track_width = self
1268                .styles
1269                .track
1270                .width
1271                .or(cx.theme().scrollbar.styles().track.width)
1272                .unwrap_or(WIDTH);
1273            let (scroll_area_size, container_size, scroll_position) = if is_vertical {
1274                (
1275                    scroll_size.height,
1276                    hitbox.size.height,
1277                    self.scroll_handle.offset().y,
1278                )
1279            } else {
1280                (
1281                    scroll_size.width,
1282                    hitbox.size.width,
1283                    self.scroll_handle.offset().x,
1284                )
1285            };
1286
1287            // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible.
1288            let margin_end = if has_both && !is_vertical {
1289                track_width
1290            } else {
1291                px(0.)
1292            };
1293
1294            // Hide scrollbar, if the scroll area is smaller than the container.
1295            if scroll_area_size <= container_size {
1296                has_both = false;
1297                continue;
1298            }
1299
1300            let bounds = Bounds {
1301                origin: if is_vertical {
1302                    point(
1303                        hitbox.origin.x + hitbox.size.width - track_width,
1304                        hitbox.origin.y,
1305                    )
1306                } else {
1307                    point(
1308                        hitbox.origin.x,
1309                        hitbox.origin.y + hitbox.size.height - track_width,
1310                    )
1311                },
1312                size: gpui::Size {
1313                    width: if is_vertical {
1314                        track_width
1315                    } else {
1316                        hitbox.size.width
1317                    },
1318                    height: if is_vertical {
1319                        hitbox.size.height
1320                    } else {
1321                        track_width
1322                    },
1323                },
1324            };
1325
1326            let is_always_to_show = mode.is_always();
1327            let is_hover_to_show = mode.is_hover();
1328            let is_hovered_on_bar = state.get().hovered_axis == Some(axis);
1329            let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis);
1330
1331            let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) =
1332                if state.get().dragged_axis == Some(axis) {
1333                    self.style_for_active(cx)
1334                } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling)
1335                    && (is_hovered_on_bar || is_hovered_on_thumb)
1336                {
1337                    if is_hovered_on_thumb {
1338                        self.style_for_hovered_thumb(cx)
1339                    } else {
1340                        self.style_for_hovered_bar(cx)
1341                    }
1342                } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) {
1343                    if is_hovered_on_thumb {
1344                        self.style_for_hovered_thumb(cx)
1345                    } else {
1346                        self.style_for_hovered_bar(cx)
1347                    }
1348                } else {
1349                    self.style_for_normal(cx)
1350                };
1351
1352            let mut width_animation = if is_vertical {
1353                state.get().vertical_width
1354            } else {
1355                state.get().horizontal_width
1356            };
1357            let (animated_width, running) = width_animation.set_target(thumb_width, expand, now);
1358            let mut updated = state.get();
1359            if is_vertical {
1360                updated.vertical_width = width_animation;
1361            } else {
1362                updated.horizontal_width = width_animation;
1363            }
1364            state.set(updated);
1365            thumb_width = animated_width;
1366            if running {
1367                window.request_animation_frame();
1368            }
1369
1370            let thumb_size = (container_size / scroll_area_size * container_size).max(min_length);
1371            let thumb_start = -(scroll_position / (scroll_area_size - container_size)
1372                * (container_size - margin_end - thumb_size));
1373            let thumb_end = (thumb_start + thumb_size).min(container_size - margin_end);
1374
1375            // The clickable area of the thumb
1376            let thumb_length = thumb_end - thumb_start - inset * 2;
1377            let thumb_bounds = if is_vertical {
1378                Bounds::from_anchor_and_size(
1379                    Anchor::TopRight,
1380                    bounds.top_right() + point(-inset, inset + thumb_start),
1381                    size(track_width, thumb_length),
1382                )
1383            } else {
1384                Bounds::from_anchor_and_size(
1385                    Anchor::BottomLeft,
1386                    bounds.bottom_left() + point(inset + thumb_start, -inset),
1387                    size(thumb_length, track_width),
1388                )
1389            };
1390
1391            // The actual render area of the thumb
1392            let thumb_fill_bounds = if is_vertical {
1393                Bounds::from_anchor_and_size(
1394                    Anchor::TopRight,
1395                    bounds.top_right() + point(-inset, inset + thumb_start),
1396                    size(thumb_width, thumb_length),
1397                )
1398            } else {
1399                Bounds::from_anchor_and_size(
1400                    Anchor::BottomLeft,
1401                    bounds.bottom_left() + point(inset + thumb_start, -inset),
1402                    size(thumb_length, thumb_width),
1403                )
1404            };
1405
1406            let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
1407                window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal)
1408            });
1409
1410            states.push(AxisPrepaintState {
1411                axis,
1412                bar_hitbox,
1413                bounds,
1414                radius,
1415                bg: bar_bg,
1416                border: bar_border,
1417                thumb_bounds,
1418                thumb_fill_bounds,
1419                thumb_bg,
1420                scroll_size: scroll_area_size,
1421                container_size,
1422                thumb_size: thumb_length,
1423                margin_end,
1424                track_width,
1425                visibility_opacity: visibility.opacity,
1426                visibility_position: visibility.position,
1427                visibility_requested: visible,
1428            })
1429        }
1430
1431        PrepaintState {
1432            hitbox,
1433            states,
1434            scrollbar_state: state,
1435        }
1436    }
1437
1438    fn paint(
1439        &mut self,
1440        _: Option<&GlobalElementId>,
1441        _: Option<&InspectorElementId>,
1442        _: Bounds<Pixels>,
1443        _: &mut Self::RequestLayoutState,
1444        prepaint: &mut Self::PrepaintState,
1445        window: &mut Window,
1446        cx: &mut App,
1447    ) {
1448        let scrollbar_state = &prepaint.scrollbar_state;
1449        let theme = cx.theme();
1450        let mode = self.mode.unwrap_or(theme.scrollbar.mode());
1451        let view_id = window.current_view();
1452        let hitbox_bounds = prepaint.hitbox.bounds;
1453        let is_hover_to_show = mode.is_hover();
1454
1455        window.with_content_mask(
1456            Some(ContentMask {
1457                bounds: hitbox_bounds,
1458            }),
1459            |window| {
1460                for state in prepaint.states.iter() {
1461                    let axis = state.axis;
1462                    let mut radius = state.radius;
1463                    if theme.tokens.radius.md.is_zero() {
1464                        radius = px(0.);
1465                    }
1466                    radius = clamp_thumb_radius(radius, state.thumb_fill_bounds);
1467                    let bounds = state.bounds;
1468                    let thumb_bounds = state.thumb_bounds;
1469                    let scroll_area_size = state.scroll_size;
1470                    let container_size = state.container_size;
1471                    let thumb_size = state.thumb_size;
1472                    let margin_end = state.margin_end;
1473                    let is_vertical = axis.is_vertical();
1474                    let visibility_opacity = state.visibility_opacity;
1475                    let is_visible = state.visibility_requested || visibility_opacity > 0.0;
1476                    let translation =
1477                        visibility_translation(axis, state.track_width, state.visibility_position);
1478                    let painted_bounds = state.bounds + translation;
1479                    let painted_thumb_bounds = state.thumb_fill_bounds + translation;
1480                    let painted_track_bg = state.bg.opacity(visibility_opacity);
1481                    let painted_border = state.border.opacity(visibility_opacity);
1482                    let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity);
1483
1484                    window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox);
1485
1486                    window.paint_layer(hitbox_bounds, |cx| {
1487                        cx.paint_quad(fill(painted_bounds, painted_track_bg));
1488
1489                        cx.paint_quad(PaintQuad {
1490                            bounds: painted_bounds,
1491                            corner_radii: (0.).into(),
1492                            background: gpui::transparent_black().into(),
1493                            border_widths: if is_vertical {
1494                                Edges {
1495                                    top: px(0.),
1496                                    right: px(0.),
1497                                    bottom: px(0.),
1498                                    left: px(0.),
1499                                }
1500                            } else {
1501                                Edges {
1502                                    top: px(0.),
1503                                    right: px(0.),
1504                                    bottom: px(0.),
1505                                    left: px(0.),
1506                                }
1507                            },
1508                            border_color: painted_border,
1509                            border_style: BorderStyle::default(),
1510                        });
1511
1512                        cx.paint_quad(
1513                            fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius),
1514                        );
1515                    });
1516
1517                    window.on_mouse_event({
1518                        let state = scrollbar_state.clone();
1519                        let scroll_handle = self.scroll_handle.clone();
1520
1521                        move |event: &ScrollWheelEvent, phase, _, cx| {
1522                            if phase.bubble() && hitbox_bounds.contains(&event.position) {
1523                                if scroll_handle.offset() != state.get().last_scroll_offset {
1524                                    state.set(state.get().with_last_scroll(
1525                                        scroll_handle.offset(),
1526                                        Some(Instant::now()),
1527                                    ));
1528                                    cx.notify(view_id);
1529                                }
1530                            }
1531                        }
1532                    });
1533
1534                    let safe_range = (-scroll_area_size + container_size)..px(0.);
1535
1536                    if is_visible {
1537                        window.on_mouse_event({
1538                            let state = scrollbar_state.clone();
1539                            let scroll_handle = self.scroll_handle.clone();
1540
1541                            move |event: &MouseDownEvent, phase, _, cx| {
1542                                if phase.bubble() && bounds.contains(&event.position) {
1543                                    cx.stop_propagation();
1544
1545                                    if thumb_bounds.contains(&event.position) {
1546                                        // click on the thumb bar, set the drag position
1547                                        let pos = event.position - thumb_bounds.origin;
1548
1549                                        scroll_handle.start_drag();
1550                                        state.set(state.get().with_drag_pos(axis, pos));
1551                                    } else {
1552                                        // click on the scrollbar, jump to the position
1553                                        // Set the thumb bar center to the click position
1554                                        let offset = scroll_handle.offset();
1555                                        let percentage = if is_vertical {
1556                                            (event.position.y - thumb_size / 2. - bounds.origin.y)
1557                                                / (bounds.size.height - thumb_size)
1558                                        } else {
1559                                            (event.position.x - thumb_size / 2. - bounds.origin.x)
1560                                                / (bounds.size.width - thumb_size)
1561                                        }
1562                                        .min(1.);
1563
1564                                        if is_vertical {
1565                                            scroll_handle.set_offset(point(
1566                                                offset.x,
1567                                                (-scroll_area_size * percentage)
1568                                                    .clamp(safe_range.start, safe_range.end),
1569                                            ));
1570                                        } else {
1571                                            scroll_handle.set_offset(point(
1572                                                (-scroll_area_size * percentage)
1573                                                    .clamp(safe_range.start, safe_range.end),
1574                                                offset.y,
1575                                            ));
1576                                        }
1577                                    }
1578
1579                                    cx.notify(view_id);
1580                                }
1581                            }
1582                        });
1583                    }
1584
1585                    window.on_mouse_event({
1586                        let scroll_handle = self.scroll_handle.clone();
1587                        let state = scrollbar_state.clone();
1588                        let max_fps_duration = Duration::from_millis((1000 / self.max_fps) as u64);
1589
1590                        move |event: &MouseMoveEvent, _, _, cx| {
1591                            let mut notify = false;
1592                            // When is hover to show mode or it was visible,
1593                            // we need to update the hovered state and increase the last_scroll_time.
1594                            let need_hover_to_update = is_hover_to_show || is_visible;
1595                            // Update hovered state for scrollbar
1596                            if bounds.contains(&event.position) && need_hover_to_update {
1597                                let hover_changed = state.get().hovered_axis != Some(axis);
1598                                state.set(state.get().with_hovered(Some(axis), Instant::now()));
1599                                notify |= hover_changed;
1600                            } else if state.get().hovered_axis == Some(axis) {
1601                                state.set(state.get().with_hovered(None, Instant::now()));
1602                                notify = true;
1603                            }
1604
1605                            // Update hovered state for scrollbar thumb
1606                            if tracks_thumb_hover(mode, is_visible)
1607                                && thumb_bounds.contains(&event.position)
1608                            {
1609                                if state.get().hovered_on_thumb != Some(axis) {
1610                                    state.set(state.get().with_hovered_on_thumb(Some(axis)));
1611                                    notify = true;
1612                                }
1613                            } else {
1614                                if state.get().hovered_on_thumb == Some(axis) {
1615                                    state.set(state.get().with_hovered_on_thumb(None));
1616                                    notify = true;
1617                                }
1618                            }
1619
1620                            // Move thumb position on dragging
1621                            if state.get().dragged_axis == Some(axis) && event.dragging() {
1622                                // Stop the event propagation to avoid selecting text or other side effects.
1623                                cx.stop_propagation();
1624
1625                                // drag_pos is the position of the mouse down event
1626                                // We need to keep the thumb bar still at the origin down position
1627                                let drag_pos = state.get().drag_pos;
1628
1629                                let percentage = (if is_vertical {
1630                                    (event.position.y - drag_pos.y - bounds.origin.y)
1631                                        / (bounds.size.height - thumb_size)
1632                                } else {
1633                                    (event.position.x - drag_pos.x - bounds.origin.x)
1634                                        / (bounds.size.width - thumb_size - margin_end)
1635                                })
1636                                .clamp(0., 1.);
1637
1638                                let offset = if is_vertical {
1639                                    point(
1640                                        scroll_handle.offset().x,
1641                                        (-(scroll_area_size - container_size) * percentage)
1642                                            .clamp(safe_range.start, safe_range.end),
1643                                    )
1644                                } else {
1645                                    point(
1646                                        (-(scroll_area_size - container_size) * percentage)
1647                                            .clamp(safe_range.start, safe_range.end),
1648                                        scroll_handle.offset().y,
1649                                    )
1650                                };
1651
1652                                if (scroll_handle.offset().y - offset.y).abs() > px(1.)
1653                                    || (scroll_handle.offset().x - offset.x).abs() > px(1.)
1654                                {
1655                                    // Limit update rate
1656                                    if state.get().last_update.elapsed() > max_fps_duration {
1657                                        scroll_handle.set_offset(offset);
1658                                        state.set(state.get().with_last_update(Instant::now()));
1659                                        notify = true;
1660                                    }
1661                                }
1662                            }
1663
1664                            if notify {
1665                                cx.notify(view_id);
1666                            }
1667                        }
1668                    });
1669
1670                    window.on_mouse_event({
1671                        let state = scrollbar_state.clone();
1672                        let scroll_handle = self.scroll_handle.clone();
1673
1674                        move |_event: &MouseUpEvent, phase, _, cx| {
1675                            if phase.bubble() && state.get().dragged_axis == Some(axis) {
1676                                scroll_handle.end_drag();
1677                                state.set(state.get().with_unset_drag_pos(Instant::now()));
1678                                cx.notify(view_id);
1679                            }
1680                        }
1681                    });
1682                }
1683            },
1684        );
1685    }
1686}
1687
1688#[cfg(test)]
1689mod tests {
1690    use super::*;
1691    use palette::WithAlpha as _;
1692
1693    use std::cell::Cell;
1694
1695    use gpui::{
1696        Context, Modifiers, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
1697        VisualTestContext, div,
1698    };
1699
1700    #[test]
1701    fn thumb_radius_is_limited_by_its_actual_bounds() {
1702        let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.)));
1703        let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.)));
1704
1705        assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.));
1706        assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.));
1707        assert_eq!(
1708            clamp_thumb_radius(Pixels::ZERO, vertical_thumb),
1709            Pixels::ZERO
1710        );
1711    }
1712
1713    /// Timing standing in for what a styled layer projects. Base itself ships
1714    /// none of these; see [`motionless_base_snaps_every_transition`].
1715    const ENTER: Duration = Duration::from_millis(300);
1716    const EXIT: Duration = Duration::from_millis(500);
1717    const EXPAND: Duration = Duration::from_millis(300);
1718
1719    #[test]
1720    fn visibility_animation_uses_direction_specific_curves_and_durations() {
1721        let start = Instant::now();
1722        let mut animation = VisibilityAnimation::hidden(start);
1723
1724        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
1725        assert_eq!(animation.sample(start).opacity, 0.0);
1726        let entering = animation.sample(start + ENTER / 2).position;
1727        assert!(entering > 0.5, "ease-out must advance quickly");
1728        let entered = animation.sample(start + ENTER);
1729        assert_eq!(entered.opacity, 1.0);
1730        assert_eq!(entered.position, 1.0);
1731
1732        animation.set_visible(
1733            false,
1734            ScrollbarEntrance::SlideAndFade,
1735            ENTER,
1736            EXIT,
1737            start + ENTER,
1738        );
1739        let exiting = animation.sample(start + ENTER + EXIT / 2).opacity;
1740        assert!(exiting > 0.5, "ease-in must remain visible early in exit");
1741        assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0);
1742    }
1743
1744    #[test]
1745    fn entrance_fades_linearly_while_position_eases_out() {
1746        let start = Instant::now();
1747        let mut animation = VisibilityAnimation::hidden(start);
1748        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
1749
1750        let halfway = animation.sample(start + ENTER / 2);
1751        assert!((halfway.opacity - 0.5).abs() < 0.001);
1752        assert!(halfway.position > halfway.opacity);
1753    }
1754
1755    #[test]
1756    fn fade_entrance_snaps_position_and_animates_opacity() {
1757        let start = Instant::now();
1758        let mut animation = VisibilityAnimation::hidden(start);
1759        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start);
1760
1761        let initial = animation.sample(start);
1762        assert_eq!(initial.opacity, 0.0);
1763        assert_eq!(initial.position, 1.0);
1764        let halfway = animation.sample(start + ENTER / 2);
1765        assert!((halfway.opacity - 0.5).abs() < 0.001);
1766        assert_eq!(halfway.position, 1.0);
1767    }
1768
1769    #[test]
1770    fn active_visibility_adopts_a_changed_entrance_policy() {
1771        let start = Instant::now();
1772        let halfway = start + ENTER / 2;
1773        let mut animation = VisibilityAnimation::hidden(start);
1774        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
1775        let before = animation.sample(halfway);
1776
1777        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway);
1778        let after = animation.sample(halfway);
1779
1780        assert_eq!(
1781            after.opacity, before.opacity,
1782            "policy changes must not flash"
1783        );
1784        assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding");
1785    }
1786
1787    #[test]
1788    fn base_ships_no_motion_of_its_own() {
1789        let motion = ScrollbarMotion::default();
1790        assert_eq!(motion.enter(), Duration::ZERO);
1791        assert_eq!(motion.exit(), Duration::ZERO);
1792        assert_eq!(motion.expand(), Duration::ZERO);
1793        assert_eq!(motion.entrance(), ScrollbarEntrance::Fade);
1794        assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade);
1795        assert_eq!(
1796            motion.idle(),
1797            DEFAULT_IDLE,
1798            "the visibility hold is behavior, not motion, and must stay usable"
1799        );
1800    }
1801
1802    #[test]
1803    fn hover_mode_slides_only_when_the_thumb_is_hovered() {
1804        let motion = ScrollbarMotion::default()
1805            .with_entrance(ScrollbarEntrance::Fade)
1806            .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade);
1807
1808        assert_eq!(
1809            motion.entrance_for(ScrollbarMode::Hover, false),
1810            ScrollbarEntrance::Fade
1811        );
1812        assert_eq!(
1813            motion.entrance_for(ScrollbarMode::Hover, true),
1814            ScrollbarEntrance::SlideAndFade
1815        );
1816        assert_eq!(
1817            motion.entrance_for(ScrollbarMode::Scrolling, true),
1818            ScrollbarEntrance::Fade
1819        );
1820    }
1821
1822    #[test]
1823    fn hidden_scrolling_mode_does_not_track_thumb_hover() {
1824        assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false));
1825        assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true));
1826        assert!(tracks_thumb_hover(ScrollbarMode::Hover, false));
1827    }
1828
1829    #[test]
1830    fn visible_scrolling_mode_stays_visible_while_hovered() {
1831        assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false));
1832        assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true));
1833        assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false));
1834    }
1835
1836    #[test]
1837    fn motionless_base_snaps_every_transition() {
1838        let now = Instant::now();
1839        let motion = ScrollbarMotion::default();
1840        let mut visibility = VisibilityAnimation::hidden(now);
1841
1842        visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now);
1843        let shown = visibility.sample(now);
1844        assert_eq!(shown.opacity, 1.0);
1845        assert_eq!(shown.position, 1.0);
1846        assert!(!shown.running, "a motionless theme must request no frames");
1847        assert_eq!(
1848            visibility_translation(Axis::Vertical, px(16.), shown.position),
1849            Point::default()
1850        );
1851
1852        visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now);
1853        let hidden = visibility.sample(now);
1854        assert_eq!(hidden.opacity, 0.0);
1855        assert_eq!(hidden.position, 0.0);
1856        assert!(!hidden.running);
1857
1858        let mut width = WidthAnimation::new(now);
1859        assert_eq!(
1860            width.set_target(px(8.), motion.expand(), now),
1861            (px(8.), false)
1862        );
1863    }
1864
1865    #[test]
1866    fn a_zero_duration_settles_a_transition_already_in_flight() {
1867        let start = Instant::now();
1868        let mut animation = VisibilityAnimation::hidden(start);
1869        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
1870
1871        // Reduced motion turns on midway through the entrance.
1872        let midway = start + ENTER / 2;
1873        animation.set_visible(
1874            true,
1875            ScrollbarEntrance::SlideAndFade,
1876            Duration::ZERO,
1877            Duration::ZERO,
1878            midway,
1879        );
1880        let settled = animation.sample(midway);
1881        assert_eq!(settled.opacity, 1.0);
1882        assert_eq!(settled.position, 1.0);
1883        assert!(!settled.running);
1884    }
1885
1886    #[test]
1887    fn thumb_expansion_animates_in_both_directions() {
1888        let start = Instant::now();
1889        let mut animation = WidthAnimation::new(start);
1890        assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false));
1891
1892        let (initial, running) = animation.set_target(px(8.), EXPAND, start);
1893        assert_eq!(initial, px(6.));
1894        assert!(running);
1895        let (expanded_halfway, _) = animation.sample(start + EXPAND / 2);
1896        assert!(expanded_halfway > px(7.));
1897
1898        let reversal = start + EXPAND / 2;
1899        let before = animation.sample(reversal).0;
1900        let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal);
1901        assert_eq!(after_reversal, before);
1902        assert!(running);
1903        assert_eq!(animation.sample(reversal + EXPAND).0, px(6.));
1904    }
1905
1906    #[test]
1907    fn reduced_motion_snaps_thumb_expansion() {
1908        let now = Instant::now();
1909        let mut animation = WidthAnimation::new(now);
1910        assert_eq!(
1911            animation.set_target(px(8.), Duration::ZERO, now),
1912            (px(8.), false)
1913        );
1914    }
1915
1916    #[test]
1917    fn visibility_translation_moves_toward_the_nearest_edge() {
1918        assert_eq!(
1919            visibility_translation(Axis::Vertical, px(16.), 0.0),
1920            point(px(16.), px(0.))
1921        );
1922        assert_eq!(
1923            visibility_translation(Axis::Horizontal, px(16.), 0.0),
1924            point(px(0.), px(16.))
1925        );
1926        assert_eq!(
1927            visibility_translation(Axis::Vertical, px(16.), 1.0),
1928            Point::default()
1929        );
1930    }
1931
1932    #[test]
1933    fn visibility_animation_reverses_from_current_progress() {
1934        let start = Instant::now();
1935        let mut animation = VisibilityAnimation::hidden(start);
1936        animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start);
1937        let reversal_time = start + Duration::from_millis(60);
1938        let before = animation.sample(reversal_time);
1939
1940        animation.set_visible(
1941            false,
1942            ScrollbarEntrance::SlideAndFade,
1943            ENTER,
1944            EXIT,
1945            reversal_time,
1946        );
1947        let reversed = animation.sample(reversal_time);
1948        assert_eq!(reversed.opacity, before.opacity);
1949        assert_eq!(reversed.position, before.position);
1950        let after = animation.sample(reversal_time + Duration::from_millis(10));
1951        assert!(after.opacity < before.opacity);
1952        assert!(after.position < before.position);
1953    }
1954
1955    #[test]
1956    fn always_hover_drag_and_recent_scroll_request_visibility() {
1957        let now = Instant::now();
1958        let idle = DEFAULT_IDLE;
1959        assert!(wants_visible(
1960            ScrollbarMode::Always,
1961            false,
1962            false,
1963            None,
1964            idle,
1965            now
1966        ));
1967        assert!(wants_visible(
1968            ScrollbarMode::Hover,
1969            true,
1970            false,
1971            None,
1972            idle,
1973            now
1974        ));
1975        assert!(wants_visible(
1976            ScrollbarMode::Scrolling,
1977            false,
1978            true,
1979            None,
1980            idle,
1981            now
1982        ));
1983        assert!(wants_visible(
1984            ScrollbarMode::Scrolling,
1985            false,
1986            false,
1987            Some(now - idle + Duration::from_millis(1)),
1988            idle,
1989            now,
1990        ));
1991        assert!(!wants_visible(
1992            ScrollbarMode::Scrolling,
1993            false,
1994            false,
1995            Some(now - idle),
1996            idle,
1997            now,
1998        ));
1999
2000        let mut settled = VisibilityAnimation::hidden(now - ENTER);
2001        settled.set_visible(
2002            true,
2003            ScrollbarEntrance::SlideAndFade,
2004            ENTER,
2005            EXIT,
2006            now - ENTER,
2007        );
2008        assert!(!settled.sample(now).running, "idle hold must not animate");
2009    }
2010
2011    #[test]
2012    fn leaving_hover_starts_a_fresh_idle_hold() {
2013        let entered_at = Instant::now();
2014        let left_at = entered_at + Duration::from_secs(5);
2015        let state = ScrollbarState::default().get();
2016
2017        let hovered = state.with_hovered(Some(Axis::Vertical), entered_at);
2018        assert_eq!(hovered.last_scroll_time, Some(entered_at));
2019        let left = hovered.with_hovered(None, left_at);
2020        assert_eq!(left.last_scroll_time, Some(left_at));
2021        assert!(wants_visible(
2022            ScrollbarMode::Hover,
2023            false,
2024            false,
2025            left.last_scroll_time,
2026            DEFAULT_IDLE,
2027            left_at + DEFAULT_IDLE - Duration::from_millis(1),
2028        ));
2029    }
2030
2031    #[test]
2032    fn idle_boundary_starts_the_exit_without_a_jump() {
2033        let activity = Instant::now();
2034        let exit_start = activity + DEFAULT_IDLE;
2035        let mut animation = VisibilityAnimation::hidden(activity - ENTER);
2036        animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER);
2037        assert!(!wants_visible(
2038            ScrollbarMode::Scrolling,
2039            false,
2040            false,
2041            Some(activity),
2042            DEFAULT_IDLE,
2043            exit_start,
2044        ));
2045
2046        animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start);
2047        let start = animation.sample(exit_start);
2048        assert_eq!(start.opacity, 1.0);
2049        assert_eq!(start.position, 1.0);
2050        assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0);
2051    }
2052
2053    #[derive(Clone)]
2054    struct TestHandle {
2055        offset: Rc<Cell<Point<Pixels>>>,
2056        content_size: Size<Pixels>,
2057        drag_starts: Rc<Cell<usize>>,
2058        drag_ends: Rc<Cell<usize>>,
2059    }
2060
2061    impl TestHandle {
2062        fn new(content_size: Size<Pixels>) -> Self {
2063            Self {
2064                offset: Rc::new(Cell::new(Point::default())),
2065                content_size,
2066                drag_starts: Rc::new(Cell::new(0)),
2067                drag_ends: Rc::new(Cell::new(0)),
2068            }
2069        }
2070    }
2071
2072    impl ScrollbarHandle for TestHandle {
2073        fn viewport_bounds(&self) -> Bounds<Pixels> {
2074            Bounds::new(Point::default(), size(px(100.), px(100.)))
2075        }
2076
2077        fn offset(&self) -> Point<Pixels> {
2078            self.offset.get()
2079        }
2080
2081        fn set_offset(&self, offset: Point<Pixels>) {
2082            self.offset.set(offset);
2083        }
2084
2085        fn content_size(&self) -> Size<Pixels> {
2086            self.content_size
2087        }
2088
2089        fn start_drag(&self) {
2090            self.drag_starts.set(self.drag_starts.get() + 1);
2091        }
2092
2093        fn end_drag(&self) {
2094            self.drag_ends.set(self.drag_ends.get() + 1);
2095        }
2096    }
2097
2098    struct ScrollbarHarness {
2099        handle: TestHandle,
2100        axis: ScrollbarAxis,
2101        mode: ScrollbarMode,
2102    }
2103
2104    impl Render for ScrollbarHarness {
2105        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2106            div()
2107                .relative()
2108                .size(px(100.))
2109                .child(Scrollbar::new(&self.handle).axis(self.axis).mode(self.mode))
2110        }
2111    }
2112
2113    fn harness(
2114        cx: &mut TestAppContext,
2115        axis: ScrollbarAxis,
2116        mode: ScrollbarMode,
2117        content_size: Size<Pixels>,
2118    ) -> (&mut VisualTestContext, TestHandle) {
2119        let handle = TestHandle::new(content_size);
2120        let (_, cx) = cx.add_window_view({
2121            let handle = handle.clone();
2122            move |_, _| ScrollbarHarness { handle, axis, mode }
2123        });
2124        cx.update(|window, cx| window.draw(cx).clear(cx));
2125        (cx, handle)
2126    }
2127
2128    #[test]
2129    fn explicit_viewport_bounds_override_handle_bounds() {
2130        let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.)));
2131        let scrollbar = Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.))))
2132            .viewport_bounds(expected);
2133
2134        assert_eq!(
2135            scrollbar.resolved_viewport_bounds(Bounds::default()),
2136            expected
2137        );
2138    }
2139
2140    #[test]
2141    fn layout_viewport_uses_current_element_bounds() {
2142        let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.)));
2143        let scrollbar =
2144            Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout();
2145
2146        assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected);
2147    }
2148
2149    #[test]
2150    fn typed_styles_are_fluent_and_include_geometry() {
2151        let track = gpui::hsla(0.1, 0.2, 0.3, 1.0);
2152        let border = gpui::hsla(0.2, 0.3, 0.4, 1.0);
2153        let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0);
2154        let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0);
2155        let active = gpui::hsla(0.5, 0.6, 0.7, 1.0);
2156        let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())).styles(|styles| {
2157            styles
2158                .track(|style| {
2159                    style
2160                        .width(px(14.))
2161                        .bg(track)
2162                        .border_color(border)
2163                        .when(false, |style| style.width(px(99.)))
2164                })
2165                .thumb(|style| {
2166                    style
2167                        .width(px(7.))
2168                        .inset(px(3.))
2169                        .radius(px(3.5))
2170                        .min_length(px(40.))
2171                        .bg(thumb)
2172                })
2173                .thumb_hover(|style| style.width(px(9.)).bg(hover))
2174                .thumb_active(|style| style.radius(px(4.5)).bg(active))
2175        });
2176
2177        assert_eq!(scrollbar.styles.track.background, Some(track));
2178        assert_eq!(scrollbar.styles.track.border, Some(border));
2179        assert_eq!(scrollbar.styles.track.width, Some(px(14.)));
2180        assert!(scrollbar.styles.thumb.background.is_some());
2181        assert_eq!(scrollbar.styles.thumb.width, Some(px(7.)));
2182        assert_eq!(scrollbar.styles.thumb.inset, Some(px(3.)));
2183        assert_eq!(scrollbar.styles.thumb.radius, Some(px(3.5)));
2184        assert_eq!(scrollbar.styles.thumb.min_length, Some(px(40.)));
2185        assert!(scrollbar.styles.thumb_hover.background.is_some());
2186        assert_eq!(scrollbar.styles.thumb_hover.width, Some(px(9.)));
2187        assert!(scrollbar.styles.thumb_active.background.is_some());
2188        assert_eq!(scrollbar.styles.thumb_active.radius, Some(px(4.5)));
2189    }
2190
2191    #[gpui::test]
2192    fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) {
2193        cx.update(|cx| {
2194            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()));
2195
2196            let light = gpui::hsla(0., 0., 0.04, 1.0);
2197            crate::Theme::global_mut(cx).tokens.colors.foreground = light;
2198            let (on_light, ..) = scrollbar.style_for_normal(cx);
2199
2200            let dark = gpui::hsla(0., 0., 0.98, 1.0);
2201            crate::Theme::global_mut(cx).tokens.colors.foreground = dark;
2202            let (on_dark, ..) = scrollbar.style_for_normal(cx);
2203
2204            assert_eq!(on_light, Background::from(light.with_alpha(0.35)));
2205            assert_eq!(on_dark, Background::from(dark.with_alpha(0.35)));
2206            // The point of the change: a thumb that never moved with the
2207            // palette was invisible on one of the two surfaces.
2208            assert_ne!(on_light, on_dark);
2209        });
2210    }
2211
2212    #[gpui::test]
2213    fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) {
2214        cx.update(|cx| {
2215            let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0);
2216            crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0);
2217
2218            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()))
2219                .styles(|styles| styles.thumb(|style| style.bg(chosen)));
2220            let (thumb, ..) = scrollbar.style_for_normal(cx);
2221
2222            assert_eq!(thumb, Background::from(chosen));
2223        });
2224    }
2225
2226    #[gpui::test]
2227    fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) {
2228        cx.update(|cx| {
2229            let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0);
2230            let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0);
2231            let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0);
2232
2233            crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new()
2234                .with_mode(ScrollbarMode::Always)
2235                .with_motion(ScrollbarMotion::default())
2236                .with_styles(
2237                    ScrollbarStyles::default()
2238                        .track(|style| style.width(px(13.)).bg(theme_track))
2239                        .thumb(|style| style.width(px(7.)).bg(theme_thumb)),
2240                );
2241
2242            let scrollbar = Scrollbar::new(&TestHandle::new(Size::default()))
2243                .styles(|styles| styles.thumb(|style| style.bg(instance_thumb)));
2244            let (thumb, track, _, width, _, _, _) = scrollbar.style_for_normal(cx);
2245
2246            assert_eq!(thumb, Background::from(instance_thumb));
2247            assert_eq!(track, theme_track);
2248            assert_eq!(width, px(7.));
2249            assert_eq!(cx.theme().scrollbar.styles().track.width, Some(px(13.)));
2250        });
2251    }
2252
2253    #[gpui::test]
2254    fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) {
2255        cx.update(|cx| {
2256            let handle = TestHandle::new(Size::default());
2257            let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling);
2258            let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always);
2259
2260            assert_eq!(scrolling.style_for_normal(cx).3, px(6.));
2261            assert_eq!(always.style_for_normal(cx).3, px(6.));
2262        });
2263    }
2264
2265    #[gpui::test]
2266    fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) {
2267        cx.update(|cx| {
2268            let handle = TestHandle::new(Size::default());
2269            for mode in [
2270                ScrollbarMode::Scrolling,
2271                ScrollbarMode::Hover,
2272                ScrollbarMode::Always,
2273            ] {
2274                let scrollbar = Scrollbar::new(&handle).mode(mode);
2275                assert_eq!(scrollbar.style_for_normal(cx).3, px(6.));
2276                assert_eq!(scrollbar.style_for_hovered_bar(cx).3, px(6.));
2277                assert_eq!(scrollbar.style_for_hovered_thumb(cx).3, px(8.));
2278            }
2279        });
2280    }
2281
2282    #[gpui::test]
2283    fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) {
2284        let (cx, vertical) = harness(
2285            cx,
2286            ScrollbarAxis::Vertical,
2287            ScrollbarMode::Always,
2288            size(px(100.), px(500.)),
2289        );
2290        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2291        assert!(vertical.offset().y < px(0.));
2292        assert_eq!(vertical.offset().x, px(0.));
2293    }
2294
2295    #[gpui::test]
2296    fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) {
2297        let (cx, horizontal) = harness(
2298            cx,
2299            ScrollbarAxis::Horizontal,
2300            ScrollbarMode::Always,
2301            size(px(500.), px(100.)),
2302        );
2303        cx.simulate_click(point(px(80.), px(95.)), Modifiers::default());
2304        assert!(horizontal.offset().x < px(0.));
2305        assert_eq!(horizontal.offset().y, px(0.));
2306    }
2307
2308    #[gpui::test]
2309    fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) {
2310        let (cx, handle) = harness(
2311            cx,
2312            ScrollbarAxis::Both,
2313            ScrollbarMode::Always,
2314            size(px(100.), px(100.)),
2315        );
2316        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2317        assert_eq!(handle.offset(), Point::default());
2318    }
2319
2320    #[gpui::test]
2321    fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) {
2322        let (cx, handle) = harness(
2323            cx,
2324            ScrollbarAxis::Vertical,
2325            ScrollbarMode::Hover,
2326            size(px(100.), px(500.)),
2327        );
2328        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2329        assert_eq!(handle.offset(), Point::default());
2330    }
2331
2332    #[gpui::test]
2333    fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) {
2334        let (cx, handle) = harness(
2335            cx,
2336            ScrollbarAxis::Vertical,
2337            ScrollbarMode::Hover,
2338            size(px(100.), px(500.)),
2339        );
2340        cx.simulate_mouse_down(
2341            point(px(95.), px(20.)),
2342            MouseButton::Left,
2343            Modifiers::default(),
2344        );
2345        cx.simulate_mouse_move(
2346            point(px(95.), px(70.)),
2347            Some(MouseButton::Left),
2348            Modifiers::default(),
2349        );
2350        cx.simulate_mouse_up(
2351            point(px(95.), px(70.)),
2352            MouseButton::Left,
2353            Modifiers::default(),
2354        );
2355
2356        assert_eq!(handle.drag_starts.get(), 0);
2357        assert_eq!(handle.drag_ends.get(), 0);
2358        assert_eq!(handle.offset(), Point::default());
2359    }
2360
2361    #[gpui::test]
2362    fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) {
2363        let (cx, handle) = harness(
2364            cx,
2365            ScrollbarAxis::Vertical,
2366            ScrollbarMode::Hover,
2367            size(px(100.), px(500.)),
2368        );
2369        // Base ships no motion, so the reveal is immediate.
2370        cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default());
2371        cx.run_until_parked();
2372
2373        cx.simulate_click(point(px(95.), px(80.)), Modifiers::default());
2374        assert!(handle.offset().y < px(0.));
2375    }
2376
2377    #[gpui::test]
2378    fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) {
2379        let (cx, handle) = harness(
2380            cx,
2381            ScrollbarAxis::Vertical,
2382            ScrollbarMode::Always,
2383            size(px(100.), px(500.)),
2384        );
2385        cx.simulate_mouse_down(
2386            point(px(95.), px(20.)),
2387            MouseButton::Left,
2388            Modifiers::default(),
2389        );
2390        cx.simulate_mouse_move(
2391            point(px(95.), px(70.)),
2392            Some(MouseButton::Left),
2393            Modifiers::default(),
2394        );
2395        cx.simulate_mouse_up(
2396            point(px(95.), px(70.)),
2397            MouseButton::Left,
2398            Modifiers::default(),
2399        );
2400
2401        assert_eq!(handle.drag_starts.get(), 1);
2402        assert_eq!(handle.drag_ends.get(), 1);
2403    }
2404}