1use dioxus::prelude::*;
6
7use crate::class::{Glass, compose};
8
9pub const VIRTUAL_LIST_DEFAULT_ITEM_SIZE: f64 = 44.0;
11
12pub const VIRTUAL_LIST_DEFAULT_OVERSCAN: usize = 4;
14
15#[derive(Clone, Debug, PartialEq)]
17pub struct VirtualListWindow {
18 pub start_index: usize,
20 pub end_index: usize,
22 pub indexes: Vec<usize>,
24 pub item_size: f64,
26 pub total_size: f64,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct VirtualListRange {
33 pub start_index: usize,
35 pub end_index: usize,
37}
38
39fn usize_to_f64(value: usize) -> f64 {
40 u32::try_from(value).map_or(f64::from(u32::MAX), f64::from)
42}
43
44fn f64_to_index(value: f64) -> usize {
45 if value.is_finite() && value > 0.0 {
46 format!("{:.0}", value.floor())
47 .parse()
48 .unwrap_or(usize::MAX)
49 } else {
50 0
51 }
52}
53
54pub fn virtual_list_window(
58 offset: f64,
59 viewport: f64,
60 item_count: usize,
61 item_size: f64,
62 overscan: usize,
63 focused_index: Option<usize>,
64) -> VirtualListWindow {
65 let count_f = usize_to_f64(item_count);
66 let size = if item_size.is_finite()
67 && item_size > 0.0
68 && item_size <= 9_007_199_254_740_991.0 / count_f.max(1.0)
69 {
70 item_size
71 } else {
72 VIRTUAL_LIST_DEFAULT_ITEM_SIZE
73 };
74 let viewport = if viewport.is_finite() && viewport > 0.0 {
75 viewport
76 } else {
77 0.0
78 };
79 let maximum_offset = (count_f * size - viewport).max(0.0);
80 let offset = if offset.is_finite() {
81 offset.clamp(0.0, maximum_offset)
82 } else {
83 0.0
84 };
85 let start_index = f64_to_index((offset / size).floor()).saturating_sub(overscan);
86 let visible_end = f64_to_index(((offset + viewport) / size).ceil()).saturating_sub(1);
87 let end_index = if item_count == 0 {
88 start_index
89 } else {
90 visible_end
92 .max(start_index)
93 .saturating_add(overscan)
94 .min(item_count - 1)
95 };
96 let mut indexes: Vec<usize> = if item_count == 0 {
97 Vec::new()
98 } else {
99 (start_index..=end_index).collect()
100 };
101
102 if let Some(focused) = focused_index.filter(|index| *index < item_count) {
103 for index in focused.saturating_sub(1)..=(focused + 1).min(item_count - 1) {
104 if !indexes.contains(&index) {
105 indexes.push(index);
106 }
107 }
108
109 indexes.sort_unstable();
110 }
111
112 VirtualListWindow {
113 start_index,
114 end_index,
115 indexes,
116 item_size: size,
117 total_size: count_f * size,
118 }
119}
120
121fn css_px(value: f64) -> String {
123 if value == 0.0 {
124 "0".to_string()
125 } else {
126 format!("{value}px")
127 }
128}
129
130#[derive(Props, Clone, PartialEq)]
132pub struct VirtualListProps {
133 pub item_count: Option<usize>,
135 pub render_item: Option<Callback<usize, Element>>,
137 pub item_key: Option<Callback<usize, String>>,
139 pub item_size: Option<f64>,
141 pub overscan: Option<usize>,
143 pub viewport_height: Option<f64>,
146 #[props(default = true)]
150 pub windowing: bool,
151 pub on_range_change: Option<EventHandler<VirtualListRange>>,
153 #[props(default = "list".to_string(), into)]
156 pub role: String,
157 #[props(default, into)]
159 pub glass: Glass,
160 #[props(into)]
162 pub class: Option<String>,
163 #[props(extends = GlobalAttributes, extends = div)]
165 pub attributes: Vec<Attribute>,
166 pub children: Element,
168}
169
170#[component]
177pub fn VirtualList(props: VirtualListProps) -> Element {
178 let glass = props.glass.class("ui-virtual-list");
179 let class = compose([
180 Some("ui-virtual-list"),
181 glass.as_deref(),
182 props.class.as_deref(),
183 ]);
184 let mut offset = use_signal(|| 0.0_f64);
185 let mut measured = use_signal(|| None::<f64>);
186 let mut focused = use_signal(|| None::<String>);
187 let mut reported = use_signal(|| None::<VirtualListRange>);
188
189 let (Some(count), Some(render_item)) = (props.item_count, props.render_item) else {
190 return rsx! {
191 div {
192 class,
193 "data-ui-item-size": props.item_size.map(|size| size.to_string()),
194 "data-ui-overscan": props.overscan.map(|overscan| overscan.to_string()),
195 "data-ui-virtual-list": "true",
196 tabindex: "0",
197 ..props.attributes,
198 {props.children}
199 }
200 };
201 };
202
203 let key_of = move |index: usize| {
204 props
205 .item_key
206 .map_or_else(|| index.to_string(), |key| key.call(index))
207 };
208 let item_key = props.item_key;
209 let focused_index = focused.read().as_ref().and_then(|key| match item_key {
211 None => key.parse::<usize>().ok().filter(|index| *index < count),
212 Some(_) => (0..count).find(|index| key_of(*index) == *key),
213 });
214 let viewport = measured.read().or(props.viewport_height).unwrap_or(0.0);
215 let mut window = virtual_list_window(
216 *offset.read(),
217 viewport,
218 count,
219 props.item_size.unwrap_or(VIRTUAL_LIST_DEFAULT_ITEM_SIZE),
220 props.overscan.unwrap_or(VIRTUAL_LIST_DEFAULT_OVERSCAN),
221 focused_index,
222 );
223
224 if !props.windowing {
225 window.start_index = 0;
226 window.end_index = count.saturating_sub(1);
227 window.indexes = (0..count).collect();
228 }
229 let range = VirtualListRange {
230 start_index: window.start_index,
231 end_index: window.end_index,
232 };
233 let on_range_change = props.on_range_change;
234
235 use_effect(use_reactive((&range,), move |(range,)| {
236 if reported.peek().as_ref() != Some(&range) {
237 reported.set(Some(range));
238
239 if let Some(handler) = on_range_change {
240 handler.call(range);
241 }
242 }
243 }));
244
245 let list = props.role == "list";
246 let size = window.item_size;
247
248 rsx! {
249 div {
250 class,
251 "data-ui-virtual-list": "true",
252 "data-ui-virtual-list-mode": "data",
253 role: props.role.clone(),
254 tabindex: "0",
255 onscroll: move |event| {
256 offset.set(event.scroll_top());
257 let height = f64::from(event.client_height());
258
259 if height > 0.0 {
260 measured.set(Some(height));
261 }
262 },
263 onresize: move |event| {
264 if let Ok(size) = event.get_content_box_size()
265 && size.height > 0.0
266 {
267 measured.set(Some(size.height));
268 }
269 },
270 onmounted: move |event| async move {
271 if let Ok(rect) = event.get_client_rect().await
272 && rect.height() > 0.0
273 && measured.peek().is_none()
274 {
275 measured.set(Some(rect.height()));
276 }
277 },
278 ..props.attributes,
279 div {
280 "data-ui-virtual-list-content": "true",
281 style: "height:{css_px(window.total_size)};position:relative",
282 for index in window.indexes.iter().copied() {
283 div {
284 key: "{key_of(index)}",
285 aria_posinset: list.then(|| (index + 1).to_string()),
286 aria_setsize: list.then(|| count.to_string()),
287 "data-ui-virtual-list-index": "{index}",
288 "data-ui-virtual-list-key": "{key_of(index)}",
289 role: list.then_some("listitem"),
290 style: "box-sizing:border-box;height:{css_px(size)};inset-inline:0;position:absolute;top:{css_px(usize_to_f64(index) * size)}",
291 onfocusin: move |_| focused.set(Some(key_of(index))),
292 onfocusout: move |_| focused.set(None),
293 {render_item.call(index)}
294 }
295 }
296 }
297 }
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::virtual_list_window;
304
305 #[test]
306 fn windows_follow_lumen_core() {
307 let window = virtual_list_window(0.0, 0.0, 7, 40.0, 2, None);
308 assert_eq!(window.indexes, [0, 1, 2]);
309 assert!((window.total_size - 280.0).abs() < f64::EPSILON);
310
311 let window = virtual_list_window(400.0, 200.0, 1000, 40.0, 4, None);
312 assert_eq!((window.start_index, window.end_index), (6, 18));
313
314 let window = virtual_list_window(1e9, 200.0, 100, 40.0, 0, None);
316 assert_eq!((window.start_index, window.end_index), (95, 99));
317 }
318
319 #[test]
320 fn focused_rows_and_neighbors_stay_rendered() {
321 let window = virtual_list_window(0.0, 80.0, 100, 40.0, 0, Some(50));
322 assert_eq!(window.indexes, [0, 1, 49, 50, 51]);
323 }
324
325 #[test]
326 fn invalid_sizes_fall_back_and_empty_lists_render_nothing() {
327 let window = virtual_list_window(f64::NAN, -5.0, 0, -1.0, 4, Some(3));
328 assert_eq!(window.indexes, Vec::<usize>::new());
329 assert!((window.item_size - 44.0).abs() < f64::EPSILON);
330 assert_eq!((window.start_index, window.end_index), (0, 0));
331 }
332}