BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / message_scroller.rs

message_scroller.rs

message_scroller.rs 20.0 KiB Download Raw
1use std::{ops::Range, rc::Rc, time::Duration};
2
3use gpui::{
4 AnyElement, App, Axis, 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::{
13 button::ButtonVariants as _,
14 scroll::{ScrollableElement as _, ScrollableMask},
15};
16
17const LIST_OVERDRAW: gpui::Pixels = px(400.);
18const JUMP_BUTTON_TRANSITION: Duration = Duration::from_millis(200);
19const BOTTOM_FADE_TRANSITION: Duration = Duration::from_millis(200);
20
21/// The entity-owned scrolling state for a [`MessageScroller`].
22///
23/// The state owns only GPUI's virtual-list bookkeeping. Message data remains
24/// with the caller and is read by the row renderer passed to
25/// [`MessageScroller::new`].
26pub struct MessageScrollerState {
27 list_state: ListState,
28}
29
30impl MessageScrollerState {
31 /// Create a state for `item_count` rows and enable tail following.
32 ///
33 /// The constructor receives the entity context so the list's scroll
34 /// handler can safely defer its entity update until GPUI has released the
35 /// list's internal borrow.
36 pub fn new(item_count: usize, cx: &mut Context<Self>) -> Self {
37 let list_state = ListState::new(item_count, ListAlignment::Top, LIST_OVERDRAW);
38 list_state.set_follow_mode(FollowMode::Tail);
39
40 let weak_state = cx.weak_entity();
41 list_state.set_scroll_handler(move |_, _, cx| {
42 let weak_state = weak_state.clone();
43
44 cx.defer(move |cx| {
45 let _ = weak_state.update(cx, |_, cx| cx.notify());
46 });
47 });
48
49 Self { list_state }
50 }
51
52 /// Return the current number of rows known by the virtual list.
53 pub fn item_count(&self) -> usize {
54 self.list_state.item_count()
55 }
56
57 /// Return whether the user has scrolled away from the latest content.
58 pub fn is_scrolled_up(&self) -> bool {
59 self.list_state.max_offset_for_scrollbar().y > px(0.)
60 && !self.list_state.is_following_tail()
61 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
62 }
63
64 /// Return whether the list is actively following its tail.
65 pub fn is_following_tail(&self) -> bool {
66 self.list_state.is_following_tail()
67 }
68
69 /// Reset the list to `item_count` rows.
70 pub fn reset(&mut self, item_count: usize, cx: &mut Context<Self>) {
71 self.list_state.reset(item_count);
72 self.list_state.set_follow_mode(FollowMode::Tail);
73 cx.notify();
74 }
75
76 /// Replace `old_range` with `count` new rows.
77 ///
78 /// Returns `false` when the range is outside the current list and leaves
79 /// the state unchanged.
80 pub fn splice(
81 &mut self,
82 old_range: Range<usize>,
83 count: usize,
84 cx: &mut Context<Self>,
85 ) -> bool {
86 if !self.valid_range(&old_range) {
87 return false;
88 }
89
90 let neighbor = old_range.start.checked_sub(1);
91 self.list_state.splice(old_range, count);
92
93 // The default row wrapper pads every row except the last, so a row
94 // whose "last" status may have flipped carries a stale measured
95 // height. Remeasure the new last row and the survivor next to the
96 // splice.
97 if let Some(last) = self.list_state.item_count().checked_sub(1) {
98 self.list_state.remeasure_items(last..last + 1);
99 if let Some(neighbor) = neighbor.filter(|neighbor| *neighbor != last) {
100 self.list_state.remeasure_items(neighbor..neighbor + 1);
101 }
102 }
103
104 cx.notify();
105 true
106 }
107
108 /// Append `count` rows to the end of the list.
109 pub fn append(&mut self, count: usize, cx: &mut Context<Self>) -> bool {
110 let item_count = self.list_state.item_count();
111 self.splice(item_count..item_count, count, cx)
112 }
113
114 /// Prepend `count` rows while preserving the current scroll anchor.
115 pub fn prepend(&mut self, count: usize, cx: &mut Context<Self>) -> bool {
116 self.splice(0..0, count, cx)
117 }
118
119 /// Mark all rows for remeasurement while preserving a proportional anchor.
120 pub fn remeasure(&mut self, cx: &mut Context<Self>) {
121 self.list_state.remeasure();
122 cx.notify();
123 }
124
125 /// Mark rows in `range` for remeasurement while preserving an item anchor.
126 ///
127 /// Returns `false` when the range is outside the current list.
128 pub fn remeasure_items(&mut self, range: Range<usize>, cx: &mut Context<Self>) -> bool {
129 if !self.valid_range(&range) {
130 return false;
131 }
132
133 self.list_state.remeasure_items(range);
134 cx.notify();
135 true
136 }
137
138 /// Scroll to the row at `index`, if it exists.
139 pub fn scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) -> bool {
140 if index >= self.list_state.item_count() {
141 return false;
142 }
143
144 self.list_state.scroll_to(ListOffset {
145 item_ix: index,
146 offset_in_item: px(0.),
147 });
148 cx.notify();
149 true
150 }
151
152 /// Stop following the tail until the next reset or `scroll_to_end`.
153 pub fn stop_following(&mut self) {
154 self.list_state.set_follow_mode(FollowMode::Normal);
155 }
156
157 /// Resume tail following and scroll to the latest row.
158 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
159 self.list_state.set_follow_mode(FollowMode::Tail);
160 self.list_state.scroll_to_end();
161 cx.notify();
162 }
163
164 fn valid_range(&self, range: &Range<usize>) -> bool {
165 range.start <= range.end && range.end <= self.list_state.item_count()
166 }
167}
168
169/// A virtualized message list with optional scrollbar and jump-to-latest UI.
170#[derive(IntoElement)]
171pub struct MessageScroller {
172 id: ElementId,
173 state: Entity<MessageScrollerState>,
174 renderer: Box<dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static>,
175 style: StyleRefinement,
176 content_style: StyleRefinement,
177 list_style: StyleRefinement,
178 row_style: StyleRefinement,
179 jump_button_style: StyleRefinement,
180 jump_button_renderer: Option<Box<dyn FnOnce(Button) -> Button>>,
181 jump_button_transition: Duration,
182 bottom_fade: Option<Hsla>,
183 scrollbar: bool,
184 jump_button: bool,
185 force_jump_button: bool,
186 on_jump: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
187 jump_button_label: SharedString,
188}
189
190impl MessageScroller {
191 /// Create a message scroller with a renderer for each row.
192 pub fn new<E>(
193 id: impl Into<ElementId>,
194 state: Entity<MessageScrollerState>,
195 renderer: impl FnMut(usize, &mut Window, &mut App) -> E + 'static,
196 ) -> Self
197 where
198 E: IntoElement,
199 {
200 let mut renderer = renderer;
201 Self {
202 id: id.into(),
203 state,
204 renderer: Box::new(move |index, window, cx| {
205 renderer(index, window, cx).into_any_element()
206 }),
207 style: StyleRefinement::default(),
208 content_style: StyleRefinement::default(),
209 list_style: StyleRefinement::default(),
210 row_style: StyleRefinement::default(),
211 jump_button_style: StyleRefinement::default(),
212 jump_button_renderer: None,
213 jump_button_transition: JUMP_BUTTON_TRANSITION,
214 bottom_fade: None,
215 scrollbar: true,
216 jump_button: true,
217 force_jump_button: false,
218 on_jump: None,
219 jump_button_label: "Jump to latest".into(),
220 }
221 }
222
223 /// Enable or disable the virtual-list scrollbar.
224 pub fn scrollbar(mut self, scrollbar: bool) -> Self {
225 self.scrollbar = scrollbar;
226 self
227 }
228
229 /// Enable or disable the built-in jump-to-latest button.
230 pub fn jump_button(mut self, jump_button: bool) -> Self {
231 self.jump_button = jump_button;
232 self
233 }
234
235 /// Show the jump button even when the list is at its end.
236 pub fn force_jump_button(mut self, force: bool) -> Self {
237 self.force_jump_button = force;
238 self
239 }
240
241 /// Run `callback` on jump-button click instead of scrolling to the end.
242 pub fn on_jump(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
243 self.on_jump = Some(Rc::new(callback));
244 self
245 }
246
247 /// Set the label used by the built-in jump-to-latest button.
248 pub fn with_jump_button_label(mut self, label: impl Into<SharedString>) -> Self {
249 self.jump_button_label = label.into();
250 self
251 }
252
253 /// Refine the viewport that contains the list and scrollbar.
254 pub fn with_content_style(mut self, style: StyleRefinement) -> Self {
255 self.content_style = style;
256 self
257 }
258
259 /// Refine the GPUI list element used to render rows.
260 pub fn with_list_style(mut self, style: StyleRefinement) -> Self {
261 self.list_style = style;
262 self
263 }
264
265 /// Refine the full-width wrapper around every rendered row.
266 pub fn with_row_style(mut self, style: StyleRefinement) -> Self {
267 self.row_style = style;
268 self
269 }
270
271 /// Refine the built-in jump-to-latest button after its defaults.
272 pub fn with_jump_button_style(mut self, style: StyleRefinement) -> Self {
273 self.jump_button_style = style;
274 self
275 }
276
277 /// Customize the built-in jump button without replacing its scroll action.
278 ///
279 /// The callback receives the fully configured Button, so its variant,
280 /// semantic size, icon, tooltip, or instance styling may be adjusted.
281 pub fn with_jump_button_renderer(
282 mut self,
283 renderer: impl FnOnce(Button) -> Button + 'static,
284 ) -> Self {
285 self.jump_button_renderer = Some(Box::new(renderer));
286 self
287 }
288
289 /// Set how long the built-in jump button takes to enter or leave.
290 ///
291 /// A zero duration disables its transition. Reduced-motion preferences
292 /// always adopt the final state immediately.
293 pub fn with_jump_button_transition(mut self, duration: Duration) -> Self {
294 self.jump_button_transition = duration;
295 self
296 }
297
298 /// Fade the transcript's bottom edge into `color`.
299 ///
300 /// A partially visible row melts into the surface behind the scroller
301 /// instead of clipping mid-line. The fade shows only while the reader is
302 /// away from the live edge — at the bottom nothing is clipped. Pass the
303 /// color of that surface; the fade is off by default and sits under the
304 /// jump button.
305 pub fn with_bottom_fade(mut self, color: impl Into<Hsla>) -> Self {
306 self.bottom_fade = Some(color.into());
307 self
308 }
309}
310
311impl Styled for MessageScroller {
312 fn style(&mut self) -> &mut StyleRefinement {
313 &mut self.style
314 }
315}
316
317impl RenderOnce for MessageScroller {
318 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
319 let root_id = self.id.clone();
320 let (list_state, scrolled_up) = {
321 let state = self.state.read(cx);
322 (state.list_state.clone(), state.is_scrolled_up())
323 };
324 let show_jump_button = self.jump_button && (scrolled_up || self.force_jump_button);
325 let jump_button_visibility = if self.jump_button {
326 transition(
327 (root_id.clone(), "jump-button-visibility"),
328 if show_jump_button { 1. } else { 0. },
329 Transition::new(self.jump_button_transition),
330 window,
331 cx,
332 )
333 } else {
334 0.
335 };
336 // At the live edge nothing is clipped below, so a visible fade would
337 // suggest more content than there is.
338 let bottom_fade_visibility = if self.bottom_fade.is_some() {
339 transition(
340 (root_id.clone(), "bottom-fade-visibility"),
341 if scrolled_up { 1. } else { 0. },
342 Transition::new(BOTTOM_FADE_TRANSITION),
343 window,
344 cx,
345 )
346 } else {
347 0.
348 };
349 let tokens = cx.theme().semantic_tokens();
350 let row_style = self.row_style;
351 let jump_button_style = self.jump_button_style;
352 let jump_button_renderer = self.jump_button_renderer;
353 let mut renderer = self.renderer;
354
355 // GPUI's `list` lays rows out at the full list width and offsets them
356 // only by vertical padding, so the horizontal component of the list
357 // style must be carried by every row wrapper instead.
358 let mut list_style = self.list_style;
359 let row_inset_left = list_style.padding.left.take();
360 let row_inset_right = list_style.padding.right.take();
361
362 // Read the count outside the row closure: the list holds a mutable
363 // borrow of its state while rendering rows, so the closure must not
364 // borrow it again. The count is stable within one render pass.
365 let item_count = list_state.item_count();
366 let list = list(list_state.clone(), move |index, window, cx| {
367 div()
368 .w_full()
369 .min_w_0()
370 .px_3()
371 // Spacing between rows only, like a CSS gap: the list's own
372 // bottom padding owns the gap after the last row.
373 .when(index + 1 < item_count, |this| this.pb_8())
374 .when_some(row_inset_left, |this, left| this.pl(left))
375 .when_some(row_inset_right, |this, right| this.pr(right))
376 .refine_style(&row_style)
377 .child(renderer(index, window, cx))
378 .into_any_element()
379 })
380 .size_full()
381 .min_h_0()
382 .py_2()
383 .refine_style(&list_style);
384
385 let viewport = div()
386 .id((root_id.clone(), "viewport"))
387 // Announce appended rows as a log region, like shadcn's
388 // `role="log"` transcript content.
389 .role(Role::Log)
390 .size_full()
391 .min_h_0()
392 .min_w_0()
393 .child(list)
394 // The fade sits above the rows but below the scrollbar and the
395 // jump button, so neither control is washed out by it.
396 .when_some(
397 self.bottom_fade.filter(|_| bottom_fade_visibility > 0.),
398 |this, color| {
399 this.child(
400 div()
401 .absolute()
402 .left_0()
403 .right_0()
404 .bottom_0()
405 .h(rems(3.))
406 .opacity(bottom_fade_visibility)
407 .bg(linear_gradient(
408 180.,
409 linear_color_stop(color.opacity(0.), 0.),
410 linear_color_stop(color, 1.),
411 )),
412 )
413 },
414 )
415 .when(self.scrollbar, |this| this.vertical_scrollbar(&list_state))
416 .refine_style(&self.content_style);
417
418 div()
419 .id(root_id.clone())
420 .relative()
421 .size_full()
422 .min_h_0()
423 .overflow_hidden()
424 .child(viewport)
425 // Keep vertical wheel scrolling from leaking into an ancestor
426 // scroller (like in Table): the mask consumes vertical-dominant
427 // wheel events while the list can move and chains to the ancestor
428 // only at the edges.
429 .child(ScrollableMask::new(Axis::Vertical, &list_state).id(root_id.clone()))
430 .when(self.jump_button && jump_button_visibility > 0., |this| {
431 let state = self.state.clone();
432 let on_jump = self.on_jump.clone();
433
434 this.child(
435 div()
436 .absolute()
437 .left_0()
438 .right_0()
439 .bottom(rems(0.5 + jump_button_visibility * 0.5))
440 .flex()
441 .justify_center()
442 .opacity(jump_button_visibility)
443 .child(
444 // No explicit width or height: Button sizes an
445 // icon-only button as a square on its own, and a
446 // renderer that adds a label or another semantic
447 // size must be able to change the layout.
448 Button::new((root_id, "jump-to-latest"))
449 .secondary()
450 .icon(IconName::ArrowDown)
451 .tooltip(self.jump_button_label)
452 .rounded(cx.theme().radius_full())
453 .border_1()
454 .border_color(tokens.colors.border)
455 .bg(tokens.colors.background)
456 .text_color(tokens.colors.foreground)
457 .refine_style(&jump_button_style)
458 .on_click(move |_, window, cx| match &on_jump {
459 Some(on_jump) => on_jump(window, cx),
460 None => state.update(cx, |state, cx| state.scroll_to_end(cx)),
461 })
462 .when_some(jump_button_renderer, |button, renderer| {
463 renderer(button)
464 })
465 .when(!show_jump_button, |button| button.disabled(true)),
466 ),
467 )
468 })
469 .refine_style(&self.style)
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use super::*;
476 use crate::Sizable as _;
477 use gpui::AppContext as _;
478
479 #[gpui::test]
480 fn test_message_scroller_state_builder(cx: &mut gpui::TestAppContext) {
481 let state = cx.new(|cx| MessageScrollerState::new(3, cx));
482
483 cx.update(|cx| {
484 assert_eq!(state.read(cx).item_count(), 3);
485 assert!(!state.read(cx).is_scrolled_up());
486 assert!(state.read(cx).is_following_tail());
487
488 state.update(cx, |state, cx| {
489 assert!(!state.scroll_to_item(3, cx));
490 assert!(state.append(2, cx));
491 assert_eq!(state.item_count(), 5);
492 assert!(state.prepend(1, cx));
493 assert_eq!(state.item_count(), 6);
494 assert!(!state.splice(5..7, 0, cx));
495 assert!(state.remeasure_items(0..6, cx));
496 assert!(!state.remeasure_items(6..7, cx));
497 assert!(state.scroll_to_item(2, cx));
498 assert!(!state.is_scrolled_up());
499 assert!(!state.is_following_tail());
500 state.scroll_to_end(cx);
501 assert!(state.is_following_tail());
502 state.reset(2, cx);
503 assert_eq!(state.item_count(), 2);
504 assert!(state.is_following_tail());
505 });
506 });
507 }
508
509 #[gpui::test]
510 fn test_message_scroller_builder(cx: &mut gpui::TestAppContext) {
511 let state = cx.new(|cx| MessageScrollerState::new(0, cx));
512 let scroller = MessageScroller::new("message-scroller", state, |_, _, _| div())
513 .scrollbar(false)
514 .jump_button(false)
515 .with_jump_button_label("Latest")
516 .with_content_style(StyleRefinement::default())
517 .with_list_style(StyleRefinement::default())
518 .with_row_style(StyleRefinement::default())
519 .with_jump_button_style(StyleRefinement::default())
520 .with_jump_button_renderer(|button| button.large())
521 .with_jump_button_transition(Duration::from_millis(300))
522 .with_bottom_fade(gpui::white());
523
524 assert!(!scroller.scrollbar);
525 assert!(!scroller.jump_button);
526 assert_eq!(scroller.jump_button_label, "Latest");
527 assert!(scroller.jump_button_renderer.is_some());
528 assert_eq!(scroller.jump_button_transition, Duration::from_millis(300));
529 assert_eq!(scroller.bottom_fade, Some(gpui::white()));
530 }
531}