Skip to main content

day_core/
list.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Recycling-list driver (docs/list.md, §10). The native list host owns scrolling + cell reuse;
5//! Day owns row *content*. day-core injects a [`day_spec::ListSource`] into the backend; when the
6//! native data-source pulls a cell, `bind_row` builds it once (per physical cell) and thereafter
7//! *rebinds* it (one slot-write) as the cell recycles.
8//!
9//! Re-entrancy (the crux): building a row uses `BuildCx`, and reactive bindings patch native
10//! widgets; both acquire `with_tree` per operation. So `bind_row` phases the tree borrow:
11//! `with_tree` (adopt cell) → build/rebind + `flush_sync` **outside** any borrow → `with_tree`
12//! (lay the row out in its cell). Holding the borrow across the build would deadlock the `RefCell`.
13
14use crate::tree::{RNode, try_with_tree, with_tree};
15use day_reactive::Scope;
16use day_spec::{
17    ListSource, RawHandle,
18    props::{RowDelta, RowHeight},
19};
20use std::cell::{Cell, RefCell};
21use std::collections::HashMap;
22use std::rc::Rc;
23
24/// Supplied by the `list()` piece, type-erased over the item type. day-core invokes these to
25/// answer the native data-source and to build/rebind rows.
26pub struct ListDriver {
27    pub row_height: RowHeight,
28    pub track_viewport: bool,
29    /// Ask the host to report the scrolls the reader starts (`follow_end`, docs/list.md
30    /// "Following the end"), delivered as [`day_spec::Event::ListReaderScrolled`].
31    pub track_reader: bool,
32    /// Current row count (reads the piece's snapshot; no tree access).
33    pub len: Box<dyn Fn() -> usize>,
34    /// Stable identity token for row `index` (for native diffing).
35    pub token_at: Box<dyn Fn(usize) -> u64>,
36    /// Build row `index` into `anchor`. Uses `BuildCx` internally, so it must be called with no
37    /// `with_tree` borrow held. Returns the row's scope + a rebind writer.
38    pub build: Box<dyn Fn(usize, RNode) -> BuiltRow>,
39    /// Drag-to-reorder half, present when the piece is `.reorderable()` (docs/list.md).
40    pub reorder: Option<ListReorderDriver>,
41    /// Swipe-to-delete half, present when the piece is `.deletable()` (docs/list.md).
42    pub delete: Option<ListDeleteDriver>,
43    /// Swipe-ACTIONS half, present when the piece declared edge actions (docs/list.md).
44    pub swipe: Option<ListSwipeDriver>,
45    /// Section headers, present when the piece declared `.sections` (docs/list.md
46    /// "Sections"). Every closure above still speaks item indices; day-core inserts the
47    /// header rows and translates item indices at the toolkit boundary.
48    pub sections: Option<ListSectionsDriver>,
49    /// The list's header, footer, empty state and content padding (docs/list.md "Header,
50    /// footer and empty state"). day-core shows them as rows of their own around the items,
51    /// so every toolkit scrolls them with the list.
52    pub supplements: ListSupplements,
53}
54
55/// Builds one supplementary row into `anchor`: the contract of [`ListDriver::build`] without
56/// an item.
57pub type SupplementBuild = Box<dyn Fn(RNode) -> BuiltRow>;
58
59/// The supplementary rows the `list()` piece supplies (docs/list.md "Header, footer and empty
60/// state"). Each is a display row the host binds like any other; none is an item, so none is
61/// selected, activated, swiped, dragged or counted by a row index.
62#[derive(Default)]
63pub struct ListSupplements {
64    /// Content above the first row, scrolling with the rows.
65    pub header: Option<SupplementBuild>,
66    /// Content below the last row.
67    pub footer: Option<SupplementBuild>,
68    /// Content shown in place of the rows while the list has none; it fills the viewport.
69    pub empty: Option<SupplementBuild>,
70    /// Space around the list's content, inside the scrolling area: the top and bottom scroll
71    /// with the rows, the sides inset every row.
72    pub padding: day_spec::Insets,
73}
74
75impl ListSupplements {
76    /// Which supplementary rows a list with these has.
77    fn shape(&self) -> SupplementShape {
78        SupplementShape {
79            pad_top: self.padding.top > 0.0,
80            header: self.header.is_some(),
81            empty: self.empty.is_some(),
82            footer: self.footer.is_some(),
83            pad_bottom: self.padding.bottom > 0.0,
84        }
85    }
86
87    /// Whether the list has any supplementary row at all.
88    pub(crate) fn any(&self) -> bool {
89        let shape = self.shape();
90        shape.pad_top || shape.header || shape.empty || shape.footer || shape.pad_bottom
91    }
92
93    /// Build supplementary row `which` into `anchor`. A padding row has no content.
94    fn build(&self, which: Supplement, anchor: RNode) -> BuiltRow {
95        let build = match which {
96            Supplement::Header => self.header.as_ref(),
97            Supplement::Footer => self.footer.as_ref(),
98            Supplement::Empty => self.empty.as_ref(),
99            Supplement::PadTop | Supplement::PadBottom => None,
100        };
101        match build {
102            Some(build) => build(anchor),
103            None => BuiltRow {
104                scope: Scope::child(),
105                rebind: Rc::new(|_| {}),
106            },
107        }
108    }
109}
110
111/// A supplementary row of a list: a row that is neither an item nor a section header.
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
113pub enum Supplement {
114    /// The content padding above everything.
115    PadTop,
116    /// The list's header.
117    Header,
118    /// The empty state, present only while the list has no items.
119    Empty,
120    /// The list's footer.
121    Footer,
122    /// The content padding below everything.
123    PadBottom,
124}
125
126impl Supplement {
127    /// The row's identity token: fixed, so a host keeps the row across reloads and splices.
128    fn token(self) -> u64 {
129        0x5DA7_5C0F_F5E7_0000
130            | match self {
131                Supplement::PadTop => 1,
132                Supplement::Header => 2,
133                Supplement::Empty => 3,
134                Supplement::Footer => 4,
135                Supplement::PadBottom => 5,
136            }
137    }
138}
139
140/// Which supplementary rows a list has ([`ListSupplements::shape`]).
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142struct SupplementShape {
143    pad_top: bool,
144    header: bool,
145    empty: bool,
146    footer: bool,
147    pad_bottom: bool,
148}
149
150/// What a bound cell holds. A host that pools every row together hands a cell of one kind to
151/// a row of another now and then; the kinds are different pieces, so `bind_row` rebuilds the
152/// cell instead of rebinding it.
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub enum CellKind {
155    /// An item's row (built by [`ListDriver::build`]).
156    Item,
157    /// A section header (built by [`ListSectionsDriver::build`]).
158    Header,
159    /// A supplementary row (built from [`ListSupplements`]).
160    Extra(Supplement),
161}
162
163/// The section half the `list()` piece supplies (docs/list.md "Sections"): a key per item and
164/// a header builder. A header row precedes every item whose key differs from the item before.
165pub struct ListSectionsDriver {
166    /// The section key of item `index` in the current snapshot (the piece snapshots keys with
167    /// its rows, and rotates them with a committed move, so this needs no app access).
168    pub key_at: Box<dyn Fn(usize) -> u64>,
169    /// Build the header of the section that starts at item `first` into `anchor`: the same
170    /// contract as [`ListDriver::build`], and its rebind writer takes the section's first item.
171    pub build: Box<dyn Fn(usize, RNode) -> BuiltRow>,
172}
173
174/// The reorder closures the `list()` piece supplies (docs/list.md). Exposed to the backend as
175/// [`day_spec::ListReorder`] by the list source adapter; also driven directly by
176/// [`list_try_reorder`] (the dayscript `reorder` step and the mock probe).
177pub struct ListReorderDriver {
178    /// Consult the app's guard: returns the accepted target index, or -1 to deny.
179    pub can_move: Box<dyn Fn(usize, usize) -> i64>,
180    /// Commit an accepted move: rotates the piece's snapshot + tokens synchronously and defers
181    /// the app's `on_reorder` callback to the next event drain.
182    pub moved: Box<dyn Fn(usize, usize)>,
183}
184
185/// The delete closures the `list()` piece supplies (docs/list.md). Exposed to the backend as
186/// [`day_spec::ListDelete`] by the list source adapter; also driven directly by [`list_try_delete`]
187/// (the dayscript `delete_row` step and the mock probe).
188pub struct ListDeleteDriver {
189    /// Consult the app's guard: may this row be deleted?
190    pub can_delete: Box<dyn Fn(usize) -> bool>,
191    /// Commit an accepted delete: drops the row from the piece's snapshot + tokens synchronously
192    /// and defers the app's `on_delete` callback to the next event drain.
193    pub deleted: Box<dyn Fn(usize)>,
194}
195
196/// The swipe-action closures the `list()` piece supplies (docs/list.md). Exposed to the
197/// backend as [`day_spec::ListSwipe`] by the list source adapter; also driven directly by
198/// [`list_try_swipe`] (the dayscript `swipe_row` step and the mock probe).
199pub struct ListSwipeDriver {
200    /// The offer: the actions for row `index` on `edge`. Pure; runs inside native swipe
201    /// callbacks.
202    pub actions_at: Box<dyn Fn(usize, day_spec::SwipeEdge) -> Vec<day_spec::ListSwipeAction>>,
203    /// Commit an activated action (an index into the offer): defers the app's handler to the
204    /// next event drain.
205    pub performed: Box<dyn Fn(usize, day_spec::SwipeEdge, usize)>,
206}
207
208/// A freshly built row: its `Scope` (owns the row's reactive graph) and a rebind writer that
209/// slot-writes item `index` into the row's `ItemSlot` when the cell is recycled.
210pub struct BuiltRow {
211    pub scope: Scope,
212    pub rebind: Rc<dyn Fn(usize)>,
213}
214
215pub(crate) struct BoundCell {
216    pub anchor: RNode,
217    /// Between `bind_row` and `recycle`: only displayed cells participate in layout.
218    pub active: bool,
219    /// The row subtree's reactive scope, disposed by `remove_subtree` when the list node
220    /// goes away (the cells live in the list machinery, not the node tree, so nothing else
221    /// would dispose their bindings).
222    pub scope: Scope,
223    pub rebind: Rc<dyn Fn(usize)>,
224    /// The width the backend last laid this cell at through `ListSource::layout_cell`: the
225    /// width the native row granted, which on GTK is the list's less the row's own
226    /// padding. Every later layout of the row (a rebind, the dirty-cell sweep, a data change)
227    /// uses it; `None` until the backend has reported one, when the list's width stands in.
228    pub native_width: Option<f64>,
229    /// The width this cell's row was last laid at, by either path. Only a width that actually
230    /// changed invalidates the row's measurement cache: the dirty-cell sweep re-lays every bound
231    /// cell on every pass, and re-measuring each row's text each time made a 500-row list's
232    /// binds take whole seconds.
233    pub laid_width: Option<f64>,
234    /// The height the row was last laid at (`ListSource::cell_height`).
235    pub laid_height: Option<f64>,
236    /// What the cell holds: an item's row, a section header, or a supplementary row.
237    pub kind: CellKind,
238    /// The identity token of the row the cell was last bound to ([`ListSource::token_at`]):
239    /// how [`list_refresh_rows`] finds the row again after the rows around it moved.
240    pub token: u64,
241    /// The host's pinned copy of a header (`ListSource::bind_pinned`): its ids stay parked, so
242    /// lookups find the header row in the list instead.
243    pub pinned: bool,
244}
245
246pub(crate) struct ListState {
247    pub driver: Rc<ListDriver>,
248    /// Physical cell (native handle as usize) → its built row.
249    pub cells: HashMap<usize, BoundCell>,
250    /// The display rows of a list with section headers or supplementary rows; `None` without
251    /// either, where display row and item index coincide.
252    pub sections: Option<Rc<SectionMap>>,
253    /// The host was last told the list has no items, so it shows the empty state (when the
254    /// list has one). Starts true: the host attaches against an empty snapshot.
255    pub showed_empty: bool,
256}
257
258/// One row as the native host sees it in a list with headers or supplementary rows.
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260pub(crate) enum DisplayRow {
261    /// The header of the section whose first item is this index.
262    Header(usize),
263    Item(usize),
264    /// A supplementary row: the list's header, footer, empty state or content padding.
265    Extra(Supplement),
266}
267
268/// A list's display rows, solved from its item count, section keys and supplementary rows:
269/// what [`SectionMap`] serves, and what [`list_sync`] diffs.
270struct DisplayLayout {
271    rows: Vec<DisplayRow>,
272    /// Item index → its display row.
273    display: Vec<usize>,
274    /// The display row of each section header, in order, with the header's identity token.
275    heads: Vec<(usize, u64)>,
276}
277
278impl DisplayLayout {
279    /// Lay `n` items out: the supplementary rows around them, and a header row in front of
280    /// every item whose section key differs from the item before.
281    fn solve(n: usize, key_at: Option<&dyn Fn(usize) -> u64>, shape: SupplementShape) -> Self {
282        let mut rows = Vec::with_capacity(n + n / 4 + 5);
283        let mut display = Vec::with_capacity(n);
284        let mut heads = Vec::new();
285        if shape.pad_top {
286            rows.push(DisplayRow::Extra(Supplement::PadTop));
287        }
288        if shape.header {
289            rows.push(DisplayRow::Extra(Supplement::Header));
290        }
291        if n == 0 && shape.empty {
292            rows.push(DisplayRow::Extra(Supplement::Empty));
293        }
294        // How often each key has opened a section so far: a key that recurs further down
295        // (a feed listed twice) opens a header of its own identity.
296        let mut seen: HashMap<u64, u64> = HashMap::new();
297        let mut previous = None;
298        for i in 0..n {
299            if let Some(key_at) = key_at {
300                let key = key_at(i);
301                if previous != Some(key) {
302                    let nth = seen.entry(key).or_default();
303                    heads.push((rows.len(), SectionMap::header_token(key, *nth)));
304                    *nth += 1;
305                    rows.push(DisplayRow::Header(i));
306                    previous = Some(key);
307                }
308            }
309            display.push(rows.len());
310            rows.push(DisplayRow::Item(i));
311        }
312        if shape.footer {
313            rows.push(DisplayRow::Extra(Supplement::Footer));
314        }
315        if shape.pad_bottom {
316            rows.push(DisplayRow::Extra(Supplement::PadBottom));
317        }
318        DisplayLayout {
319            rows,
320            display,
321            heads,
322        }
323    }
324
325    /// Every display row's identity token, given the items' tokens.
326    fn tokens(&self, token_at: &dyn Fn(usize) -> u64) -> Vec<u64> {
327        let mut heads = self.heads.iter();
328        self.rows
329            .iter()
330            .map(|row| match row {
331                DisplayRow::Item(i) => token_at(*i),
332                DisplayRow::Header(_) => heads.next().map_or(0, |(_, token)| *token),
333                DisplayRow::Extra(which) => which.token(),
334            })
335            .collect()
336    }
337}
338
339/// The most row deltas [`diff_rows`] answers with. A change that needs more is a different
340/// list more than an edited one: the host reloads, which costs it one pass instead of one
341/// animated step per row.
342pub const SPLICE_MAX_DELTAS: usize = 512;
343
344/// The row deltas that turn `old` into `new`, two lists of row identity tokens, or `None`
345/// when a reload serves better (docs/list.md "Keyed updates").
346///
347/// The deltas are sequential, as [`RowDelta`] defines them: removals first, from the bottom
348/// up, then one insert per new row and one move per row that changed its place among the
349/// rows that stayed, placed from the bottom up so each lands directly above a row already in
350/// place. The moves are the fewest possible: the rows on a longest increasing run keep still.
351///
352/// `None` when either list is empty, when the two share no row, when a token repeats (a
353/// repeated key cannot say which row moved), or when the change needs more than
354/// [`SPLICE_MAX_DELTAS`] deltas. `Some(vec![])` when the lists are equal.
355#[must_use]
356pub fn diff_rows(old: &[u64], new: &[u64]) -> Option<Vec<RowDelta>> {
357    if old == new {
358        return Some(Vec::new());
359    }
360    if old.is_empty() || new.is_empty() {
361        return None;
362    }
363    let mut new_at: HashMap<u64, usize> = HashMap::with_capacity(new.len());
364    for (i, token) in new.iter().enumerate() {
365        if new_at.insert(*token, i).is_some() {
366            return None;
367        }
368    }
369    // The survivors, in the old order, by their place in the new list.
370    let mut seen = std::collections::HashSet::with_capacity(old.len());
371    let mut survivors: Vec<usize> = Vec::with_capacity(old.len().min(new.len()));
372    let mut deltas = Vec::new();
373    for (i, token) in old.iter().enumerate().rev() {
374        if !seen.insert(*token) {
375            return None;
376        }
377        match new_at.get(token) {
378            Some(at) => survivors.push(*at),
379            None => deltas.push(RowDelta::Remove(i)),
380        }
381    }
382    survivors.reverse();
383    if survivors.is_empty() {
384        return None;
385    }
386    let still = longest_increasing(&survivors);
387    let changes = deltas.len() + (new.len() - survivors.len()) + (survivors.len() - still.len());
388    if changes > SPLICE_MAX_DELTAS {
389        return None;
390    }
391    let mut keeps = vec![false; new.len()];
392    for at in &still {
393        keeps[*at] = true;
394    }
395    let mut survives = vec![false; new.len()];
396    for at in &survivors {
397        survives[*at] = true;
398    }
399    // The working list: the survivors as the removals left them, as places in `new`.
400    let mut work = survivors;
401    for i in (0..new.len()).rev() {
402        if keeps[i] {
403            continue;
404        }
405        // Row `i` lands directly above the row that follows it in `new`, which is in place.
406        let before = |work: &[usize]| {
407            work.iter()
408                .position(|at| *at == i + 1)
409                .unwrap_or(work.len())
410        };
411        if survives[i] {
412            let from = work.iter().position(|at| *at == i)?;
413            work.remove(from);
414            let to = before(&work);
415            work.insert(to, i);
416            if from != to {
417                deltas.push(RowDelta::Move(from, to));
418            }
419        } else {
420            let to = before(&work);
421            work.insert(to, i);
422            deltas.push(RowDelta::Insert(to));
423        }
424    }
425    Some(deltas)
426}
427
428/// The values of one longest strictly increasing subsequence of `seq` (patience sorting).
429fn longest_increasing(seq: &[usize]) -> Vec<usize> {
430    // `tails[k]`: the index in `seq` of the smallest value ending a run of length `k + 1`.
431    let mut tails: Vec<usize> = Vec::new();
432    let mut previous: Vec<Option<usize>> = vec![None; seq.len()];
433    for (i, value) in seq.iter().enumerate() {
434        let k = tails.partition_point(|t| seq[*t] < *value);
435        previous[i] = k.checked_sub(1).map(|k| tails[k]);
436        if k == tails.len() {
437            tails.push(i);
438        } else {
439            tails[k] = i;
440        }
441    }
442    let mut run = Vec::with_capacity(tails.len());
443    let mut at = tails.last().copied();
444    while let Some(i) = at {
445        run.push(seq[i]);
446        at = previous[i];
447    }
448    run.reverse();
449    run
450}
451
452/// A list's display rows (docs/list.md "Sections" and "Header, footer and empty state"): the
453/// items with a header row in front of each section and the supplementary rows around them.
454/// The native host counts, binds, selects and scrolls display rows; the
455/// app, the piece and dayscript speak item indices. Everything that crosses between them
456/// translates here: the `ListSource` closures, the patches the tree sends, and the selection
457/// events the toolkit raises (through the event sink, which may run inside a tree borrow, so
458/// the map lives outside the tree, in `SECTION_MAPS`).
459pub(crate) struct SectionMap {
460    driver: Rc<ListDriver>,
461    rows: RefCell<Vec<DisplayRow>>,
462    /// Item index → its display row.
463    display: RefCell<Vec<usize>>,
464    /// The display row of each header, in order, with the header's identity token.
465    heads: RefCell<Vec<(usize, u64)>>,
466    /// The snapshot changed since the rows were computed (a reload, a splice, a commit).
467    stale: Cell<bool>,
468}
469
470impl SectionMap {
471    fn new(driver: Rc<ListDriver>) -> Self {
472        SectionMap {
473            driver,
474            rows: RefCell::new(Vec::new()),
475            display: RefCell::new(Vec::new()),
476            heads: RefCell::new(Vec::new()),
477            stale: Cell::new(true),
478        }
479    }
480
481    /// The snapshot changed: recompute on the next read.
482    pub(crate) fn invalidate(&self) {
483        self.stale.set(true);
484    }
485
486    fn ensure(&self) {
487        let driver = &self.driver;
488        let n = (driver.len)();
489        // A changed item count is a change nobody announced yet (the piece refreshes its
490        // snapshot a moment before it reloads the host): never serve rows for the old one.
491        if !self.stale.get() && self.display.borrow().len() == n {
492            return;
493        }
494        let key_at = driver.sections.as_ref().map(|s| &*s.key_at);
495        let layout = DisplayLayout::solve(n, key_at, driver.supplements.shape());
496        *self.rows.borrow_mut() = layout.rows;
497        *self.display.borrow_mut() = layout.display;
498        *self.heads.borrow_mut() = layout.heads;
499        self.stale.set(false);
500    }
501
502    pub(crate) fn len(&self) -> usize {
503        self.ensure();
504        self.rows.borrow().len()
505    }
506
507    pub(crate) fn row(&self, display: usize) -> Option<DisplayRow> {
508        self.ensure();
509        self.rows.borrow().get(display).copied()
510    }
511
512    /// The item at display row `display`; `None` for a header or past the end.
513    pub(crate) fn item_of(&self, display: usize) -> Option<usize> {
514        match self.row(display)? {
515            DisplayRow::Item(i) => Some(i),
516            DisplayRow::Header(_) | DisplayRow::Extra(_) => None,
517        }
518    }
519
520    /// The items among display rows `first..=last`, as a half-open range of item indices:
521    /// empty when the rows hold headers and supplementary rows only.
522    pub(crate) fn items_in(&self, first: usize, last: usize) -> std::ops::Range<usize> {
523        self.ensure();
524        let display = self.display.borrow();
525        let start = display.partition_point(|d| *d < first);
526        let end = display.partition_point(|d| *d <= last);
527        start..end.max(start)
528    }
529
530    /// Whether display row `display` is a supplementary row.
531    pub(crate) fn is_supplement(&self, display: usize) -> bool {
532        matches!(self.row(display), Some(DisplayRow::Extra(_)))
533    }
534
535    /// The display row of supplementary row `which`, when the list shows it.
536    pub(crate) fn supplement_row(&self, which: Supplement) -> Option<usize> {
537        self.ensure();
538        self.rows
539            .borrow()
540            .iter()
541            .position(|row| *row == DisplayRow::Extra(which))
542    }
543
544    /// How many display rows sit above the first item when no section header does: what
545    /// separates an item index from its display row in a list without sections.
546    pub(crate) fn lead(&self) -> usize {
547        self.ensure();
548        self.display.borrow().first().copied().unwrap_or_else(|| {
549            self.rows
550                .borrow()
551                .iter()
552                .take_while(|row| {
553                    !matches!(
554                        row,
555                        DisplayRow::Extra(Supplement::Footer | Supplement::PadBottom)
556                    )
557                })
558                .count()
559        })
560    }
561
562    pub(crate) fn display_of(&self, item: usize) -> Option<usize> {
563        self.ensure();
564        self.display.borrow().get(item).copied()
565    }
566
567    /// The section around display row `display`, when that row is an item: the display
568    /// rows of its first and last items, and the number of rows above it that are not items,
569    /// which is what separates a display row from its item index inside the section. A list
570    /// without sections is one section of all its items.
571    pub(crate) fn span(&self, display: usize) -> Option<SectionSpan> {
572        let item = self.item_of(display)?;
573        let heads = self.heads.borrow();
574        let items = self.display.borrow();
575        let (first, last) = if heads.is_empty() {
576            (*items.first()?, *items.last()?)
577        } else {
578            let section = heads
579                .partition_point(|(h, _)| *h <= display)
580                .checked_sub(1)?;
581            let last = match heads.get(section + 1) {
582                Some((next, _)) => next - 1,
583                None => *items.last()?,
584            };
585            (heads[section].0 + 1, last)
586        };
587        Some(SectionSpan {
588            first,
589            last,
590            headers: display - item,
591        })
592    }
593
594    /// The identity token of the header at display row `display`.
595    pub(crate) fn header_token_at(&self, display: usize) -> Option<u64> {
596        self.ensure();
597        let heads = self.heads.borrow();
598        let at = heads.binary_search_by_key(&display, |(h, _)| *h).ok()?;
599        Some(heads[at].1)
600    }
601
602    /// A header's identity token: its section key and how many sections with that key came
603    /// before it, so a section keeps its header while rows move inside it, and two sections
604    /// with the same key (a feed that recurs further down) never share one.
605    fn header_token(key: u64, nth: u64) -> u64 {
606        (key ^ nth.wrapping_mul(0x9E37_79B9_7F4A_7C15)).rotate_left(29) ^ 0xD1B5_4A32_D192_ED03
607    }
608
609    /// A drag of display row `from` toward display row `to`, in item indices: a header never
610    /// moves, and a row stays in its section, so a target past either end lands at that end
611    /// (docs/list.md "Sections"). Answers the span with the clamped item move.
612    fn move_within(&self, from: usize, to: usize) -> Option<(SectionSpan, usize, usize)> {
613        let span = self.span(from)?;
614        let to = to.clamp(span.first, span.last);
615        Some((span, from - span.headers, to - span.headers))
616    }
617}
618
619/// The rows of one section of a sectioned list, as [`SectionMap::span`] answers them.
620#[derive(Clone, Copy, Debug, PartialEq, Eq)]
621pub(crate) struct SectionSpan {
622    /// The display row of the section's first item.
623    pub first: usize,
624    /// The display row of the section's last item.
625    pub last: usize,
626    /// The rows above this section's items that are not items (headers and supplementary
627    /// rows): an item's display row less this is its index.
628    pub headers: usize,
629}
630
631impl SectionSpan {
632    /// The display row of item `item`, when it falls inside this section.
633    fn display_of(&self, item: usize) -> Option<usize> {
634        let display = item + self.headers;
635        (self.first..=self.last)
636            .contains(&display)
637            .then_some(display)
638    }
639}
640
641day_reactive::tls_slots! {
642    list;
643    /// Each sectioned list's map by node, for the event sink (which cannot borrow the tree).
644    /// Weak: the list's state owns the map, and an entry outlives its list only until the next
645    /// registration prunes it.
646    static SECTION_MAPS: RefCell<HashMap<day_spec::NodeId, std::rc::Weak<SectionMap>>> =
647        RefCell::new(HashMap::new());
648    /// [`set_scripted_reorder`]'s routes by node.
649    static SCRIPTED_REORDERS: RefCell<HashMap<day_spec::NodeId, ScriptedReorder>> =
650        RefCell::new(HashMap::new());
651}
652
653/// The map of the sectioned list at `node`; `None` for a list without sections.
654fn section_map(node: RNode) -> Option<Rc<SectionMap>> {
655    let id = crate::tree::rnode_to_id(node);
656    SECTION_MAPS.with(|m| m.borrow().get(&id).and_then(std::rc::Weak::upgrade))
657}
658
659/// The map a sectioned list at `node` shares with its source closures and the event sink.
660pub(crate) fn register_sections(node: RNode, driver: Rc<ListDriver>) -> Rc<SectionMap> {
661    let map = Rc::new(SectionMap::new(driver));
662    SECTION_MAPS.with(|m| {
663        let mut m = m.borrow_mut();
664        m.retain(|_, w| w.strong_count() > 0);
665        m.insert(crate::tree::rnode_to_id(node), Rc::downgrade(&map));
666    });
667    map
668}
669
670/// A toolkit's row event on a sectioned list, in display rows, as the item-index event the
671/// piece expects. A header is not an item, so a selection or activation of one (a host that
672/// failed to refuse it) is dropped; every other event passes unchanged.
673pub(crate) fn translate_native_event(
674    id: day_spec::NodeId,
675    ev: day_spec::Event,
676) -> Option<day_spec::Event> {
677    use day_spec::Event;
678    if !matches!(
679        ev,
680        Event::SelectionChanged(_) | Event::SelectionSet(_) | Event::ListActivated(_)
681    ) {
682        return Some(ev);
683    }
684    let Some(map) = SECTION_MAPS.with(|m| m.borrow().get(&id).and_then(std::rc::Weak::upgrade))
685    else {
686        return Some(ev);
687    };
688    match ev {
689        Event::SelectionChanged(i) if i >= 0 => map
690            .item_of(i as usize)
691            .map(|i| Event::SelectionChanged(i as i64)),
692        Event::SelectionSet(rows) => Some(Event::SelectionSet(
693            rows.iter()
694                .filter(|r| **r >= 0)
695                .filter_map(|r| map.item_of(*r as usize))
696                .map(|i| i as i64)
697                .collect(),
698        )),
699        Event::ListActivated(i) => map.item_of(i).map(Event::ListActivated),
700        other => Some(other),
701    }
702}
703
704/// Whether a `bind_row` must build a new row (fresh anchor) or rebind a recycled cell.
705pub enum CellStep {
706    Build {
707        anchor: RNode,
708    },
709    Rebind {
710        rebind: Rc<dyn Fn(usize)>,
711        anchor: RNode,
712    },
713}
714
715/// Register a list's driver and wire its native host's data-source. Call after the list node and
716/// its native handle exist (from within the piece build; `with_tree` is acquired per op).
717pub fn install_list(node: RNode, driver: ListDriver) {
718    with_tree(|t| t.install_list(node, driver));
719}
720
721/// Tell the native list its data changed (re-query the source). Call with no borrow held.
722pub fn list_reload(node: RNode) {
723    with_tree(|t| t.list_reload(node));
724}
725
726/// Row-level deltas to the native host, in item indices: the animatable alternative to
727/// [`list_reload`], for sources that know exactly how their set changed (a live query's
728/// maintainer does).
729pub fn list_splice(node: RNode, deltas: Vec<RowDelta>) {
730    with_tree(|t| t.list_splice(node, deltas));
731}
732
733/// One snapshot of a list's rows, for [`list_sync`]: the items' identity tokens, and their
734/// section keys when the list is sectioned.
735#[derive(Clone, Copy, Debug)]
736pub struct ListRows<'a> {
737    pub tokens: &'a [u64],
738    pub sections: Option<&'a [u64]>,
739}
740
741/// What [`list_sync`] told the native host.
742#[derive(Clone, Copy, Debug, PartialEq, Eq)]
743pub enum ListSync {
744    /// The rows are the same rows in the same order: the host heard nothing.
745    Unchanged,
746    /// The host got this many row deltas ([`day_spec::props::ListPatch::Splice`]).
747    Spliced(usize),
748    /// The change was one a splice cannot express ([`diff_rows`]): the host re-queries.
749    Reloaded,
750}
751
752/// Tell the native host how the list's rows changed, from the snapshot it shows (`old`) to
753/// the one the driver now serves (`new`), with the smallest patch that says it
754/// (docs/list.md "Keyed updates"): nothing, a splice, or a reload. Section headers and
755/// supplementary rows are diffed with the items, so a sectioned list splices too. Rows that
756/// stay bound are then rebound to their items ([`list_refresh_rows`]), which is how a
757/// changed value reaches a row whose slot holds a copy. Call with no borrow held.
758pub fn list_sync(node: RNode, old: ListRows<'_>, new: ListRows<'_>) -> ListSync {
759    let Some(driver) = with_tree(|t| t.list_driver(node)) else {
760        return ListSync::Unchanged;
761    };
762    let shape = driver.supplements.shape();
763    let display = |rows: ListRows<'_>| {
764        let keys = rows.sections;
765        let key_at = |i: usize| keys.and_then(|k| k.get(i)).copied().unwrap_or_default();
766        let key_at: Option<&dyn Fn(usize) -> u64> = keys.is_some().then_some(&key_at);
767        DisplayLayout::solve(rows.tokens.len(), key_at, shape)
768            .tokens(&|i| rows.tokens.get(i).copied().unwrap_or_default())
769    };
770    let outcome = match diff_rows(&display(old), &display(new)) {
771        Some(deltas) if deltas.is_empty() => ListSync::Unchanged,
772        Some(deltas) => {
773            let count = deltas.len();
774            with_tree(|t| t.list_splice_rows(node, deltas));
775            ListSync::Spliced(count)
776        }
777        None => {
778            list_reload(node);
779            ListSync::Reloaded
780        }
781    };
782    // A reload makes the host rebind what it shows; anything less leaves the bound rows to us.
783    if outcome != ListSync::Reloaded {
784        list_refresh_rows(node);
785    }
786    outcome
787}
788
789/// A bound cell as [`list_refresh_rows`] sees it.
790pub struct LiveCell {
791    /// The physical cell (the native handle as `usize`).
792    pub key: usize,
793    /// The identity token of the row the cell was last bound to.
794    pub token: u64,
795    /// What the cell holds.
796    pub kind: CellKind,
797    /// The row's rebind writer ([`BuiltRow::rebind`]).
798    pub rebind: Rc<dyn Fn(usize)>,
799}
800
801/// Rebind every row the list has bound to the item that now carries its identity token, and
802/// lay it out again: the visible rows only, with no native reload. A row whose token left the
803/// list is skipped (the host recycles its cell). Call with no borrow held.
804pub fn list_refresh_rows(node: RNode) {
805    let Some((driver, cells)) = with_tree(|t| {
806        let driver = t.list_driver(node)?;
807        Some((driver, t.list_live_cells(node)))
808    }) else {
809        return;
810    };
811    if cells.is_empty() {
812        return;
813    }
814    let map = section_map(node);
815    // Where each bound row now sits: one pass over the rows, looking only for bound tokens.
816    let mut wanted: HashMap<u64, Vec<usize>> = HashMap::with_capacity(cells.len());
817    for (at, cell) in cells.iter().enumerate() {
818        wanted.entry(cell.token).or_default().push(at);
819    }
820    let mut found: Vec<Option<usize>> = vec![None; cells.len()];
821    match &map {
822        Some(map) => {
823            for display in 0..map.len() {
824                let (token, item) = match map.row(display) {
825                    Some(DisplayRow::Item(i)) => ((driver.token_at)(i), i),
826                    Some(DisplayRow::Header(first)) => {
827                        (map.header_token_at(display).unwrap_or_default(), first)
828                    }
829                    Some(DisplayRow::Extra(which)) => (which.token(), 0),
830                    None => continue,
831                };
832                for at in wanted.get(&token).into_iter().flatten() {
833                    found[*at] = Some(item);
834                }
835            }
836        }
837        None => {
838            for i in 0..(driver.len)() {
839                for at in wanted.get(&(driver.token_at)(i)).into_iter().flatten() {
840                    found[*at] = Some(i);
841                }
842            }
843        }
844    }
845    let mut touched = Vec::with_capacity(cells.len());
846    for (cell, item) in cells.iter().zip(found) {
847        if let Some(item) = item {
848            // A supplementary row has no item: its bindings follow their own signals.
849            if !matches!(cell.kind, CellKind::Extra(_)) {
850                (cell.rebind)(item);
851            }
852            touched.push(cell.key);
853        }
854    }
855    // The slot writes patch natives through their own `with_tree`; then lay the rows out.
856    day_reactive::flush_sync();
857    with_tree(|t| {
858        for key in touched {
859            t.list_layout_cell(node, key);
860        }
861    });
862}
863
864/// Imperatively scroll the native list to the very end of its content (a chat timeline
865/// following its newest message). A no-op while the list is empty. `animated` asks for the
866/// platform's scroll animation, which the reduce-motion setting turns off. Call with no
867/// borrow held.
868pub fn list_scroll_to_end(node: RNode, animated: bool) {
869    with_tree(|t| t.list_scroll(node, None, day_spec::RowAlign::Nearest, animated));
870}
871
872/// Imperatively scroll the native list so row `row` is visible (docs/list.md), realizing it if
873/// needed, landing where `align` says. Clamped to the row count; a no-op while the list is
874/// empty. Call with no borrow held.
875pub fn list_scroll_to_row(node: RNode, row: usize, align: day_spec::RowAlign, animated: bool) {
876    with_tree(|t| t.list_scroll(node, Some(row), align, animated));
877}
878
879/// Programmatically sync the list's selected rows (empty = clear selection). Applied by the
880/// toolkit without re-emitting a selection event. Call with no borrow held.
881pub fn list_set_selected(node: RNode, rows: Vec<usize>) {
882    with_tree(|t| t.list_set_selected(node, rows));
883}
884
885/// Enter or leave the list's native editing mode (`ListPatch::Editing`, docs/list.md).
886pub fn list_set_editing(node: RNode, on: bool) {
887    with_tree(|t| t.list_set_editing(node, on));
888}
889
890/// Programmatically reorder a list row through the same guard → commit path a native drag takes
891/// (docs/list.md): consult the piece's guard (which may retarget), rotate the snapshot, defer the
892/// app's `on_reorder`, and tell the native host to re-query. This is how the dayscript `reorder`
893/// step and the mock probe drive reordering without a native gesture. Returns the index the row
894/// actually landed at. Call with no borrow held.
895///
896/// # Errors
897///
898/// Returns the reason when `node` has no list, the list is not reorderable, an index is out of
899/// bounds, the guard denies the move, or the move would leave the row's section.
900pub fn list_try_reorder(node: RNode, from: usize, to: usize) -> Result<usize, &'static str> {
901    let hook = SCRIPTED_REORDERS.with(|m| m.borrow().get(&crate::tree::rnode_to_id(node)).cloned());
902    if let Some(hook) = hook {
903        return hook(from, to);
904    }
905    let driver = with_tree(|t| t.list_driver(node)).ok_or("no list at this node")?;
906    let Some(re) = driver.reorder.as_ref() else {
907        return Err("list is not reorderable");
908    };
909    let len = (driver.len)();
910    if from >= len || to >= len {
911        return Err("row index out of bounds");
912    }
913    // A sectioned list keeps the row in its section, as the native drag does.
914    let span = section_map(node).and_then(|map| {
915        let span = map.span(map.display_of(from)?)?;
916        Some((map, span))
917    });
918    let to = match &span {
919        Some((map, span)) => {
920            let display = map.display_of(to).unwrap_or(span.last);
921            display.clamp(span.first, span.last) - span.headers
922        }
923        None => to,
924    };
925    let accepted = (re.can_move)(from, to);
926    if accepted < 0 {
927        return Err("reorder denied by the guard");
928    }
929    let accepted = (accepted as usize).min(len - 1);
930    if let Some((_, span)) = &span
931        && span.display_of(accepted).is_none()
932    {
933        return Err("reorder would leave the row's section");
934    }
935    if accepted != from {
936        (re.moved)(from, accepted);
937    }
938    // No native animation on this path; a reload re-binds the visible rows in the new order.
939    list_reload(node);
940    Ok(accepted)
941}
942
943/// A scripted reorder for a node that reorders without a list driver: a toolkit's own sidebar
944/// (`Cap::NavReorder` Native), whose rows the nav moves itself.
945type ScriptedReorder = Rc<dyn Fn(usize, usize) -> Result<usize, &'static str>>;
946
947/// Route [`list_try_reorder`] at `node` (the dayscript `reorder` step) to `reorder`, for a piece
948/// that reorders rows with no list driver of its own. `reorder` gets the step's `from` and `to`
949/// and answers where the row landed, or why it did not move. Replaces any earlier route.
950pub fn set_scripted_reorder(
951    node: RNode,
952    reorder: impl Fn(usize, usize) -> Result<usize, &'static str> + 'static,
953) {
954    let id = crate::tree::rnode_to_id(node);
955    SCRIPTED_REORDERS.with(|m| m.borrow_mut().insert(id, Rc::new(reorder)));
956}
957
958/// Programmatically delete a list row through the same guard → commit path a native swipe takes
959/// (docs/list.md): consult the piece's guard, drop the row from the snapshot, defer the app's
960/// `on_delete`, and tell the native host to re-query. This is how the dayscript `delete_row` step
961/// and the mock probe drive deletion without a native gesture. Call with no borrow held.
962///
963/// # Errors
964///
965/// Returns the reason when `node` has no list, the list is not deletable, `index` is out of
966/// bounds, or the guard denies the delete.
967pub fn list_try_delete(node: RNode, index: usize) -> Result<(), &'static str> {
968    let driver = with_tree(|t| t.list_driver(node)).ok_or("no list at this node")?;
969    let Some(del) = driver.delete.as_ref() else {
970        return Err("list is not deletable");
971    };
972    if index >= (driver.len)() {
973        return Err("row index out of bounds");
974    }
975    if !(del.can_delete)(index) {
976        return Err("delete denied by the guard");
977    }
978    (del.deleted)(index);
979    // No native animation on this path; a reload re-binds the visible rows without the deleted
980    // one.
981    list_reload(node);
982    Ok(())
983}
984
985/// Programmatically run a swipe action through the same offer → commit path a native gesture
986/// takes (docs/list.md): pull the row's offer for the edge, refuse when the action is not in
987/// it, and defer the commit. This is how the dayscript `swipe_row` step and the mock probe
988/// drive the swipe path without a native gesture. `expect` pins the button by its label: offers
989/// are state-dependent, and a pinned step must refuse to press a different button rather
990/// than press it and complain (pressing anyway flips state the script did not mean to flip,
991/// which is how one aborted run poisons every later one). Answers the activated label.
992/// Call with no borrow held.
993///
994/// # Errors
995///
996/// Returns the reason when `node` has no list, the list has no swipe actions, `index` is out of
997/// bounds, the row's offer has no such action, or the action's label differs from `expect`.
998pub fn list_try_swipe(
999    node: RNode,
1000    index: usize,
1001    edge: day_spec::SwipeEdge,
1002    action: usize,
1003    expect: Option<&str>,
1004) -> Result<String, String> {
1005    let driver = with_tree(|t| t.list_driver(node)).ok_or("no list at this node")?;
1006    let Some(sw) = driver.swipe.as_ref() else {
1007        return Err("list has no swipe actions".into());
1008    };
1009    if index >= (driver.len)() {
1010        return Err("row index out of bounds".into());
1011    }
1012    let offer = (sw.actions_at)(index, edge);
1013    let Some(a) = offer.get(action) else {
1014        return Err("no such action in this row's offer".into());
1015    };
1016    if let Some(want) = expect
1017        && a.label != want
1018    {
1019        return Err(format!(
1020            "the offer holds {:?}, expected {want:?} — not pressed",
1021            a.label
1022        ));
1023    }
1024    let label = a.label.clone();
1025    (sw.performed)(index, edge, action);
1026    Ok(label)
1027}
1028
1029/// The host's two viewport reports, a full one and the first-visible-only one, both
1030/// enqueue-only, deduplicated, and translated to item indices: the opt-in source of
1031/// [`day_spec::Event::ListViewport`].
1032type ViewportReports = (
1033    Option<Rc<dyn Fn(usize)>>,
1034    Option<Rc<dyn Fn(day_spec::ListViewport)>>,
1035    Rc<Cell<Option<ViewportKey>>>,
1036);
1037
1038/// What makes one viewport report differ from the next: the visible items' range, the
1039/// distance to the end by its bits, and the row count.
1040type ViewportKey = (usize, usize, Option<u64>, usize);
1041
1042fn driver_viewport(
1043    node: RNode,
1044    driver: &Rc<ListDriver>,
1045    sections: Option<Rc<SectionMap>>,
1046) -> ViewportReports {
1047    // The last report, by its bits: a distance is compared exactly, and `None` is its own value.
1048    let previous: Rc<Cell<Option<ViewportKey>>> = Rc::new(Cell::new(None));
1049    if !driver.track_viewport {
1050        return (None, None, previous);
1051    }
1052    let report = {
1053        let (driver, previous) = (driver.clone(), previous.clone());
1054        // `last` is `None` from a host that reports its first visible row only: the range
1055        // then holds that one row.
1056        Rc::new(
1057            move |first: usize, last: Option<usize>, end_distance: Option<f64>| {
1058                let n = (driver.len)();
1059                let rows = match (&sections, last) {
1060                    (Some(map), Some(last)) => map.items_in(first, last),
1061                    // A header stands for its section's first item.
1062                    (Some(map), None) => {
1063                        let start = map.items_in(first, first).start;
1064                        start..(start + 1).min(n)
1065                    }
1066                    (None, Some(last)) => first.min(n)..(last + 1).min(n),
1067                    (None, None) => first.min(n)..(first + 1).min(n),
1068                };
1069                let rows = rows.start..rows.end.max(rows.start);
1070                // The row count is part of the key: a report after the rows changed always
1071                // goes through, which is what re-arms `on_end_reached`.
1072                let key = (rows.start, rows.end, end_distance.map(f64::to_bits), n);
1073                if previous.replace(Some(key)) != Some(key) {
1074                    crate::tree::enqueue_event(
1075                        crate::tree::rnode_to_id(node),
1076                        day_spec::Event::ListViewport { rows, end_distance },
1077                    );
1078                }
1079            },
1080        )
1081    };
1082    let first_only = {
1083        let report = report.clone();
1084        Rc::new(move |row: usize| report(row, None, None)) as Rc<dyn Fn(usize)>
1085    };
1086    let full = Rc::new(move |v: day_spec::ListViewport| {
1087        report(
1088            v.first,
1089            Some(v.last.max(v.first)),
1090            Some(v.end_distance.max(0.0)),
1091        );
1092    }) as Rc<dyn Fn(day_spec::ListViewport)>;
1093    (Some(first_only), Some(full), previous)
1094}
1095
1096/// Build the `ListSource` the backend calls from its data-source. `len`/`token_at` read the driver
1097/// directly (no tree). `bind_row` phases the tree borrow around the build + flush (see module doc).
1098/// With `sections`, every closure speaks display rows and translates to the driver's items.
1099pub(crate) fn make_source(
1100    node: RNode,
1101    driver: &Rc<ListDriver>,
1102    sections: Option<&Rc<SectionMap>>,
1103) -> ListSource {
1104    // The row the host means, in the driver's terms: a plain list's rows are its items.
1105    let row_of = {
1106        let sections = sections.cloned();
1107        move |display: usize| match &sections {
1108            Some(map) => map.row(display),
1109            None => Some(DisplayRow::Item(display)),
1110        }
1111    };
1112    let item_of = {
1113        let row_of = row_of.clone();
1114        move |display: usize| match row_of(display) {
1115            Some(DisplayRow::Item(i)) => Some(i),
1116            _ => None,
1117        }
1118    };
1119    let (first_visible, viewport, previous_report) =
1120        driver_viewport(node, driver, sections.cloned());
1121    let sectioned = driver.sections.is_some();
1122    let token_at: Rc<dyn Fn(usize) -> u64> = {
1123        let (d, row_of, sections) = (driver.clone(), row_of.clone(), sections.cloned());
1124        Rc::new(move |i| match row_of(i) {
1125            Some(DisplayRow::Item(i)) => (d.token_at)(i),
1126            Some(DisplayRow::Header(first)) => sections
1127                .as_ref()
1128                .and_then(|map| map.header_token_at(i))
1129                .unwrap_or_else(|| (d.token_at)(first)),
1130            Some(DisplayRow::Extra(which)) => which.token(),
1131            // Past the end (a stale pull mid-animation): any token, the row is empty.
1132            None => (d.token_at)(i),
1133        })
1134    };
1135    let reader_scroll = driver.track_reader.then(|| {
1136        let id = crate::tree::rnode_to_id(node);
1137        Rc::new(move || {
1138            // The piece counts the reader as away until the list next reports, so that report
1139            // must reach it even when it repeats the last one (a drag against the end).
1140            previous_report.set(None);
1141            crate::tree::enqueue_event(id, day_spec::Event::ListReaderScrolled);
1142        }) as Rc<dyn Fn()>
1143    });
1144    ListSource {
1145        first_visible,
1146        viewport,
1147        reader_scroll,
1148        is_supplement: sections.filter(|_| driver.supplements.any()).map(|map| {
1149            let map = map.clone();
1150            Rc::new(move |i| map.is_supplement(i)) as Rc<dyn Fn(usize) -> bool>
1151        }),
1152        len: {
1153            let (d, sections) = (driver.clone(), sections.cloned());
1154            Rc::new(move || match &sections {
1155                Some(map) => map.len(),
1156                None => (d.len)(),
1157            })
1158        },
1159        token_at: token_at.clone(),
1160        is_header: sections.filter(|_| sectioned).map(|map| {
1161            let map = map.clone();
1162            Rc::new(move |i| matches!(map.row(i), Some(DisplayRow::Header(_))))
1163                as Rc<dyn Fn(usize) -> bool>
1164        }),
1165        bind_row: bind_with(
1166            node,
1167            driver.clone(),
1168            row_of.clone(),
1169            token_at.clone(),
1170            false,
1171        ),
1172        bind_pinned: bind_with(node, driver.clone(), row_of.clone(), token_at, true),
1173        // The cell stays pooled; only its dayscript ids clear, so a hidden row past a shrunk
1174        // source stops answering lookups (`try_with_tree`: a backend may recycle while a
1175        // snapshot draw holds the borrow; the ids clear on the next pass then).
1176        layout_cell: Rc::new(move |cell, width| {
1177            // From the native cell's own layout pass: skip inside a snapshot borrow, the next
1178            // real pass corrects it (same rule as bind_row).
1179            let _ = try_with_tree(|t| t.list_layout_cell_width(node, cell as usize, width));
1180        }),
1181        cell_height: Rc::new(move |cell| {
1182            try_with_tree(|t| t.list_cell_height(node, cell as usize)).unwrap_or(0.0)
1183        }),
1184        recycle: Rc::new(move |cell| {
1185            let _ = try_with_tree(|t| t.list_recycle_cell(node, cell as usize));
1186        }),
1187        // The host's goodbye to a cell: dispose the row built in it. Never dropped under a
1188        // borrow, unlike the park above: a host tears cells down from inside a reload or a
1189        // removal Day itself started, and a release lost there is the leak this seam closes.
1190        release: Rc::new(move |cell| {
1191            let key = cell as usize;
1192            crate::tree::run_posted_or_defer(Box::new(move || {
1193                let _ = try_with_tree(|t| t.list_release_cell(node, key));
1194            }));
1195        }),
1196        // A sectioned list offers no native delete: the gesture animates one row out, and
1197        // deleting a section's last row takes its header with it, which the host's row count
1198        // would not expect (docs/list.md "Sections"). The scripted path still drives it.
1199        delete: driver
1200            .delete
1201            .as_ref()
1202            .filter(|_| !sectioned)
1203            .map(|_| day_spec::ListDelete {
1204                // Only an item deletes: a supplementary row answers no.
1205                can_delete: {
1206                    let (d, item_of) = (driver.clone(), item_of.clone());
1207                    Rc::new(move |i| {
1208                        item_of(i).is_some_and(|i| {
1209                            (d.delete.as_ref().expect("mapped from Some").can_delete)(i)
1210                        })
1211                    })
1212                },
1213                delete_row: {
1214                    let (d, item_of) = (driver.clone(), item_of.clone());
1215                    Rc::new(move |i| {
1216                        if let Some(i) = item_of(i) {
1217                            (d.delete.as_ref().expect("mapped from Some").deleted)(i);
1218                        }
1219                    })
1220                },
1221            }),
1222        // A sectioned list reorders within a section, the platforms' own rule for grouped
1223        // tables: a header never lifts, a drop past either end of the row's section lands at
1224        // that end, and the guard sees item indices (docs/list.md "Sections").
1225        reorder: driver.reorder.as_ref().map(|_| day_spec::ListReorder {
1226            can_move: {
1227                let (d, sections) = (driver.clone(), sections.cloned());
1228                Rc::new(move |from, to| {
1229                    let re = d.reorder.as_ref().expect("mapped from Some");
1230                    let Some(map) = &sections else {
1231                        return (re.can_move)(from, to);
1232                    };
1233                    let Some((span, from, to)) = map.move_within(from, to) else {
1234                        return -1;
1235                    };
1236                    let accepted = (re.can_move)(from, to);
1237                    usize::try_from(accepted)
1238                        .ok()
1239                        .and_then(|i| span.display_of(i))
1240                        .map_or(-1, |display| display as i64)
1241                })
1242            },
1243            move_row: {
1244                let (d, sections) = (driver.clone(), sections.cloned());
1245                Rc::new(move |from, to| {
1246                    let re = d.reorder.as_ref().expect("mapped from Some");
1247                    let Some(map) = &sections else {
1248                        return (re.moved)(from, to);
1249                    };
1250                    // Hosts commit only a target `can_move` accepted, which is in the section.
1251                    if let Some((_, from, to)) = map.move_within(from, to) {
1252                        (re.moved)(from, to);
1253                        map.invalidate();
1254                    }
1255                })
1256            },
1257        }),
1258        // Swipe actions belong to items: a header offers none.
1259        swipe: driver.swipe.as_ref().map(|_| day_spec::ListSwipe {
1260            actions_at: {
1261                let (d, item_of) = (driver.clone(), item_of.clone());
1262                Rc::new(move |i, e| match item_of(i) {
1263                    Some(i) => (d.swipe.as_ref().expect("mapped from Some").actions_at)(i, e),
1264                    None => Vec::new(),
1265                })
1266            },
1267            perform: {
1268                let (d, item_of) = (driver.clone(), item_of.clone());
1269                Rc::new(move |i, e, a| {
1270                    if let Some(i) = item_of(i) {
1271                        (d.swipe.as_ref().expect("mapped from Some").performed)(i, e, a);
1272                    }
1273                })
1274            },
1275        }),
1276    }
1277}
1278
1279/// `bind_row`, and with `pinned` its `bind_pinned` twin: the same build or rebind, after which a
1280/// pinned copy's ids are parked again (`ListSource::bind_pinned`).
1281fn bind_with(
1282    node: RNode,
1283    d: Rc<ListDriver>,
1284    row_of: impl Fn(usize) -> Option<DisplayRow> + 'static,
1285    token_of: Rc<dyn Fn(usize) -> u64>,
1286    pinned: bool,
1287) -> Rc<dyn Fn(usize, RawHandle)> {
1288    Rc::new(move |index, cell| {
1289        let key = cell as usize;
1290        // A stale index past the end binds as an item: the driver answers it with an empty row,
1291        // as it always has.
1292        let (kind, at) = match row_of(index) {
1293            Some(DisplayRow::Header(first)) => (CellKind::Header, first),
1294            Some(DisplayRow::Item(i)) => (CellKind::Item, i),
1295            Some(DisplayRow::Extra(which)) => (CellKind::Extra(which), 0),
1296            None => (CellKind::Item, index),
1297        };
1298        let token = token_of(index);
1299        // A backend snapshot draws the window while holding the tree borrow; if that draw
1300        // re-enters here (a lazy list realizing a row mid-`cacheDisplayInRect`), skip rather than
1301        // double-borrow; the row binds on the next real layout pass (tree.rs::try_with_tree).
1302        let Some(step) = try_with_tree(|t| t.list_prepare_cell(node, key, cell, kind, token))
1303        else {
1304            return;
1305        };
1306        match step {
1307            CellStep::Build { anchor } => {
1308                // Build outside the borrow; BuildCx re-acquires with_tree per op.
1309                let built = match (kind, d.sections.as_ref()) {
1310                    (CellKind::Header, Some(s)) => (s.build)(at, anchor),
1311                    (CellKind::Extra(which), _) => d.supplements.build(which, anchor),
1312                    _ => (d.build)(at, anchor),
1313                };
1314                with_tree(|t| t.list_store_cell(node, key, anchor, built, kind, token));
1315            }
1316            // A supplementary row has no item to rebind to.
1317            CellStep::Rebind { rebind, .. } => {
1318                if !matches!(kind, CellKind::Extra(_)) {
1319                    rebind(at);
1320                }
1321            }
1322        }
1323        // Apply the slot-write (or first bindings); reactive effects patch natives via their own
1324        // with_tree, so this too runs with no borrow held. Then lay the row out.
1325        day_reactive::flush_sync();
1326        with_tree(|t| {
1327            t.list_layout_cell(node, key);
1328            if pinned {
1329                t.list_pin_cell(node, key);
1330            }
1331        });
1332    })
1333}
1334
1335#[cfg(test)]
1336mod tests {
1337    use super::*;
1338
1339    /// Apply sequential deltas to `rows`, taking each inserted row from `new`.
1340    fn apply(old: &[u64], new: &[u64], deltas: &[RowDelta]) -> Vec<u64> {
1341        // An insert names an index; the row that goes there is whichever of `new` is missing,
1342        // found once every delta has run. Mark the holes, then fill them in order.
1343        let mut rows: Vec<Option<u64>> = old.iter().copied().map(Some).collect();
1344        for delta in deltas {
1345            match *delta {
1346                RowDelta::Insert(at) => rows.insert(at, None),
1347                RowDelta::Remove(at) => {
1348                    rows.remove(at);
1349                }
1350                RowDelta::Move(from, to) => {
1351                    let row = rows.remove(from);
1352                    rows.insert(to, row);
1353                }
1354            }
1355        }
1356        assert_eq!(rows.len(), new.len(), "row count after {deltas:?}");
1357        rows.iter()
1358            .zip(new)
1359            .map(|(row, want)| row.unwrap_or(*want))
1360            .collect()
1361    }
1362
1363    fn check(old: &[u64], new: &[u64]) -> Vec<RowDelta> {
1364        let deltas = diff_rows(old, new).expect("a splice");
1365        assert_eq!(
1366            apply(old, new, &deltas),
1367            new,
1368            "{old:?} -> {new:?} by {deltas:?}"
1369        );
1370        deltas
1371    }
1372
1373    #[test]
1374    fn equal_lists_need_no_delta() {
1375        assert_eq!(diff_rows(&[1, 2, 3], &[1, 2, 3]), Some(Vec::new()));
1376        assert_eq!(diff_rows(&[], &[]), Some(Vec::new()));
1377    }
1378
1379    #[test]
1380    fn an_append_is_one_insert_at_the_end() {
1381        assert_eq!(check(&[1, 2, 3], &[1, 2, 3, 4]), vec![RowDelta::Insert(3)]);
1382    }
1383
1384    #[test]
1385    fn a_prepend_is_one_insert_at_the_top() {
1386        assert_eq!(check(&[1, 2, 3], &[9, 1, 2, 3]), vec![RowDelta::Insert(0)]);
1387    }
1388
1389    #[test]
1390    fn inserts_in_the_middle_are_sequential() {
1391        let deltas = check(&[1, 2, 3], &[1, 7, 8, 2, 3]);
1392        assert_eq!(deltas.len(), 2);
1393        assert!(deltas.iter().all(|d| matches!(d, RowDelta::Insert(_))));
1394    }
1395
1396    #[test]
1397    fn removals_run_from_the_bottom_up() {
1398        assert_eq!(
1399            check(&[1, 2, 3, 4, 5], &[1, 3, 5]),
1400            vec![RowDelta::Remove(3), RowDelta::Remove(1)]
1401        );
1402    }
1403
1404    #[test]
1405    fn one_row_moved_is_one_move() {
1406        assert_eq!(
1407            check(&[1, 2, 3, 4], &[2, 3, 4, 1]),
1408            vec![RowDelta::Move(0, 3)]
1409        );
1410        assert_eq!(
1411            check(&[1, 2, 3, 4], &[4, 1, 2, 3]),
1412            vec![RowDelta::Move(3, 0)]
1413        );
1414        assert_eq!(check(&[1, 2, 3, 4, 5], &[1, 4, 2, 3, 5]).len(), 1);
1415    }
1416
1417    #[test]
1418    fn a_swap_of_neighbors_is_one_move() {
1419        assert_eq!(check(&[1, 2, 3], &[1, 3, 2]).len(), 1);
1420    }
1421
1422    #[test]
1423    fn a_reversal_moves_all_but_one_row() {
1424        let deltas = check(&[1, 2, 3, 4, 5], &[5, 4, 3, 2, 1]);
1425        assert_eq!(deltas.len(), 4);
1426        assert!(deltas.iter().all(|d| matches!(d, RowDelta::Move(..))));
1427    }
1428
1429    #[test]
1430    fn mixed_changes_apply_in_order() {
1431        check(&[1, 2, 3, 4, 5, 6], &[6, 9, 2, 8, 4, 1]);
1432        check(&[10, 20, 30], &[30, 15, 10, 5]);
1433        check(&[1, 2, 3, 4, 5, 6, 7, 8], &[8, 1, 3, 2, 11, 7, 12]);
1434    }
1435
1436    #[test]
1437    fn every_small_permutation_with_edits_round_trips() {
1438        // A deterministic shuffle (a multiplicative generator), over many shapes of change.
1439        let mut seed: u64 = 0x2545_F491_4F6C_DD1D;
1440        let mut next = move |bound: usize| {
1441            seed ^= seed << 13;
1442            seed ^= seed >> 7;
1443            seed ^= seed << 17;
1444            (seed % bound as u64) as usize
1445        };
1446        for round in 0..400 {
1447            let n = 1 + next(12);
1448            let old: Vec<u64> = (0..n as u64).collect();
1449            let mut new = old.clone();
1450            for _ in 0..next(6) {
1451                if !new.is_empty() {
1452                    let at = next(new.len());
1453                    new.remove(at);
1454                }
1455            }
1456            for k in 0..next(6) {
1457                let at = next(new.len() + 1);
1458                new.insert(at, 1000 + round * 10 + k as u64);
1459            }
1460            for _ in 0..next(5) {
1461                if new.len() > 1 {
1462                    let (a, b) = (next(new.len()), next(new.len()));
1463                    new.swap(a, b);
1464                }
1465            }
1466            match diff_rows(&old, &new) {
1467                Some(deltas) => assert_eq!(apply(&old, &new, &deltas), new, "{old:?} -> {new:?}"),
1468                // Only a list with nothing in common, or an empty one, reloads here.
1469                None => assert!(
1470                    new.is_empty() || !new.iter().any(|t| old.contains(t)),
1471                    "{old:?} -> {new:?} should splice"
1472                ),
1473            }
1474        }
1475    }
1476
1477    #[test]
1478    fn what_a_splice_cannot_say_reloads() {
1479        // From or to nothing, nothing in common, a repeated token on either side.
1480        assert_eq!(diff_rows(&[], &[1]), None);
1481        assert_eq!(diff_rows(&[1], &[]), None);
1482        assert_eq!(diff_rows(&[1, 2], &[3, 4]), None);
1483        assert_eq!(diff_rows(&[1, 1, 2], &[1, 2]), None);
1484        assert_eq!(diff_rows(&[1, 2], &[1, 2, 2]), None);
1485    }
1486
1487    #[test]
1488    fn a_change_past_the_limit_reloads() {
1489        let old: Vec<u64> = (0..2000).collect();
1490        let mut grown = old.clone();
1491        grown.extend(5000..5000 + SPLICE_MAX_DELTAS as u64);
1492        assert_eq!(check(&old, &grown).len(), SPLICE_MAX_DELTAS);
1493        grown.push(9999);
1494        assert_eq!(diff_rows(&old, &grown), None);
1495        let reversed: Vec<u64> = old.iter().rev().copied().collect();
1496        assert_eq!(diff_rows(&old, &reversed), None);
1497    }
1498
1499    #[test]
1500    fn the_longest_run_keeps_still() {
1501        assert_eq!(longest_increasing(&[3, 0, 1, 2]), vec![0, 1, 2]);
1502        assert_eq!(longest_increasing(&[0, 1, 2]), vec![0, 1, 2]);
1503        assert_eq!(longest_increasing(&[2, 1, 0]).len(), 1);
1504        assert_eq!(longest_increasing(&[]), [] as [usize; 0]);
1505    }
1506
1507    fn shape(header: bool, empty: bool, footer: bool) -> SupplementShape {
1508        SupplementShape {
1509            header,
1510            empty,
1511            footer,
1512            ..SupplementShape::default()
1513        }
1514    }
1515
1516    #[test]
1517    fn sections_put_a_header_before_each_run_of_one_key() {
1518        let keys = [7_u64, 7, 8, 7];
1519        let key_at = |i: usize| keys[i];
1520        let layout = DisplayLayout::solve(4, Some(&key_at), SupplementShape::default());
1521        assert_eq!(
1522            layout.rows,
1523            vec![
1524                DisplayRow::Header(0),
1525                DisplayRow::Item(0),
1526                DisplayRow::Item(1),
1527                DisplayRow::Header(2),
1528                DisplayRow::Item(2),
1529                DisplayRow::Header(3),
1530                DisplayRow::Item(3),
1531            ]
1532        );
1533        assert_eq!(layout.display, vec![1, 2, 4, 6]);
1534        // The key that recurs opens a header of its own identity.
1535        assert_ne!(layout.heads[0].1, layout.heads[2].1);
1536    }
1537
1538    #[test]
1539    fn supplements_surround_the_items_and_the_empty_state_stands_in_for_them() {
1540        let layout = DisplayLayout::solve(2, None, shape(true, true, true));
1541        assert_eq!(
1542            layout.rows,
1543            vec![
1544                DisplayRow::Extra(Supplement::Header),
1545                DisplayRow::Item(0),
1546                DisplayRow::Item(1),
1547                DisplayRow::Extra(Supplement::Footer),
1548            ]
1549        );
1550        let empty = DisplayLayout::solve(0, None, shape(true, true, true));
1551        assert_eq!(
1552            empty.rows,
1553            vec![
1554                DisplayRow::Extra(Supplement::Header),
1555                DisplayRow::Extra(Supplement::Empty),
1556                DisplayRow::Extra(Supplement::Footer),
1557            ]
1558        );
1559    }
1560
1561    #[test]
1562    fn a_sectioned_change_diffs_headers_with_the_rows() {
1563        // Two sections; a row joins the second. The headers keep their tokens, so the
1564        // change is the one insert.
1565        let tokens = |layout: &DisplayLayout, items: &[u64]| layout.tokens(&|i| items[i]);
1566        let (old_items, old_keys) = ([1_u64, 2, 3], [10_u64, 10, 20]);
1567        let (new_items, new_keys) = ([1_u64, 2, 3, 4], [10_u64, 10, 20, 20]);
1568        let old = DisplayLayout::solve(3, Some(&|i| old_keys[i]), SupplementShape::default());
1569        let new = DisplayLayout::solve(4, Some(&|i| new_keys[i]), SupplementShape::default());
1570        let (old, new) = (tokens(&old, &old_items), tokens(&new, &new_items));
1571        assert_eq!(check(&old, &new), vec![RowDelta::Insert(5)]);
1572
1573        // A row that opens a new section brings its header: two inserts.
1574        let newer_keys = [10_u64, 10, 20, 30];
1575        let newer = DisplayLayout::solve(4, Some(&|i| newer_keys[i]), SupplementShape::default());
1576        let newer = tokens(&newer, &new_items);
1577        assert_eq!(check(&old, &newer).len(), 2);
1578
1579        // The last row of a section leaves and takes its header with it.
1580        let (fewer_items, fewer_keys) = ([1_u64, 2], [10_u64, 10]);
1581        let fewer = DisplayLayout::solve(2, Some(&|i| fewer_keys[i]), SupplementShape::default());
1582        let fewer = tokens(&fewer, &fewer_items);
1583        assert_eq!(check(&old, &fewer).len(), 2);
1584    }
1585
1586    #[test]
1587    fn the_first_row_replaces_the_empty_state_by_a_splice() {
1588        let empty = DisplayLayout::solve(0, None, shape(true, true, false));
1589        let one = DisplayLayout::solve(1, None, shape(true, true, false));
1590        let (old, new) = (empty.tokens(&|_| 0), one.tokens(&|_| 42));
1591        // The header stays; the empty state goes and the row comes.
1592        let deltas = check(&old, &new);
1593        assert_eq!(deltas.len(), 2);
1594    }
1595}