1use std::{ops::Range, time::Duration};
2
3use gpui::{
4 AnyElement, App, Context, ElementId, Entity, FollowMode, Hsla, InteractiveElement as _,
5 IntoElement, ListAlignment, ListOffset, ListState, ParentElement as _, RenderOnce, Role,
6 SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
7 linear_color_stop, linear_gradient, list, prelude::FluentBuilder as _, px, rems,
8};
9use gpui_base::motion::{Transition, transition};
10
11use crate::{ActiveTheme as _, Disableable as _, IconName, StyledExt as _, button::Button};
12use crate::{button::ButtonVariants as _, scroll::ScrollableElement as _};
13
14const LIST_OVERDRAW: gpui::Pixels = px(400.);
15const JUMP_BUTTON_TRANSITION: Duration = Duration::from_millis(200);
16const BOTTOM_FADE_TRANSITION: Duration = Duration::from_millis(200);
17
18pub struct MessageScrollerState {
24 list_state: ListState,
25}
26
27impl MessageScrollerState {
28 pub fn new(item_count: usize, cx: &mut Context<Self>) -> Self {
34 let list_state = ListState::new(item_count, ListAlignment::Top, LIST_OVERDRAW);
35 list_state.set_follow_mode(FollowMode::Tail);
36
37 let weak_state = cx.weak_entity();
38 list_state.set_scroll_handler(move |_, _, cx| {
39 let weak_state = weak_state.clone();
40
41 cx.defer(move |cx| {
42 let _ = weak_state.update(cx, |_, cx| cx.notify());
43 });
44 });
45
46 Self { list_state }
47 }
48
49 pub fn item_count(&self) -> usize {
51 self.list_state.item_count()
52 }
53
54 pub fn is_scrolled_up(&self) -> bool {
56 self.list_state.max_offset_for_scrollbar().y > px(0.)
57 && !self.list_state.is_following_tail()
58 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
59 }
60
61 pub fn is_following_tail(&self) -> bool {
63 self.list_state.is_following_tail()
64 }
65
66 pub fn logical_scroll_top(&self) -> ListOffset {
74 self.list_state.logical_scroll_top()
75 }
76
77 pub fn reset(&mut self, item_count: usize, cx: &mut Context<Self>) {
79 self.list_state.reset(item_count);
80 self.list_state.set_follow_mode(FollowMode::Tail);
81 cx.notify();
82 }
83
84 pub fn splice(
89 &mut self,
90 old_range: Range<usize>,
91 count: usize,
92 cx: &mut Context<Self>,
93 ) -> bool {
94 if !self.valid_range(&old_range) {
95 return false;
96 }
97
98 let neighbor = old_range.start.checked_sub(1);
99 let touches_start = old_range.start == 0;
100 self.list_state.splice(old_range, count);
101
102 if let Some(last) = self.list_state.item_count().checked_sub(1) {
107 self.list_state.remeasure_items(last..last + 1);
108 if let Some(neighbor) = neighbor.filter(|neighbor| *neighbor != last) {
109 self.list_state.remeasure_items(neighbor..neighbor + 1);
110 }
111 }
112
113 if touches_start {
116 for index in [0, count] {
117 if index < self.list_state.item_count() {
118 self.list_state.remeasure_items(index..index + 1);
119 }
120 }
121 }
122
123 cx.notify();
124 true
125 }
126
127 pub fn append(&mut self, count: usize, cx: &mut Context<Self>) -> bool {
129 let item_count = self.list_state.item_count();
130 self.splice(item_count..item_count, count, cx)
131 }
132
133 pub fn prepend(&mut self, count: usize, cx: &mut Context<Self>) -> bool {
135 self.splice(0..0, count, cx)
136 }
137
138 pub fn remeasure(&mut self, cx: &mut Context<Self>) {
140 self.list_state.remeasure();
141 cx.notify();
142 }
143
144 pub fn remeasure_items(&mut self, range: Range<usize>, cx: &mut Context<Self>) -> bool {
148 if !self.valid_range(&range) {
149 return false;
150 }
151
152 self.list_state.remeasure_items(range);
153 cx.notify();
154 true
155 }
156
157 pub fn scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) -> bool {
159 self.scroll_to_offset(
160 ListOffset {
161 item_ix: index,
162 offset_in_item: px(0.),
163 },
164 cx,
165 )
166 }
167
168 pub fn scroll_to_offset(&mut self, offset: ListOffset, cx: &mut Context<Self>) -> bool {
174 if offset.item_ix >= self.list_state.item_count() {
175 return false;
176 }
177
178 self.list_state.scroll_to(offset);
179 cx.notify();
180 true
181 }
182
183 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
185 self.list_state.set_follow_mode(FollowMode::Tail);
186 self.list_state.scroll_to_end();
187 cx.notify();
188 }
189
190 fn valid_range(&self, range: &Range<usize>) -> bool {
191 range.start <= range.end && range.end <= self.list_state.item_count()
192 }
193}
194
195#[derive(IntoElement)]
197pub struct MessageScroller {
198 id: ElementId,
199 state: Entity<MessageScrollerState>,
200 renderer: Box<dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static>,
201 style: StyleRefinement,
202 content_style: StyleRefinement,
203 list_style: StyleRefinement,
204 row_style: StyleRefinement,
205 jump_button_style: StyleRefinement,
206 jump_button_renderer: Option<Box<dyn FnOnce(Button) -> Button>>,
207 jump_button_transition: Duration,
208 bottom_fade: Option<Hsla>,
209 scrollbar: bool,
210 jump_button: bool,
211 jump_button_label: SharedString,
212}
213
214impl MessageScroller {
215 pub fn new<E>(
217 id: impl Into<ElementId>,
218 state: Entity<MessageScrollerState>,
219 renderer: impl FnMut(usize, &mut Window, &mut App) -> E + 'static,
220 ) -> Self
221 where
222 E: IntoElement,
223 {
224 let mut renderer = renderer;
225 Self {
226 id: id.into(),
227 state,
228 renderer: Box::new(move |index, window, cx| {
229 renderer(index, window, cx).into_any_element()
230 }),
231 style: StyleRefinement::default(),
232 content_style: StyleRefinement::default(),
233 list_style: StyleRefinement::default(),
234 row_style: StyleRefinement::default(),
235 jump_button_style: StyleRefinement::default(),
236 jump_button_renderer: None,
237 jump_button_transition: JUMP_BUTTON_TRANSITION,
238 bottom_fade: None,
239 scrollbar: true,
240 jump_button: true,
241 jump_button_label: "Jump to latest".into(),
242 }
243 }
244
245 pub fn scrollbar(mut self, scrollbar: bool) -> Self {
247 self.scrollbar = scrollbar;
248 self
249 }
250
251 pub fn jump_button(mut self, jump_button: bool) -> Self {
253 self.jump_button = jump_button;
254 self
255 }
256
257 pub fn with_jump_button_label(mut self, label: impl Into<SharedString>) -> Self {
259 self.jump_button_label = label.into();
260 self
261 }
262
263 pub fn with_content_style(mut self, style: StyleRefinement) -> Self {
265 self.content_style = style;
266 self
267 }
268
269 pub fn with_list_style(mut self, style: StyleRefinement) -> Self {
271 self.list_style = style;
272 self
273 }
274
275 pub fn with_row_style(mut self, style: StyleRefinement) -> Self {
277 self.row_style = style;
278 self
279 }
280
281 pub fn with_jump_button_style(mut self, style: StyleRefinement) -> Self {
283 self.jump_button_style = style;
284 self
285 }
286
287 pub fn with_jump_button_renderer(
292 mut self,
293 renderer: impl FnOnce(Button) -> Button + 'static,
294 ) -> Self {
295 self.jump_button_renderer = Some(Box::new(renderer));
296 self
297 }
298
299 pub fn with_jump_button_transition(mut self, duration: Duration) -> Self {
304 self.jump_button_transition = duration;
305 self
306 }
307
308 pub fn with_bottom_fade(mut self, color: impl Into<Hsla>) -> Self {
316 self.bottom_fade = Some(color.into());
317 self
318 }
319}
320
321impl Styled for MessageScroller {
322 fn style(&mut self) -> &mut StyleRefinement {
323 &mut self.style
324 }
325}
326
327impl RenderOnce for MessageScroller {
328 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
329 let root_id = self.id.clone();
330 let (list_state, scrolled_up) = {
331 let state = self.state.read(cx);
332 (state.list_state.clone(), state.is_scrolled_up())
333 };
334 let show_jump_button = self.jump_button && scrolled_up;
335 let jump_button_visibility = if self.jump_button {
336 transition(
337 (root_id.clone(), "jump-button-visibility"),
338 if show_jump_button { 1. } else { 0. },
339 Transition::new(self.jump_button_transition),
340 window,
341 cx,
342 )
343 } else {
344 0.
345 };
346 let bottom_fade_visibility = if self.bottom_fade.is_some() {
349 transition(
350 (root_id.clone(), "bottom-fade-visibility"),
351 if scrolled_up { 1. } else { 0. },
352 Transition::new(BOTTOM_FADE_TRANSITION),
353 window,
354 cx,
355 )
356 } else {
357 0.
358 };
359 let tokens = cx.theme().semantic_tokens();
360 let row_style = self.row_style;
361 let jump_button_style = self.jump_button_style;
362 let jump_button_renderer = self.jump_button_renderer;
363 let mut renderer = self.renderer;
364
365 let mut list_style = self.list_style;
377 let row_inset_left = list_style.padding.left.take();
378 let row_inset_right = list_style.padding.right.take();
379 let row_inset_top = list_style.padding.top.take();
380 let row_inset_bottom = list_style.padding.bottom.take();
381
382 let item_count = list_state.item_count();
386 let list = list(list_state.clone(), move |index, window, cx| {
387 div()
388 .w_full()
389 .when(index == 0, |this| match row_inset_top {
390 Some(top) => this.pt(top),
391 None => this.pt_2(),
392 })
393 .when(index + 1 == item_count, |this| match row_inset_bottom {
394 Some(bottom) => this.pb(bottom),
395 None => this.pb_2(),
396 })
397 .child(
398 div()
399 .w_full()
400 .min_w_0()
401 .px_3()
402 .when(index + 1 < item_count, |this| this.pb_8())
403 .when_some(row_inset_left, |this, left| this.pl(left))
404 .when_some(row_inset_right, |this, right| this.pr(right))
405 .refine_style(&row_style)
406 .child(renderer(index, window, cx)),
407 )
408 .into_any_element()
409 })
410 .size_full()
411 .min_h_0()
412 .refine_style(&list_style);
413
414 let viewport = div()
415 .id((root_id.clone(), "viewport"))
416 .role(Role::Log)
419 .size_full()
420 .min_h_0()
421 .min_w_0()
422 .child(
423 gpui_base::ScrollBounce::new((root_id.clone(), "bounce"), &list_state, list)
426 .on_scroll({
427 let state = self.state.downgrade();
428 move |_, cx| {
429 let _ = state.update(cx, |_, cx| cx.notify());
430 }
431 }),
432 )
433 .when_some(
436 self.bottom_fade.filter(|_| bottom_fade_visibility > 0.),
437 |this, color| {
438 this.child(
439 div()
440 .absolute()
441 .left_0()
442 .right_0()
443 .bottom_0()
444 .h(rems(3.))
445 .opacity(bottom_fade_visibility)
446 .bg(linear_gradient(
447 180.,
448 linear_color_stop(color.opacity(0.), 0.),
449 linear_color_stop(color, 1.),
450 )),
451 )
452 },
453 )
454 .when(self.scrollbar, |this| this.vertical_scrollbar(&list_state))
455 .refine_style(&self.content_style);
456
457 div()
458 .id(root_id.clone())
459 .relative()
460 .size_full()
461 .min_h_0()
462 .overflow_hidden()
463 .child(viewport)
464 .when(self.jump_button && jump_button_visibility > 0., |this| {
465 let state = self.state.clone();
466
467 this.child(
468 div()
469 .absolute()
470 .left_0()
471 .right_0()
472 .bottom(rems(0.5 + jump_button_visibility * 0.5))
473 .flex()
474 .justify_center()
475 .opacity(jump_button_visibility)
476 .child(
477 Button::new((root_id, "jump-to-latest"))
482 .secondary()
483 .icon(IconName::ArrowDown)
484 .tooltip(self.jump_button_label)
485 .rounded(cx.theme().radius_full())
486 .border_1()
487 .border_color(tokens.colors.border)
488 .bg(tokens.colors.background)
489 .text_color(tokens.colors.foreground)
490 .refine_style(&jump_button_style)
491 .on_click(move |_, _, cx| {
492 state.update(cx, |state, cx| state.scroll_to_end(cx));
493 })
494 .when_some(jump_button_renderer, |button, renderer| {
495 renderer(button)
496 })
497 .when(!show_jump_button, |button| button.disabled(true)),
498 ),
499 )
500 })
501 .refine_style(&self.style)
502 }
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508 use crate::Sizable as _;
509 use gpui::AppContext as _;
510
511 #[gpui::test]
512 fn test_message_scroller_state_builder(cx: &mut gpui::TestAppContext) {
513 let state = cx.new(|cx| MessageScrollerState::new(3, cx));
514
515 cx.update(|cx| {
516 assert_eq!(state.read(cx).item_count(), 3);
517 assert!(!state.read(cx).is_scrolled_up());
518 assert!(state.read(cx).is_following_tail());
519
520 state.update(cx, |state, cx| {
521 assert!(!state.scroll_to_item(3, cx));
522 assert!(state.append(2, cx));
523 assert_eq!(state.item_count(), 5);
524 assert!(state.prepend(1, cx));
525 assert_eq!(state.item_count(), 6);
526 assert!(!state.splice(5..7, 0, cx));
527 assert!(state.remeasure_items(0..6, cx));
528 assert!(!state.remeasure_items(6..7, cx));
529 assert!(state.scroll_to_item(2, cx));
530 assert!(!state.is_scrolled_up());
531 assert!(!state.is_following_tail());
532 state.scroll_to_end(cx);
533 assert!(state.is_following_tail());
534 state.reset(2, cx);
535 assert_eq!(state.item_count(), 2);
536 assert!(state.is_following_tail());
537 });
538 });
539 }
540
541 struct ScrollerHarness {
542 state: Entity<MessageScrollerState>,
543 }
544
545 impl gpui::Render for ScrollerHarness {
546 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
547 div().size(px(400.)).child(
548 MessageScroller::new("messages", self.state.clone(), |_, _, _| div().h(px(40.)))
549 .scrollbar(false)
550 .jump_button(false),
551 )
552 }
553 }
554
555 #[gpui::test]
556 fn test_logical_scroll_top_reports_the_row_at_the_top(cx: &mut gpui::TestAppContext) {
557 cx.update(crate::init);
558 let state = cx.new(|cx| MessageScrollerState::new(30, cx));
559 let (_, cx) = cx.add_window_view({
560 let state = state.clone();
561 move |_, _| ScrollerHarness { state }
562 });
563 let draw = |cx: &mut gpui::VisualTestContext| {
564 cx.run_until_parked();
565 cx.update(|window, cx| {
566 _ = window.draw(cx);
567 });
568 };
569 let top = |cx: &mut gpui::VisualTestContext| {
570 cx.update(|_, cx| state.read(cx).logical_scroll_top())
571 };
572 draw(cx);
573
574 let tail = top(cx);
576 assert!(
577 tail.item_ix > 0 && tail.item_ix < 30,
578 "the row at the top while following the tail: {tail:?}"
579 );
580
581 cx.update(|_, cx| state.update(cx, |state, cx| state.scroll_to_item(10, cx)));
582 draw(cx);
583 assert_eq!(top(cx).item_ix, 10);
584
585 cx.simulate_event(gpui::ScrollEvent {
587 position: gpui::point(px(200.), px(200.)),
588 delta: gpui::ScrollDelta::Pixels(gpui::point(px(0.), px(-72.))),
589 ..Default::default()
590 });
591 let after_wheel = top(cx);
592 assert_eq!(
593 (after_wheel.item_ix, after_wheel.offset_in_item),
594 (11, px(0.))
595 );
596 }
597
598 #[gpui::test]
599 fn test_scroll_to_offset_restores_a_saved_position(cx: &mut gpui::TestAppContext) {
600 cx.update(crate::init);
601 let state = cx.new(|cx| MessageScrollerState::new(30, cx));
602 let (_, cx) = cx.add_window_view({
603 let state = state.clone();
604 move |_, _| ScrollerHarness { state }
605 });
606 let draw = |cx: &mut gpui::VisualTestContext| {
607 cx.run_until_parked();
608 cx.update(|window, cx| {
609 _ = window.draw(cx);
610 });
611 };
612 draw(cx);
613
614 let saved = ListOffset {
615 item_ix: 10,
616 offset_in_item: px(17.),
617 };
618 cx.update(|_, cx| {
619 state.update(cx, |state, cx| {
620 let past_the_end = ListOffset {
621 item_ix: 30,
622 offset_in_item: px(0.),
623 };
624 assert!(!state.scroll_to_offset(past_the_end, cx));
625
626 state.reset(30, cx);
628 assert!(state.scroll_to_offset(saved, cx));
629 assert!(!state.is_following_tail());
630 })
631 });
632 draw(cx);
633 let top = cx.update(|_, cx| state.read(cx).logical_scroll_top());
634 assert_eq!((top.item_ix, top.offset_in_item), (10, px(17.)));
635 }
636
637 #[gpui::test]
642 fn the_scrollbar_drag_range_reaches_the_end_of_the_content(cx: &mut gpui::TestAppContext) {
643 cx.update(crate::init);
644 let state = cx.new(|cx| MessageScrollerState::new(10, cx));
645 let (_, cx) = cx.add_window_view({
646 let state = state.clone();
647 move |_, _| ScrollerHarness { state }
648 });
649 let draw = |cx: &mut gpui::VisualTestContext| {
650 cx.run_until_parked();
651 cx.update(|window, cx| {
652 _ = window.draw(cx);
653 });
654 };
655 draw(cx);
656
657 cx.update(|_, cx| {
660 let list_state = state.read(cx).list_state.clone();
661 list_state.scrollbar_drag_started();
662 let max = list_state.max_offset_for_scrollbar().y;
663 list_state.set_offset_from_scrollbar(gpui::point(px(0.), -max));
664 list_state.scrollbar_drag_ended();
665 });
666
667 cx.update(|_, cx| {
668 let list_state = state.read(cx).list_state.clone();
669 assert_eq!(
670 list_state.is_scrolled_to_end(),
671 Some(true),
672 "the drag must land on the end of the content"
673 );
674 assert!(
675 list_state.is_following_tail(),
676 "the drag to the end must resume the tail"
677 );
678 assert!(
679 !state.read(cx).is_scrolled_up(),
680 "the jump-to-latest button must hide at the end of the content"
681 );
682 });
683 }
684
685 struct PaddedScrollerHarness {
686 state: Entity<MessageScrollerState>,
687 list_style: StyleRefinement,
688 }
689
690 impl gpui::Render for PaddedScrollerHarness {
691 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
692 div().size(px(400.)).child(
693 MessageScroller::new("messages", self.state.clone(), |_, _, _| div().h(px(40.)))
694 .scrollbar(false)
695 .jump_button(false)
696 .with_list_style(self.list_style.clone())
697 .with_row_style(StyleRefinement::default().pt(px(6.)).pb(px(6.))),
698 )
699 }
700 }
701
702 #[gpui::test]
706 fn a_custom_list_padding_rides_on_the_first_and_the_last_row(cx: &mut gpui::TestAppContext) {
707 cx.update(crate::init);
708
709 let first = cx.new(|cx| MessageScrollerState::new(10, cx));
710 let second = cx.new(|cx| MessageScrollerState::new(10, cx));
711 let third = cx.new(|cx| MessageScrollerState::new(10, cx));
712
713 let extent = |cx: &mut gpui::TestAppContext,
714 state: Entity<MessageScrollerState>,
715 list_style: StyleRefinement| {
716 let (_, context) = cx.add_window_view({
717 let state = state.clone();
718 move |_, _| PaddedScrollerHarness { state, list_style }
719 });
720 context.run_until_parked();
721 context.update(|window, cx| {
722 _ = window.draw(cx);
723 state.read(cx).list_state.max_offset_for_scrollbar().y
724 })
725 };
726
727 let first_extent = extent(
728 cx,
729 first,
730 StyleRefinement::default().pt(px(20.)).pb(px(40.)),
731 );
732 let second_extent = extent(
733 cx,
734 second,
735 StyleRefinement::default().pt(px(20.)).pb(px(20.)),
736 );
737 let third_extent = extent(
738 cx,
739 third,
740 StyleRefinement::default().pt(px(40.)).pb(px(20.)),
741 );
742
743 assert_eq!(
746 first_extent - second_extent,
747 px(20.),
748 "the bottom inset must ride on the last row only"
749 );
750 assert_eq!(
752 third_extent - second_extent,
753 px(20.),
754 "the top inset must ride on the first row only"
755 );
756 }
757
758 #[gpui::test]
759 fn test_message_scroller_builder(cx: &mut gpui::TestAppContext) {
760 let state = cx.new(|cx| MessageScrollerState::new(0, cx));
761 let scroller = MessageScroller::new("message-scroller", state, |_, _, _| div())
762 .scrollbar(false)
763 .jump_button(false)
764 .with_jump_button_label("Latest")
765 .with_content_style(StyleRefinement::default())
766 .with_list_style(StyleRefinement::default())
767 .with_row_style(StyleRefinement::default())
768 .with_jump_button_style(StyleRefinement::default())
769 .with_jump_button_renderer(|button| button.large())
770 .with_jump_button_transition(Duration::from_millis(300))
771 .with_bottom_fade(gpui::white());
772
773 assert!(!scroller.scrollbar);
774 assert!(!scroller.jump_button);
775 assert_eq!(scroller.jump_button_label, "Latest");
776 assert!(scroller.jump_button_renderer.is_some());
777 assert_eq!(scroller.jump_button_transition, Duration::from_millis(300));
778 assert_eq!(scroller.bottom_fade, Some(gpui::white()));
779 }
780}