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