BlueGit

ict rusty-teams

Files

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

message_scroller.rs

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