1use std::cell::Cell;
5use std::hash::Hash;
6use std::rc::Rc;
7
8use crabshell_reactive::{Memo, Signal, untrack};
9
10use crate::cx::Cx;
11use crate::geometry::{Point, Size};
12use crate::prop::{IntoProp, Prop};
13use crate::scroll::{Built, ScrollView, Spot, highlight, keep_in_view, prop_fn};
14use crate::style::Style;
15use crate::widgets::{Column, Common, Element, Row, Stack, Widget, visibility_methods};
16
17pub struct GridView {
37 build: Build,
39 props: GridViewProps,
40 common: Common,
41}
42
43type Build = Box<dyn FnOnce(&Cx, GridViewProps) -> Element>;
45
46struct GridViewProps {
47 cell_width: Option<Prop<u32>>,
48 cell_height: Option<Prop<u32>>,
49 height: Option<Prop<u32>>,
50 current: Option<Prop<Option<usize>>>,
51 offset: Option<Signal<f32>>,
52 style: Option<Prop<Style>>,
53 highlight: Option<Prop<Option<Style>>>,
54 scroll_bar: Option<Prop<Option<Style>>>,
55 kinetic: Option<Prop<bool>>,
56 overshoot: Option<Prop<bool>>,
57}
58
59impl GridView {
60 pub const DEFAULT_CELL: u32 = 100;
62 pub const DEFAULT_HEIGHT: u32 = 240;
64
65 pub fn new<T, K, W>(
68 items: impl FnMut() -> Vec<T> + 'static,
69 key: impl FnMut(&T) -> K + 'static,
70 view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
71 ) -> GridView
72 where
73 T: Clone + PartialEq + 'static,
74 K: Eq + Hash + 'static,
75 W: Widget,
76 {
77 GridView {
78 build: Box::new(move |cx, props| build(cx, props, items, key, view)),
79 props: GridViewProps {
80 cell_width: None,
81 cell_height: None,
82 height: None,
83 current: None,
84 offset: None,
85 style: None,
86 highlight: None,
87 scroll_bar: None,
88 kinetic: None,
89 overshoot: None,
90 },
91 common: Common::default(),
92 }
93 }
94
95 pub fn cell_size(mut self, width: impl IntoProp<u32>, height: impl IntoProp<u32>) -> GridView {
99 self.props.cell_width = Some(width.into_prop());
100 self.props.cell_height = Some(height.into_prop());
101 self
102 }
103
104 pub fn height(mut self, height: impl IntoProp<u32>) -> GridView {
107 self.props.height = Some(height.into_prop());
108 self
109 }
110
111 pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> GridView {
117 self.props.current = Some(index.into_prop());
118 self
119 }
120
121 pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
124 self.props.highlight = Some(style.into_prop());
125 self
126 }
127
128 pub fn offset(mut self, offset: Signal<f32>) -> GridView {
130 self.props.offset = Some(offset);
131 self
132 }
133
134 pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> GridView {
137 self.props.kinetic = Some(kinetic.into_prop());
138 self
139 }
140
141 pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> GridView {
144 self.props.overshoot = Some(overshoot.into_prop());
145 self
146 }
147
148 pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
150 self.props.scroll_bar = Some(style.into_prop());
151 self
152 }
153
154 pub fn style(mut self, style: impl IntoProp<Style>) -> GridView {
156 self.props.style = Some(style.into_prop());
157 self
158 }
159
160 visibility_methods!();
161}
162
163impl Widget for GridView {
164 fn into_element(self: Box<Self>) -> Element {
165 let GridView {
166 build,
167 props,
168 common,
169 } = *self;
170 let mut once = Some((build, props));
171 let mut element = Box::new(Stack::new().children_keyed(
174 || vec![()],
175 |_| (),
176 move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
177 ))
178 .into_element();
179 element.name = "GridView";
180 element.common = common;
181 element
182 }
183}
184
185fn build<T, K, W>(
186 cx: &Cx,
187 props: GridViewProps,
188 mut items: impl FnMut() -> Vec<T> + 'static,
189 key: impl FnMut(&T) -> K + 'static,
190 mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
191) -> Element
192where
193 T: Clone + PartialEq + 'static,
194 K: Eq + Hash + 'static,
195 W: Widget,
196{
197 let GridViewProps {
198 cell_width,
199 cell_height,
200 height,
201 current,
202 offset,
203 style,
204 highlight: highlight_style,
205 scroll_bar,
206 kinetic,
207 overshoot,
208 } = props;
209 let offset = offset.unwrap_or_else(|| cx.signal(0.0));
210 let cell_width = cx.memo(prop_fn(cell_width, GridView::DEFAULT_CELL));
211 let cell_height = cx.memo(prop_fn(cell_height, GridView::DEFAULT_CELL));
212 let cell = move || {
213 Size::new(
214 cell_width.get().max(1) as f32,
215 cell_height.get().max(1) as f32,
216 )
217 };
218 let height = cx.memo(prop_fn(height, GridView::DEFAULT_HEIGHT));
219 let style = style.map(Prop::shared);
220 let inner = {
222 let style = style.clone();
223 cx.memo(move || {
224 let own = style.as_ref().map(|style| style()).unwrap_or_default();
225 let padding = own.padding.unwrap_or_default();
226 let border = own.border.map_or(0.0, |border| border.width.max(0.0));
227 let sides = (padding.top + padding.bottom) as f32 + 2.0 * border;
228 (height.get() as f32 - sides).max(0.0)
229 })
230 };
231 let width = cx.signal(0.0_f32);
233 let columns = cx.memo(move || ((width.get() / cell().width) as usize).max(1));
234 let all = cx.signal(Vec::<T>::new());
235 let changes = cx.signal(0_u64);
237 cx.effect(move || {
238 all.set(items());
239 changes.update(|n| *n += 1);
240 });
241 let count = cx.memo(move || all.with(Vec::len));
242 let rows = move || count.get().div_ceil(columns.get());
243 let shown = move || {
245 let most = (rows() as f32 * cell().height - inner.get()).max(0.0);
246 let offset = offset.get();
247 if offset.is_nan() {
248 0.0
249 } else {
250 offset.clamp(0.0, most)
251 }
252 };
253 let range = cx.memo(move || {
255 let row = cell().height;
256 let top = shown();
257 let first = ((top / row).floor() as usize).saturating_sub(1);
258 let last = (((top + inner.get()) / row).ceil() as usize + 1).min(rows());
259 first..last.max(first)
260 });
261 let moving = Rc::new(Cell::new(false));
266 let current = current.map(Prop::shared);
267 {
268 let current = current.clone();
269 let moving = Rc::clone(&moving);
270 let mut was = None;
271 let mut asked = None;
272 cx.effect(move || {
273 let columns = columns.get();
274 let index = current.as_ref().and_then(|current| current());
275 let viewport = inner.get();
276 let row = cell().height;
277 let laid_out = width.get() > 0.0;
278 let count = count.get();
279 untrack(|| {
280 let now = shown();
281 let mut next = now;
282 let raw = offset.get();
283 let regrid = was.is_some_and(|was| was != columns);
284 if let Some(was) = was.filter(|_| regrid) {
285 let most = (count.div_ceil(was) as f32 * row - viewport).max(0.0);
287 let before = if raw.is_nan() {
288 0.0
289 } else {
290 raw.clamp(0.0, most)
291 };
292 let top = (before / row).floor();
293 let first = top as usize * was;
294 next = (first / columns) as f32 * row + (before - top * row);
295 }
296 if laid_out {
298 was = Some(columns);
299 }
300 let wanted = index.filter(|&index| index < count);
301 let ask = (index, viewport, row);
302 let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
303 if let Some(index) = wanted.filter(|_| (regrid || fresh) && !moving.get()) {
305 let start = (index / columns) as f32 * row;
306 next = keep_in_view(start, start + row, viewport, next);
307 }
308 if next != now || (regrid && next != raw) {
310 offset.set(next);
311 }
312 });
313 });
314 }
315 let mut content = Column::new().style(move || Style::new().height(rows() as f32 * cell().height));
316 if let (Some(style), Some(current)) = (highlight_style, current) {
317 let spot = cx.memo(move || {
318 let index = current()?;
319 if index >= count.get() {
320 return None;
321 }
322 let (columns, size) = (columns.get(), cell());
323 Some(Spot {
324 at: Point::new(
325 (index % columns) as f32 * size.width,
326 (index / columns) as f32 * size.height,
327 ),
328 size,
329 target: (index, changes.get()),
330 })
331 });
332 content = content.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
333 }
334 let content = content
335 .child(Stack::new().style(move || {
336 Style::new()
337 .height(range.get().start as f32 * cell().height)
338 .shrink(0.0)
339 }))
340 .child(
341 Row::new()
342 .wrap(true)
343 .style(move || {
344 Style::new()
345 .width(columns.get() as f32 * cell().width)
346 .shrink(0.0)
347 })
348 .children_keyed(
349 move || {
350 let (range, columns) = (range.get(), columns.get());
351 all.with(|all| {
352 let end = (range.end * columns).min(all.len());
353 all[(range.start * columns).min(end)..end].to_vec()
354 })
355 },
356 key,
357 move |cx, item| {
358 Stack::new()
359 .style(move || {
360 let size = cell();
361 Style::new()
362 .width(size.width)
363 .height(size.height)
364 .shrink(0.0)
365 })
366 .child(view(cx, item))
367 },
368 ),
369 );
370 let mut content = Box::new(content).into_element();
371 content.common.measure = Some(Rc::new(move |size: Size| {
372 if width.try_get() != Some(size.width) {
374 width.try_set(size.width);
375 }
376 }));
377 let mut scroll = ScrollView::new(Built(Some(content))).offset(offset);
378 scroll.scroll.moving = Some(moving);
379 if let Some(bar) = scroll_bar {
380 scroll = scroll.scroll_bar(bar);
381 }
382 if let Some(kinetic) = kinetic {
383 scroll = scroll.kinetic(kinetic);
384 }
385 if let Some(overshoot) = overshoot {
386 scroll = scroll.overshoot(overshoot);
387 }
388 scroll = scroll.style(move || {
389 let own = style.as_ref().map(|style| style()).unwrap_or_default();
390 own.height(height.get() as f32)
391 });
392 Box::new(scroll).into_element()
393}