Skip to main content

crabshell_ui/
grid_view.rs

1//! [`GridView`], a scrolling grid of cells of one size that builds only
2//! the rows of cells in view.
3
4use 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
19/// A scrolling grid of cells of one size, in as many columns as fit its
20/// width and at least one, for app and wallpaper pickers. It builds only
21/// the rows of cells in view, so a grid of thousands costs what a
22/// screenful does, and follows a list of items as
23/// [`children_keyed`](Column::children_keyed) does: each cell is kept
24/// while its item's key stays in the list. When its width changes the
25/// number of columns, the cell at the top left stays in view.
26///
27/// ```
28/// use crabshell_ui::{GridView, Icon};
29///
30/// let apps = GridView::new(
31///     || vec!["firefox", "foot", "gimp"],
32///     |name| *name,
33///     |_cx, name| Icon::new(name.get()).size(48),
34/// )
35/// .cell_size(72, 72)
36/// .height(288);
37/// ```
38pub struct GridView {
39  /// Builds the grid once it has a context for its signals.
40  build: Build,
41  props: GridViewProps,
42  common: Common,
43}
44
45/// Builds a grid's element from its properties, with a context.
46type 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  /// The default cell width and height, in logical pixels, as Qt's.
65  pub const DEFAULT_CELL: u32 = 100;
66  /// The default height of the grid, in logical pixels.
67  pub const DEFAULT_HEIGHT: u32 = 240;
68
69  /// A grid with a cell for each of `items`, built by `view` and kept by
70  /// `key`, as in [`children_keyed`](Column::children_keyed).
71  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  /// Fills each column top to bottom, then the next, and scrolls
102  /// sideways, as Qt's `GridView.FlowTopToBottom`. [`height`](Self::height)
103  /// then means the grid's width, its height comes from its style or its
104  /// parent, and a column holds as many cells as fit it, at least one.
105  /// [`current`](Self::current), the highlight and the offset go along
106  /// the columns. Off by default.
107  pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> GridView {
108    self.props.horizontal = Some(horizontal.into_prop());
109    self
110  }
111
112  /// Sets every cell's width and height in logical pixels, 100 by
113  /// default. A cell's content is laid out in that box; a size of 0
114  /// counts as 1.
115  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  /// Sets the grid's height in logical pixels, or its width in a
122  /// [`horizontal`](Self::horizontal) grid. The other side comes from its
123  /// style or its parent.
124  pub fn height(mut self, height: impl IntoProp<u32>) -> GridView {
125    self.props.height = Some(height.into_prop());
126    self
127  }
128
129  /// Keeps the cell at this index in view, scrolling as little as needed
130  /// whenever it, the height or the number of columns changes. An index
131  /// past the end is scrolled to once the items reach it; `None` scrolls
132  /// nothing. While the grid moves, a change scrolls nothing, as in
133  /// [`ListView::current`](crate::ListView::current).
134  pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> GridView {
135    self.props.current = Some(index.into_prop());
136    self
137  }
138
139  /// Draws a box in this style behind the [`current`](Self::current)
140  /// cell, as [`ListView::highlight`](crate::ListView::highlight) does.
141  pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
142    self.props.highlight = Some(style.into_prop());
143    self
144  }
145
146  /// Shares the offset, as [`ScrollView::offset`] does.
147  pub fn offset(mut self, offset: Signal<f32>) -> GridView {
148    self.props.offset = Some(offset);
149    self
150  }
151
152  /// Keeps the grid moving after a fling, as [`ScrollView::kinetic`]
153  /// does. On by default.
154  pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> GridView {
155    self.props.kinetic = Some(kinetic.into_prop());
156    self
157  }
158
159  /// Lets a mouse drag the grid's cells, as [`ScrollView::mouse_drag`]
160  /// does. On by default.
161  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  /// Lets the grid go past its ends, as [`ScrollView::overshoot`] does.
167  /// On by default.
168  pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> GridView {
169    self.props.overshoot = Some(overshoot.into_prop());
170    self
171  }
172
173  /// Draws a scroll bar, as [`ScrollView::scroll_bar`] does.
174  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  /// Sets the grid's style.
180  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    // A keyed list of one is how a widget gets a context to make its
197    // signals with.
198    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  // A cell's length along the way the grid scrolls, and across it.
247  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  // What the grid's padding and border take, across and down.
252  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  // The length cells show in: the grid's, less its padding and border.
265  let inner =
266    cx.memo(move || (height.get() as f32 - along(horizontal.get(), sides.get())).max(0.0));
267  // The grid's own size, which its parent or style sets and its cells
268  // don't, 0 until the first layout.
269  let outer = cx.signal(Size::default());
270  // The room across the grid that cells fit in.
271  let width = cx.memo(move || {
272    let across = !horizontal.get();
273    (along(across, outer.get()) - along(across, sides.get())).max(0.0)
274  });
275  // Cells across: the columns, or the rows of a horizontal grid. Then
276  // `rows` are the lines of cells along it.
277  let columns = cx.memo(move || ((width.get() / breadth()) as usize).max(1));
278  let all = cx.signal(Vec::<T>::new());
279  // How often the items changed, for the highlight.
280  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  // The offset as the scroll view shows it: past either end, that end.
288  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  // The rows of cells in view, and one more each side.
298  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  // A new number of columns keeps the cell at the top left in view, and
306  // then the current one. The current one is shown too when it, the
307  // height or the cells' height changes, or when the items first reach
308  // it, but not for a width that keeps the columns.
309  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          // Where the old columns showed it, before the new ones clamp it.
330          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        // An offset set before the first layout is the config's own.
341        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        // A view in motion goes on, as Qt's does.
348        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        // A regrid also puts right an offset past the new end.
353        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  // A horizontal grid's cells fill a column, then wrap to the next.
412  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    // As CSS's `min-width: 0`: the cells don't hold the grid wide.
444    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  // Measured outside the cells, so their row can't hold the grid wide.
453  scroll.common.measure = Some(Rc::new(move |size: Size| {
454    // Run with no effect running; a grid gone by then is left alone.
455    if outer.try_get() != Some(size) {
456      outer.try_set(size);
457    }
458  }));
459  scroll
460}
461
462/// `size`'s height, or its width if `horizontal`: its length along a
463/// grid that scrolls that way.
464fn along(horizontal: bool, size: Size) -> f32 {
465  if horizontal { size.width } else { size.height }
466}