Skip to main content

lumen_dioxus/layout/
message_scroller.rs

1//! `MessageScroller` and `MessageScrollerJump`.
2//!
3//! With `auto_scroll`, the scroller follows new messages while the reader is at the end, like
4//! `createLumenMessageScrollerController` in `lumen-core`: it starts at the newest message,
5//! re-scrolls after every render while at the end (within `scroll_threshold` pixels), and stops
6//! following once the reader scrolls up.
7//!
8//! It scrolls through the mounted element, which web and desktop support. Dioxus Native has no
9//! element scrolling or scroll events yet, so there it renders the same markup and the reader
10//! scrolls by hand.
11
12use std::cell::Cell;
13use std::rc::Rc;
14
15use dioxus::html::geometry::PixelsVector2D;
16use dioxus::prelude::*;
17
18use super::headers::has_content;
19use crate::class::{Glass, compose};
20use crate::{Button, ButtonSize, ButtonVariant};
21
22/// Whether a scroll position is within `threshold` pixels of the end.
23pub(crate) fn message_scroller_at_end(
24    scroll_top: f64,
25    scroll_height: f64,
26    client_height: f64,
27    threshold: f64,
28) -> bool {
29    scroll_height - client_height - scroll_top <= threshold
30}
31
32#[derive(Clone, Copy)]
33struct MessageScrollerContext {
34    at_end: Signal<bool>,
35    viewport: Signal<Option<Rc<MountedData>>>,
36    /// The scroller's `on_at_end_change`, kept current on every render.
37    on_change: CopyValue<Option<EventHandler<bool>>>,
38}
39
40fn scroll_to_end(viewport: Option<Rc<MountedData>>) {
41    let Some(viewport) = viewport else {
42        return;
43    };
44
45    spawn(async move {
46        if let Ok(size) = viewport.get_scroll_size().await {
47            let _ = viewport
48                .scroll(
49                    PixelsVector2D::new(0.0, size.height),
50                    ScrollBehavior::Instant,
51                )
52                .await;
53        }
54    });
55}
56
57/// Props for [`MessageScroller`].
58#[derive(Props, Clone, PartialEq)]
59pub struct MessageScrollerProps {
60    /// Glass intensity.
61    #[props(default, into)]
62    pub glass: Glass,
63    /// Follows new messages while the reader is at the end.
64    #[props(default)]
65    pub auto_scroll: bool,
66    /// Distance from the end, in pixels, that still counts as at the end. Defaults to 32;
67    /// negative or non-finite values use 32.
68    #[props(default = 32.0)]
69    pub scroll_threshold: f64,
70    /// Called when the reader reaches or leaves the end.
71    pub on_at_end_change: Option<EventHandler<bool>>,
72    /// Tab order. With `auto_scroll`, it defaults to `0` once mounted, so keyboard users can scroll.
73    #[props(into)]
74    pub tabindex: Option<String>,
75    /// Extra classes appended after the Lumen classes.
76    #[props(into)]
77    pub class: Option<String>,
78    /// Any other `<div>` or global attribute. Name the conversation with `aria_label`.
79    #[props(extends = GlobalAttributes, extends = div)]
80    pub attributes: Vec<Attribute>,
81    /// Messages, oldest first, and an optional [`MessageScrollerJump`].
82    pub children: Element,
83}
84
85/// A scrolling conversation that can keep the newest message in view.
86#[component]
87pub fn MessageScroller(props: MessageScrollerProps) -> Element {
88    let threshold = if props.scroll_threshold.is_finite() && props.scroll_threshold >= 0.0 {
89        props.scroll_threshold
90    } else {
91        32.0
92    };
93    let mut viewport = use_signal(|| None::<Rc<MountedData>>);
94    let mut at_end = use_signal(|| true);
95    let on_change = props.on_at_end_change;
96    let mut change_store = use_hook(|| CopyValue::new(None::<EventHandler<bool>>));
97    change_store.set(on_change);
98    use_context_provider(|| MessageScrollerContext {
99        at_end,
100        viewport,
101        on_change: change_store,
102    });
103
104    // Re-run the follow effect after every render, which is when new messages arrive.
105    let renders = use_hook(|| Rc::new(Cell::new(0_u64)));
106    renders.set(renders.get() + 1);
107    let render = renders.get();
108    let auto_scroll = props.auto_scroll;
109    use_effect(use_reactive((&render, &auto_scroll), move |(_, follow)| {
110        if follow && *at_end.peek() {
111            scroll_to_end(viewport.peek().clone());
112        }
113    }));
114
115    let mounted = viewport.read().is_some();
116    let enhanced = auto_scroll && mounted;
117    let tabindex = props
118        .tabindex
119        .clone()
120        .or_else(|| enhanced.then(|| "0".to_string()));
121    let glass = props.glass.class("ui-message-scroller");
122    let class = compose([
123        Some("ui-message-scroller"),
124        glass.as_deref(),
125        props.class.as_deref(),
126    ]);
127
128    rsx! {
129        div {
130            class,
131            "data-at-end": enhanced.then(|| at_end().to_string()),
132            tabindex,
133            onmounted: move |event| viewport.set(Some(event.data())),
134            onscroll: move |event| {
135                let next = message_scroller_at_end(
136                    event.scroll_top(),
137                    f64::from(event.scroll_height()),
138                    f64::from(event.client_height()),
139                    threshold,
140                );
141
142                if *at_end.peek() != next {
143                    at_end.set(next);
144
145                    if let Some(handler) = on_change {
146                        handler.call(next);
147                    }
148                }
149            },
150            ..props.attributes,
151            {props.children}
152        }
153    }
154}
155
156/// Props for [`MessageScrollerJump`].
157#[derive(Props, Clone, PartialEq)]
158pub struct MessageScrollerJumpProps {
159    /// Button variant. Defaults to secondary.
160    #[props(default = ButtonVariant::Secondary)]
161    pub variant: ButtonVariant,
162    /// Button size. Defaults to small.
163    #[props(default = ButtonSize::Sm)]
164    pub size: ButtonSize,
165    /// Extra classes appended after the button classes.
166    #[props(into)]
167    pub class: Option<String>,
168    /// Any other `<button>` or global attribute.
169    #[props(extends = GlobalAttributes, extends = button)]
170    pub attributes: Vec<Attribute>,
171    /// Button label. Defaults to "Jump to latest".
172    pub children: Element,
173}
174
175/// A button inside a [`MessageScroller`] (`data-ui-message-jump`) that is hidden at the end and
176/// scrolls back to the newest message.
177#[component]
178pub fn MessageScrollerJump(props: MessageScrollerJumpProps) -> Element {
179    let scroller = try_use_context::<MessageScrollerContext>().unwrap_or_else(|| {
180        panic!("MessageScrollerJump must be used inside a Lumen MessageScroller.")
181    });
182    let hidden = (scroller.at_end)();
183    let mut attributes = vec![
184        Attribute::new("data-ui-message-jump", "true", None, false),
185        Attribute::new("hidden", hidden, None, false),
186    ];
187    attributes.extend(props.attributes);
188    let label = if has_content(&props.children) {
189        props.children
190    } else {
191        rsx! { "Jump to latest" }
192    };
193
194    rsx! {
195        Button {
196            class: props.class,
197            onclick: move |_| {
198                let mut at_end = scroller.at_end;
199
200                if !*at_end.peek() {
201                    at_end.set(true);
202
203                    if let Some(handler) = *scroller.on_change.peek() {
204                        handler.call(true);
205                    }
206                }
207
208                scroll_to_end(scroller.viewport.peek().clone());
209            },
210            size: props.size,
211            variant: props.variant,
212            attributes,
213            {label}
214        }
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::message_scroller_at_end;
221
222    #[test]
223    fn at_end_uses_the_threshold() {
224        assert!(message_scroller_at_end(600.0, 1000.0, 400.0, 32.0));
225        assert!(message_scroller_at_end(570.0, 1000.0, 400.0, 32.0));
226        assert!(!message_scroller_at_end(560.0, 1000.0, 400.0, 32.0));
227        assert!(message_scroller_at_end(0.0, 300.0, 400.0, 0.0));
228    }
229}