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