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