lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `VirtualList`: renders only the rows near the scroll position of a long, fixed-height list.

// cspell:words onfocusin onfocusout onresize unitless

use dioxus::prelude::*;

use crate::class::{Glass, compose};

/// Default row height in CSS pixels.
pub const VIRTUAL_LIST_DEFAULT_ITEM_SIZE: f64 = 44.0;

/// Default number of extra rows rendered before and after the visible ones.
pub const VIRTUAL_LIST_DEFAULT_OVERSCAN: usize = 4;

/// The rows a [`VirtualList`] renders for one scroll position.
#[derive(Clone, Debug, PartialEq)]
pub struct VirtualListWindow {
    /// First row of the visible range, including overscan.
    pub start_index: usize,
    /// Last row of the visible range, including overscan. Equals `start_index` when empty.
    pub end_index: usize,
    /// Rendered row indexes, sorted; includes a focused row and its neighbors.
    pub indexes: Vec<usize>,
    /// Row height in CSS pixels.
    pub item_size: f64,
    /// Height of all rows in CSS pixels.
    pub total_size: f64,
}

/// The visible range reported by `on_range_change`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VirtualListRange {
    /// First rendered row, including overscan.
    pub start_index: usize,
    /// Last rendered row, including overscan.
    pub end_index: usize,
}

fn usize_to_f64(value: usize) -> f64 {
    // Row counts above 2^53 cannot be laid out anyway; saturate instead of losing precision.
    u32::try_from(value).map_or(f64::from(u32::MAX), f64::from)
}

fn f64_to_index(value: f64) -> usize {
    if value.is_finite() && value > 0.0 {
        format!("{:.0}", value.floor())
            .parse()
            .unwrap_or(usize::MAX)
    } else {
        0
    }
}

/// Computes the rows to render, like `getLumenVirtualWindow` in `lumen-core`: the rows inside
/// `offset..offset + viewport` plus `overscan` rows on each side, and the focused row with its
/// neighbors so keyboard users can Tab out of the window.
pub fn virtual_list_window(
    offset: f64,
    viewport: f64,
    item_count: usize,
    item_size: f64,
    overscan: usize,
    focused_index: Option<usize>,
) -> VirtualListWindow {
    let count_f = usize_to_f64(item_count);
    let size = if item_size.is_finite()
        && item_size > 0.0
        && item_size <= 9_007_199_254_740_991.0 / count_f.max(1.0)
    {
        item_size
    } else {
        VIRTUAL_LIST_DEFAULT_ITEM_SIZE
    };
    let viewport = if viewport.is_finite() && viewport > 0.0 {
        viewport
    } else {
        0.0
    };
    let maximum_offset = (count_f * size - viewport).max(0.0);
    let offset = if offset.is_finite() {
        offset.clamp(0.0, maximum_offset)
    } else {
        0.0
    };
    let start_index = f64_to_index((offset / size).floor()).saturating_sub(overscan);
    let visible_end = f64_to_index(((offset + viewport) / size).ceil()).saturating_sub(1);
    let end_index = if item_count == 0 {
        start_index
    } else {
        // `overscan` is caller input and may be as large as `usize::MAX`.
        visible_end
            .max(start_index)
            .saturating_add(overscan)
            .min(item_count - 1)
    };
    let mut indexes: Vec<usize> = if item_count == 0 {
        Vec::new()
    } else {
        (start_index..=end_index).collect()
    };

    if let Some(focused) = focused_index.filter(|index| *index < item_count) {
        for index in focused.saturating_sub(1)..=(focused + 1).min(item_count - 1) {
            if !indexes.contains(&index) {
                indexes.push(index);
            }
        }

        indexes.sort_unstable();
    }

    VirtualListWindow {
        start_index,
        end_index,
        indexes,
        item_size: size,
        total_size: count_f * size,
    }
}

/// CSS pixel length the way React serializes numeric styles: `0` stays unitless.
fn css_px(value: f64) -> String {
    if value == 0.0 {
        "0".to_string()
    } else {
        format!("{value}px")
    }
}

/// Props for [`VirtualList`].
#[derive(Props, Clone, PartialEq)]
pub struct VirtualListProps {
    /// Number of rows. Setting it, with `render_item`, turns on data mode.
    pub item_count: Option<usize>,
    /// Renders the row at an index.
    pub render_item: Option<Callback<usize, Element>>,
    /// Stable key of the row at an index; defaults to the index. Keys must be unique.
    pub item_key: Option<Callback<usize, String>>,
    /// Row height in CSS pixels. Defaults to 44.
    pub item_size: Option<f64>,
    /// Extra rows rendered on each side of the visible ones. Defaults to 4.
    pub overscan: Option<usize>,
    /// Viewport height in CSS pixels used until the renderer reports one through scroll,
    /// resize, or mount events.
    pub viewport_height: Option<f64>,
    /// Renders only the rows near the scroll offset. Set it to `false` on Dioxus Native, which
    /// reports no scroll events: every row then renders at its fixed height, so the list still
    /// scrolls correctly, without virtualization.
    #[props(default = true)]
    pub windowing: bool,
    /// Called when the rendered range changes.
    pub on_range_change: Option<EventHandler<VirtualListRange>>,
    /// ARIA role of the root in data mode. Defaults to `list`, which also gives rows
    /// `listitem` with their position and set size.
    #[props(default = "list".to_string(), into)]
    pub role: String,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the list with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Rows of the frame mode, used when `item_count` is not set. They are all rendered.
    pub children: Element,
}

