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::{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
17/// A scrolling grid of cells of one size, in as many columns as fit its
18/// width and at least one, for app and wallpaper pickers. It builds only
19/// the rows of cells in view, so a grid of thousands costs what a
20/// screenful does, and follows a list of items as
21/// [`children_keyed`](Column::children_keyed) does: each cell is kept
22/// while its item's key stays in the list. When its width changes the
23/// number of columns, the cell at the top left stays in view.
24///
25/// ```
26/// use crabshell_ui::{GridView, Icon};
27///
28/// let apps = GridView::new(
29///     || vec!["firefox", "foot", "gimp"],
30///     |name| *name,
31///     |_cx, name| Icon::new(name.get()).size(48),
32/// )
33/// .cell_size(72, 72)
34/// .height(288);
35/// ```
36pub struct GridView {
37  /// Builds the grid once it has a context for its signals.
38  build: Build,
39  props: GridViewProps,
40  common: Common,
41}
42
43/// Builds a grid's element from its properties, with a context.
44type 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  /// The default cell width and height, in logical pixels, as Qt's.
61  pub const DEFAULT_CELL: u32 = 100;
62  /// The default height of the grid, in logical pixels.
63  pub const DEFAULT_HEIGHT: u32 = 240;
64
65  /// A grid with a cell for each of `items`, built by `view` and kept by
66  /// `key`, as in [`children_keyed`](Column::children_keyed).
67  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  /// Sets every cell's width and height in logical pixels, 100 by
96  /// default. A cell's content is laid out in that box; a size of 0
97  /// counts as 1.
98  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  /// Sets the grid's height in logical pixels. Its width comes from its
105  /// style or its parent.
106  pub fn height(mut self, height: impl IntoProp<u32>) -> GridView {
107    self.props.height = Some(height.into_prop());
108    self
109  }
110
111  /// Keeps the cell at this index in view, scrolling as little as needed
112  /// whenever it, the height or the number of columns changes. An index
113  /// past the end is scrolled to once the items reach it; `None` scrolls
114  /// nothing. While the grid moves, a change scrolls nothing, as in
115  /// [`ListView::current`](crate::ListView::current).
116  pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> GridView {
117    self.props.current = Some(index.into_prop());
118    self
119  }
120
121  /// Draws a box in this style behind the [`current`](Self::current)
122  /// cell, as [`ListView::highlight`](crate::ListView::highlight) does.
123  pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> GridView {
124    self.props.highlight = Some(style.into_prop());
125    self
126  }
127
128  /// Shares the offset, as [`ScrollView::offset`] does.
129  pub fn offset(mut self, offset: Signal<f32>) -> GridView {
130    self.props.offset = Some(offset);
131    self
132  }
133
134  /// Keeps the grid moving after a fling, as [`ScrollView::kinetic`]
135  /// does. On by default.
136  pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> GridView {
137    self.props.kinetic = Some(kinetic.into_prop());
138    self
139  }
140
141  /// Lets the grid go past its ends, as [`ScrollView::overshoot`] does.
142  /// On by default.
143  pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> GridView {
144    self.props.overshoot = Some(overshoot.into_prop());
145    self
146  }
147
148  /// Draws a scroll bar, as [`ScrollView::scroll_bar`] does.
149  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  /// Sets the grid's style.
155  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    // A keyed list of one is how a widget gets a context to make its
172    // signals with.
173    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  // The height cells show in: the grid's, less its padding and border.
221  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  // The width cells fit in, 0 until the first layout.
232  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  // How often the items changed, for the highlight.
236  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  // The offset as the scroll view shows it: past either end, that end.
244  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  // The rows of cells in view, and one more each side.
254  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  // A new number of columns keeps the cell at the top left in view, and
262  // then the current one. The current one is shown too when it, the
263  // height or the cells' height changes, or when the items first reach
264  // it, but not for a width that keeps the columns.
265  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          // Where the old columns showed it, before the new ones clamp it.
286          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        // An offset set before the first layout is the config's own.
297        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        // A view in motion goes on, as Qt's does.
304        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        // A regrid also puts right an offset past the new end.
309        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    // Run with no effect running; a grid gone by then is left alone.
373    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}