use std::{ops::Range, rc::Rc, time::Duration}; use gpui::{ AnyElement, App, Axis, Context, ElementId, Entity, FollowMode, Hsla, InteractiveElement as _, IntoElement, ListAlignment, ListOffset, ListState, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, linear_color_stop, linear_gradient, list, prelude::FluentBuilder as _, px, rems, }; use gpui_base::motion::{Transition, transition}; use crate::{ActiveTheme as _, Disableable as _, IconName, StyledExt as _, button::Button}; use crate::{ button::ButtonVariants as _, scroll::{ScrollableElement as _, ScrollableMask}, }; const LIST_OVERDRAW: gpui::Pixels = px(400.); const JUMP_BUTTON_TRANSITION: Duration = Duration::from_millis(200); const BOTTOM_FADE_TRANSITION: Duration = Duration::from_millis(200); /// The entity-owned scrolling state for a [`MessageScroller`]. /// /// The state owns only GPUI's virtual-list bookkeeping. Message data remains /// with the caller and is read by the row renderer passed to /// [`MessageScroller::new`]. pub struct MessageScrollerState { list_state: ListState, top_inset: gpui::Pixels, inset_scroll_pending: bool, } impl MessageScrollerState { /// Create a state for `item_count` rows and enable tail following. /// /// The constructor receives the entity context so the list's scroll /// handler can safely defer its entity update until GPUI has released the /// list's internal borrow. pub fn new(item_count: usize, cx: &mut Context) -> Self { let list_state = ListState::new(item_count, ListAlignment::Top, LIST_OVERDRAW); list_state.set_follow_mode(FollowMode::Tail); let weak_state = cx.weak_entity(); list_state.set_scroll_handler(move |_, _, cx| { let weak_state = weak_state.clone(); cx.defer(move |cx| { let _ = weak_state.update(cx, |_, cx| cx.notify()); }); }); Self { list_state, top_inset: px(0.), inset_scroll_pending: false, } } /// Return the current number of rows known by the virtual list. pub fn item_count(&self) -> usize { self.list_state.item_count() } /// Return whether the user has scrolled away from the latest content. pub fn is_scrolled_up(&self) -> bool { self.list_state.max_offset_for_scrollbar().y > px(0.) && !self.list_state.is_following_tail() && !self.list_state.is_scrolled_to_end().unwrap_or(false) } /// Return the index of the row at the top of the viewport. pub fn top_item(&self) -> usize { self.list_state.logical_scroll_top().item_ix } /// Return whether the list is actively following its tail. pub fn is_following_tail(&self) -> bool { self.list_state.is_following_tail() } /// Reset the list to `item_count` rows. pub fn reset(&mut self, item_count: usize, cx: &mut Context) { self.list_state.reset(item_count); self.list_state.set_follow_mode(FollowMode::Tail); cx.notify(); } /// Replace `old_range` with `count` new rows. /// /// Returns `false` when the range is outside the current list and leaves /// the state unchanged. pub fn splice( &mut self, old_range: Range, count: usize, cx: &mut Context, ) -> bool { if !self.valid_range(&old_range) { return false; } let neighbor = old_range.start.checked_sub(1); self.list_state.splice(old_range, count); // The default row wrapper pads every row except the last, so a row // whose "last" status may have flipped carries a stale measured // height. Remeasure the new last row and the survivor next to the // splice. if let Some(last) = self.list_state.item_count().checked_sub(1) { self.list_state.remeasure_items(last..last + 1); if let Some(neighbor) = neighbor.filter(|neighbor| *neighbor != last) { self.list_state.remeasure_items(neighbor..neighbor + 1); } } cx.notify(); true } /// Append `count` rows to the end of the list. pub fn append(&mut self, count: usize, cx: &mut Context) -> bool { let item_count = self.list_state.item_count(); self.splice(item_count..item_count, count, cx) } /// Prepend `count` rows while preserving the current scroll anchor. pub fn prepend(&mut self, count: usize, cx: &mut Context) -> bool { self.splice(0..0, count, cx) } /// Mark all rows for remeasurement while preserving a proportional anchor. pub fn remeasure(&mut self, cx: &mut Context) { self.list_state.remeasure(); cx.notify(); } /// Mark rows in `range` for remeasurement while preserving an item anchor. /// /// Returns `false` when the range is outside the current list. pub fn remeasure_items(&mut self, range: Range, cx: &mut Context) -> bool { if !self.valid_range(&range) { return false; } self.list_state.remeasure_items(range); cx.notify(); true } /// Scroll to the row at `index`, if it exists, below the top inset. pub fn scroll_to_item(&mut self, index: usize, cx: &mut Context) -> bool { if index >= self.list_state.item_count() { return false; } self.list_state.scroll_to(ListOffset { item_ix: index, offset_in_item: px(0.), }); self.inset_scroll_pending = index > 0 && self.top_inset > px(0.); cx.notify(); true } /// Return the space kept free above the first row. pub fn top_inset(&self) -> gpui::Pixels { self.top_inset } fn sync_top_inset(&mut self, inset: gpui::Pixels) { if self.top_inset == inset { return; } self.top_inset = inset; if self.list_state.item_count() > 0 { self.list_state.remeasure_items(0..1); } } fn take_inset_scroll(&mut self) -> Option { std::mem::take(&mut self.inset_scroll_pending).then_some(self.top_inset) } /// Stop following the tail until the next reset or `scroll_to_end`. pub fn stop_following(&mut self) { self.list_state.set_follow_mode(FollowMode::Normal); } /// Resume tail following and scroll to the latest row. pub fn scroll_to_end(&mut self, cx: &mut Context) { self.list_state.set_follow_mode(FollowMode::Tail); self.list_state.scroll_to_end(); cx.notify(); } fn valid_range(&self, range: &Range) -> bool { range.start <= range.end && range.end <= self.list_state.item_count() } } /// A virtualized message list with optional scrollbar and jump-to-latest UI. #[derive(IntoElement)] pub struct MessageScroller { id: ElementId, state: Entity, renderer: Box AnyElement + 'static>, style: StyleRefinement, content_style: StyleRefinement, list_style: StyleRefinement, row_style: StyleRefinement, jump_button_style: StyleRefinement, jump_button_renderer: Option Button>>, jump_button_transition: Duration, bottom_fade: Option, top_inset: gpui::Pixels, scrollbar: bool, jump_button: bool, force_jump_button: bool, on_jump: Option>, jump_button_label: SharedString, } impl MessageScroller { /// Create a message scroller with a renderer for each row. pub fn new( id: impl Into, state: Entity, renderer: impl FnMut(usize, &mut Window, &mut App) -> E + 'static, ) -> Self where E: IntoElement, { let mut renderer = renderer; Self { id: id.into(), state, renderer: Box::new(move |index, window, cx| { renderer(index, window, cx).into_any_element() }), style: StyleRefinement::default(), content_style: StyleRefinement::default(), list_style: StyleRefinement::default(), row_style: StyleRefinement::default(), jump_button_style: StyleRefinement::default(), jump_button_renderer: None, jump_button_transition: JUMP_BUTTON_TRANSITION, bottom_fade: None, top_inset: px(0.), scrollbar: true, jump_button: true, force_jump_button: false, on_jump: None, jump_button_label: "Jump to latest".into(), } } /// Enable or disable the virtual-list scrollbar. pub fn scrollbar(mut self, scrollbar: bool) -> Self { self.scrollbar = scrollbar; self } /// Enable or disable the built-in jump-to-latest button. pub fn jump_button(mut self, jump_button: bool) -> Self { self.jump_button = jump_button; self } /// Show the jump button even when the list is at its end. pub fn force_jump_button(mut self, force: bool) -> Self { self.force_jump_button = force; self } /// Run `callback` on jump-button click instead of scrolling to the end. pub fn on_jump(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self { self.on_jump = Some(Rc::new(callback)); self } /// Set the label used by the built-in jump-to-latest button. pub fn with_jump_button_label(mut self, label: impl Into) -> Self { self.jump_button_label = label.into(); self } /// Refine the viewport that contains the list and scrollbar. pub fn with_content_style(mut self, style: StyleRefinement) -> Self { self.content_style = style; self } /// Refine the GPUI list element used to render rows. pub fn with_list_style(mut self, style: StyleRefinement) -> Self { self.list_style = style; self } /// Refine the full-width wrapper around every rendered row. pub fn with_row_style(mut self, style: StyleRefinement) -> Self { self.row_style = style; self } /// Refine the built-in jump-to-latest button after its defaults. pub fn with_jump_button_style(mut self, style: StyleRefinement) -> Self { self.jump_button_style = style; self } /// Customize the built-in jump button without replacing its scroll action. /// /// The callback receives the fully configured Button, so its variant, /// semantic size, icon, tooltip, or instance styling may be adjusted. pub fn with_jump_button_renderer( mut self, renderer: impl FnOnce(Button) -> Button + 'static, ) -> Self { self.jump_button_renderer = Some(Box::new(renderer)); self } /// Set how long the built-in jump button takes to enter or leave. /// /// A zero duration disables its transition. Reduced-motion preferences /// always adopt the final state immediately. pub fn with_jump_button_transition(mut self, duration: Duration) -> Self { self.jump_button_transition = duration; self } /// Fade the transcript's bottom edge into `color`. /// /// A partially visible row melts into the surface behind the scroller /// instead of clipping mid-line. The fade shows only while the reader is /// away from the live edge — at the bottom nothing is clipped. Pass the /// color of that surface; the fade is off by default and sits under the /// jump button. pub fn with_bottom_fade(mut self, color: impl Into) -> Self { self.bottom_fade = Some(color.into()); self } /// Keep `inset` free above the first row for an overlay at the top. /// /// The rows scroll behind the overlay, and the inset scrolls with the /// content, so the first row can still be scrolled out from under it. /// [`MessageScrollerState::scroll_to_item`] lands rows below the inset. pub fn with_top_inset(mut self, inset: gpui::Pixels) -> Self { self.top_inset = inset; self } } impl Styled for MessageScroller { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } impl RenderOnce for MessageScroller { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let root_id = self.id.clone(); let (list_state, scrolled_up) = { let state = self.state.read(cx); (state.list_state.clone(), state.is_scrolled_up()) }; let show_jump_button = self.jump_button && (scrolled_up || self.force_jump_button); let jump_button_visibility = if self.jump_button { transition( (root_id.clone(), "jump-button-visibility"), if show_jump_button { 1. } else { 0. }, Transition::new(self.jump_button_transition), window, cx, ) } else { 0. }; // At the live edge nothing is clipped below, so a visible fade would // suggest more content than there is. let bottom_fade_visibility = if self.bottom_fade.is_some() { transition( (root_id.clone(), "bottom-fade-visibility"), if scrolled_up { 1. } else { 0. }, Transition::new(BOTTOM_FADE_TRANSITION), window, cx, ) } else { 0. }; let top_inset = self.top_inset; let inset_scroll = self.state.update(cx, |state, _| { state.sync_top_inset(top_inset); state.take_inset_scroll() }); // The rows above the target are only measured by the layout of this // frame, so the step back by the inset waits for the next one. if let Some(inset) = inset_scroll { let list_state = list_state.clone(); let state = self.state.clone(); window.on_next_frame(move |_, cx| { list_state.scroll_by(-inset); state.update(cx, |_, cx| cx.notify()); }); } let tokens = cx.theme().semantic_tokens(); let row_style = self.row_style; let jump_button_style = self.jump_button_style; let jump_button_renderer = self.jump_button_renderer; let mut renderer = self.renderer; // GPUI's `list` lays rows out at the full list width and offsets them // only by vertical padding, so the horizontal component of the list // style must be carried by every row wrapper instead. let mut list_style = self.list_style; let row_inset_left = list_style.padding.left.take(); let row_inset_right = list_style.padding.right.take(); // Read the count outside the row closure: the list holds a mutable // borrow of its state while rendering rows, so the closure must not // borrow it again. The count is stable within one render pass. let item_count = list_state.item_count(); let list = list(list_state.clone(), move |index, window, cx| { div() .w_full() .min_w_0() .px_3() // Spacing between rows only, like a CSS gap: the list's own // bottom padding owns the gap after the last row. .when(index + 1 < item_count, |this| this.pb_8()) .when_some(row_inset_left, |this, left| this.pl(left)) .when_some(row_inset_right, |this, right| this.pr(right)) .refine_style(&row_style) .when(index == 0 && top_inset > px(0.), |this| this.pt(top_inset)) .child(renderer(index, window, cx)) .into_any_element() }) .size_full() .min_h_0() .py_2() .refine_style(&list_style); let viewport = div() .id((root_id.clone(), "viewport")) // Announce appended rows as a log region, like shadcn's // `role="log"` transcript content. .role(Role::Log) .size_full() .min_h_0() .min_w_0() .child(list) // The fade sits above the rows but below the scrollbar and the // jump button, so neither control is washed out by it. .when_some( self.bottom_fade.filter(|_| bottom_fade_visibility > 0.), |this, color| { this.child( div() .absolute() .left_0() .right_0() .bottom_0() .h(rems(3.)) .opacity(bottom_fade_visibility) .bg(linear_gradient( 180., linear_color_stop(color.opacity(0.), 0.), linear_color_stop(color, 1.), )), ) }, ) .when(self.scrollbar, |this| this.vertical_scrollbar(&list_state)) .refine_style(&self.content_style); div() .id(root_id.clone()) .relative() .size_full() .min_h_0() .overflow_hidden() .child(viewport) // Keep vertical wheel scrolling from leaking into an ancestor // scroller (like in Table): the mask consumes vertical-dominant // wheel events while the list can move and chains to the ancestor // only at the edges. .child(ScrollableMask::new(Axis::Vertical, &list_state).id(root_id.clone())) .when(self.jump_button && jump_button_visibility > 0., |this| { let state = self.state.clone(); let on_jump = self.on_jump.clone(); this.child( div() .absolute() .left_0() .right_0() .bottom(rems(0.5 + jump_button_visibility * 0.5)) .flex() .justify_center() .opacity(jump_button_visibility) .child( // No explicit width or height: Button sizes an // icon-only button as a square on its own, and a // renderer that adds a label or another semantic // size must be able to change the layout. Button::new((root_id, "jump-to-latest")) .secondary() .icon(IconName::ArrowDown) .tooltip(self.jump_button_label) .rounded(cx.theme().radius_full()) .border_1() .border_color(tokens.colors.border) .bg(tokens.colors.background) .text_color(tokens.colors.foreground) .refine_style(&jump_button_style) .on_click(move |_, window, cx| match &on_jump { Some(on_jump) => on_jump(window, cx), None => state.update(cx, |state, cx| state.scroll_to_end(cx)), }) .when_some(jump_button_renderer, |button, renderer| { renderer(button) }) .when(!show_jump_button, |button| button.disabled(true)), ), ) }) .refine_style(&self.style) } } #[cfg(test)] mod tests { use super::*; use crate::Sizable as _; use gpui::AppContext as _; #[gpui::test] fn test_message_scroller_state_builder(cx: &mut gpui::TestAppContext) { let state = cx.new(|cx| MessageScrollerState::new(3, cx)); cx.update(|cx| { assert_eq!(state.read(cx).item_count(), 3); assert!(!state.read(cx).is_scrolled_up()); assert!(state.read(cx).is_following_tail()); state.update(cx, |state, cx| { assert!(!state.scroll_to_item(3, cx)); assert!(state.append(2, cx)); assert_eq!(state.item_count(), 5); assert!(state.prepend(1, cx)); assert_eq!(state.item_count(), 6); assert!(!state.splice(5..7, 0, cx)); assert!(state.remeasure_items(0..6, cx)); assert!(!state.remeasure_items(6..7, cx)); assert!(state.scroll_to_item(2, cx)); assert_eq!(state.take_inset_scroll(), None); state.sync_top_inset(px(48.)); assert_eq!(state.top_inset(), px(48.)); assert!(state.scroll_to_item(2, cx)); assert_eq!(state.take_inset_scroll(), Some(px(48.))); assert_eq!(state.take_inset_scroll(), None); assert!(state.scroll_to_item(0, cx)); assert_eq!(state.take_inset_scroll(), None); assert!(state.scroll_to_item(2, cx)); assert!(!state.is_scrolled_up()); assert!(!state.is_following_tail()); state.scroll_to_end(cx); assert!(state.is_following_tail()); state.reset(2, cx); assert_eq!(state.item_count(), 2); assert!(state.is_following_tail()); }); }); } #[gpui::test] fn test_message_scroller_builder(cx: &mut gpui::TestAppContext) { let state = cx.new(|cx| MessageScrollerState::new(0, cx)); let scroller = MessageScroller::new("message-scroller", state, |_, _, _| div()) .scrollbar(false) .jump_button(false) .with_jump_button_label("Latest") .with_content_style(StyleRefinement::default()) .with_list_style(StyleRefinement::default()) .with_row_style(StyleRefinement::default()) .with_jump_button_style(StyleRefinement::default()) .with_jump_button_renderer(|button| button.large()) .with_jump_button_transition(Duration::from_millis(300)) .with_bottom_fade(gpui::white()) .with_top_inset(px(48.)); assert!(!scroller.scrollbar); assert!(!scroller.jump_button); assert_eq!(scroller.jump_button_label, "Latest"); assert!(scroller.jump_button_renderer.is_some()); assert_eq!(scroller.jump_button_transition, Duration::from_millis(300)); assert_eq!(scroller.bottom_fade, Some(gpui::white())); assert_eq!(scroller.top_inset, px(48.)); } }