Skip to main content

gpui_base/
scrollbar.rs

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