Skip to main content

crabshell_ui/
scroll.rs

1//! [`ScrollView`], a box that shows part of a taller child, and
2//! [`ListView`], a scrolling list that builds only the rows in view.
3
4use std::cell::{Cell, RefCell};
5use std::collections::HashMap;
6use std::hash::Hash;
7use std::rc::Rc;
8
9use crabshell_reactive::{Memo, Signal, untrack};
10
11use crate::cx::Cx;
12use crate::geometry::{Point, Size};
13use crate::prop::{IntoProp, Prop};
14use crate::style::Style;
15use crate::widgets::{
16  Column, Common, Element, ElementChild, ElementKind, Stack, Widget, visibility_methods,
17};
18
19/// Logical pixels a mouse wheel scrolls per notch.
20pub(crate) const PIXELS_PER_NOTCH: f32 = 48.0;
21
22/// The scroll bar's thickness when its style sets no `width`.
23pub(crate) const BAR_WIDTH: f32 = 6.0;
24
25/// The shortest a scroll bar's handle gets, so a long list's stays
26/// grabbable.
27pub(crate) const BAR_MIN_LENGTH: f32 = 16.0;
28
29pub(crate) struct ScrollProps {
30  pub(crate) offset: Option<Signal<f32>>,
31  pub(crate) horizontal: Option<Prop<bool>>,
32  pub(crate) kinetic: Option<Prop<bool>>,
33  pub(crate) overshoot: Option<Prop<bool>>,
34  pub(crate) scroll_bar: Option<Prop<Option<Style>>>,
35  /// What a list moved the offset by to keep the rows shown still, which
36  /// a fling takes as its own motion rather than a write that stops it.
37  pub(crate) shifts: Option<Rc<Cell<f32>>>,
38  /// Whether the view is moving: a touchpad gesture or a drag of its
39  /// child, a fling or a spring-back. A list doesn't scroll to its current
40  /// row meanwhile.
41  pub(crate) moving: Option<Rc<Cell<bool>>>,
42}
43
44/// A box that shows part of its child, which may be taller, and scrolls
45/// it with the mouse wheel or touchpad. Children are cut to the box. Give
46/// it a height through its style, or let its parent size it.
47///
48/// ```
49/// use crabshell_ui::{Column, ScrollView, Style, Text};
50///
51/// let log = ScrollView::new(Column::new().child(Text::new("first line")))
52///     .style(Style::new().height(200.0));
53/// ```
54pub struct ScrollView {
55  pub(crate) scroll: ScrollProps,
56  common: Common,
57  child: Box<dyn Widget>,
58}
59
60impl ScrollView {
61  /// A scroll view of `child`.
62  pub fn new(child: impl Widget) -> ScrollView {
63    ScrollView {
64      scroll: ScrollProps {
65        offset: None,
66        horizontal: None,
67        kinetic: None,
68        overshoot: None,
69        scroll_bar: None,
70        shifts: None,
71        moving: None,
72      },
73      common: Common::default(),
74      child: Box::new(child),
75    }
76  }
77
78  /// Shares the offset: how many logical pixels of the child are
79  /// scrolled out of view above, or to the left in a horizontal view.
80  /// Scrolling writes it, and setting it scrolls, stopping a fling. Values
81  /// past either end show that end.
82  pub fn offset(mut self, offset: Signal<f32>) -> ScrollView {
83    self.scroll.offset = Some(offset);
84    self
85  }
86
87  /// Scrolls sideways instead: the child is laid out at its full width
88  /// rather than its full height, and the wheel, tilted or turned, and the
89  /// touchpad's sideways motion scroll it. Both at once isn't offered.
90  pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ScrollView {
91    self.scroll.horizontal = Some(horizontal.into_prop());
92    self
93  }
94
95  /// Keeps the child moving after a touchpad fling or a drag of the child
96  /// ends, slowing down by 1500 logical pixels a second each second from
97  /// at most 2500 a second, as Qt's `Flickable`. On by default. A mouse
98  /// wheel's notch still moves 48 pixels at once.
99  pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ScrollView {
100    self.scroll.kinetic = Some(kinetic.into_prop());
101    self
102  }
103
104  /// Lets a touchpad, a drag or a fling carry the child past either end,
105  /// against a pull that grows with the distance and stops it within a
106  /// quarter of the box, and springs it back once let go, as Qt's
107  /// `DragAndOvershootBounds`. Only shown: the offset stays within the
108  /// content. On by default.
109  pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ScrollView {
110    self.scroll.overshoot = Some(overshoot.into_prop());
111    self
112  }
113
114  /// Draws a scroll bar while the child is longer than the box: a handle
115  /// along the right edge, or the bottom of a horizontal view, inside the
116  /// border, as long as the part shown and placed by the offset, over
117  /// the child. Its style's `background` and `radius` draw the handle,
118  /// and its `width`, 6 by default, is its thickness. Dragging the handle
119  /// scrolls, and a press beside it pages toward the press. `None`, the
120  /// default, draws none.
121  pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ScrollView {
122    self.scroll.scroll_bar = Some(style.into_prop());
123    self
124  }
125
126  /// Sets the style. A scroll view cuts its child to the inside of its
127  /// border whatever `clip` says.
128  pub fn style(mut self, style: impl IntoProp<Style>) -> ScrollView {
129    self.common.style = Some(style.into_prop());
130    self
131  }
132
133  visibility_methods!();
134}
135
136impl Widget for ScrollView {
137  fn into_element(self: Box<Self>) -> Element {
138    let ScrollView {
139      scroll,
140      common,
141      child,
142    } = *self;
143    Element {
144      name: "ScrollView",
145      common,
146      kind: ElementKind::Scroll(Box::new(scroll)),
147      children: vec![ElementChild::One(Box::new(child.into_element()))],
148    }
149  }
150}
151
152/// A scrolling list that builds only the rows in view, so a list of
153/// thousands costs what a screenful does. Offsets are `f32`, which stays
154/// exact to about 16 million pixels: some 700,000 rows of 24 pixels. It
155/// follows a list of items as [`children_keyed`](Column::children_keyed)
156/// does: each row is kept while its item's key stays in the list.
157///
158/// Rows may differ in height. Each is at least
159/// [`row_height`](Self::row_height) tall and grows to fit its content,
160/// and its height, measured once it is laid out, is kept by its key. A row
161/// not built yet counts as `row_height`, so set it near the usual row's
162/// height. A row that starts above the view grows upward, so the rows
163/// shown stay where they are.
164///
165/// ```
166/// use crabshell_ui::{ListView, Text};
167///
168/// let apps = ListView::new(
169///     || (1..=500).map(|n| format!("app {n}")).collect::<Vec<_>>(),
170///     |name| name.clone(),
171///     |_cx, name| Text::new(move || name.get()),
172/// )
173/// .row_height(28)
174/// .height(280);
175/// ```
176pub struct ListView {
177  /// Builds the list once it has a context for its signals.
178  build: Build,
179  props: ListProps,
180  common: Common,
181}
182
183/// Builds a list's element from its properties, with a context.
184type Build = Box<dyn FnOnce(&Cx, ListProps) -> Element>;
185
186struct ListProps {
187  row_height: Option<Prop<u32>>,
188  height: Option<Prop<u32>>,
189  current: Option<Prop<Option<usize>>>,
190  offset: Option<Signal<f32>>,
191  style: Option<Prop<Style>>,
192  scroll_bar: Option<Prop<Option<Style>>>,
193  kinetic: Option<Prop<bool>>,
194  overshoot: Option<Prop<bool>>,
195  horizontal: Option<Prop<bool>>,
196  highlight: Option<Prop<Option<Style>>>,
197}
198
199impl ListView {
200  /// The default row height, in logical pixels.
201  pub const DEFAULT_ROW_HEIGHT: u32 = 24;
202  /// The default height of the list, in logical pixels.
203  pub const DEFAULT_HEIGHT: u32 = 240;
204
205  /// A list with a row for each of `items`, built by `view` and kept by
206  /// `key`, as in [`children_keyed`](Column::children_keyed).
207  pub fn new<T, K, W>(
208    items: impl FnMut() -> Vec<T> + 'static,
209    key: impl FnMut(&T) -> K + 'static,
210    view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
211  ) -> ListView
212  where
213    T: Clone + PartialEq + 'static,
214    K: Eq + Hash + 'static,
215    W: Widget,
216  {
217    ListView {
218      build: Box::new(move |cx, props| build(cx, props, items, key, view)),
219      props: ListProps {
220        row_height: None,
221        height: None,
222        current: None,
223        offset: None,
224        style: None,
225        scroll_bar: None,
226        kinetic: None,
227        overshoot: None,
228        horizontal: None,
229        highlight: None,
230      },
231      common: Common::default(),
232    }
233  }
234
235  /// Runs the rows left to right in a horizontal scroll view instead.
236  /// [`row_height`](Self::row_height) and [`height`](Self::height) then
237  /// mean each row's width and the list's, and each row is as tall as the
238  /// list. Turning it measures every row again.
239  pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ListView {
240    self.props.horizontal = Some(horizontal.into_prop());
241    self
242  }
243
244  /// Sets the height in logical pixels that each row has at least, and
245  /// that a row not yet built counts as. 24 by default.
246  pub fn row_height(mut self, height: impl IntoProp<u32>) -> ListView {
247    self.props.row_height = Some(height.into_prop());
248    self
249  }
250
251  /// Sets the list's height in logical pixels.
252  pub fn height(mut self, height: impl IntoProp<u32>) -> ListView {
253    self.props.height = Some(height.into_prop());
254    self
255  }
256
257  /// Keeps the row at this index in view, scrolling as little as needed
258  /// whenever it changes. A row not built yet is found by `row_height`,
259  /// then shown whole once it is measured. An index past the end is
260  /// scrolled to once the items reach it; `None` scrolls nothing. While
261  /// the list moves, in a fling, a drag, a touchpad gesture or a
262  /// spring-back, a change scrolls nothing, though a highlight still
263  /// follows it, and the motion's end doesn't scroll back to it.
264  pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> ListView {
265    self.props.current = Some(index.into_prop());
266    self
267  }
268
269  /// Draws a box in this style behind the [`current`](Self::current)
270  /// row, as long as the row and across the list. When the current row
271  /// changes, the box moves to it over the style's `transition` rather
272  /// than jumping, and takes its length at once. It is drawn moved, so a
273  /// move repaints but doesn't lay the window out. No current row, or
274  /// `None`, the default, draws none.
275  pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
276    self.props.highlight = Some(style.into_prop());
277    self
278  }
279
280  /// Shares the offset, as [`ScrollView::offset`] does.
281  pub fn offset(mut self, offset: Signal<f32>) -> ListView {
282    self.props.offset = Some(offset);
283    self
284  }
285
286  /// Keeps the list moving after a fling, as [`ScrollView::kinetic`]
287  /// does. On by default.
288  pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ListView {
289    self.props.kinetic = Some(kinetic.into_prop());
290    self
291  }
292
293  /// Lets the list go past its ends, as [`ScrollView::overshoot`] does.
294  /// On by default.
295  pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ListView {
296    self.props.overshoot = Some(overshoot.into_prop());
297    self
298  }
299
300  /// Draws a scroll bar, as [`ScrollView::scroll_bar`] does.
301  pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
302    self.props.scroll_bar = Some(style.into_prop());
303    self
304  }
305
306  /// Sets the list's style.
307  pub fn style(mut self, style: impl IntoProp<Style>) -> ListView {
308    self.props.style = Some(style.into_prop());
309    self
310  }
311
312  visibility_methods!();
313}
314
315impl Widget for ListView {
316  fn into_element(self: Box<Self>) -> Element {
317    let ListView {
318      build,
319      props,
320      common,
321    } = *self;
322    let mut once = Some((build, props));
323    // A keyed list of one is how a widget gets a context to make its
324    // signals with.
325    let mut element = Box::new(Stack::new().children_keyed(
326      || vec![()],
327      |_| (),
328      move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
329    ))
330    .into_element();
331    element.name = "ListView";
332    element.common = common;
333    element
334  }
335}
336
337/// An element already described, as a widget.
338pub(crate) struct Built(pub(crate) Option<Element>);
339
340impl Widget for Built {
341  fn into_element(self: Box<Self>) -> Element {
342    self
343      .0
344      .unwrap_or_else(|| Box::new(Stack::new()).into_element())
345  }
346}
347
348/// What a list knows of its rows' lengths.
349struct Lengths<K> {
350  /// Each item's index, by key; a repeated key keeps the first.
351  index: HashMap<K, usize>,
352  /// Each item's measured length, by index, once its row was laid out.
353  measured: Vec<Option<f32>>,
354  /// Rows measured since the last look: their index and length.
355  pending: Vec<(usize, f32)>,
356  /// A current row scrolled to by the estimate, shown again once it is
357  /// measured.
358  seek: Option<usize>,
359}
360
361/// Where each row starts if a row not measured is `estimate` long, and
362/// where the last ends.
363fn starts(measured: &[Option<f32>], estimate: f32) -> Vec<f32> {
364  let mut starts = Vec::with_capacity(measured.len() + 1);
365  let mut at = 0.0;
366  starts.push(at);
367  for length in measured {
368    at += length.unwrap_or(estimate);
369    starts.push(at);
370  }
371  starts
372}
373
374/// The offset that shows `start..end` in a view `viewport` long at `now`,
375/// scrolling as little as it can.
376pub(crate) fn keep_in_view(start: f32, end: f32, viewport: f32, now: f32) -> f32 {
377  if start < now {
378    start
379  } else if end > now + viewport {
380    end - viewport
381  } else {
382    now
383  }
384}
385
386fn build<T, K, W>(
387  cx: &Cx,
388  props: ListProps,
389  mut items: impl FnMut() -> Vec<T> + 'static,
390  key: impl FnMut(&T) -> K + 'static,
391  mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
392) -> Element
393where
394  T: Clone + PartialEq + 'static,
395  K: Eq + Hash + 'static,
396  W: Widget,
397{
398  let ListProps {
399    row_height,
400    height,
401    current,
402    offset,
403    style,
404    scroll_bar,
405    kinetic,
406    overshoot,
407    horizontal,
408    highlight: highlight_style,
409  } = props;
410  let offset = offset.unwrap_or_else(|| cx.signal(0.0));
411  let horizontal = cx.memo(prop_fn(horizontal, false));
412  let row_height = cx.memo(prop_fn(row_height, ListView::DEFAULT_ROW_HEIGHT));
413  let estimate = move || row_height.get().max(1) as f32;
414  let height = cx.memo(prop_fn(height, ListView::DEFAULT_HEIGHT));
415  let style = style.map(Prop::shared);
416  // The length rows show in: the list's, less its padding and border.
417  let inner = {
418    let style = style.clone();
419    cx.memo(move || {
420      let own = style.as_ref().map(|style| style()).unwrap_or_default();
421      let padding = own.padding.unwrap_or_default();
422      let border = own.border.map_or(0.0, |border| border.width.max(0.0));
423      let sides = if horizontal.get() {
424        padding.left + padding.right
425      } else {
426        padding.top + padding.bottom
427      };
428      (height.get() as f32 - sides as f32 - 2.0 * border).max(0.0)
429    })
430  };
431  // Shared by the list, its keyed rows and each row, which never call it
432  // inside one another.
433  let key = Rc::new(RefCell::new(key));
434  let lengths = Rc::new(RefCell::new(Lengths {
435    index: HashMap::new(),
436    measured: Vec::new(),
437    pending: Vec::new(),
438    seek: None,
439  }));
440  // Set whenever `measured` changes, and whenever a row is measured.
441  let remeasure = cx.signal(());
442  let measured = cx.signal(());
443  // How often the items changed.
444  let changes = cx.signal(0_u64);
445  let all = cx.signal(Vec::<T>::new());
446  {
447    let (key, lengths) = (Rc::clone(&key), Rc::clone(&lengths));
448    cx.effect(move || {
449      let list = items();
450      let keys: Vec<K> = list.iter().map(|item| (key.borrow_mut())(item)).collect();
451      let mut lengths = lengths.borrow_mut();
452      let old = std::mem::take(&mut lengths.measured);
453      let mut index = HashMap::with_capacity(keys.len());
454      let mut measured = Vec::with_capacity(keys.len());
455      // Where each old index went, for rows measured but not yet looked at.
456      let mut moved = vec![None; old.len()];
457      for (at, item_key) in keys.into_iter().enumerate() {
458        let was = lengths.index.get(&item_key).copied();
459        if let Some(was) = was {
460          moved[was].get_or_insert(at);
461        }
462        measured.push(was.and_then(|was| old[was]));
463        index.entry(item_key).or_insert(at);
464      }
465      lengths.index = index;
466      lengths.measured = measured;
467      let pending = std::mem::take(&mut lengths.pending);
468      lengths.pending = pending
469        .into_iter()
470        .filter_map(|(was, length)| Some((moved.get(was).copied().flatten()?, length)))
471        .collect();
472      drop(lengths);
473      all.set(list);
474      changes.update(|n| *n += 1);
475      remeasure.set(());
476    });
477  }
478  // Turned, every length measured is the other way.
479  {
480    let lengths = Rc::clone(&lengths);
481    let mut was = None;
482    cx.effect(move || {
483      let now = horizontal.get();
484      if was.replace(now).is_some_and(|was| was != now) {
485        lengths.borrow_mut().measured.fill(None);
486        remeasure.set(());
487      }
488    });
489  }
490  let count = cx.memo(move || all.with(Vec::len));
491  let starts = {
492    let lengths = Rc::clone(&lengths);
493    cx.memo(move || {
494      remeasure.get();
495      starts(&lengths.borrow().measured, estimate())
496    })
497  };
498  let total = move || starts.with(|starts| starts.last().copied().unwrap_or(0.0));
499  // The offset as the scroll view shows it: past either end, that end.
500  let shown = move || {
501    let most = (total() - inner.get()).max(0.0);
502    let offset = offset.get();
503    if offset.is_nan() {
504      0.0
505    } else {
506      offset.clamp(0.0, most)
507    }
508  };
509  // The rows in view, and one more each side so a short scroll shows no
510  // gap before the next layout.
511  let range = cx.memo(move || {
512    let top = shown();
513    let bottom = top + inner.get();
514    starts.with(|starts| {
515      let rows = starts.len() - 1;
516      let first = starts
517        .partition_point(|&start| start <= top)
518        .saturating_sub(2);
519      let last = (starts.partition_point(|&start| start < bottom) + 1).min(rows);
520      first..last.max(first)
521    })
522  });
523  // Rows measured: a row that starts above the view grows or shrinks
524  // upward, so the rows shown stay where they are.
525  let shifts = Rc::new(Cell::new(0.0));
526  {
527    let lengths = Rc::clone(&lengths);
528    let shifts = Rc::clone(&shifts);
529    cx.effect(move || {
530      measured.get();
531      let (old, top, estimate) = untrack(|| (starts.get(), shown(), estimate()));
532      let mut lengths = lengths.borrow_mut();
533      let mut changed = false;
534      let mut shift = 0.0;
535      for (at, length) in std::mem::take(&mut lengths.pending) {
536        let Some(slot) = lengths.measured.get_mut(at) else {
537          continue;
538        };
539        if *slot == Some(length) {
540          continue;
541        }
542        if old[at] < top {
543          shift += length - slot.unwrap_or(estimate);
544        }
545        *slot = Some(length);
546        changed = true;
547      }
548      let seek = lengths
549        .seek
550        .filter(|&at| lengths.measured.get(at).is_some_and(Option::is_some));
551      if seek.is_some() {
552        lengths.seek = None;
553      }
554      drop(lengths);
555      if !changed {
556        return;
557      }
558      remeasure.set(());
559      if shift != 0.0 {
560        // A fling goes on from the moved offset.
561        shifts.set(shifts.get() + shift);
562        offset.set(top + shift);
563      }
564      if let Some(at) = seek {
565        untrack(|| {
566          let (start, end) = starts.with(|starts| (starts[at], starts[at + 1]));
567          let now = shown();
568          let next = keep_in_view(start, end, inner.get(), now);
569          if next != now {
570            offset.set(next);
571          }
572        });
573      }
574    });
575  }
576  let moving = Rc::new(Cell::new(false));
577  let current = current.map(Prop::shared);
578  if let Some(current) = current.clone() {
579    let lengths = Rc::clone(&lengths);
580    let moving = Rc::clone(&moving);
581    let mut asked = None;
582    cx.effect(move || {
583      let index = current();
584      // A change of estimate or height shows the row again, and so do
585      // items that first reach it, but not items that keep it.
586      let ask = (index, row_height.get(), inner.get());
587      let wanted = index.filter(|&index| index < count.get());
588      let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
589      let Some(index) = wanted else {
590        lengths.borrow_mut().seek = None;
591        return;
592      };
593      // A view in motion goes on, as Qt's does; the highlight still
594      // follows, and the motion's end scrolls nothing.
595      if !fresh || moving.get() {
596        lengths.borrow_mut().seek = None;
597        return;
598      }
599      let viewport = ask.2;
600      let (start, end) = untrack(|| starts.with(|starts| (starts[index], starts[index + 1])));
601      let now = untrack(shown);
602      let next = keep_in_view(start, end, viewport, now);
603      if next != now {
604        offset.set(next);
605      }
606      let mut lengths = lengths.borrow_mut();
607      let unmeasured = lengths.measured.get(index).is_some_and(Option::is_none);
608      lengths.seek = unmeasured.then_some(index);
609    });
610  }
611  let mut rows = Column::new().style(move || along(horizontal.get(), Style::new(), total()));
612  // How wide the rows are, or how tall in a horizontal list, for the
613  // highlight.
614  let cross = cx.signal(0.0_f32);
615  if let (Some(style), Some(current)) = (highlight_style, current) {
616    let spot = cx.memo(move || {
617      let index = current()?;
618      let (start, end) =
619        starts.with(|starts| Some((*starts.get(index)?, *starts.get(index + 1)?)))?;
620      let target = (index, changes.get());
621      let (length, across) = (end - start, cross.get());
622      Some(if horizontal.get() {
623        Spot {
624          at: Point::new(start, 0.0),
625          size: Size::new(length, across),
626          target,
627        }
628      } else {
629        Spot {
630          at: Point::new(0.0, start),
631          size: Size::new(across, length),
632          target,
633        }
634      })
635    });
636    rows = rows.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
637  }
638  let rows = rows
639    .child(Stack::new().style(move || {
640      let first = starts.with(|starts| starts[range.get().start]);
641      along(horizontal.get(), Style::new(), first).shrink(0.0)
642    }))
643    .children_keyed(
644      move || {
645        let range = range.get();
646        all.with(|all| {
647          let end = range.end.min(all.len());
648          all[range.start.min(end)..end].to_vec()
649        })
650      },
651      {
652        let key = Rc::clone(&key);
653        move |item| (key.borrow_mut())(item)
654      },
655      move |cx, item| {
656        let own = (key.borrow_mut())(&item.get_untracked());
657        let lengths = Rc::clone(&lengths);
658        let measure = move |size: Size| {
659          let mut lengths = lengths.borrow_mut();
660          if let Some(&at) = lengths.index.get(&own) {
661            let length = if horizontal.try_get().unwrap_or_default() {
662              size.width
663            } else {
664              size.height
665            };
666            lengths.pending.push((at, length));
667            drop(lengths);
668            measured.try_set(());
669          }
670        };
671        let row = Stack::new()
672          .style(move || {
673            let least = row_height.get() as f32;
674            let style = Style::new().shrink(0.0);
675            if horizontal.get() {
676              style.min_width(least)
677            } else {
678              style.min_height(least)
679            }
680          })
681          .child(view(cx, item));
682        let mut row = Box::new(row).into_element();
683        row.common.measure = Some(Rc::new(measure));
684        Built(Some(row))
685      },
686    );
687  let mut rows = Box::new(rows).into_element();
688  rows.common.measure = Some(Rc::new(move |size: Size| {
689    let across = if horizontal.try_get().unwrap_or_default() {
690      size.height
691    } else {
692      size.width
693    };
694    if cross.try_get() != Some(across) {
695      cross.try_set(across);
696    }
697  }));
698  if let ElementKind::Flex(flex) = &mut rows.kind {
699    flex.column_binding = Some((move || !horizontal.get()).into_prop());
700  }
701  let mut scroll = ScrollView::new(Built(Some(rows)))
702    .offset(offset)
703    .horizontal(move || horizontal.get());
704  scroll.scroll.shifts = Some(shifts);
705  scroll.scroll.moving = Some(moving);
706  if let Some(bar) = scroll_bar {
707    scroll = scroll.scroll_bar(bar);
708  }
709  if let Some(kinetic) = kinetic {
710    scroll = scroll.kinetic(kinetic);
711  }
712  if let Some(overshoot) = overshoot {
713    scroll = scroll.overshoot(overshoot);
714  }
715  scroll = scroll.style(move || {
716    let own = style.as_ref().map(|style| style()).unwrap_or_default();
717    along(horizontal.get(), own, height.get() as f32)
718  });
719  Box::new(scroll).into_element()
720}
721
722/// `style` with its width, if `horizontal`, or else its height, set to
723/// `length`.
724fn along(horizontal: bool, style: Style, length: f32) -> Style {
725  if horizontal {
726    style.width(length)
727  } else {
728    style.height(length)
729  }
730}
731
732/// Where a view's highlight goes in its content: the current item's
733/// corner and size.
734#[derive(Clone, Copy, PartialEq)]
735pub(crate) struct Spot {
736  pub(crate) at: Point,
737  pub(crate) size: Size,
738  /// The item it is on: its index and how often the items changed. A
739  /// spot that moves with the same target, as a row is measured, jumps.
740  pub(crate) target: (usize, u64),
741}
742
743/// A box drawn in `style` at `spot`, behind what follows it. The outer
744/// box is moved there by a paint translate over the style's transition,
745/// and the inner one takes the size and the style, so a move fades
746/// without a layout while a new size comes at once.
747pub(crate) fn highlight(cx: &Cx, style: Memo<Option<Style>>, spot: Memo<Option<Spot>>) -> Stack {
748  // A new size alone leaves the move as it is.
749  let place = cx.memo(move || spot.get().map(|spot| (spot.at, spot.target)));
750  let shape = Stack::new().style(move || {
751    let own = style.get().unwrap_or_default();
752    match spot.get() {
753      Some(spot) => own.width(spot.size.width).height(spot.size.height),
754      None => own,
755    }
756  });
757  let mut last = None;
758  Stack::new()
759    .visible(move || style.with(Option::is_some) && spot.with(Option::is_some))
760    .style(move || {
761      // Hidden, so where doesn't matter, and shown again it jumps.
762      let Some((at, target)) = place.get() else {
763        return Style::new().left(0.0).top(0.0);
764      };
765      let moved = last.replace(target) != Some(target);
766      let mover = Style::new().left(0.0).top(0.0).translate(at.x, at.y);
767      match style.get().and_then(|style| style.transition) {
768        Some(transition) if moved => mover.transition(transition),
769        _ => mover,
770      }
771    })
772    .child(shape)
773}
774
775/// `prop` as a closure, or `default` when unset.
776pub(crate) fn prop_fn<T: Clone + 'static>(
777  prop: Option<Prop<T>>,
778  default: T,
779) -> impl FnMut() -> T + 'static {
780  let prop = prop.map(Prop::shared);
781  move || match prop.as_ref() {
782    Some(prop) => prop(),
783    None => default.clone(),
784  }
785}