use std::cell::Cell;
use std::hash::Hash;
use std::rc::Rc;
use crabshell_reactive::{Memo, Signal, untrack};
use crate::cx::Cx;
use crate::geometry::{Point, Size};
use crate::prop::{IntoProp, Prop};
use crate::scroll::{Built, ScrollView, Spot, highlight, keep_in_view, prop_fn};
use crate::style::Style;
use crate::widgets::{Column, Common, Element, Row, Stack, Widget, visibility_methods};
pub struct GridView {
build: Build,
props: GridViewProps,
common: Common,
}
type Build = Box<dyn FnOnce(&Cx, GridViewProps) -> Element>;
struct GridViewProps {
cell_width: Option<Prop<u32>>,
cell_height: Option<Prop<u32>>,
height: Option<Prop<u32>>,
current: Option<Prop<Option<usize>>>,
offset: Option<Signal<f32>>,
style: Option<Prop<Style>>,
highlight: Option<Prop<Option<Style>>>,
scroll_bar: Option<Prop<Option<Style>>>,
kinetic: Option<Prop<bool>>,
overshoot: Option<Prop<bool>>,
}
impl GridView {
pub const DEFAULT_CELL: u32 = 100;
pub const DEFAULT_HEIGHT: u32 = 240;
pub fn new<T, K, W>(
items: impl FnMut() -> Vec<T> + 'static,
key: impl FnMut(&T) -> K + 'static,
view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
) -> GridView
where
T: Clone + PartialEq + 'static,
K: Eq + Hash + 'static,
W: Widget,
{
GridView {
build: Box::new(move |cx, props| build(cx, props, items, key, view)),
props: GridViewProps {
cell_width: None,
cell_height: None,
height: None,
current: None,
offset: None,
style: None,
highlight: None,
scroll_bar: None,
kinetic: None,
overshoot: None,
},
common: Common::default(),
}
}
pub fn cell_size(mut self, width: impl IntoProp<u32>, height: impl IntoProp<u32>) -> GridView {
self.props.cell_width = Some(width.into_prop());
self.props.cell_height = Some(height.into_prop());
self
}
pub fn height(mut self, height: impl IntoProp<u32>) -> GridView {
self.props.height = Some(height.into_prop());
self
}
pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> GridView {
self.props.current = Some(index.into_prop());
self
}
pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
self.props.highlight = Some(style.into_prop());
self
}
pub fn offset(mut self, offset: Signal<f32>) -> GridView {
self.props.offset = Some(offset);
self
}
pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> GridView {
self.props.kinetic = Some(kinetic.into_prop());
self
}
pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> GridView {
self.props.overshoot = Some(overshoot.into_prop());
self
}
pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
self.props.scroll_bar = Some(style.into_prop());
self
}
pub fn style(mut self, style: impl IntoProp<Style>) -> GridView {
self.props.style = Some(style.into_prop());
self
}
visibility_methods!();
}
impl Widget for GridView {
fn into_element(self: Box<Self>) -> Element {
let GridView {
build,
props,
common,
} = *self;
let mut once = Some((build, props));
let mut element = Box::new(Stack::new().children_keyed(
|| vec![()],
|_| (),
move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
))
.into_element();
element.name = "GridView";
element.common = common;
element
}
}
fn build<T, K, W>(
cx: &Cx,
props: GridViewProps,
mut items: impl FnMut() -> Vec<T> + 'static,
key: impl FnMut(&T) -> K + 'static,
mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
) -> Element
where
T: Clone + PartialEq + 'static,
K: Eq + Hash + 'static,
W: Widget,
{
let GridViewProps {
cell_width,
cell_height,
height,
current,
offset,
style,
highlight: highlight_style,
scroll_bar,
kinetic,
overshoot,
} = props;
let offset = offset.unwrap_or_else(|| cx.signal(0.0));
let cell_width = cx.memo(prop_fn(cell_width, GridView::DEFAULT_CELL));
let cell_height = cx.memo(prop_fn(cell_height, GridView::DEFAULT_CELL));
let cell = move || {
Size::new(
cell_width.get().max(1) as f32,
cell_height.get().max(1) as f32,
)
};
let height = cx.memo(prop_fn(height, GridView::DEFAULT_HEIGHT));
let style = style.map(Prop::shared);
let inner = {
let style = style.clone();
cx.memo(move || {
let own = style.as_ref().map(|style| style()).unwrap_or_default();
let padding = own.padding.unwrap_or_default();
let border = own.border.map_or(0.0, |border| border.width.max(0.0));
let sides = (padding.top + padding.bottom) as f32 + 2.0 * border;
(height.get() as f32 - sides).max(0.0)
})
};
let width = cx.signal(0.0_f32);
let columns = cx.memo(move || ((width.get() / cell().width) as usize).max(1));
let all = cx.signal(Vec::<T>::new());
let changes = cx.signal(0_u64);
cx.effect(move || {
all.set(items());
changes.update(|n| *n += 1);
});
let count = cx.memo(move || all.with(Vec::len));
let rows = move || count.get().div_ceil(columns.get());
let shown = move || {
let most = (rows() as f32 * cell().height - inner.get()).max(0.0);
let offset = offset.get();
if offset.is_nan() {
0.0
} else {
offset.clamp(0.0, most)
}
};
let range = cx.memo(move || {
let row = cell().height;
let top = shown();
let first = ((top / row).floor() as usize).saturating_sub(1);
let last = (((top + inner.get()) / row).ceil() as usize + 1).min(rows());
first..last.max(first)
});
let moving = Rc::new(Cell::new(false));
let current = current.map(Prop::shared);
{
let current = current.clone();
let moving = Rc::clone(&moving);
let mut was = None;
let mut asked = None;
cx.effect(move || {
let columns = columns.get();
let index = current.as_ref().and_then(|current| current());
let viewport = inner.get();
let row = cell().height;
let laid_out = width.get() > 0.0;
let count = count.get();
untrack(|| {
let now = shown();
let mut next = now;
let raw = offset.get();
let regrid = was.is_some_and(|was| was != columns);
if let Some(was) = was.filter(|_| regrid) {
let most = (count.div_ceil(was) as f32 * row - viewport).max(0.0);
let before = if raw.is_nan() {
0.0
} else {
raw.clamp(0.0, most)
};
let top = (before / row).floor();
let first = top as usize * was;
next = (first / columns) as f32 * row + (before - top * row);
}
if laid_out {
was = Some(columns);
}
let wanted = index.filter(|&index| index < count);
let ask = (index, viewport, row);
let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
if let Some(index) = wanted.filter(|_| (regrid || fresh) && !moving.get()) {
let start = (index / columns) as f32 * row;
next = keep_in_view(start, start + row, viewport, next);
}
if next != now || (regrid && next != raw) {
offset.set(next);
}
});
});
}
let mut content = Column::new().style(move || Style::new().height(rows() as f32 * cell().height));
if let (Some(style), Some(current)) = (highlight_style, current) {
let spot = cx.memo(move || {
let index = current()?;
if index >= count.get() {
return None;
}
let (columns, size) = (columns.get(), cell());
Some(Spot {
at: Point::new(
(index % columns) as f32 * size.width,
(index / columns) as f32 * size.height,
),
size,
target: (index, changes.get()),
})
});
content = content.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
}
let content = content
.child(Stack::new().style(move || {
Style::new()
.height(range.get().start as f32 * cell().height)
.shrink(0.0)
}))
.child(
Row::new()
.wrap(true)
.style(move || {
Style::new()
.width(columns.get() as f32 * cell().width)
.shrink(0.0)
})
.children_keyed(
move || {
let (range, columns) = (range.get(), columns.get());
all.with(|all| {
let end = (range.end * columns).min(all.len());
all[(range.start * columns).min(end)..end].to_vec()
})
},
key,
move |cx, item| {
Stack::new()
.style(move || {
let size = cell();
Style::new()
.width(size.width)
.height(size.height)
.shrink(0.0)
})
.child(view(cx, item))
},
),
);
let mut content = Box::new(content).into_element();
content.common.measure = Some(Rc::new(move |size: Size| {
if width.try_get() != Some(size.width) {
width.try_set(size.width);
}
}));
let mut scroll = ScrollView::new(Built(Some(content))).offset(offset);
scroll.scroll.moving = Some(moving);
if let Some(bar) = scroll_bar {
scroll = scroll.scroll_bar(bar);
}
if let Some(kinetic) = kinetic {
scroll = scroll.kinetic(kinetic);
}
if let Some(overshoot) = overshoot {
scroll = scroll.overshoot(overshoot);
}
scroll = scroll.style(move || {
let own = style.as_ref().map(|style| style()).unwrap_or_default();
own.height(height.get() as f32)
});
Box::new(scroll).into_element()
}