BlueGit

ict rusty-teams

Files

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

message_scroller.rs

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