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::{self, Built, ScrollView, Spot, highlight, keep_in_view, prop_fn};
14use crate::style::Style;
15use crate::widgets::{
16 Column, Common, Element, ElementKind, Row, Stack, Widget, visibility_methods,
17};
18
19pub struct GridView {
39 build: Build,
41 props: GridViewProps,
42 common: Common,
43}
44
45type Build = Box<dyn FnOnce(&Cx, GridViewProps) -> Element>;
47
48struct GridViewProps {
49 cell_width: Option<Prop<u32>>,
50 cell_height: Option<Prop<u32>>,
51 height: Option<Prop<u32>>,
52 current: Option<Prop<Option<usize>>>,
53 offset: Option<Signal<f32>>,
54 style: Option<Prop<Style>>,
55 highlight: Option<Prop<Option<Style>>>,
56 scroll_bar: Option<Prop<Option<Style>>>,
57 kinetic: Option<Prop<bool>>,
58 overshoot: Option<Prop<bool>>,
59 mouse_drag: Option<Prop<bool>>,
60 horizontal: Option<Prop<bool>>,
61}
62
63impl GridView {
64 pub const DEFAULT_CELL: u32 = 100;
66 pub const DEFAULT_HEIGHT: u32 = 240;
68
69 pub fn new<T, K, W>(
72 items: impl FnMut() -> Vec<T> + 'static,
73 key: impl FnMut(&T) -> K + 'static,
74 view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
75 ) -> GridView
76 where
77 T: Clone + PartialEq + 'static,
78 K: Eq + Hash + 'static,
79 W: Widget,
80 {
81 GridView {
82 build: Box::new(move |cx, props| build(cx, props, items, key, view)),
83 props: GridViewProps {
84 cell_width: None,
85 cell_height: None,
86 height: None,
87 current: None,
88 offset: None,
89 style: None,
90 highlight: None,
91 scroll_bar: None,
92 kinetic: None,
93 overshoot: None,
94 mouse_drag: None,
95 horizontal: None,
96 },
97 common: Common::default(),
98 }
99 }
100
101 pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> GridView {
108 self.props.horizontal = Some(horizontal.into_prop());
109 self
110 }
111
112 pub fn cell_size(mut self, width: impl IntoProp<u32>, height: impl IntoProp<u32>) -> GridView {
116 self.props.cell_width = Some(width.into_prop());
117 self.props.cell_height = Some(height.into_prop());
118 self
119 }
120
121 pub fn height(mut self, height: impl IntoProp<u32>) -> GridView {
125 self.props.height = Some(height.into_prop());
126 self
127 }
128
129 pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> GridView {
135 self.props.current = Some(index.into_prop());
136 self
137 }
138
139 pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
142 self.props.highlight = Some(style.into_prop());
143 self
144 }
145
146 pub fn offset(mut self, offset: Signal<f32>) -> GridView {
148 self.props.offset = Some(offset);
149 self
150 }
151
152 pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> GridView {
155 self.props.kinetic = Some(kinetic.into_prop());
156 self
157 }
158
159 pub fn mouse_drag(mut self, mouse_drag: impl IntoProp<bool>) -> GridView {
162 self.props.mouse_drag = Some(mouse_drag.into_prop());
163 self
164 }
165
166 pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> GridView {
169 self.props.overshoot = Some(overshoot.into_prop());
170 self
171 }
172
173 pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
175 self.props.scroll_bar = Some(style.into_prop());
176 self
177 }
178
179 pub fn style(mut self, style: impl IntoProp<Style>) -> GridView {
181 self.props.style = Some(style.into_prop());
182 self
183 }
184
185 visibility_methods!();
186}
187
188impl Widget for GridView {
189 fn into_element(self: Box<Self>) -> Element {
190 let GridView {
191 build,
192 props,
193 common,
194 } = *self;
195 let mut once = Some((build, props));
196 let mut element = Box::new(Stack::new().children_keyed(
199 || vec![()],
200 |_| (),
201 move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
202 ))
203 .into_element();
204 element.name = "GridView";
205 element.common = common;
206 element
207 }
208}
209
210fn build<T, K, W>(
211 cx: &Cx,
212 props: GridViewProps,
213 mut items: impl FnMut() -> Vec<T> + 'static,
214 key: impl FnMut(&T) -> K + 'static,
215 mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
216) -> Element
217where
218 T: Clone + PartialEq + 'static,
219 K: Eq + Hash + 'static,
220 W: Widget,
221{
222 let GridViewProps {
223 cell_width,
224 cell_height,
225 height,
226 current,
227 offset,
228 style,
229 highlight: highlight_style,
230 scroll_bar,
231 kinetic,
232 overshoot,
233 mouse_drag,
234 horizontal,
235 } = props;
236 let offset = offset.unwrap_or_else(|| cx.signal(0.0));
237 let cell_width = cx.memo(prop_fn(cell_width, GridView::DEFAULT_CELL));
238 let cell_height = cx.memo(prop_fn(cell_height, GridView::DEFAULT_CELL));
239 let cell = move || {
240 Size::new(
241 cell_width.get().max(1) as f32,
242 cell_height.get().max(1) as f32,
243 )
244 };
245 let horizontal = cx.memo(prop_fn(horizontal, false));
246 let length = move || along(horizontal.get(), cell());
248 let breadth = move || along(!horizontal.get(), cell());
249 let height = cx.memo(prop_fn(height, GridView::DEFAULT_HEIGHT));
250 let style = style.map(Prop::shared);
251 let sides = {
253 let style = style.clone();
254 cx.memo(move || {
255 let own = style.as_ref().map(|style| style()).unwrap_or_default();
256 let padding = own.padding.unwrap_or_default();
257 let border = 2.0 * own.border.map_or(0.0, |border| border.width.max(0.0));
258 Size::new(
259 (padding.left + padding.right) as f32 + border,
260 (padding.top + padding.bottom) as f32 + border,
261 )
262 })
263 };
264 let inner =
266 cx.memo(move || (height.get() as f32 - along(horizontal.get(), sides.get())).max(0.0));
267 let outer = cx.signal(Size::default());
270 let width = cx.memo(move || {
272 let across = !horizontal.get();
273 (along(across, outer.get()) - along(across, sides.get())).max(0.0)
274 });
275 let columns = cx.memo(move || ((width.get() / breadth()) as usize).max(1));
278 let all = cx.signal(Vec::<T>::new());
279 let changes = cx.signal(0_u64);
281 cx.effect(move || {
282 all.set(items());
283 changes.update(|n| *n += 1);
284 });
285 let count = cx.memo(move || all.with(Vec::len));
286 let rows = move || count.get().div_ceil(columns.get());
287 let shown = move || {
289 let most = (rows() as f32 * length() - inner.get()).max(0.0);
290 let offset = offset.get();
291 if offset.is_nan() {
292 0.0
293 } else {
294 offset.clamp(0.0, most)
295 }
296 };
297 let range = cx.memo(move || {
299 let row = length();
300 let top = shown();
301 let first = ((top / row).floor() as usize).saturating_sub(1);
302 let last = (((top + inner.get()) / row).ceil() as usize + 1).min(rows());
303 first..last.max(first)
304 });
305 let moving = Rc::new(Cell::new(false));
310 let current = current.map(Prop::shared);
311 {
312 let current = current.clone();
313 let moving = Rc::clone(&moving);
314 let mut was = None;
315 let mut asked = None;
316 cx.effect(move || {
317 let columns = columns.get();
318 let index = current.as_ref().and_then(|current| current());
319 let viewport = inner.get();
320 let row = length();
321 let laid_out = width.get() > 0.0;
322 let count = count.get();
323 untrack(|| {
324 let now = shown();
325 let mut next = now;
326 let raw = offset.get();
327 let regrid = was.is_some_and(|was| was != columns);
328 if let Some(was) = was.filter(|_| regrid) {
329 let most = (count.div_ceil(was) as f32 * row - viewport).max(0.0);
331 let before = if raw.is_nan() {
332 0.0
333 } else {
334 raw.clamp(0.0, most)
335 };
336 let top = (before / row).floor();
337 let first = top as usize * was;
338 next = (first / columns) as f32 * row + (before - top * row);
339 }
340 if laid_out {
342 was = Some(columns);
343 }
344 let wanted = index.filter(|&index| index < count);
345 let ask = (index, viewport, row);
346 let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
347 if let Some(index) = wanted.filter(|_| (regrid || fresh) && !moving.get()) {
349 let start = (index / columns) as f32 * row;
350 next = keep_in_view(start, start + row, viewport, next);
351 }
352 if next != now || (regrid && next != raw) {
354 offset.set(next);
355 }
356 });
357 });
358 }
359 let mut content = Column::new()
360 .style(move || scroll::along(horizontal.get(), Style::new(), rows() as f32 * length()));
361 if let (Some(style), Some(current)) = (highlight_style, current) {
362 let spot = cx.memo(move || {
363 let index = current()?;
364 if index >= count.get() {
365 return None;
366 }
367 let (columns, size) = (columns.get(), cell());
368 let (line, place) = ((index / columns) as f32, (index % columns) as f32);
369 Some(Spot {
370 at: if horizontal.get() {
371 Point::new(line * size.width, place * size.height)
372 } else {
373 Point::new(place * size.width, line * size.height)
374 },
375 size,
376 target: (index, changes.get()),
377 })
378 });
379 content = content.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
380 }
381 let mut cells = Box::new(
382 Row::new()
383 .wrap(true)
384 .style(move || {
385 let across = columns.get() as f32 * breadth();
386 scroll::along(!horizontal.get(), Style::new(), across).shrink(0.0)
387 })
388 .children_keyed(
389 move || {
390 let (range, columns) = (range.get(), columns.get());
391 all.with(|all| {
392 let end = (range.end * columns).min(all.len());
393 all[(range.start * columns).min(end)..end].to_vec()
394 })
395 },
396 key,
397 move |cx, item| {
398 Stack::new()
399 .style(move || {
400 let size = cell();
401 Style::new()
402 .width(size.width)
403 .height(size.height)
404 .shrink(0.0)
405 })
406 .child(view(cx, item))
407 },
408 ),
409 )
410 .into_element();
411 if let ElementKind::Flex(flex) = &mut cells.kind {
413 flex.column_binding = Some((move || horizontal.get()).into_prop());
414 }
415 let content = content
416 .child(Stack::new().style(move || {
417 let start = range.get().start as f32 * length();
418 scroll::along(horizontal.get(), Style::new(), start).shrink(0.0)
419 }))
420 .child(Built(Some(cells)));
421 let mut content = Box::new(content).into_element();
422 if let ElementKind::Flex(flex) = &mut content.kind {
423 flex.column_binding = Some((move || !horizontal.get()).into_prop());
424 }
425 let mut scroll = ScrollView::new(Built(Some(content)))
426 .offset(offset)
427 .horizontal(move || horizontal.get());
428 scroll.scroll.moving = Some(moving);
429 if let Some(bar) = scroll_bar {
430 scroll = scroll.scroll_bar(bar);
431 }
432 if let Some(kinetic) = kinetic {
433 scroll = scroll.kinetic(kinetic);
434 }
435 if let Some(overshoot) = overshoot {
436 scroll = scroll.overshoot(overshoot);
437 }
438 if let Some(mouse_drag) = mouse_drag {
439 scroll = scroll.mouse_drag(mouse_drag);
440 }
441 scroll = scroll.style(move || {
442 let own = style.as_ref().map(|style| style()).unwrap_or_default();
443 let own = match (horizontal.get(), own.min_width, own.min_height) {
445 (false, None, _) => own.min_width(0.0),
446 (true, _, None) => own.min_height(0.0),
447 _ => own,
448 };
449 scroll::along(horizontal.get(), own, height.get() as f32)
450 });
451 let mut scroll = Box::new(scroll).into_element();
452 scroll.common.measure = Some(Rc::new(move |size: Size| {
454 if outer.try_get() != Some(size) {
456 outer.try_set(size);
457 }
458 }));
459 scroll
460}
461
462fn along(horizontal: bool, size: Size) -> f32 {
465 if horizontal { size.width } else { size.height }
466}