BlueGit

ict rusty-teams

Files

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

message_scroller.rs

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