Skip to main content

nightshade_api/web/
util.rs

1use leptos::prelude::*;
2
3/// The half-open range of item indices to render for a virtualized, fixed-row-height
4/// list, given the current scroll offset and viewport. Shared by every windowed view
5/// (`VirtualList`, `Table`, `CodeSurface`, `MultiEditor`).
6pub fn visible_range(
7    scroll_top: f64,
8    viewport_height: f64,
9    item_height: f64,
10    overscan: usize,
11    total: usize,
12) -> (usize, usize) {
13    let view = viewport_height.max(item_height);
14    let first = ((scroll_top / item_height).floor() as usize).saturating_sub(overscan);
15    let count = (view / item_height).ceil() as usize + overscan * 2 + 1;
16    let start = first.min(total);
17    let end = (start + count).min(total);
18    (start, end)
19}
20
21/// A per-owner store that keeps values (typically `Closure`s) alive and drops them
22/// on cleanup. Use this instead of `Closure::forget` so one-shot JS callbacks are
23/// reclaimed when the component unmounts. Create it once at component init with
24/// [`use_retained_closures`], then `retain` from any later handler; the handle is
25/// `Copy`, so callbacks can capture it freely.
26#[derive(Clone, Copy)]
27pub struct RetainedClosures(StoredValue<Vec<Box<dyn std::any::Any>>, LocalStorage>);
28
29impl RetainedClosures {
30    pub fn retain<T: 'static>(&self, value: T) {
31        self.0.update_value(|held| held.push(Box::new(value)));
32    }
33}
34
35/// Creates an owner-scoped [`RetainedClosures`] store. Call this in a component body.
36pub fn use_retained_closures() -> RetainedClosures {
37    RetainedClosures(StoredValue::new_local(Vec::new()))
38}