lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `MessageScroller` and `MessageScrollerJump`.
//!
//! With `auto_scroll`, the scroller follows new messages while the reader is at the end, like
//! `createLumenMessageScrollerController` in `lumen-core`: it starts at the newest message,
//! re-scrolls after every render while at the end (within `scroll_threshold` pixels), and stops
//! following once the reader scrolls up.
//!
//! It scrolls through the mounted element, which web and desktop support. Dioxus Native has no
//! element scrolling or scroll events yet, so there it renders the same markup and the reader
//! scrolls by hand.

use std::cell::Cell;
use std::rc::Rc;

use dioxus::html::geometry::PixelsVector2D;
use dioxus::prelude::*;

use super::headers::has_content;
use crate::class::{Glass, compose};
use crate::{Button, ButtonSize, ButtonVariant};

/// Whether a scroll position is within `threshold` pixels of the end.
pub(crate) fn message_scroller_at_end(
    scroll_top: f64,
    scroll_height: f64,
    client_height: f64,
    threshold: f64,
) -> bool {
    scroll_height - client_height - scroll_top <= threshold
}

#[derive(Clone, Copy)]
struct MessageScrollerContext {
    at_end: Signal<bool>,
    viewport: Signal<Option<Rc<MountedData>>>,
    /// The scroller's `on_at_end_change`, kept current on every render.
    on_change: CopyValue<Option<EventHandler<bool>>>,
}

fn scroll_to_end(viewport: Option<Rc<MountedData>>) {
    let Some(viewport) = viewport else {
        return;
    };

    spawn(async move {
        if let Ok(size) = viewport.get_scroll_size().await {
            let _ = viewport
                .scroll(
                    PixelsVector2D::new(0.0, size.height),
                    ScrollBehavior::Instant,
                )
                .await;
        }
    });
}

/// Props for [`MessageScroller`].
#[derive(Props, Clone, PartialEq)]
pub struct MessageScrollerProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Follows new messages while the reader is at the end.
    #[props(default)]
    pub auto_scroll: bool,
    /// Distance from the end, in pixels, that still counts as at the end. Defaults to 32;
    /// negative or non-finite values use 32.
    #[props(default = 32.0)]
    pub scroll_threshold: f64,
    /// Called when the reader reaches or leaves the end.
    pub on_at_end_change: Option<EventHandler<bool>>,
    /// Tab order. With `auto_scroll`, it defaults to `0` once mounted, so keyboard users can scroll.
    #[props(into)]
    pub tabindex: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the conversation with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Messages, oldest first, and an optional [`MessageScrollerJump`].
    pub children: Element,
}

/// A scrolling conversation that can keep the newest message in view.
#[component]
pub fn MessageScroller(props: MessageScrollerProps) -> Element {
    let threshold = if props.scroll_threshold.is_finite() && props.scroll_threshold >= 0.0 {
        props.scroll_threshold
    } else {
        32.0
    };
    let mut viewport = use_signal(|| None::<Rc<MountedData>>);
    let mut at_end = use_signal(|| true);
    let on_change = props.on_at_end_change;
    let mut change_store = use_hook(|| CopyValue::new(None::<EventHandler<bool>>));
    change_store.set(on_change);
    use_context_provider(|| MessageScrollerContext {
        at_end,
        viewport,
        on_change: change_store,
    });

    // Re-run the follow effect after every render, which is when new messages arrive.
    let renders = use_hook(|| Rc::new(Cell::new(0_u64)));
    renders.set(renders.get() + 1);
    let render = renders.get();
    let auto_scroll = props.auto_scroll;
    use_effect(use_reactive((&render, &auto_scroll), move |(_, follow)| {
        if follow && *at_end.peek() {
            scroll_to_end(viewport.peek().clone());
        }
    }));

    let mounted = viewport.read().is_some();
    let enhanced = auto_scroll && mounted;
    let tabindex = props
        .tabindex
        .clone()
        .or_else(|| enhanced.then(|| "0".to_string()));
    let glass = props.glass.class("ui-message-scroller");
    let class = compose([
        Some("ui-message-scroller"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        div {
            class,
            "data-at-end": enhanced.then(|| at_end().to_string()),
            tabindex,
            onmounted: move |event| viewport.set(Some(event.data())),
            onscroll: move |event| {
                let next = message_scroller_at_end(
                    event.scroll_top(),
                    f64::from(event.scroll_height()),
                    f64::from(event.client_height()),
                    threshold,
                );

                if *at_end.peek() != next {
                    at_end.set(next);

                    if let Some(handler) = on_change {
                        handler.call(next);
                    }
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`MessageScrollerJump`].
#[derive(Props, Clone, PartialEq)]
pub struct MessageScrollerJumpProps {
    /// Button variant. Defaults to secondary.
    #[props(default = ButtonVariant::Secondary)]
    pub variant: ButtonVariant,
    /// Button size. Defaults to small.
    #[props(default = ButtonSize::Sm)]
    pub size: ButtonSize,
    /// Extra classes appended after the button classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Button label. Defaults to "Jump to latest".
    pub children: Element,
}

/// A button inside a [`MessageScroller`] (`data-ui-message-jump`) that is hidden at the end and
/// scrolls back to the newest message.
#[component]
pub fn MessageScrollerJump(props: MessageScrollerJumpProps) -> Element {
    let scroller = try_use_context::<MessageScrollerContext>().unwrap_or_else(|| {
        panic!("MessageScrollerJump must be used inside a Lumen MessageScroller.")
    });
    let hidden = (scroller.at_end)();
    let mut attributes = vec![
        Attribute::new("data-ui-message-jump", "true", None, false),
        Attribute::new("hidden", hidden, None, false),
    ];
    attributes.extend(props.attributes);
    let label = if has_content(&props.children) {
        props.children
    } else {
        rsx! { "Jump to latest" }
    };

    rsx! {
        Button {
            class: props.class,
            onclick: move |_| {
                let mut at_end = scroller.at_end;

                if !*at_end.peek() {
                    at_end.set(true);

                    if let Some(handler) = *scroller.on_change.peek() {
                        handler.call(true);
                    }
                }

                scroll_to_end(scroller.viewport.peek().clone());
            },
            size: props.size,
            variant: props.variant,
            attributes,
            {label}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::message_scroller_at_end;

    #[test]
    fn at_end_uses_the_threshold() {
        assert!(message_scroller_at_end(600.0, 1000.0, 400.0, 32.0));
        assert!(message_scroller_at_end(570.0, 1000.0, 400.0, 32.0));
        assert!(!message_scroller_at_end(560.0, 1000.0, 400.0, 32.0));
        assert!(message_scroller_at_end(0.0, 300.0, 400.0, 0.0));
    }
}