A chat transcript that sticks to the newest message unless the reader scrolls up.
use std::time::Duration;
use gpui::{div, prelude::*, px, svg, Context, Entity, Subscription, Task, Window};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize};
use crate::ui::input::{InputEvent, TextInput};
use crate::ui::marker::Marker;
use crate::ui::message::{Message, MessageAlign};
use crate::ui::message_scroller::MessageScroller;
use crate::ui::spinner::Spinner;
use crate::icons::ARROW_UP;
// Stand-ins for a model's streamed output: a pause to "think", then one word per tick.
const THINKING: Duration = Duration::from_millis(900);
const WORD: Duration = Duration::from_millis(45);
const REPLIES: [&str; 3] = [
"Start by moving the theme tokens into one file so every component reads the same values. \
Then replace hard-coded colors with those tokens, one component at a time, and check each \
in light and dark mode. Finally, add a preview for each component so regressions show up \
in review instead of in production. Most teams finish this in a week or two.",
"Keep the scroll position owned by the transcript, not by each message. New output should \
only move the view while the reader is at the bottom; once they scroll up to reread \
something, leave them there and offer a way back to the latest message.",
"Stream the reply into the last message instead of appending new rows. That keeps the \
list stable, lets the scroller follow the growing text and avoids a flash of empty \
bubbles while the first tokens arrive.",
];
struct ChatMessage {
from_user: bool,
text: String,
}
#[derive(Default)]
pub struct MessageScrollerDemo {
messages: Vec<ChatMessage>,
composer: Option<Entity<TextInput>>,
/// The reply being streamed; dropping it stops the stream.
stream: Option<Task<()>>,
replies_sent: usize,
_submit: Option<Subscription>,
}
impl MessageScrollerDemo {
fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(composer) = self.composer.clone() else {
return;
};
let text = composer.read(cx).text();
if text.trim().is_empty() || self.stream.is_some() {
return;
}
composer.update(cx, |input, cx| input.set_text("", window, cx));
self.messages.push(ChatMessage {
from_user: true,
text: text.to_string(),
});
self.stream_reply(cx);
}
fn stream_reply(&mut self, cx: &mut Context<Self>) {
let reply = REPLIES[self.replies_sent % REPLIES.len()];
self.replies_sent += 1;
self.messages.push(ChatMessage {
from_user: false,
text: String::new(),
});
self.stream = Some(cx.spawn(async move |this, cx| {
cx.background_executor().timer(THINKING).await;
for word in reply.split_whitespace() {
let appended = this.update(cx, |this, cx| {
if let Some(last) = this.messages.last_mut() {
if !last.text.is_empty() {
last.text.push(' ');
}
last.text.push_str(word);
}
cx.notify();
});
if appended.is_err() {
return;
}
cx.background_executor().timer(WORD).await;
}
this.update(cx, |this, cx| {
this.stream = None;
cx.notify();
})
.ok();
}));
cx.notify();
}
}
impl Render for MessageScrollerDemo {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.composer.is_none() {
let composer = cx.new(|cx| TextInput::new(cx).placeholder("Send a message...").bare());
self._submit =
Some(
cx.subscribe_in(&composer, window, |this, _, event, window, cx| {
if let InputEvent::Submit(_) = event {
this.send(window, cx);
}
}),
);
self.composer = Some(composer);
self.messages = vec![
ChatMessage { from_user: true, text: "Our design system drifted. Where do we start?".into() },
ChatMessage { from_user: false, text: "Audit what you have first: list every color, radius and spacing value in use, then group the near-duplicates.".into() },
ChatMessage { from_user: true, text: "Done, we found 31 grays. What next?".into() },
];
self.stream_reply(cx);
}
let theme = cx.theme();
let (muted_fg, primary_fg) = (theme.muted_foreground, theme.primary_foreground);
let streaming = self.stream.is_some();
let sent = self
.messages
.iter()
.filter(|message| message.from_user)
.count();
let rows = self.messages.iter().enumerate().map(|(ix, message)| {
if message.from_user {
Message::new().align(MessageAlign::End).child(
Bubble::new(("message", ix))
.align(BubbleAlign::End)
.child(message.text.clone()),
)
} else if message.text.is_empty() {
Message::new()
.avatar(Avatar::new("AI").size(AvatarSize::Sm))
.child(
Marker::new(("thinking", ix))
.icon(Spinner::new().color(muted_fg))
.shimmer(true)
.child("Thinking..."),
)
} else {
Message::new()
.avatar(Avatar::new("AI").size(AvatarSize::Sm))
.child(
Bubble::new(("message", ix))
.variant(BubbleVariant::Muted)
.child(message.text.clone()),
)
}
});
div()
.w(px(600.0))
.h(px(312.0))
.flex()
.flex_col()
.rounded(theme.radius + px(4.0))
.border_1()
.border_color(theme.border)
.bg(theme.background)
.overflow_hidden()
.child(
MessageScroller::new("chat")
.flex_1()
.min_h_0()
// Sending a message brings the reader back to the end.
.jump_on_change(sent)
.children(rows),
)
.child(
div()
.flex()
.items_center()
.gap_2()
.px_4()
.py_2()
.border_t_1()
.border_color(theme.border)
.child(div().flex_1().min_w_0().children(self.composer.clone()))
.child(
Button::new("send", "")
.size(ButtonSize::Sm)
.icon_only()
.rounded_full()
.disabled(streaming)
.leading(svg().data(ARROW_UP).size(px(16.0)).text_color(primary_fg))
.on_click(cx.listener(|this, _, window, cx| this.send(window, cx))),
),
)
}
}Installation
Copies src/ui/message_scroller.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/message_scroller.rs.src/ui/message_scroller.rs use std::{sync::Arc, time::Duration}; use gpui::{ div, point, prelude::*, px, svg, Animation, AnimationExt, AnyElement, App, ElementId, Pixels, Point, Refineable, ScrollHandle, SharedString, StyleRefinement, Window, }; use crate::theme::ActiveTheme; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::popover::animation_clock; use crate::ui::scroll_area::ScrollArea; use crate::icons::ARROW_DOWN; /// How close to the end still counts as "at the latest message", so sub-pixel layout /// differences don't drop the reader off the live edge. const LIVE_EDGE: Pixels = px(4.0); /// Content further below the view than this shows the jump button, like shadcn's /// `scrollEdgeThreshold`. const EDGE_THRESHOLD: Pixels = px(8.0); const JUMP_IN: Duration = Duration::from_millis(200); const JUMP_OUT: Duration = Duration::from_millis(400); /// A CSS cubic-bézier timing function: solves x for `t` by Newton's method and returns y. fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 { move |t| { let at = |a: f32, b: f32, s: f32| 3.0 * a * s * (1.0 - s).powi(2) + 3.0 * b * s * s * (1.0 - s) + s.powi(3); let slope = |a: f32, b: f32, s: f32| 3.0 * a * (1.0 - s).powi(2) + 6.0 * (b - a) * s * (1.0 - s) + 3.0 * (1.0 - b) * s * s; let mut s = t.clamp(0.0, 1.0); for _ in 0..8 { let dx = slope(x1, x2, s); if dx.abs() < 1e-6 { break; } s = (s - (at(x1, x2, s) - t) / dx).clamp(0.0, 1.0); } at(y1, y2, s) } } /// How much of the previous message stays visible above an anchored one, like shadcn's /// `scrollPreviousItemPeek`. const PREVIOUS_ITEM_PEEK: Pixels = px(64.0); /// Following the live edge is pointer state the app has no reason to own (shadcn's scroller /// tracks it imperatively too), and only the scroll offset after layout says whether the /// reader is at the end, so it lives here. struct ScrollerState { handle: ScrollHandle, /// Keep the newest message in view as content arrives. follow: bool, /// The offset after the last layout. A different offset at the next render means the /// reader scrolled (wheel, touch or scrollbar drag) since. settled: Point<Pixels>, jump_key: Option<usize>, /// The last anchored child this scroller has seen, so each new one is placed once. anchor_key: Option<usize>, /// An anchored child waiting for its first layout before it can be scrolled to. pending: Option<usize>, /// While set, the view holds the anchored message at this scroll distance from the top. hold: Option<Pixels>, /// Whether the content keeps room below it for an anchored message: from an anchor until /// the reply below it fills the view. The room stays when the reader scrolls away, so /// scrolling back down returns to the anchored place. spacer: bool, /// The anchored scroll distance the room is sized for. room: Pixels, /// Whether the jump button is showing, and how many times that has changed, so each /// change replays its fade. jump_shown: bool, jump_changes: usize, /// When the button was last hidden, on `animation_clock`, so it unmounts once faded out. jump_hidden_at: Duration, /// Each child's top and bottom from the top of the scrolled content, after the last layout. items: Vec<(Pixels, Pixels)>, } /// A chat transcript that sticks to the newest message while it streams in. Scrolling up /// releases it and shows a jump button; scrolling back down or pressing the button follows /// again. Give it a height (or `flex_1()` in a column) and add the messages as children, /// oldest first. /// /// With [`scroll_anchor`](Self::scroll_anchor) it works like a chat that keeps your place, /// as shadcn's `scrollAnchor` items do: a newly sent message is scrolled near the top with /// the end of the previous reply peeking above it, and stays there while the reply streams /// in below. #[derive(IntoElement)] pub struct MessageScroller { id: ElementId, jump_label: SharedString, jump_key: Option<usize>, auto_scroll: bool, anchor: Option<usize>, peek: Pixels, gap: Pixels, padding_x: Pixels, padding_y: Pixels, style: StyleRefinement, children: Vec<AnyElement>, } impl MessageScroller { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), jump_label: "Jump to latest".into(), jump_key: None, auto_scroll: true, anchor: None, peek: PREVIOUS_ITEM_PEEK, gap: px(24.0), padding_x: px(16.0), padding_y: px(16.0), style: StyleRefinement::default(), children: Vec::new(), } } /// Jumps to the newest message and follows again whenever `key` changes. Pass e.g. the /// number of messages the reader has sent, so sending one brings them to the end even if /// they had scrolled up. pub fn jump_on_change(mut self, key: usize) -> Self { self.jump_key = Some(key); self } /// The text of the button that returns to the newest message. An empty label draws a /// round arrow button, like shadcn's `MessageScrollerButton`. pub fn jump_label(mut self, label: impl Into<SharedString>) -> Self { self.jump_label = label.into(); self } /// Follow new content while the view is at the end. On by default; shadcn's chat demo /// turns it off and relies on [`scroll_anchor`](Self::scroll_anchor) alone. pub fn auto_scroll(mut self, auto_scroll: bool) -> Self { self.auto_scroll = auto_scroll; self } /// The index of the child to keep your place at, usually the message the reader sent /// last. Each time it names a new child, that child is scrolled to `peek` below the top /// and held there while the content after it is shorter than the view. With /// `auto_scroll` on, the view goes back to following the end once the reply fills it. pub fn scroll_anchor(mut self, child: Option<usize>) -> Self { self.anchor = child; self } /// How much of the previous message stays visible above an anchored one; 64px by default. pub fn previous_item_peek(mut self, peek: impl Into<Pixels>) -> Self { self.peek = peek.into(); self } /// The space between messages; 24px by default. pub fn content_gap(mut self, gap: impl Into<Pixels>) -> Self { self.gap = gap.into(); self } /// The inset around the messages: `x` on the sides, `y` above and below; 16px by default. pub fn content_padding(mut self, x: impl Into<Pixels>, y: impl Into<Pixels>) -> Self { self.padding_x = x.into(); self.padding_y = y.into(); self } } impl Styled for MessageScroller { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } impl ParentElement for MessageScroller { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for MessageScroller { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let state = window.use_keyed_state(self.id.clone(), cx, |_, _| ScrollerState { handle: ScrollHandle::new(), follow: true, settled: Point::default(), jump_key: self.jump_key, anchor_key: None, pending: None, hold: None, spacer: false, room: px(0.0), jump_shown: false, jump_changes: 0, jump_hidden_at: Duration::ZERO, items: Vec::new(), }); let (jump_key, anchor, auto_scroll, peek) = (self.jump_key, self.anchor, self.auto_scroll, self.peek); let (gap, padding_y) = (self.gap, self.padding_y); let count = self.children.len(); let now = animation_clock(cx); let (min_height, show_jump, pending) = state.update(cx, |state, _| { let handle = state.handle.clone(); let viewport = handle.bounds().size.height; if state.jump_key != jump_key { state.jump_key = jump_key; state.follow = true; state.hold = None; state.spacer = false; handle.scroll_to_bottom(); } // Children that went away (a reset) take their anchor with them. if anchor.is_none_or(|ix| ix >= count) { state.anchor_key = None; state.pending = None; state.hold = None; if anchor.is_none() { state.spacer = false; } } // An anchor past the last child is ignored, so a wait for its layout can't stick. if let Some(ix) = anchor.filter(|&ix| ix < count && Some(ix) != state.anchor_key) { state.anchor_key = Some(ix); state.pending = Some(ix); state.follow = false; } let offset = handle.offset(); // Any scroll by the reader (wheel, touch, scrollbar drag) or by code lets go of // the anchored message. The room below it keeps the held offset in range, so a // changed offset is never just layout clamping it. let reader_scrolled = offset != state.settled; if reader_scrolled && state.pending.is_none() { state.hold = None; } if let Some(ix) = state.pending { // Laid out last frame with this child in it: place it now. if let Some(&(top, _)) = state.items.get(ix).filter(|_| state.items.len() == count) { let target = (top - padding_y - peek).max(px(0.0)); state.hold = Some(target); state.room = target; state.pending = None; state.spacer = true; } } // Where the messages end, as of the last layout. let end = state.items.last().map_or(px(0.0), |&(_, bottom)| bottom + padding_y); let scroll_top = state.hold.unwrap_or(-offset.y); // Room below the content so the anchored message can sit near the top: the content // is made at least one view taller than the anchored scroll distance. As a min // height it is resolved in the same layout as the content, so it never lags a frame. let mut min_height = None; if state.spacer { min_height = Some(state.room + viewport); if end >= state.room + viewport && state.pending.is_none() { // The reply filled the view: hand over to following the end. state.spacer = false; state.hold = None; if auto_scroll { state.follow = true; } } } if let Some(target) = state.hold { let held = point(px(0.0), -target); handle.set_offset(held); state.settled = held; } else if auto_scroll && state.follow && !reader_scrolled { // Applied during this frame's layout, against the new content height. handle.scroll_to_bottom(); } let show_jump = state.pending.is_none() && end - scroll_top - viewport > EDGE_THRESHOLD; if show_jump != state.jump_shown { state.jump_shown = show_jump; state.jump_changes += 1; if !show_jump { state.jump_hidden_at = now; } } // Mounted while shown and while it fades out; after that it is gone, cursor and all. let fading = !show_jump && state.jump_changes > 0 && now < state.jump_hidden_at + JUMP_OUT; let mounted = show_jump || fading; (min_height.filter(|_| state.spacer), (show_jump, state.jump_changes, mounted), state.pending.is_some()) }); let (shown, changes, mounted) = show_jump; // Keep drawing through a fade-out so the button unmounts as soon as it ends. if pending || (mounted && !shown) { window.request_animation_frame(); } let handle = state.read(cx).handle.clone(); let theme = cx.theme(); let (fg, bg) = (theme.foreground, theme.background); let jump = mounted.then(|| { let state = state.clone(); let icon_only = self.jump_label.is_empty(); let button = Button::new("jump-to-latest", self.jump_label) .variant(ButtonVariant::Outline) .size(if icon_only { ButtonSize::Compact } else { ButtonSize::Sm }) .when(icon_only, |this| this.icon_only()) .rounded_full() .leading(svg().data(ARROW_DOWN).size(px(16.0)).text_color(fg)) // A hidden button stays drawn while it fades, so it only takes clicks when shown. .when(shown, |this| { this.on_click(move |_, _, cx| { state.update(cx, |state, cx| { state.follow = true; state.hold = None; state.spacer = false; state.handle.scroll_to_bottom(); cx.notify(); }); }) }); // shadcn's round icon button sits flat on the thread; the labeled pill floats over // it with a shadow, painted under the whole wrapper so it gets the button's shape. let button = if icon_only { div().child(button) } else { div().rounded_full().bg(bg).shadow_md().child(button) }; // shadcn's `MessageScrollerButton` fades and slides up by its own height: in over // 200ms on `cubic-bezier(0.23, 1, 0.32, 1)`, out over 400ms on // `cubic-bezier(0.7, 0, 0.84, 0)`. Its 95% scale is left out; GPUI can't scale a div. let (duration, easing) = if shown { (JUMP_IN, cubic_bezier(0.23, 1.0, 0.32, 1.0)) } else { (JUMP_OUT, cubic_bezier(0.7, 0.0, 0.84, 0.0)) }; let rise = if icon_only { px(28.0) } else { px(32.0) }; div() .absolute() .left_0() .right_0() .bottom_4() .flex() .justify_center() .child( div() .relative() .child(button) .with_animation( ("jump-fade", changes), Animation::new(duration).with_easing(easing), move |this, t| { let visible = if shown { t } else { 1.0 - t }; this.opacity(visible).top(rise * (1.0 - visible)) }, ), ) }); let measure = state.clone(); let mut root = div().relative().flex().flex_col().overflow_hidden(); root.style().refine(&self.style); // The jump button and the anchor hold follow the scroll position, so draw again. root.on_scroll(move |_, window, _| window.refresh()) .on_children_prepainted(move |_, window, cx| { let changed = measure.update(cx, |state, _| { let offset = state.handle.offset(); let max = state.handle.max_offset(); let follow = if offset != state.settled { -offset.y >= max.y - LIVE_EDGE } else { state.follow }; if offset != state.settled { state.hold = None; } let changed = follow != state.follow; state.follow = follow && state.hold.is_none() && state.pending.is_none(); state.settled = offset; changed }); // A notify while the frame is being drawn is dropped, so ask for the next frame // to show or hide the jump button. if changed { window.request_animation_frame(); } }) .child( ScrollArea::new(ElementId::NamedChild(Arc::new(self.id), "viewport".into())) .track_scroll(&handle) .size_full() .child( div() .flex() .flex_col() .gap(gap) .px(self.padding_x) .py(padding_y) // Hidden for the frame between an anchored message's arrival and its // scroll, like shadcn's `data-pending-scroll`. .when(pending, |this| this.opacity(0.0)) .on_children_prepainted({ let state = state.clone(); move |bounds, _, cx| { state.update(cx, |state, _| { // Children are prepainted scrolled; undo that to get their // place in the content. let origin = state.handle.bounds().top() + state.handle.offset().y; let mut items: Vec<(Pixels, Pixels)> = bounds .iter() .map(|bounds| (bounds.top() - origin, bounds.bottom() - origin)) .collect(); items.truncate(count); state.items = items; }); } }) .when_some(min_height, |this, height| this.min_h(height)) .children(self.children), ), ) .children(jump) } }Register the module
// src/ui/mod.rs pub mod message_scroller;
Usage
use crate::ui::message_scroller::*;API Reference
MessageScroller
A chat transcript that sticks to the newest message while it streams in. Scrolling up releases it and shows a jump button; scrolling back down or pressing the button follows again. Give it a height (or flex_1() in a column) and add the messages as children, oldest first. With [scroll_anchor](Self::scroll_anchor) it works like a chat that keeps your place, as shadcn's scrollAnchor items do: a newly sent message is scrolled near the top with the end of the previous reply peeking above it, and stays there while the reply streams in below.
MessageScroller::new(id: impl Into<ElementId>) -> Self.jump_on_change(key: usize)Jumps to the newest message and follows again whenever key changes. Pass e.g. the number of messages the reader has sent, so sending one brings them to the end even if they had scrolled up.
.jump_label(label: impl Into<SharedString>)The text of the button that returns to the newest message. An empty label draws a round arrow button, like shadcn's MessageScrollerButton.
.auto_scroll(auto_scroll: bool)Follow new content while the view is at the end. On by default; shadcn's chat demo turns it off and relies on [scroll_anchor](Self::scroll_anchor) alone.
.scroll_anchor(child: Option<usize>)The index of the child to keep your place at, usually the message the reader sent last. Each time it names a new child, that child is scrolled to peek below the top and held there while the content after it is shorter than the view. With auto_scroll on, the view goes back to following the end once the reply fills it.
.previous_item_peek(peek: impl Into<Pixels>)How much of the previous message stays visible above an anchored one; 64px by default.
.content_gap(gap: impl Into<Pixels>)The space between messages; 24px by default.
.content_padding(x: impl Into<Pixels>, y: impl Into<Pixels>)The inset around the messages: x on the sides, y above and below; 16px by default.