use super::{Ui, WidgetKind, WidgetState, typed};
use crate::style::{Declaration, Sides};
use crate::tree::{Behavior, KeySource, LengthAuto, Overflow, Position, Response, hash_of};
pub const LIST_OVERSCAN: usize = 2;
impl Ui {
#[track_caller]
pub fn list(
&mut self,
selector: &str,
rows: usize,
row_height: f32,
mut row: impl FnMut(&mut Self, usize),
) -> Response {
let selector = typed("list", selector);
let height = row_span(row_height);
let mut focused = None;
let response = self.block_with(
&selector,
&[Declaration::Overflow(Overflow::Scroll)],
Behavior::NONE,
|ui| focused = ui.list_rows(rows, height, &mut row),
);
self.set_widget_state(response.key, WidgetState::Rows(focused));
self.mark(response.key, WidgetKind::List);
response
}
fn list_rows(
&mut self,
rows: usize,
height: f32,
row: &mut impl FnMut(&mut Self, usize),
) -> Option<usize> {
let list = self.nodes[*self.open.last().expect("called inside the list block")].key;
let window = self.row_window(rows, height);
let content = [
Declaration::Height(LengthAuto::Px(rows as f32 * height)),
Declaration::FlexShrink(0.0),
];
let mut focused = None;
self.block(".list-content", &content, |ui| {
let outside = ui
.kept_row(list, rows, |ui, index| {
ui.key(KeySource::Keyed(hash_of(index)))
})
.filter(|&index| index < window.first || index >= window.end);
let indices = outside
.filter(|&index| index < window.first)
.into_iter()
.chain(window.first..window.end)
.chain(outside.filter(|&index| index >= window.end));
for index in indices {
let inline = row_inline(index, height);
let response =
ui.block_keyed_with(index, ".list-row", &inline, Behavior::BUTTON, |ui| {
row(ui, index);
});
ui.mark(response.key, WidgetKind::ListRow);
if response.focused {
focused = Some(index);
}
}
});
focused
}
}
pub(super) fn row_span(row_height: f32) -> f32 {
if row_height.is_finite() {
row_height.max(1.0)
} else {
1.0
}
}
pub(super) fn row_inline(index: usize, height: f32) -> [Declaration; 5] {
[
Declaration::Position(Position::Absolute),
Declaration::Inset(Sides::Top, LengthAuto::Px(index as f32 * height)),
Declaration::Inset(Sides::Left, LengthAuto::Px(0.0)),
Declaration::Inset(Sides::Right, LengthAuto::Px(0.0)),
Declaration::Height(LengthAuto::Px(height)),
]
}