use dioxus::prelude::*;
use crate::class::{Glass, compose};
pub const VIRTUAL_LIST_DEFAULT_ITEM_SIZE: f64 = 44.0;
pub const VIRTUAL_LIST_DEFAULT_OVERSCAN: usize = 4;
#[derive(Clone, Debug, PartialEq)]
pub struct VirtualListWindow {
pub start_index: usize,
pub end_index: usize,
pub indexes: Vec<usize>,
pub item_size: f64,
pub total_size: f64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VirtualListRange {
pub start_index: usize,
pub end_index: usize,
}
fn usize_to_f64(value: usize) -> f64 {
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
}
}
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 {
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,
}
}
fn css_px(value: f64) -> String {
if value == 0.0 {
"0".to_string()
} else {
format!("{value}px")
}
}
#[derive(Props, Clone, PartialEq)]
pub struct VirtualListProps {
pub item_count: Option<usize>,
pub render_item: Option<Callback<usize, Element>>,
pub item_key: Option<Callback<usize, String>>,
pub item_size: Option<f64>,
pub overscan: Option<usize>,
pub viewport_height: Option<f64>,
#[props(default = true)]
pub windowing: bool,
pub on_range_change: Option<EventHandler<VirtualListRange>>,
#[props(default = "list".to_string(), into)]
pub role: String,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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;
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));
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));
}
}