BlueGit

ict rusty-teams

Files

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

message_scroller.rs

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