1use std::{cell::RefCell, rc::Rc};
21
22use arc_motion::{arc_spring, is_reduced_motion, motion_now};
23use arc_tokens::{ActiveArcTheme as _, Radii};
24use gpui_kit::{
25 AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
26 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce, Role,
27 ScrollDelta, ScrollEvent, SharedString, Styled, TestSupportExt as _, Window, canvas, div,
28 linear_color_stop, linear_gradient, prelude::*, px,
29};
30
31pub const SCROLL_AREA_MIN_THUMB: f32 = 28.0;
33pub const SCROLL_AREA_DEFAULT_FADE: f32 = 28.0;
35pub const SCROLL_AREA_DEFAULT_HIDE_DELAY_SECS: f64 = 0.90;
37
38#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
40pub enum ScrollAreaOrientation {
41 #[default]
42 Vertical,
43 Horizontal,
44 Both,
45}
46
47#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49pub enum ScrollbarsVisibility {
50 #[default]
52 Auto,
53 Always,
55}
56
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
59pub struct ScrollAreaEdges {
60 pub top: bool,
61 pub bottom: bool,
62 pub left: bool,
63 pub right: bool,
64}
65
66pub fn scroll_area_track_inset(corner_radius_px: f32) -> f32 {
69 let r = corner_radius_px.max(0.0);
70 if r <= 3.0 { 3.0 } else { r.ceil().max(6.0) }
71}
72
73pub fn scroll_area_thumb_metrics(
76 scroll: f32,
77 client_len: f32,
78 content_len: f32,
79 track_len: f32,
80) -> Option<(f32, f32)> {
81 let max_scroll = (content_len - client_len).max(0.0);
82 if max_scroll <= 0.5 || track_len <= 1.0 || content_len <= 1.0 {
83 return None;
84 }
85 let size = (track_len * (client_len / content_len))
86 .max(SCROLL_AREA_MIN_THUMB)
87 .min(track_len);
88 let ratio = (scroll.clamp(0.0, max_scroll)) / max_scroll;
89 let offset = (track_len - size) * ratio;
90 Some((size, offset))
91}
92
93pub fn scroll_area_edge_fades(scroll: f32, max_scroll: f32, fade_cap: f32) -> (f32, f32) {
99 if fade_cap <= 0.0 || max_scroll <= 0.5 {
100 return (0.0, 0.0);
101 }
102 let clamped = scroll.clamp(0.0, max_scroll);
103 let start = clamped.min(fade_cap);
104 let end = (max_scroll - clamped).max(0.0).min(fade_cap);
105 (start, end)
106}
107
108#[derive(Clone, Copy, Debug, Eq, PartialEq)]
109enum DragAxis {
110 Y,
111 X,
112}
113
114type EdgeCallback = Rc<dyn Fn(&ScrollAreaEdges, &mut Window, &mut App)>;
115
116#[derive(Clone)]
117struct ScrollAreaInternal {
118 scroll_top: f32,
119 scroll_left: f32,
120 last_scroll_at: f64,
121 root_hovered: bool,
122 track_y_hovered: bool,
123 track_x_hovered: bool,
124 dragging: Option<DragAxis>,
125 drag_start_coord: f32,
126 drag_start_scroll: f32,
127 drag_ratio: f32,
128 last_edges: ScrollAreaEdges,
129 viewport_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
130 content_size: Rc<RefCell<(f32, f32)>>,
131 focus_handle: FocusHandle,
132}
133
134impl ScrollAreaInternal {
135 fn new(now: f64, focus_handle: FocusHandle) -> Self {
136 Self {
137 scroll_top: 0.0,
138 scroll_left: 0.0,
139 last_scroll_at: now - 10.0,
140 root_hovered: false,
141 track_y_hovered: false,
142 track_x_hovered: false,
143 dragging: None,
144 drag_start_coord: 0.0,
145 drag_start_scroll: 0.0,
146 drag_ratio: 1.0,
147 last_edges: ScrollAreaEdges::default(),
148 viewport_bounds: Rc::new(RefCell::new(None)),
149 content_size: Rc::new(RefCell::new((320.0, 480.0))),
150 focus_handle,
151 }
152 }
153}
154
155#[derive(IntoElement)]
158pub struct ScrollArea {
159 id: ElementId,
160 orientation: ScrollAreaOrientation,
161 fade: f32,
162 corner_radius: f32,
163 scrollbars: ScrollbarsVisibility,
164 hide_delay_secs: f64,
165 max_height: Option<f32>,
166 max_width: Option<f32>,
167 content_width: Option<f32>,
168 content_height: Option<f32>,
169 wheel_to_horizontal: bool,
170 label: Option<SharedString>,
171 surface_color: Option<Hsla>,
172 on_edge_change: Option<EdgeCallback>,
173 body: Option<AnyElement>,
174}
175
176impl ScrollArea {
177 pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
178 Self {
179 id: id.into(),
180 orientation: ScrollAreaOrientation::Vertical,
181 fade: SCROLL_AREA_DEFAULT_FADE,
182 corner_radius: f32::from(Radii::CONTROL),
183 scrollbars: ScrollbarsVisibility::Auto,
184 hide_delay_secs: SCROLL_AREA_DEFAULT_HIDE_DELAY_SECS,
185 max_height: None,
186 max_width: None,
187 content_width: None,
188 content_height: None,
189 wheel_to_horizontal: true,
190 label: None,
191 surface_color: None,
192 on_edge_change: None,
193 body: Some(content.into_any_element()),
194 }
195 }
196
197 pub fn orientation(mut self, orientation: ScrollAreaOrientation) -> Self {
198 self.orientation = orientation;
199 self
200 }
201
202 pub fn corner_radius(mut self, radius: impl Into<Pixels>) -> Self {
205 self.corner_radius = f32::from(radius.into()).max(0.0);
206 self
207 }
208
209 pub fn fade(mut self, fade_px: f32) -> Self {
211 self.fade = fade_px.max(0.0);
212 self
213 }
214
215 pub fn scrollbars(mut self, scrollbars: ScrollbarsVisibility) -> Self {
216 self.scrollbars = scrollbars;
217 self
218 }
219
220 pub fn hide_delay_ms(mut self, ms: u64) -> Self {
222 self.hide_delay_secs = (ms as f64) / 1000.0;
223 self
224 }
225
226 pub fn max_height(mut self, max_height_px: f32) -> Self {
227 self.max_height = Some(max_height_px.max(60.0));
228 self
229 }
230
231 pub fn max_width(mut self, max_width_px: f32) -> Self {
232 self.max_width = Some(max_width_px.max(120.0));
233 self
234 }
235
236 pub fn content_size(mut self, width: Option<f32>, height: Option<f32>) -> Self {
238 self.content_width = width;
239 self.content_height = height;
240 self
241 }
242
243 pub fn wheel_to_horizontal(mut self, enabled: bool) -> Self {
244 self.wheel_to_horizontal = enabled;
245 self
246 }
247
248 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
249 self.label = Some(label.into());
250 self
251 }
252
253 pub fn surface_color(mut self, color: Hsla) -> Self {
254 self.surface_color = Some(color);
255 self
256 }
257
258 pub fn on_edge_change(
259 mut self,
260 handler: impl Fn(&ScrollAreaEdges, &mut Window, &mut App) + 'static,
261 ) -> Self {
262 self.on_edge_change = Some(Rc::new(handler));
263 self
264 }
265}
266
267impl RenderOnce for ScrollArea {
268 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
269 let theme = cx.arc_theme().clone();
270 let colors = theme.colors;
271 let motion = theme.motion;
272 let reduced = is_reduced_motion(cx);
273 let now = motion_now(cx);
274
275 let state_id =
276 ElementId::NamedChild(self.id.clone().into(), "__arc-scroll-area-state".into());
277 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
278 ScrollAreaInternal::new(now, cx.focus_handle())
279 });
280
281 let snap = internal.read(cx).clone();
282 let vertical = self.orientation != ScrollAreaOrientation::Horizontal;
283 let horizontal = self.orientation != ScrollAreaOrientation::Vertical;
284
285 let vp_rect = *snap.viewport_bounds.borrow();
286 let client_w = vp_rect
287 .map(|b| f32::from(b.size.width))
288 .or(self.max_width)
289 .unwrap_or(480.0)
290 .max(60.0);
291 let client_h = vp_rect
292 .map(|b| f32::from(b.size.height))
293 .or(self.max_height)
294 .unwrap_or(240.0)
295 .max(60.0);
296
297 let (measured_w, measured_h) = *snap.content_size.borrow();
298 let content_w = self.content_width.unwrap_or(measured_w).max(client_w);
299 let content_h = self.content_height.unwrap_or(measured_h).max(client_h);
300
301 let max_y = if vertical {
302 (content_h - client_h).max(0.0)
303 } else {
304 0.0
305 };
306 let max_x = if horizontal {
307 (content_w - client_w).max(0.0)
308 } else {
309 0.0
310 };
311
312 let scroll_y = snap.scroll_top.clamp(0.0, max_y);
313 let scroll_x = snap.scroll_left.clamp(0.0, max_x);
314
315 let edges = ScrollAreaEdges {
316 top: vertical && scroll_y > 0.5,
317 bottom: vertical && (max_y - scroll_y) > 0.5,
318 left: horizontal && scroll_x > 0.5,
319 right: horizontal && (max_x - scroll_x) > 0.5,
320 };
321 if edges != snap.last_edges {
322 internal.update(cx, |s, _| {
323 s.last_edges = edges;
324 });
325 if let Some(cb) = self.on_edge_change.clone() {
326 window.defer(cx, move |window, cx| {
327 cb(&edges, window, cx);
328 });
329 }
330 }
331
332 let scrolling_active = (now - snap.last_scroll_at) < self.hide_delay_secs;
333 if scrolling_active {
334 window.request_animation_frame();
335 }
336
337 let bars_visible = self.scrollbars == ScrollbarsVisibility::Always
338 || snap.root_hovered
339 || snap.dragging.is_some()
340 || scrolling_active;
341 let bar_alpha = if reduced {
342 if bars_visible { 1.0 } else { 0.0 }
343 } else {
344 arc_spring(
345 (self.id.clone(), "bar-alpha"),
346 if bars_visible { 1.0 } else { 0.0 },
347 motion.spring.snappy,
348 window,
349 cx,
350 )
351 };
352
353 let (fade_top, fade_bottom) = if vertical {
354 scroll_area_edge_fades(scroll_y, max_y, self.fade)
355 } else {
356 (0.0, 0.0)
357 };
358 let (fade_left, fade_right) = if horizontal {
359 scroll_area_edge_fades(scroll_x, max_x, self.fade)
360 } else {
361 (0.0, 0.0)
362 };
363
364 let both_axes = self.orientation == ScrollAreaOrientation::Both;
365 let corner_inset = scroll_area_track_inset(self.corner_radius);
366 let track_y_start = corner_inset;
367 let track_y_end = if both_axes {
368 corner_inset.max(13.0)
369 } else {
370 corner_inset
371 };
372 let track_x_start = corner_inset;
373 let track_x_end = if both_axes {
374 corner_inset.max(13.0)
375 } else {
376 corner_inset
377 };
378 let track_y_len = (client_h - track_y_start - track_y_end).max(28.0);
379 let track_x_len = (client_w - track_x_start - track_x_end).max(28.0);
380
381 let thumb_y = if vertical {
382 scroll_area_thumb_metrics(scroll_y, client_h, content_h, track_y_len)
383 } else {
384 None
385 };
386 let thumb_x = if horizontal {
387 scroll_area_thumb_metrics(scroll_x, client_w, content_w, track_x_len)
388 } else {
389 None
390 };
391
392 let vp_ref = snap.viewport_bounds.clone();
393 let vp_ref_paint = snap.viewport_bounds.clone();
394 let drag_state = snap.dragging;
395 let int_win = internal.clone();
396 let viewport_probe = canvas(
397 move |rect, _, _| {
398 *vp_ref.borrow_mut() = Some(rect);
399 },
400 move |rect, _, window, _| {
401 let prev = *vp_ref_paint.borrow();
402 if prev.is_none_or(|b| {
403 (f32::from(b.size.width) - f32::from(rect.size.width)).abs() > 0.5
404 || (f32::from(b.size.height) - f32::from(rect.size.height)).abs() > 0.5
405 }) {
406 *vp_ref_paint.borrow_mut() = Some(rect);
407 window.request_animation_frame();
408 }
409 if let Some(axis) = drag_state {
410 let st_move = int_win.clone();
411 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
412 if !phase.bubble() {
413 return;
414 }
415 let t = motion_now(cx);
416 let coord = match axis {
417 DragAxis::Y => f32::from(event.position.y),
418 DragAxis::X => f32::from(event.position.x),
419 };
420 st_move.update(cx, |s, _| {
421 let delta = (coord - s.drag_start_coord) * s.drag_ratio;
422 match axis {
423 DragAxis::Y => {
424 s.scroll_top = (s.drag_start_scroll + delta).clamp(0.0, max_y);
425 }
426 DragAxis::X => {
427 s.scroll_left = (s.drag_start_scroll + delta).clamp(0.0, max_x);
428 }
429 }
430 s.last_scroll_at = t;
431 });
432 window.refresh();
433 });
434
435 let st_up = int_win.clone();
436 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
437 if !phase.bubble() {
438 return;
439 }
440 let t = motion_now(cx);
441 st_up.update(cx, |s, _| {
442 s.dragging = None;
443 s.last_scroll_at = t;
444 });
445 window.refresh();
446 });
447 }
448 },
449 )
450 .absolute()
451 .inset_0();
452
453 let content_ref = snap.content_size.clone();
454 let content_probe = canvas(
455 move |rect, _, _| {
456 let w = f32::from(rect.size.width);
457 let h = f32::from(rect.size.height);
458 if w > 4.0 && h > 4.0 {
459 *content_ref.borrow_mut() = (w, h);
460 }
461 },
462 |_, _, _, _| {},
463 )
464 .absolute()
465 .inset_0();
466
467 let mut inner = div()
468 .relative()
469 .flex_none()
470 .top(px(-scroll_y))
471 .left(px(-scroll_x))
472 .child(content_probe);
473 if let Some(cw) = self.content_width {
474 inner = inner.w(px(cw));
475 } else if !horizontal {
476 inner = inner.w_full();
477 } else {
478 inner = inner.min_w_full();
479 }
480 if let Some(ch) = self.content_height {
481 inner = inner.h(px(ch));
482 }
483 if let Some(body) = self.body {
484 inner = inner.child(body);
485 }
486
487 let fade_color = self.surface_color.unwrap_or(colors.surface);
488
489 let int_hover = internal.clone();
490 let int_wheel = internal.clone();
491 let int_key = internal.clone();
492 let focus_click = snap.focus_handle.clone();
493 let orient = self.orientation;
494 let wheel_horiz = self.wheel_to_horizontal;
495
496 let mut root = div()
497 .id(self.id.clone())
498 .test_support()
499 .track_focus(&snap.focus_handle)
500 .relative()
501 .w_full()
502 .overflow_hidden()
503 .when_some(self.max_height, |d, h| d.h(px(h)))
504 .when_some(self.max_width, |d, w| d.max_w(px(w)))
505 .when_some(self.label, |d, lbl| d.role(Role::Region).aria_label(lbl))
506 .on_hover(move |hovered, window, cx| {
507 int_hover.update(cx, |s, _| {
508 s.root_hovered = *hovered;
509 });
510 window.refresh();
511 })
512 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
513 focus_click.focus(window, cx);
514 })
515 .on_scroll(move |event: &ScrollEvent, window, cx| {
516 let (dx, dy) = match event.delta {
517 ScrollDelta::Pixels(pt) => (-f32::from(pt.x), -f32::from(pt.y)),
518 ScrollDelta::Lines(pt) => (-pt.x * 28.0, -pt.y * 28.0),
519 };
520 let shift = event.modifiers.shift;
521 let t = motion_now(cx);
522 let mut should_stop = false;
523 int_wheel.update(cx, |s, _| {
524 let prev_top = s.scroll_top;
525 let prev_left = s.scroll_left;
526 let use_horizontal = (orient == ScrollAreaOrientation::Horizontal
527 && (wheel_horiz || shift))
528 || (horizontal && shift);
529
530 if use_horizontal && dx.abs() < dy.abs() {
531 s.scroll_left = (s.scroll_left + dy).clamp(0.0, max_x);
532 should_stop =
533 shift || max_x > 0.5 || (s.scroll_left - prev_left).abs() > 0.01;
534 } else if shift && !horizontal {
535 should_stop = true;
536 } else {
537 if vertical {
538 s.scroll_top = (s.scroll_top + dy).clamp(0.0, max_y);
539 if max_y > 0.5 || (s.scroll_top - prev_top).abs() > 0.01 {
540 should_stop = true;
541 }
542 }
543 if horizontal {
544 s.scroll_left = (s.scroll_left + dx).clamp(0.0, max_x);
545 if shift || max_x > 0.5 || (s.scroll_left - prev_left).abs() > 0.01 {
546 should_stop = true;
547 }
548 }
549 }
550 s.last_scroll_at = t;
551 });
552 if should_stop {
553 cx.stop_propagation();
554 }
555 window.refresh();
556 })
557 .on_key_down(move |event: &KeyDownEvent, window, cx| {
558 let key = event.keystroke.key.as_str();
559 let t = motion_now(cx);
560 let mut handled = true;
561 int_key.update(cx, |s, _| {
562 match key {
563 "down" | "arrowdown" if vertical => {
564 s.scroll_top = (s.scroll_top + 36.0).clamp(0.0, max_y);
565 }
566 "up" | "arrowup" if vertical => {
567 s.scroll_top = (s.scroll_top - 36.0).clamp(0.0, max_y);
568 }
569 "right" | "arrowright" if horizontal => {
570 s.scroll_left = (s.scroll_left + 36.0).clamp(0.0, max_x);
571 }
572 "left" | "arrowleft" if horizontal => {
573 s.scroll_left = (s.scroll_left - 36.0).clamp(0.0, max_x);
574 }
575 "pagedown" if vertical => {
576 s.scroll_top = (s.scroll_top + client_h * 0.9).clamp(0.0, max_y);
577 }
578 "pageup" if vertical => {
579 s.scroll_top = (s.scroll_top - client_h * 0.9).clamp(0.0, max_y);
580 }
581 "home" => {
582 if vertical {
583 s.scroll_top = 0.0;
584 } else if horizontal {
585 s.scroll_left = 0.0;
586 }
587 }
588 "end" => {
589 if vertical {
590 s.scroll_top = max_y;
591 } else if horizontal {
592 s.scroll_left = max_x;
593 }
594 }
595 _ => {
596 handled = false;
597 }
598 }
599 if handled {
600 s.last_scroll_at = t;
601 }
602 });
603 if handled {
604 window.refresh();
605 }
606 })
607 .child(viewport_probe)
608 .child(inner);
609
610 if fade_top > 0.5 {
611 root = root.child(
612 div()
613 .absolute()
614 .top_0()
615 .left_0()
616 .right_0()
617 .h(px(fade_top))
618 .bg(linear_gradient(
619 180.0,
620 linear_color_stop(fade_color, 0.0),
621 linear_color_stop(fade_color.opacity(0.0), 1.0),
622 )),
623 );
624 }
625 if fade_bottom > 0.5 {
626 root = root.child(
627 div()
628 .absolute()
629 .bottom_0()
630 .left_0()
631 .right_0()
632 .h(px(fade_bottom))
633 .bg(linear_gradient(
634 180.0,
635 linear_color_stop(fade_color.opacity(0.0), 0.0),
636 linear_color_stop(fade_color, 1.0),
637 )),
638 );
639 }
640 if fade_left > 0.5 {
641 root = root.child(
642 div()
643 .absolute()
644 .top_0()
645 .bottom_0()
646 .left_0()
647 .w(px(fade_left))
648 .bg(linear_gradient(
649 90.0,
650 linear_color_stop(fade_color, 0.0),
651 linear_color_stop(fade_color.opacity(0.0), 1.0),
652 )),
653 );
654 }
655 if fade_right > 0.5 {
656 root = root.child(
657 div()
658 .absolute()
659 .top_0()
660 .bottom_0()
661 .right_0()
662 .w(px(fade_right))
663 .bg(linear_gradient(
664 90.0,
665 linear_color_stop(fade_color.opacity(0.0), 0.0),
666 linear_color_stop(fade_color, 1.0),
667 )),
668 );
669 }
670
671 if let Some((thumb_h, thumb_y_off)) = thumb_y {
673 let active_y = snap.track_y_hovered || snap.dragging == Some(DragAxis::Y);
674 let pill_w = if active_y { 7.0 } else { 5.0 };
675 let pill_right = if active_y { 2.0 } else { 3.0 };
676 let pill_color = colors
677 .foreground
678 .opacity((if active_y { 0.46 } else { 0.30 }) * bar_alpha);
679
680 let int_y_hover = internal.clone();
681 let int_y_thumb = internal.clone();
682 let int_y_track = internal.clone();
683 let vp_for_y = snap.viewport_bounds.clone();
684
685 root = root.child(
686 div()
687 .id(ElementId::NamedChild(
688 self.id.clone().into(),
689 "track-y".into(),
690 ))
691 .test_support()
692 .absolute()
693 .top(px(track_y_start))
694 .right(px(1.0))
695 .bottom(px(track_y_end))
696 .w(px(11.0))
697 .overflow_hidden()
698 .cursor_pointer()
699 .on_hover(move |hovered, window, cx| {
700 int_y_hover.update(cx, |s, _| {
701 s.track_y_hovered = *hovered;
702 });
703 window.refresh();
704 })
705 .on_mouse_down(
706 MouseButton::Left,
707 move |event: &MouseDownEvent, window, cx| {
708 if let Some(vp) = *vp_for_y.borrow() {
709 let local_y = f32::from(event.position.y)
710 - f32::from(vp.origin.y)
711 - track_y_start;
712 if local_y < thumb_y_off || local_y > thumb_y_off + thumb_h {
713 let dir = if local_y < thumb_y_off { -1.0 } else { 1.0 };
714 let t = motion_now(cx);
715 int_y_track.update(cx, |s, _| {
716 s.scroll_top =
717 (s.scroll_top + client_h * 0.9 * dir).clamp(0.0, max_y);
718 s.last_scroll_at = t;
719 });
720 window.refresh();
721 }
722 }
723 },
724 )
725 .child(
726 div()
727 .id(ElementId::NamedChild(
728 self.id.clone().into(),
729 "thumb-y".into(),
730 ))
731 .test_support()
732 .absolute()
733 .top(px(thumb_y_off))
734 .right(px(pill_right))
735 .w(px(pill_w))
736 .h(px(thumb_h))
737 .rounded(Radii::PILL)
738 .bg(pill_color)
739 .on_mouse_down(
740 MouseButton::Left,
741 move |event: &MouseDownEvent, window, cx| {
742 let t = motion_now(cx);
743 let ratio = max_y / (track_y_len - thumb_h).max(1.0);
744 int_y_thumb.update(cx, |s, _| {
745 s.dragging = Some(DragAxis::Y);
746 s.drag_start_coord = f32::from(event.position.y);
747 s.drag_start_scroll = s.scroll_top;
748 s.drag_ratio = ratio;
749 s.last_scroll_at = t;
750 });
751 window.refresh();
752 },
753 ),
754 ),
755 );
756 }
757
758 if let Some((thumb_w, thumb_x_off)) = thumb_x {
760 let active_x = snap.track_x_hovered || snap.dragging == Some(DragAxis::X);
761 let pill_h = if active_x { 7.0 } else { 5.0 };
762 let pill_bottom = if active_x { 2.0 } else { 3.0 };
763 let pill_color = colors
764 .foreground
765 .opacity((if active_x { 0.46 } else { 0.30 }) * bar_alpha);
766
767 let int_x_hover = internal.clone();
768 let int_x_thumb = internal.clone();
769 let int_x_track = internal.clone();
770 let vp_for_x = snap.viewport_bounds.clone();
771
772 root = root.child(
773 div()
774 .id(ElementId::NamedChild(
775 self.id.clone().into(),
776 "track-x".into(),
777 ))
778 .test_support()
779 .absolute()
780 .left(px(track_x_start))
781 .right(px(track_x_end))
782 .bottom(px(1.0))
783 .h(px(11.0))
784 .overflow_hidden()
785 .cursor_pointer()
786 .on_hover(move |hovered, window, cx| {
787 int_x_hover.update(cx, |s, _| {
788 s.track_x_hovered = *hovered;
789 });
790 window.refresh();
791 })
792 .on_mouse_down(
793 MouseButton::Left,
794 move |event: &MouseDownEvent, window, cx| {
795 if let Some(vp) = *vp_for_x.borrow() {
796 let local_x = f32::from(event.position.x)
797 - f32::from(vp.origin.x)
798 - track_x_start;
799 if local_x < thumb_x_off || local_x > thumb_x_off + thumb_w {
800 let dir = if local_x < thumb_x_off { -1.0 } else { 1.0 };
801 let t = motion_now(cx);
802 int_x_track.update(cx, |s, _| {
803 s.scroll_left = (s.scroll_left + client_w * 0.9 * dir)
804 .clamp(0.0, max_x);
805 s.last_scroll_at = t;
806 });
807 window.refresh();
808 }
809 }
810 },
811 )
812 .child(
813 div()
814 .id(ElementId::NamedChild(
815 self.id.clone().into(),
816 "thumb-x".into(),
817 ))
818 .test_support()
819 .absolute()
820 .left(px(thumb_x_off))
821 .bottom(px(pill_bottom))
822 .w(px(thumb_w))
823 .h(px(pill_h))
824 .rounded(Radii::PILL)
825 .bg(pill_color)
826 .on_mouse_down(
827 MouseButton::Left,
828 move |event: &MouseDownEvent, window, cx| {
829 let t = motion_now(cx);
830 let ratio = max_x / (track_x_len - thumb_w).max(1.0);
831 int_x_thumb.update(cx, |s, _| {
832 s.dragging = Some(DragAxis::X);
833 s.drag_start_coord = f32::from(event.position.x);
834 s.drag_start_scroll = s.scroll_left;
835 s.drag_ratio = ratio;
836 s.last_scroll_at = t;
837 });
838 window.refresh();
839 },
840 ),
841 ),
842 );
843 }
844
845 root
846 }
847}
848
849#[cfg(test)]
850mod tests {
851 use super::*;
852
853 #[test]
854 fn scroll_area_thumb_metrics_respects_min_thumb_and_bounds() {
855 assert!(scroll_area_thumb_metrics(0.0, 300.0, 280.0, 294.0).is_none());
857
858 let (size, off0) = scroll_area_thumb_metrics(0.0, 200.0, 400.0, 200.0).unwrap();
860 assert!((size - 100.0).abs() < 1e-4);
861 assert!(off0.abs() < 1e-4);
862
863 let (_, off_end) = scroll_area_thumb_metrics(200.0, 200.0, 400.0, 200.0).unwrap();
864 assert!((off_end - 100.0).abs() < 1e-4);
865
866 let (tiny_size, _) = scroll_area_thumb_metrics(0.0, 200.0, 10_000.0, 200.0).unwrap();
868 assert!((tiny_size - SCROLL_AREA_MIN_THUMB).abs() < 1e-4);
869 }
870
871 #[test]
872 fn scroll_area_edge_fades_grow_proportionally_up_to_cap() {
873 let (top0, bot0) = scroll_area_edge_fades(0.0, 300.0, 28.0);
874 assert!(top0.abs() < 1e-4);
875 assert!((bot0 - 28.0).abs() < 1e-4);
876
877 let (top10, bot10) = scroll_area_edge_fades(10.0, 300.0, 28.0);
878 assert!((top10 - 10.0).abs() < 1e-4);
879 assert!((bot10 - 28.0).abs() < 1e-4);
880
881 let (top_end, bot_end) = scroll_area_edge_fades(300.0, 300.0, 28.0);
882 assert!((top_end - 28.0).abs() < 1e-4);
883 assert!(bot_end.abs() < 1e-4);
884 }
885
886 #[test]
887 fn scroll_area_track_inset_clears_rounded_corners() {
888 assert!((scroll_area_track_inset(0.0) - 3.0).abs() < 1e-4);
889 assert!((scroll_area_track_inset(18.0) - 18.0).abs() < 1e-4);
890 assert!((scroll_area_track_inset(34.0) - 34.0).abs() < 1e-4);
891 }
892}