Skip to main content

fc_ui/capabilities/scroll/
scrollbar.rs

1//! Scrollbar component - Scrollbar control for scrollable containers.
2
3use std::{
4    cell::Cell,
5    rc::Rc,
6    time::{Duration, Instant},
7};
8
9use gpui::{
10    fill, point, px, relative, size, App, Axis, Bounds, ContentMask, Corner, CursorStyle, Element,
11    GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IntoElement, LayoutId,
12    MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, Position, ScrollEvent,
13    ScrollHandle, Size, Style, Window,
14};
15
16use crate::capabilities::foundation::theme::use_theme;
17
18pub(crate) const WIDTH: Pixels = px(12.0);
19const MIN_THUMB_SIZE: f32 = 48.;
20
21const THUMB_WIDTH: Pixels = px(6.);
22const THUMB_RADIUS: Pixels = px(3.);
23const THUMB_INSET: Pixels = px(3.);
24
25const THUMB_ACTIVE_WIDTH: Pixels = px(8.);
26const THUMB_ACTIVE_RADIUS: Pixels = px(4.);
27const THUMB_ACTIVE_INSET: Pixels = px(2.);
28
29const FADE_OUT_DURATION: f32 = 3.0;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ScrollbarAxis {
33    Vertical,
34    Horizontal,
35    Both,
36}
37
38impl ScrollbarAxis {
39    pub fn is_vertical(&self) -> bool {
40        matches!(self, Self::Vertical)
41    }
42
43    pub fn is_horizontal(&self) -> bool {
44        matches!(self, Self::Horizontal)
45    }
46
47    pub fn is_both(&self) -> bool {
48        matches!(self, Self::Both)
49    }
50
51    #[inline]
52    pub fn has_vertical(&self) -> bool {
53        matches!(self, Self::Vertical | Self::Both)
54    }
55
56    #[inline]
57    pub fn has_horizontal(&self) -> bool {
58        matches!(self, Self::Horizontal | Self::Both)
59    }
60
61    #[inline]
62    fn all(&self) -> Vec<Axis> {
63        match self {
64            Self::Vertical => vec![Axis::Vertical],
65            Self::Horizontal => vec![Axis::Horizontal],
66            Self::Both => vec![Axis::Horizontal, Axis::Vertical],
67        }
68    }
69}
70
71#[derive(Debug, Clone)]
72pub struct ScrollbarState(Rc<Cell<ScrollbarStateInner>>);
73
74#[derive(Debug, Clone, Copy)]
75pub struct ScrollbarStateInner {
76    hovered_on_thumb: Option<Axis>,
77    dragged_axis: Option<Axis>,
78    drag_pos: Point<Pixels>,
79    last_scroll_offset: Point<Pixels>,
80    last_scroll_time: Option<Instant>,
81    last_update: Instant,
82}
83
84impl Default for ScrollbarState {
85    fn default() -> Self {
86        Self(Rc::new(Cell::new(ScrollbarStateInner {
87            hovered_on_thumb: None,
88            dragged_axis: None,
89            drag_pos: point(px(0.), px(0.)),
90            last_scroll_offset: point(px(0.), px(0.)),
91            last_scroll_time: None,
92            last_update: Instant::now(),
93        })))
94    }
95}
96
97impl ScrollbarState {
98    pub fn init_visible(&self) {
99        let inner = self.0.get();
100        self.0
101            .set(inner.with_last_scroll(inner.last_scroll_offset, Some(Instant::now())));
102    }
103}
104
105impl ScrollbarStateInner {
106    fn with_drag_pos(&self, axis: Axis, pos: Point<Pixels>) -> Self {
107        let mut state = *self;
108        if axis == Axis::Vertical {
109            state.drag_pos.y = pos.y;
110        } else {
111            state.drag_pos.x = pos.x;
112        }
113        state.dragged_axis = Some(axis);
114        state
115    }
116
117    fn with_unset_drag_pos(&self) -> Self {
118        let mut state = *self;
119        state.dragged_axis = None;
120        state
121    }
122
123    fn with_hovered_on_thumb(&self, axis: Option<Axis>) -> Self {
124        let mut state = *self;
125        state.hovered_on_thumb = axis;
126        if axis.is_some() {
127            state.last_scroll_time = Some(Instant::now());
128        }
129        state
130    }
131
132    fn with_last_scroll(
133        &self,
134        last_scroll_offset: Point<Pixels>,
135        last_scroll_time: Option<Instant>,
136    ) -> Self {
137        let mut state = *self;
138        state.last_scroll_offset = last_scroll_offset;
139        state.last_scroll_time = last_scroll_time;
140        state
141    }
142
143    fn with_last_update(&self, t: Instant) -> Self {
144        let mut state = *self;
145        state.last_update = t;
146        state
147    }
148
149    fn is_scrollbar_visible(&self) -> bool {
150        if self.dragged_axis.is_some() {
151            return true;
152        }
153
154        if let Some(last_time) = self.last_scroll_time {
155            let elapsed = Instant::now().duration_since(last_time).as_secs_f32();
156            elapsed < FADE_OUT_DURATION
157        } else {
158            false
159        }
160    }
161}
162
163pub struct Scrollbar {
164    axis: ScrollbarAxis,
165    scroll_handle: ScrollHandle,
166    state: ScrollbarState,
167    scroll_size: Option<Size<Pixels>>,
168    always_visible: bool,
169    horizontal_at_top: bool,
170}
171
172impl Scrollbar {
173    pub fn new(axis: ScrollbarAxis, state: &ScrollbarState, scroll_handle: &ScrollHandle) -> Self {
174        Self {
175            state: state.clone(),
176            axis,
177            scroll_handle: scroll_handle.clone(),
178            scroll_size: None,
179            always_visible: false,
180            horizontal_at_top: false,
181        }
182    }
183
184    pub fn vertical(state: &ScrollbarState, scroll_handle: &ScrollHandle) -> Self {
185        Self::new(ScrollbarAxis::Vertical, state, scroll_handle)
186    }
187
188    pub fn horizontal(state: &ScrollbarState, scroll_handle: &ScrollHandle) -> Self {
189        Self::new(ScrollbarAxis::Horizontal, state, scroll_handle)
190    }
191
192    pub fn both(state: &ScrollbarState, scroll_handle: &ScrollHandle) -> Self {
193        Self::new(ScrollbarAxis::Both, state, scroll_handle)
194    }
195
196    pub fn always_visible(mut self) -> Self {
197        self.always_visible = true;
198        self
199    }
200
201    pub fn axis(mut self, axis: ScrollbarAxis) -> Self {
202        self.axis = axis;
203        self
204    }
205
206    pub fn horizontal_top(mut self) -> Self {
207        self.horizontal_at_top = true;
208        self
209    }
210
211    pub fn scroll_size(mut self, scroll_size: Size<Pixels>) -> Self {
212        self.scroll_size = Some(scroll_size);
213        self
214    }
215
216    fn get_thumb_color(&self, theme: &crate::capabilities::foundation::theme::Theme) -> Hsla {
217        theme.tokens.muted_foreground.opacity(0.6)
218    }
219
220    fn get_track_color(&self, theme: &crate::capabilities::foundation::theme::Theme) -> Hsla {
221        theme.tokens.muted.opacity(0.3)
222    }
223
224    fn get_hover_thumb_color(&self, theme: &crate::capabilities::foundation::theme::Theme) -> Hsla {
225        theme.tokens.muted_foreground.opacity(0.8)
226    }
227}
228
229impl IntoElement for Scrollbar {
230    type Element = Self;
231
232    fn into_element(self) -> Self::Element {
233        self
234    }
235}
236
237pub struct PrepaintState {
238    hitbox: Hitbox,
239    states: Vec<AxisPrepaintState>,
240}
241
242pub struct AxisPrepaintState {
243    axis: Axis,
244    bar_hitbox: Hitbox,
245    bounds: Bounds<Pixels>,
246    radius: Pixels,
247    bg: Hsla,
248    thumb_bounds: Bounds<Pixels>,
249    thumb_fill_bounds: Bounds<Pixels>,
250    thumb_bg: Hsla,
251    scroll_size: Pixels,
252    container_size: Pixels,
253    thumb_size: Pixels,
254    margin_end: Pixels,
255}
256
257impl Element for Scrollbar {
258    type RequestLayoutState = ();
259    type PrepaintState = PrepaintState;
260
261    fn id(&self) -> Option<gpui::ElementId> {
262        None
263    }
264
265    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
266        None
267    }
268
269    fn request_layout(
270        &mut self,
271        _: Option<&GlobalElementId>,
272        _: Option<&InspectorElementId>,
273        window: &mut Window,
274        cx: &mut App,
275    ) -> (LayoutId, Self::RequestLayoutState) {
276        let style = Style {
277            position: Position::Absolute,
278            flex_grow: 1.0,
279            flex_shrink: 1.0,
280            size: gpui::Size {
281                width: relative(1.).into(),
282                height: relative(1.).into(),
283            },
284            ..Style::default()
285        };
286
287        (window.request_layout(style, None, cx), ())
288    }
289
290    fn prepaint(
291        &mut self,
292        _: Option<&GlobalElementId>,
293        _: Option<&InspectorElementId>,
294        bounds: Bounds<Pixels>,
295        _: &mut Self::RequestLayoutState,
296        window: &mut Window,
297        cx: &mut App,
298    ) -> Self::PrepaintState {
299        let theme = use_theme(cx);
300
301        let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
302            window.insert_hitbox(bounds, HitboxBehavior::Normal)
303        });
304
305        let mut states = vec![];
306        let mut has_both = self.axis.is_both();
307
308        let scroll_size = self
309            .scroll_size
310            .unwrap_or_else(|| self.scroll_handle.max_offset() + self.scroll_handle.bounds().size);
311
312        for axis in self.axis.all().into_iter() {
313            let is_vertical = axis == Axis::Vertical;
314            let (scroll_area_size, container_size, scroll_position) = if is_vertical {
315                (
316                    scroll_size.height,
317                    hitbox.size.height,
318                    self.scroll_handle.offset().y,
319                )
320            } else {
321                (
322                    scroll_size.width,
323                    hitbox.size.width,
324                    self.scroll_handle.offset().x,
325                )
326            };
327
328            let margin_end = if has_both && !is_vertical {
329                WIDTH
330            } else {
331                px(0.)
332            };
333
334            if scroll_area_size <= container_size {
335                has_both = false;
336                continue;
337            }
338
339            let thumb_length =
340                (container_size / scroll_area_size * container_size).max(px(MIN_THUMB_SIZE));
341            let thumb_start = -(scroll_position / (scroll_area_size - container_size)
342                * (container_size - margin_end - thumb_length));
343            let thumb_end = (thumb_start + thumb_length).min(container_size - margin_end);
344
345            let bounds = Bounds {
346                origin: if is_vertical {
347                    point(hitbox.origin.x + hitbox.size.width - WIDTH, hitbox.origin.y)
348                } else if self.horizontal_at_top {
349                    // Position horizontal scrollbar at top
350                    point(hitbox.origin.x, hitbox.origin.y)
351                } else {
352                    // Position horizontal scrollbar at bottom (default)
353                    point(
354                        hitbox.origin.x,
355                        hitbox.origin.y + hitbox.size.height - WIDTH,
356                    )
357                },
358                size: size(
359                    if is_vertical {
360                        WIDTH
361                    } else {
362                        hitbox.size.width
363                    },
364                    if is_vertical {
365                        hitbox.size.height
366                    } else {
367                        WIDTH
368                    },
369                ),
370            };
371
372            let state_inner = self.state.0.get();
373            let is_hovered_on_thumb = state_inner.hovered_on_thumb == Some(axis);
374            let is_dragged = state_inner.dragged_axis == Some(axis);
375
376            let (thumb_bg, track_bg, thumb_width, inset, radius) =
377                if is_dragged || is_hovered_on_thumb {
378                    (
379                        self.get_hover_thumb_color(&theme),
380                        self.get_track_color(&theme),
381                        THUMB_ACTIVE_WIDTH,
382                        THUMB_ACTIVE_INSET,
383                        THUMB_ACTIVE_RADIUS,
384                    )
385                } else {
386                    (
387                        self.get_thumb_color(&theme),
388                        self.get_track_color(&theme),
389                        THUMB_WIDTH,
390                        THUMB_INSET,
391                        THUMB_RADIUS,
392                    )
393                };
394
395            let thumb_length = thumb_end - thumb_start - inset * 2;
396            let thumb_bounds = if is_vertical {
397                Bounds::from_corner_and_size(
398                    Corner::TopRight,
399                    bounds.top_right() + point(-inset, inset + thumb_start),
400                    size(WIDTH, thumb_length),
401                )
402            } else if self.horizontal_at_top {
403                Bounds::from_corner_and_size(
404                    Corner::TopLeft,
405                    bounds.origin + point(inset + thumb_start, inset),
406                    size(thumb_length, WIDTH),
407                )
408            } else {
409                Bounds::from_corner_and_size(
410                    Corner::BottomLeft,
411                    bounds.bottom_left() + point(inset + thumb_start, -inset),
412                    size(thumb_length, WIDTH),
413                )
414            };
415
416            let thumb_fill_bounds = if is_vertical {
417                Bounds::from_corner_and_size(
418                    Corner::TopRight,
419                    bounds.top_right() + point(-inset, inset + thumb_start),
420                    size(thumb_width, thumb_length),
421                )
422            } else if self.horizontal_at_top {
423                Bounds::from_corner_and_size(
424                    Corner::TopLeft,
425                    bounds.origin + point(inset + thumb_start, inset),
426                    size(thumb_length, thumb_width),
427                )
428            } else {
429                Bounds::from_corner_and_size(
430                    Corner::BottomLeft,
431                    bounds.bottom_left() + point(inset + thumb_start, -inset),
432                    size(thumb_length, thumb_width),
433                )
434            };
435
436            let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
437                window.insert_hitbox(bounds, HitboxBehavior::Normal)
438            });
439
440            states.push(AxisPrepaintState {
441                axis,
442                bar_hitbox,
443                bounds,
444                radius,
445                bg: track_bg,
446                thumb_bounds,
447                thumb_fill_bounds,
448                thumb_bg,
449                scroll_size: scroll_area_size,
450                container_size,
451                thumb_size: thumb_length,
452                margin_end,
453            })
454        }
455
456        PrepaintState { hitbox, states }
457    }
458
459    fn paint(
460        &mut self,
461        _: Option<&GlobalElementId>,
462        _: Option<&InspectorElementId>,
463        _: Bounds<Pixels>,
464        _: &mut Self::RequestLayoutState,
465        prepaint: &mut Self::PrepaintState,
466        window: &mut Window,
467        cx: &mut App,
468    ) {
469        let view_id = window.current_view();
470        let hitbox_bounds = prepaint.hitbox.bounds;
471        let is_visible = self.state.0.get().is_scrollbar_visible() || self.always_visible;
472
473        if self.scroll_handle.offset() != self.state.0.get().last_scroll_offset {
474            self.state.0.set(
475                self.state
476                    .0
477                    .get()
478                    .with_last_scroll(self.scroll_handle.offset(), Some(Instant::now())),
479            );
480            cx.notify(view_id);
481        }
482
483        if !is_visible && !self.always_visible {
484            return;
485        }
486
487        if !self.always_visible {
488            let state = self.state.0.get();
489            if state.dragged_axis.is_none() && state.hovered_on_thumb.is_none() {
490                if let Some(last_scroll_time) = state.last_scroll_time {
491                    let remaining = FADE_OUT_DURATION - last_scroll_time.elapsed().as_secs_f32();
492                    if remaining > 0.0 {
493                        cx.spawn(async move |cx| {
494                            cx.background_executor()
495                                .timer(Duration::from_secs_f32(remaining))
496                                .await;
497                            _ = cx.update(|cx| cx.notify(view_id));
498                        })
499                        .detach();
500                    }
501                }
502            }
503        }
504
505        window.with_content_mask(
506            Some(ContentMask {
507                bounds: hitbox_bounds,
508            }),
509            |window| {
510                for state in prepaint.states.iter() {
511                    let axis = state.axis;
512                    let radius = state.radius;
513                    let bounds = state.bounds;
514                    let thumb_bounds = state.thumb_bounds;
515                    let scroll_area_size = state.scroll_size;
516                    let container_size = state.container_size;
517                    let thumb_size = state.thumb_size;
518                    let margin_end = state.margin_end;
519                    let is_vertical = axis == Axis::Vertical;
520
521                    window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox);
522
523                    window.paint_layer(hitbox_bounds, |cx| {
524                        cx.paint_quad(fill(state.bounds, state.bg));
525
526                        cx.paint_quad(
527                            fill(state.thumb_fill_bounds, state.thumb_bg).corner_radii(radius),
528                        );
529                    });
530
531                    window.on_mouse_event({
532                        let state = self.state.clone();
533                        let scroll_handle = self.scroll_handle.clone();
534
535                        move |event: &ScrollEvent, phase, _hitbox, cx| {
536                            if phase.bubble()
537                                && hitbox_bounds.contains(&event.position)
538                                && scroll_handle.offset() != state.0.get().last_scroll_offset
539                            {
540                                state.0.set(state.0.get().with_last_scroll(
541                                    scroll_handle.offset(),
542                                    Some(Instant::now()),
543                                ));
544                                cx.notify(view_id);
545                            }
546                        }
547                    });
548
549                    let safe_range = (-scroll_area_size + container_size)..px(0.);
550
551                    window.on_mouse_event({
552                        let state = self.state.clone();
553                        let scroll_handle = self.scroll_handle.clone();
554
555                        move |event: &MouseDownEvent, phase, _hitbox, cx| {
556                            if phase.bubble() && bounds.contains(&event.position) {
557                                cx.stop_propagation();
558
559                                if thumb_bounds.contains(&event.position) {
560                                    let pos = event.position - thumb_bounds.origin;
561                                    state.0.set(state.0.get().with_drag_pos(axis, pos));
562                                    cx.notify(view_id);
563                                } else {
564                                    let offset = scroll_handle.offset();
565                                    let percentage = if is_vertical {
566                                        (event.position.y - thumb_size / 2. - bounds.origin.y)
567                                            / (bounds.size.height - thumb_size)
568                                    } else {
569                                        (event.position.x - thumb_size / 2. - bounds.origin.x)
570                                            / (bounds.size.width - thumb_size)
571                                    }
572                                    .min(1.);
573
574                                    if is_vertical {
575                                        scroll_handle.set_offset(point(
576                                            offset.x,
577                                            (-scroll_area_size * percentage)
578                                                .clamp(safe_range.start, safe_range.end),
579                                        ));
580                                    } else {
581                                        scroll_handle.set_offset(point(
582                                            (-scroll_area_size * percentage)
583                                                .clamp(safe_range.start, safe_range.end),
584                                            offset.y,
585                                        ));
586                                    }
587                                }
588                            }
589                        }
590                    });
591
592                    window.on_mouse_event({
593                        let scroll_handle = self.scroll_handle.clone();
594                        let state = self.state.clone();
595
596                        move |event: &MouseMoveEvent, _phase, _hitbox, cx| {
597                            let mut notify = false;
598
599                            if thumb_bounds.contains(&event.position) {
600                                if state.0.get().hovered_on_thumb != Some(axis) {
601                                    state.0.set(state.0.get().with_hovered_on_thumb(Some(axis)));
602                                    notify = true;
603                                }
604                            } else {
605                                if state.0.get().hovered_on_thumb == Some(axis) {
606                                    state.0.set(state.0.get().with_hovered_on_thumb(None));
607                                    notify = true;
608                                }
609                            }
610
611                            if state.0.get().dragged_axis == Some(axis) && event.dragging() {
612                                let drag_pos = state.0.get().drag_pos;
613
614                                let percentage = (if is_vertical {
615                                    (event.position.y - drag_pos.y - bounds.origin.y)
616                                        / (bounds.size.height - thumb_size)
617                                } else {
618                                    (event.position.x - drag_pos.x - bounds.origin.x)
619                                        / (bounds.size.width - thumb_size - margin_end)
620                                })
621                                .clamp(0., 1.);
622
623                                let offset = if is_vertical {
624                                    point(
625                                        scroll_handle.offset().x,
626                                        (-(scroll_area_size - container_size) * percentage)
627                                            .clamp(safe_range.start, safe_range.end),
628                                    )
629                                } else {
630                                    point(
631                                        (-(scroll_area_size - container_size) * percentage)
632                                            .clamp(safe_range.start, safe_range.end),
633                                        scroll_handle.offset().y,
634                                    )
635                                };
636
637                                if (scroll_handle.offset().y - offset.y).abs() > px(1.)
638                                    || (scroll_handle.offset().x - offset.x).abs() > px(1.)
639                                {
640                                    scroll_handle.set_offset(offset);
641                                    state.0.set(state.0.get().with_last_update(Instant::now()));
642                                    notify = true;
643                                }
644                            }
645
646                            if notify {
647                                cx.notify(view_id);
648                            }
649                        }
650                    });
651
652                    window.on_mouse_event({
653                        let state = self.state.clone();
654
655                        move |_event: &MouseUpEvent, phase, _hitbox, cx| {
656                            if phase.bubble() {
657                                state.0.set(state.0.get().with_unset_drag_pos());
658                                cx.notify(view_id);
659                            }
660                        }
661                    });
662                }
663            },
664        );
665    }
666}