BlueGit

ict rusty-teams

Files

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

message_scroller.rs

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