Skip to main content

gpui_base/
scrollbar.rs

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