Skip to main content

gpui_deck/
message_scroller.rs

1//! A keyed conversation viewport over the ordinary, nonvirtualized ScrollArea.
2
3use std::{cell::Cell, rc::Rc};
4
5use gpui::{
6    AnyElement, App, Bounds, Context, Element, ElementId, Entity, GlobalElementId,
7    InspectorElementId, IntoElement, LayoutId, ParentElement as _, Pixels, RenderOnce,
8    ScrollHandle, SharedString, StyleRefinement, Styled, Window, px,
9};
10
11use crate::{ScrollArea, ScrollbarMode, ScrollbarStyles, StateStyle};
12
13struct Frame {
14    ids: Vec<ElementId>,
15    top: Pixels,
16}
17
18/// Retained scrolling state for one conversation in one viewport.
19///
20/// Content and stable message identities belong to the application. Reuse this
21/// state across appends, streamed edits, and prepended history; create a new state
22/// when switching conversations. The first frame starts at the latest message.
23pub struct MessageScrollerState {
24    scroll: ScrollHandle,
25    frame: Option<Frame>,
26    following: bool,
27    unread: usize,
28    jump: bool,
29}
30
31impl MessageScrollerState {
32    pub fn new(_: &mut Context<Self>) -> Self {
33        Self {
34            scroll: ScrollHandle::new(),
35            frame: None,
36            following: true,
37            unread: 0,
38            jump: false,
39        }
40    }
41
42    pub fn scroll_handle(&self) -> &ScrollHandle {
43        &self.scroll
44    }
45
46    /// Whether the last laid-out viewport was at its bottom edge.
47    pub fn is_following(&self) -> bool {
48        self.following
49    }
50
51    /// Appended messages received while the reader was away from the bottom.
52    /// Edits to an existing message and prepended history do not increase this.
53    pub fn unread_count(&self) -> usize {
54        self.unread
55    }
56
57    /// Returns to the latest content and resumes following subsequent growth.
58    /// The application's jump control retains focus; messages do not receive it.
59    pub fn jump_to_latest(&mut self, window: &mut Window, cx: &mut Context<Self>) {
60        self.jump = true;
61        self.following = true;
62        self.unread = 0;
63        self.scroll.scroll_to_bottom();
64        cx.notify();
65        window.refresh();
66    }
67}
68
69/// An unstyled vertical message viewport with stable keyed scroll anchoring.
70///
71/// Give it a bounded height and add each message with [`Self::item`]. IDs must be
72/// unique and stable within a conversation, including when loading older history.
73/// Each item is a direct child of the existing ScrollArea. No virtual list,
74/// transport, message model, new keyboard scope, or live region is introduced.
75///
76/// At the bottom, append/stream/resize follows the latest content. Away from it,
77/// the first visible message keeps its pixel position even when earlier messages
78/// are inserted or change height. If that message is removed, native scrolling
79/// clamps the existing offset. Observe the retained state to update an app-owned
80/// unread badge or jump Button. User scrolling back to the bottom clears unread.
81#[derive(IntoElement)]
82pub struct MessageScroller {
83    area: ScrollArea,
84    state: Entity<MessageScrollerState>,
85    items: Vec<(ElementId, Rc<Cell<Option<LayoutId>>>)>,
86}
87
88impl MessageScroller {
89    pub fn new(id: impl Into<ElementId>, state: &Entity<MessageScrollerState>, cx: &App) -> Self {
90        Self {
91            area: ScrollArea::new(id, state.read(cx).scroll_handle())
92                .content_styles(|style| style.flex().flex_col()),
93            state: state.clone(),
94            items: Vec::new(),
95        }
96    }
97
98    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
99        self.area = self.area.accessibility_label(label);
100        self
101    }
102
103    pub fn content_styles(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
104        self.area = self.area.content_styles(build);
105        self
106    }
107
108    pub fn scrollbar_mode(mut self, mode: ScrollbarMode) -> Self {
109        self.area = self.area.scrollbar_mode(mode);
110        self
111    }
112
113    pub fn scrollbar_styles(
114        mut self,
115        build: impl FnOnce(ScrollbarStyles) -> ScrollbarStyles,
116    ) -> Self {
117        self.area = self.area.scrollbar_styles(build);
118        self
119    }
120
121    pub fn item(mut self, id: impl Into<ElementId>, content: impl IntoElement) -> Self {
122        let id = id.into();
123        let layout = Rc::new(Cell::new(None));
124        self.items.push((id.clone(), layout.clone()));
125        self.area = self.area.child(MeasuredItem {
126            id,
127            child: content.into_any_element(),
128            layout,
129        });
130        self
131    }
132}
133
134impl Styled for MessageScroller {
135    fn style(&mut self) -> &mut StyleRefinement {
136        self.area.style()
137    }
138}
139
140impl RenderOnce for MessageScroller {
141    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
142        AnchoredArea {
143            area: self.area.into_any_element(),
144            state: self.state,
145            items: self.items,
146        }
147    }
148}
149
150// Read the new item layout before ScrollArea prepaints. This lets its existing
151// viewport clamp and paint the corrected offset in the same frame, avoiding an
152// intermediate frame at the wrong reading position when history is prepended.
153struct AnchoredArea {
154    area: AnyElement,
155    state: Entity<MessageScrollerState>,
156    items: Vec<(ElementId, Rc<Cell<Option<LayoutId>>>)>,
157}
158
159impl IntoElement for AnchoredArea {
160    type Element = Self;
161    fn into_element(self) -> Self {
162        self
163    }
164}
165
166impl Element for AnchoredArea {
167    type RequestLayoutState = ();
168    type PrepaintState = ();
169
170    fn id(&self) -> Option<ElementId> {
171        None
172    }
173    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
174        None
175    }
176
177    fn request_layout(
178        &mut self,
179        _: Option<&GlobalElementId>,
180        _: Option<&InspectorElementId>,
181        window: &mut Window,
182        cx: &mut App,
183    ) -> (LayoutId, ()) {
184        (self.area.request_layout(window, cx), ())
185    }
186
187    fn prepaint(
188        &mut self,
189        _: Option<&GlobalElementId>,
190        _: Option<&InspectorElementId>,
191        bounds: Bounds<Pixels>,
192        _: &mut (),
193        window: &mut Window,
194        cx: &mut App,
195    ) {
196        let previous = self.state.update(cx, |state, _| {
197            let previous = (state.following, state.unread);
198            let offset = state.scroll.offset();
199            let following = state.jump
200                || state.frame.is_none()
201                || (offset.y + state.scroll.max_offset().y).abs() <= px(1.);
202            if let Some(frame) = &state.frame {
203                if !following {
204                    if let Some(last) = frame.ids.last()
205                        && let Some(index) = self.items.iter().position(|(id, _)| id == last)
206                    {
207                        state.unread += self.items.len() - index - 1;
208                    }
209                    let index = state.scroll.top_item();
210                    if let Some(id) = frame.ids.get(index)
211                        && let Some(old) = state.scroll.bounds_for_item(index)
212                        && let Some((_, layout)) = self.items.iter().find(|(key, _)| key == id)
213                        && let Some(layout) = layout.get()
214                    {
215                        let new = window.layout_bounds(layout);
216                        let mut anchored = offset;
217                        anchored.y += (old.top() - frame.top) - (new.top() - bounds.top());
218                        state.scroll.set_offset(anchored);
219                    }
220                }
221            }
222            if following {
223                state.scroll.scroll_to_bottom();
224            }
225            state.jump = false;
226            state.frame = Some(Frame {
227                ids: self.items.iter().map(|(id, _)| id.clone()).collect(),
228                top: bounds.top(),
229            });
230            previous
231        });
232        self.area.prepaint(window, cx);
233        self.state.update(cx, |state, cx| {
234            state.following =
235                (state.scroll.offset().y + state.scroll.max_offset().y).abs() <= px(1.);
236            if state.following {
237                state.unread = 0;
238            }
239            if previous != (state.following, state.unread) {
240                cx.notify();
241            }
242        });
243    }
244
245    fn paint(
246        &mut self,
247        _: Option<&GlobalElementId>,
248        _: Option<&InspectorElementId>,
249        _: Bounds<Pixels>,
250        _: &mut (),
251        _: &mut (),
252        window: &mut Window,
253        cx: &mut App,
254    ) {
255        self.area.paint(window, cx);
256    }
257}
258
259struct MeasuredItem {
260    id: ElementId,
261    child: AnyElement,
262    layout: Rc<Cell<Option<LayoutId>>>,
263}
264
265impl IntoElement for MeasuredItem {
266    type Element = Self;
267    fn into_element(self) -> Self {
268        self
269    }
270}
271
272impl Element for MeasuredItem {
273    type RequestLayoutState = ();
274    type PrepaintState = ();
275    fn id(&self) -> Option<ElementId> {
276        Some(self.id.clone())
277    }
278    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
279        None
280    }
281    fn request_layout(
282        &mut self,
283        _: Option<&GlobalElementId>,
284        _: Option<&InspectorElementId>,
285        window: &mut Window,
286        cx: &mut App,
287    ) -> (LayoutId, ()) {
288        let layout = self.child.request_layout(window, cx);
289        self.layout.set(Some(layout));
290        (layout, ())
291    }
292    fn prepaint(
293        &mut self,
294        _: Option<&GlobalElementId>,
295        _: Option<&InspectorElementId>,
296        _: Bounds<Pixels>,
297        _: &mut (),
298        window: &mut Window,
299        cx: &mut App,
300    ) {
301        self.child.prepaint(window, cx);
302    }
303    fn paint(
304        &mut self,
305        _: Option<&GlobalElementId>,
306        _: Option<&InspectorElementId>,
307        _: Bounds<Pixels>,
308        _: &mut (),
309        _: &mut (),
310        window: &mut Window,
311        cx: &mut App,
312    ) {
313        self.child.paint(window, cx);
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    use gpui::{AppContext as _, Context, Render, TestAppContext, div, point};
321
322    struct Conversation {
323        state: Entity<MessageScrollerState>,
324        items: Vec<(usize, f32)>,
325        height: f32,
326    }
327    impl Render for Conversation {
328        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
329            self.items.iter().fold(
330                MessageScroller::new("messages", &self.state, cx)
331                    .w(px(200.))
332                    .h(px(self.height)),
333                |area, &(id, height)| area.item(id, div().h(px(height)).flex_shrink_0()),
334            )
335        }
336    }
337
338    #[gpui::test]
339    fn follow_stream_preserve_keyed_history_and_jump(cx: &mut TestAppContext) {
340        cx.update(crate::init);
341        let (view, cx) = cx.add_window_view(|_, cx| Conversation {
342            state: cx.new(MessageScrollerState::new),
343            items: (0..5).map(|id| (id, 50.)).collect(),
344            height: 100.,
345        });
346        let state = view.read_with(cx, |view, _| view.state.clone());
347        let scroll = state.read_with(cx, |state, _| state.scroll_handle().clone());
348        cx.update(|window, cx| window.draw(cx).clear(cx));
349        assert_eq!(scroll.offset().y, px(-150.));
350        view.update(cx, |view, cx| {
351            view.items[4].1 = 80.;
352            cx.notify();
353        });
354        cx.update(|window, cx| window.draw(cx).clear(cx));
355        assert_eq!(scroll.offset().y, px(-180.));
356
357        // Reader is partway through message 1, not aligned to an item edge.
358        scroll.set_offset(point(px(0.), px(-65.)));
359        view.update(cx, |view, cx| {
360            view.items.insert(0, (8, 35.));
361            view.items.push((9, 50.));
362            cx.notify();
363        });
364        cx.update(|window, cx| window.draw(cx).clear(cx));
365        assert_eq!(scroll.offset().y, px(-100.));
366        assert_eq!(state.read_with(cx, |state, _| state.unread_count()), 1);
367        view.update(cx, |view, cx| {
368            view.items.last_mut().unwrap().1 = 110.;
369            cx.notify();
370        });
371        cx.update(|window, cx| window.draw(cx).clear(cx));
372        assert_eq!(scroll.offset().y, px(-100.));
373        assert_eq!(state.read_with(cx, |state, _| state.unread_count()), 1);
374        cx.update(|window, cx| state.update(cx, |state, cx| state.jump_to_latest(window, cx)));
375        cx.update(|window, cx| window.draw(cx).clear(cx));
376        assert_eq!(scroll.offset().y, -scroll.max_offset().y);
377        assert_eq!(state.read_with(cx, |state, _| state.unread_count()), 0);
378
379        // A resize can reveal all unread content without an extra scroll event.
380        scroll.set_offset(point(px(0.), px(-65.)));
381        view.update(cx, |view, cx| {
382            view.items.push((10, 50.));
383            cx.notify();
384        });
385        cx.update(|window, cx| window.draw(cx).clear(cx));
386        assert_eq!(state.read_with(cx, |state, _| state.unread_count()), 1);
387        cx.update(|window, cx| {
388            view.update(cx, |view, cx| {
389                view.height = 600.;
390                cx.notify();
391            });
392            window.refresh();
393            window.draw(cx).clear(cx);
394            assert_eq!(scroll.offset().y, px(0.));
395            assert_eq!(scroll.max_offset().y, px(0.));
396            assert!(state.read(cx).is_following());
397            assert_eq!(state.read(cx).unread_count(), 0);
398        });
399    }
400
401    #[cfg(feature = "test-support")]
402    #[gpui::test]
403    fn message_ids_scope_child_focus_across_reordering(cx: &mut TestAppContext) {
404        use crate::{Button, test_support};
405        use gpui::{InteractiveElement as _, Modifiers};
406
407        struct Replies {
408            state: Entity<MessageScrollerState>,
409            ids: Vec<usize>,
410        }
411        impl Render for Replies {
412            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
413                div().tab_group().child(
414                    self.ids.iter().fold(
415                        MessageScroller::new("messages", &self.state, cx)
416                            .w(px(200.))
417                            .h(px(100.)),
418                        |area, &id| {
419                            area.item(
420                                id,
421                                Button::new("reply")
422                                    .accessibility_label(format!("Reply {id}"))
423                                    .h(px(50.))
424                                    .flex_shrink_0()
425                                    .child("Reply"),
426                            )
427                        },
428                    ),
429                )
430            }
431        }
432
433        let (view, cx) = cx.add_window_view(|_, cx| Replies {
434            state: cx.new(MessageScrollerState::new),
435            ids: vec![0, 1],
436        });
437        let first = cx.update(|window, cx| {
438            window.draw(cx).clear(cx);
439            let replies = test_support::find_all(window, &[], &"reply".into());
440            assert_eq!(replies.len(), 2);
441            replies[0].bounds().center()
442        });
443        cx.simulate_click(first, Modifiers::default());
444        view.update(cx, |view, cx| {
445            view.ids.reverse();
446            cx.notify();
447        });
448        cx.update(|window, cx| {
449            window.draw(cx).clear(cx);
450            let replies = test_support::find_all(window, &[], &"reply".into());
451            assert_eq!(replies[0].label(), Some("Reply 1"));
452            assert_eq!(replies[0].focused(), Some(false));
453            assert_eq!(replies[1].label(), Some("Reply 0"));
454            assert_eq!(replies[1].focused(), Some(true));
455            window.focus_next(cx);
456        });
457        cx.update(|window, cx| {
458            window.draw(cx).clear(cx);
459            let replies = test_support::find_all(window, &[], &"reply".into());
460            assert_eq!(replies[0].focused(), Some(true));
461            assert_eq!(replies[1].focused(), Some(false));
462        });
463    }
464}