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