1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
//! `MessageScroller`: the scrolling column of a chat.
//!
//! Built on GPUI's virtualized `list`, anchored to the bottom like a chat log:
//! - it follows new and streamed messages while the reader is at the bottom,
//! - prepending history keeps the reader's place instead of jumping,
//! - a "Jump to latest" button appears when the reader has scrolled up,
//! - [`MessageScrollerState::scroll_to_message`] jumps to any message.
use std::rc::Rc;
use gpui::{
div, list, prelude::*, px, AnyElement, App, ListAlignment, ListOffset, ListState,
StyleRefinement, Window,
};
use super::button::{Button, IconPosition};
use crate::sx::SxStyled;
use crate::{icon::IconName, styles, styles::ApplyStyleOverrides};
styles! {
MESSAGE_SCROLLER = {
root: { position: relative, display: flex, direction: column },
row: { width: full, padding_x: 4, padding_y: 1.5 },
jump_bar: {
position: absolute,
bottom: 3,
left: 0,
width: full,
display: flex,
justify: center,
},
jump: { radius: full, shadow: md },
}
}
/// Scroll position and message count of a [`MessageScroller`]. Keep it in your
/// view and tell it when messages change. Cheap to clone; clones share state.
#[derive(Clone)]
pub struct MessageScrollerState {
list: ListState,
}
impl MessageScrollerState {
/// A scroller showing `message_count` messages, scrolled to the latest.
#[must_use]
pub fn new(message_count: usize) -> Self {
Self {
list: ListState::new(message_count, ListAlignment::Bottom, px(800.)),
}
}
/// The number of messages shown.
#[must_use]
pub fn message_count(&self) -> usize {
self.list.item_count()
}
/// `count` messages were added at the end.
pub fn push(&self, count: usize) {
let end = self.list.item_count();
self.list.splice(end..end, count);
}
/// `count` older messages were added at the start (history loaded). The
/// reader stays on the message they were looking at.
pub fn prepend(&self, count: usize) {
self.list.splice(0..0, count);
}
/// The message at `index` changed size (a streamed reply grew); re-measure it.
pub fn message_changed(&self, index: usize) {
if index < self.list.item_count() {
self.list.splice(index..index + 1, 1);
}
}
/// Replace everything (open a different transcript), scrolled to the latest.
pub fn reset(&self, message_count: usize) {
self.list.reset(message_count);
}
/// Put message `index` at the top of the view.
pub fn scroll_to_message(&self, index: usize) {
self.list.scroll_to(ListOffset {
item_ix: index,
offset_in_item: px(0.),
});
}
/// Scroll so message `index` is fully visible, moving as little as possible.
pub fn reveal_message(&self, index: usize) {
self.list.scroll_to_reveal_item(index);
}
/// Scroll to the newest message.
pub fn scroll_to_bottom(&self) {
self.list.scroll_to(ListOffset {
item_ix: self.list.item_count(),
offset_in_item: px(0.),
});
}
/// Whether the newest message is in view (the scroller is following).
#[must_use]
pub fn is_at_bottom(&self) -> bool {
if self.list.logical_scroll_top().item_ix >= self.list.item_count() {
return true;
}
let max_scroll = self.list.max_offset_for_scrollbar().height;
let scrolled = -self.list.scroll_px_offset_for_scrollbar().y;
scrolled >= max_scroll - px(2.)
}
}
type RenderMessage = Rc<dyn Fn(usize, &mut Window, &mut App) -> AnyElement>;
/// ```no_run
/// # use rok_ui::prelude::*;
/// # #[derive(Clone)] struct ChatMessage(SharedString);
/// # fn render_message(message: &ChatMessage) -> impl IntoElement { div().child(message.0.clone()) }
/// struct Chat {
/// scroller: MessageScrollerState,
/// messages: Vec<ChatMessage>,
/// }
///
/// impl Chat {
/// fn load_older_messages(&mut self, _: &mut Context<Self>) {}
/// }
///
/// impl Render for Chat {
/// fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
/// MessageScroller::new(&self.scroller, {
/// let messages = self.messages.clone();
/// move |index, _, _| render_message(&messages[index]).into_any_element()
/// })
/// .on_reach_top(cx.listener(|view, _, _, cx| view.load_older_messages(cx)))
/// .h_full()
/// }
/// }
/// ```
#[derive(IntoElement)]
pub struct MessageScroller {
state: MessageScrollerState,
render_message: RenderMessage,
on_reach_top: Option<crate::hooks::EventHandler<()>>,
jump_label: gpui::SharedString,
sx: crate::sx::Sx,
style_overrides: StyleRefinement,
}
crate::implement_style_overrides!(MessageScroller);
impl MessageScroller {
/// A scroller for messages; keep its state with `use_message_scroller_state`.
pub fn new(
state: &MessageScrollerState,
render_message: impl Fn(usize, &mut Window, &mut App) -> AnyElement + 'static,
) -> Self {
Self {
state: state.clone(),
render_message: Rc::new(render_message),
on_reach_top: None,
jump_label: "Jump to latest".into(),
sx: crate::sx::Sx::new(),
style_overrides: StyleRefinement::default(),
}
}
/// Called when the oldest loaded message scrolls into view; load history here
/// and call [`MessageScrollerState::prepend`].
#[must_use]
pub fn on_reach_top(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_reach_top = Some(Rc::new(handler));
self
}
/// Text of the button shown when scrolled away from the latest message.
#[must_use]
pub fn jump_label(mut self, label: impl Into<gpui::SharedString>) -> Self {
self.jump_label = label.into();
self
}
}
impl RenderOnce for MessageScroller {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let list_state = self.state.list.clone();
if let Some(on_reach_top) = self.on_reach_top.clone() {
list_state.set_scroll_handler(move |event, window, cx| {
if event.is_scrolled && event.visible_range.start == 0 {
on_reach_top(&(), window, cx);
}
});
}
let render_message = self.render_message.clone();
let show_jump = !self.state.is_at_bottom();
let jump_state = self.state.clone();
div()
.sx((&MESSAGE_SCROLLER.root, &self.sx))
.child(
list(list_state, move |index, window, cx| {
div()
.sx(&MESSAGE_SCROLLER.row)
.child(render_message(index, window, cx))
.into_any_element()
})
.size_full(),
)
.when(show_jump, |scroller| {
scroller.child(
div().sx(&MESSAGE_SCROLLER.jump_bar).child(
Button::new("message-scroller-jump")
.outline()
.small()
.sx(&MESSAGE_SCROLLER.jump)
.label(self.jump_label)
.icon(IconName::ArrowDown)
.icon_position(IconPosition::End)
.on_click(move |_, window, _| {
jump_state.scroll_to_bottom();
window.refresh();
}),
),
)
})
.apply_style_overrides(&self.style_overrides)
}
}