/// A scrollable list that windows long collections.
///
/// In data mode (`item_count` and `render_item`) only the rows near the scroll offset are
/// rendered, from the `onscroll` data the renderer reports. Without them it renders the
/// `ui-virtual-list` frame around its children, like lumen-react's mounted mode, but leaves all
/// rows in the tree because there is no DOM controller to hide them.
#[component]
pub fn VirtualList(props: VirtualListProps) -> Element {
    let glass = props.glass.class("ui-virtual-list");
    let class = compose([
        Some("ui-virtual-list"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);
    let mut offset = use_signal(|| 0.0_f64);
    let mut measured = use_signal(|| None::<f64>);
    let mut focused = use_signal(|| None::<String>);
    let mut reported = use_signal(|| None::<VirtualListRange>);

    let (Some(count), Some(render_item)) = (props.item_count, props.render_item) else {
        return rsx! {
            div {
                class,
                "data-ui-item-size": props.item_size.map(|size| size.to_string()),
                "data-ui-overscan": props.overscan.map(|overscan| overscan.to_string()),
                "data-ui-virtual-list": "true",
                tabindex: "0",
                ..props.attributes,
                {props.children}
            }
        };
    };

    let key_of = move |index: usize| {
        props
            .item_key
            .map_or_else(|| index.to_string(), |key| key.call(index))
    };
    let item_key = props.item_key;
    // Index keys parse directly; custom keys need a scan, which only runs while a row has focus.
    let focused_index = focused.read().as_ref().and_then(|key| match item_key {
        None => key.parse::<usize>().ok().filter(|index| *index < count),
        Some(_) => (0..count).find(|index| key_of(*index) == *key),
    });
    let viewport = measured.read().or(props.viewport_height).unwrap_or(0.0);
    let mut window = virtual_list_window(
        *offset.read(),
        viewport,
        count,
        props.item_size.unwrap_or(VIRTUAL_LIST_DEFAULT_ITEM_SIZE),
        props.overscan.unwrap_or(VIRTUAL_LIST_DEFAULT_OVERSCAN),
        focused_index,
    );

    if !props.windowing {
        window.start_index = 0;
        window.end_index = count.saturating_sub(1);
        window.indexes = (0..count).collect();
    }
    let range = VirtualListRange {
        start_index: window.start_index,
        end_index: window.end_index,
    };
    let on_range_change = props.on_range_change;

    use_effect(use_reactive((&range,), move |(range,)| {
        if reported.peek().as_ref() != Some(&range) {
            reported.set(Some(range));

            if let Some(handler) = on_range_change {
                handler.call(range);
            }
        }
    }));

    let list = props.role == "list";
    let size = window.item_size;

    rsx! {
        div {
            class,
            "data-ui-virtual-list": "true",
            "data-ui-virtual-list-mode": "data",
            role: props.role.clone(),
            tabindex: "0",
            onscroll: move |event| {
                offset.set(event.scroll_top());
                let height = f64::from(event.client_height());

                if height > 0.0 {
                    measured.set(Some(height));
                }
            },
            onresize: move |event| {
                if let Ok(size) = event.get_content_box_size()
                    && size.height > 0.0
                {
                    measured.set(Some(size.height));
                }
            },
            onmounted: move |event| async move {
                if let Ok(rect) = event.get_client_rect().await
                    && rect.height() > 0.0
                    && measured.peek().is_none()
                {
                    measured.set(Some(rect.height()));
                }
            },
            ..props.attributes,
            div {
                "data-ui-virtual-list-content": "true",
                style: "height:{css_px(window.total_size)};position:relative",
                for index in window.indexes.iter().copied() {
                    div {
                        key: "{key_of(index)}",
                        aria_posinset: list.then(|| (index + 1).to_string()),
                        aria_setsize: list.then(|| count.to_string()),
                        "data-ui-virtual-list-index": "{index}",
                        "data-ui-virtual-list-key": "{key_of(index)}",
                        role: list.then_some("listitem"),
                        style: "box-sizing:border-box;height:{css_px(size)};inset-inline:0;position:absolute;top:{css_px(usize_to_f64(index) * size)}",
                        onfocusin: move |_| focused.set(Some(key_of(index))),
                        onfocusout: move |_| focused.set(None),
                        {render_item.call(index)}
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn windows_follow_lumen_core() {
        let window = virtual_list_window(0.0, 0.0, 7, 40.0, 2, None);
        assert_eq!(window.indexes, [0, 1, 2]);
        assert!((window.total_size - 280.0).abs() < f64::EPSILON);

        let window = virtual_list_window(400.0, 200.0, 1000, 40.0, 4, None);
        assert_eq!((window.start_index, window.end_index), (6, 18));

        // Offsets past the end clamp to the last page.
        let window = virtual_list_window(1e9, 200.0, 100, 40.0, 0, None);
        assert_eq!((window.start_index, window.end_index), (95, 99));
    }

    #[test]
    fn focused_rows_and_neighbors_stay_rendered() {
        let window = virtual_list_window(0.0, 80.0, 100, 40.0, 0, Some(50));
        assert_eq!(window.indexes, [0, 1, 49, 50, 51]);
    }

    #[test]
    fn invalid_sizes_fall_back_and_empty_lists_render_nothing() {
        let window = virtual_list_window(f64::NAN, -5.0, 0, -1.0, 4, Some(3));
        assert_eq!(window.indexes, Vec::<usize>::new());
        assert!((window.item_size - 44.0).abs() < f64::EPSILON);
        assert_eq!((window.start_index, window.end_index), (0, 0));
    }
}