scrollbar.rs

  1use std::{any::Any, cell::Cell, fmt::Debug, ops::Range, rc::Rc, sync::Arc};
  2
  3use crate::{IntoElement, prelude::*, px, relative};
  4use gpui::{
  5    Along, App, Axis as ScrollbarAxis, BorderStyle, Bounds, ContentMask, Corners, Edges, Element,
  6    ElementId, Entity, EntityId, GlobalElementId, Hitbox, Hsla, IsZero, LayoutId, ListState,
  7    MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, ScrollHandle, ScrollWheelEvent,
  8    Size, Style, UniformListScrollHandle, Window, quad,
  9};
 10
 11pub struct Scrollbar {
 12    thumb: Range<f32>,
 13    state: ScrollbarState,
 14    kind: ScrollbarAxis,
 15}
 16
 17#[derive(Default, Debug, Clone, Copy)]
 18enum ThumbState {
 19    #[default]
 20    Inactive,
 21    Hover,
 22    Dragging(Pixels),
 23}
 24
 25impl ScrollableHandle for UniformListScrollHandle {
 26    fn content_size(&self) -> Size<Pixels> {
 27        self.0.borrow().base_handle.content_size()
 28    }
 29
 30    fn set_offset(&self, point: Point<Pixels>) {
 31        self.0.borrow().base_handle.set_offset(point);
 32    }
 33
 34    fn offset(&self) -> Point<Pixels> {
 35        self.0.borrow().base_handle.offset()
 36    }
 37
 38    fn viewport(&self) -> Bounds<Pixels> {
 39        self.0.borrow().base_handle.bounds()
 40    }
 41}
 42
 43impl ScrollableHandle for ListState {
 44    fn content_size(&self) -> Size<Pixels> {
 45        self.content_size_for_scrollbar()
 46    }
 47
 48    fn set_offset(&self, point: Point<Pixels>) {
 49        self.set_offset_from_scrollbar(point);
 50    }
 51
 52    fn offset(&self) -> Point<Pixels> {
 53        self.scroll_px_offset_for_scrollbar()
 54    }
 55
 56    fn drag_started(&self) {
 57        self.scrollbar_drag_started();
 58    }
 59
 60    fn drag_ended(&self) {
 61        self.scrollbar_drag_ended();
 62    }
 63
 64    fn viewport(&self) -> Bounds<Pixels> {
 65        self.viewport_bounds()
 66    }
 67}
 68
 69impl ScrollableHandle for ScrollHandle {
 70    fn content_size(&self) -> Size<Pixels> {
 71        self.padded_content_size()
 72    }
 73
 74    fn set_offset(&self, point: Point<Pixels>) {
 75        self.set_offset(point);
 76    }
 77
 78    fn offset(&self) -> Point<Pixels> {
 79        self.offset()
 80    }
 81
 82    fn viewport(&self) -> Bounds<Pixels> {
 83        self.bounds()
 84    }
 85}
 86
 87pub trait ScrollableHandle: Any + Debug {
 88    fn content_size(&self) -> Size<Pixels>;
 89    fn set_offset(&self, point: Point<Pixels>);
 90    fn offset(&self) -> Point<Pixels>;
 91    fn viewport(&self) -> Bounds<Pixels>;
 92    fn drag_started(&self) {}
 93    fn drag_ended(&self) {}
 94}
 95
 96/// A scrollbar state that should be persisted across frames.
 97#[derive(Clone, Debug)]
 98pub struct ScrollbarState {
 99    thumb_state: Rc<Cell<ThumbState>>,
100    parent_id: Option<EntityId>,
101    scroll_handle: Arc<dyn ScrollableHandle>,
102}
103
104impl ScrollbarState {
105    pub fn new(scroll: impl ScrollableHandle) -> Self {
106        Self {
107            thumb_state: Default::default(),
108            parent_id: None,
109            scroll_handle: Arc::new(scroll),
110        }
111    }
112
113    /// Set a parent model which should be notified whenever this Scrollbar gets a scroll event.
114    pub fn parent_entity<V: 'static>(mut self, v: &Entity<V>) -> Self {
115        self.parent_id = Some(v.entity_id());
116        self
117    }
118
119    pub fn scroll_handle(&self) -> &Arc<dyn ScrollableHandle> {
120        &self.scroll_handle
121    }
122
123    pub fn is_dragging(&self) -> bool {
124        matches!(self.thumb_state.get(), ThumbState::Dragging(_))
125    }
126
127    fn set_dragging(&self, drag_offset: Pixels) {
128        self.set_thumb_state(ThumbState::Dragging(drag_offset));
129        self.scroll_handle.drag_started();
130    }
131
132    fn set_thumb_hovered(&self, hovered: bool) {
133        self.set_thumb_state(if hovered {
134            ThumbState::Hover
135        } else {
136            ThumbState::Inactive
137        });
138    }
139
140    fn set_thumb_state(&self, state: ThumbState) {
141        self.thumb_state.set(state);
142    }
143
144    fn thumb_range(&self, axis: ScrollbarAxis) -> Option<Range<f32>> {
145        const MINIMUM_THUMB_SIZE: Pixels = px(25.);
146        let content_size = self.scroll_handle.content_size().along(axis);
147        let viewport_size = self.scroll_handle.viewport().size.along(axis);
148        if content_size.is_zero() || viewport_size.is_zero() || content_size < viewport_size {
149            return None;
150        }
151
152        let max_offset = content_size - viewport_size;
153        let current_offset = self
154            .scroll_handle
155            .offset()
156            .along(axis)
157            .clamp(-max_offset, Pixels::ZERO)
158            .abs();
159
160        let visible_percentage = viewport_size / content_size;
161        let thumb_size = MINIMUM_THUMB_SIZE.max(viewport_size * visible_percentage);
162        if thumb_size > viewport_size {
163            return None;
164        }
165        let start_offset = (current_offset / max_offset) * (viewport_size - thumb_size);
166        let thumb_percentage_start = start_offset / viewport_size;
167        let thumb_percentage_end = (start_offset + thumb_size) / viewport_size;
168        Some(thumb_percentage_start..thumb_percentage_end)
169    }
170}
171
172impl Scrollbar {
173    pub fn vertical(state: ScrollbarState) -> Option<Self> {
174        Self::new(state, ScrollbarAxis::Vertical)
175    }
176
177    pub fn horizontal(state: ScrollbarState) -> Option<Self> {
178        Self::new(state, ScrollbarAxis::Horizontal)
179    }
180
181    fn new(state: ScrollbarState, kind: ScrollbarAxis) -> Option<Self> {
182        let thumb = state.thumb_range(kind)?;
183        Some(Self { thumb, state, kind })
184    }
185}
186
187impl Element for Scrollbar {
188    type RequestLayoutState = ();
189    type PrepaintState = Hitbox;
190
191    fn id(&self) -> Option<ElementId> {
192        None
193    }
194
195    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
196        None
197    }
198
199    fn request_layout(
200        &mut self,
201        _id: Option<&GlobalElementId>,
202        _inspector_id: Option<&gpui::InspectorElementId>,
203        window: &mut Window,
204        cx: &mut App,
205    ) -> (LayoutId, Self::RequestLayoutState) {
206        let mut style = Style::default();
207        style.flex_grow = 1.;
208        style.flex_shrink = 1.;
209
210        if self.kind == ScrollbarAxis::Vertical {
211            style.size.width = px(12.).into();
212            style.size.height = relative(1.).into();
213        } else {
214            style.size.width = relative(1.).into();
215            style.size.height = px(12.).into();
216        }
217
218        (window.request_layout(style, None, cx), ())
219    }
220
221    fn prepaint(
222        &mut self,
223        _id: Option<&GlobalElementId>,
224        _inspector_id: Option<&gpui::InspectorElementId>,
225        bounds: Bounds<Pixels>,
226        _request_layout: &mut Self::RequestLayoutState,
227        window: &mut Window,
228        _: &mut App,
229    ) -> Self::PrepaintState {
230        window.with_content_mask(Some(ContentMask { bounds }), |window| {
231            window.insert_hitbox(bounds, false)
232        })
233    }
234
235    fn paint(
236        &mut self,
237        _id: Option<&GlobalElementId>,
238        _inspector_id: Option<&gpui::InspectorElementId>,
239        bounds: Bounds<Pixels>,
240        _request_layout: &mut Self::RequestLayoutState,
241        _prepaint: &mut Self::PrepaintState,
242        window: &mut Window,
243        cx: &mut App,
244    ) {
245        const EXTRA_PADDING: Pixels = px(5.0);
246        window.with_content_mask(Some(ContentMask { bounds }), |window| {
247            let axis = self.kind;
248            let colors = cx.theme().colors();
249            let thumb_base_color = match self.state.thumb_state.get() {
250                ThumbState::Dragging(_) => colors.scrollbar_thumb_active_background,
251                ThumbState::Hover => colors.scrollbar_thumb_hover_background,
252                ThumbState::Inactive => colors.scrollbar_thumb_background,
253            };
254
255            let thumb_background = colors.surface_background.blend(thumb_base_color);
256
257            let padded_bounds = Bounds::from_corners(
258                bounds
259                    .origin
260                    .apply_along(axis, |origin| origin + EXTRA_PADDING),
261                bounds
262                    .bottom_right()
263                    .apply_along(axis, |track_end| track_end - 3.0 * EXTRA_PADDING),
264            );
265
266            let thumb_offset = self.thumb.start * padded_bounds.size.along(axis);
267            let thumb_end = self.thumb.end * padded_bounds.size.along(axis);
268
269            let thumb_bounds = Bounds::new(
270                padded_bounds
271                    .origin
272                    .apply_along(axis, |origin| origin + thumb_offset),
273                padded_bounds
274                    .size
275                    .apply_along(axis, |_| thumb_end - thumb_offset)
276                    .apply_along(axis.invert(), |width| width / 1.5),
277            );
278
279            let corners = Corners::all(thumb_bounds.size.along(axis.invert()) / 2.0);
280
281            window.paint_quad(quad(
282                thumb_bounds,
283                corners,
284                thumb_background,
285                Edges::default(),
286                Hsla::transparent_black(),
287                BorderStyle::default(),
288            ));
289
290            let scroll = self.state.scroll_handle.clone();
291
292            enum ScrollbarMouseEvent {
293                GutterClick,
294                ThumbDrag(Pixels),
295            }
296
297            let compute_click_offset =
298                move |event_position: Point<Pixels>,
299                      item_size: Size<Pixels>,
300                      event_type: ScrollbarMouseEvent| {
301                    let viewport_size = padded_bounds.size.along(axis);
302
303                    let thumb_size = thumb_bounds.size.along(axis);
304
305                    let thumb_offset = match event_type {
306                        ScrollbarMouseEvent::GutterClick => thumb_size / 2.,
307                        ScrollbarMouseEvent::ThumbDrag(thumb_offset) => thumb_offset,
308                    };
309
310                    let thumb_start = (event_position.along(axis)
311                        - padded_bounds.origin.along(axis)
312                        - thumb_offset)
313                        .clamp(px(0.), viewport_size - thumb_size);
314
315                    let max_offset = (item_size.along(axis) - viewport_size).max(px(0.));
316                    let percentage = if viewport_size > thumb_size {
317                        thumb_start / (viewport_size - thumb_size)
318                    } else {
319                        0.
320                    };
321
322                    -max_offset * percentage
323                };
324
325            window.on_mouse_event({
326                let scroll = scroll.clone();
327                let state = self.state.clone();
328                move |event: &MouseDownEvent, phase, _, _| {
329                    if !(phase.bubble() && bounds.contains(&event.position)) {
330                        return;
331                    }
332
333                    if thumb_bounds.contains(&event.position) {
334                        let offset = event.position.along(axis) - thumb_bounds.origin.along(axis);
335                        state.set_dragging(offset);
336                    } else {
337                        let click_offset = compute_click_offset(
338                            event.position,
339                            scroll.content_size(),
340                            ScrollbarMouseEvent::GutterClick,
341                        );
342                        scroll.set_offset(scroll.offset().apply_along(axis, |_| click_offset));
343                    }
344                }
345            });
346
347            window.on_mouse_event({
348                let scroll = scroll.clone();
349                move |event: &ScrollWheelEvent, phase, window, _| {
350                    if phase.bubble() && bounds.contains(&event.position) {
351                        let current_offset = scroll.offset();
352                        scroll.set_offset(
353                            current_offset + event.delta.pixel_delta(window.line_height()),
354                        );
355                    }
356                }
357            });
358
359            let state = self.state.clone();
360            window.on_mouse_event(move |event: &MouseMoveEvent, _, window, cx| {
361                match state.thumb_state.get() {
362                    ThumbState::Dragging(drag_state) if event.dragging() => {
363                        let drag_offset = compute_click_offset(
364                            event.position,
365                            scroll.content_size(),
366                            ScrollbarMouseEvent::ThumbDrag(drag_state),
367                        );
368                        scroll.set_offset(scroll.offset().apply_along(axis, |_| drag_offset));
369                        window.refresh();
370                        if let Some(id) = state.parent_id {
371                            cx.notify(id);
372                        }
373                    }
374                    _ => state.set_thumb_hovered(thumb_bounds.contains(&event.position)),
375                }
376            });
377            let state = self.state.clone();
378            let scroll = self.state.scroll_handle.clone();
379            window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| {
380                if phase.bubble() {
381                    if state.is_dragging() {
382                        state.set_thumb_hovered(thumb_bounds.contains(&event.position));
383                    }
384                    scroll.drag_ended();
385                    if let Some(id) = state.parent_id {
386                        cx.notify(id);
387                    }
388                }
389            });
390        })
391    }
392}
393
394impl IntoElement for Scrollbar {
395    type Element = Self;
396
397    fn into_element(self) -> Self::Element {
398        self
399    }
400}