Skip to main content

day_pieces/
structure.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Data-driven structure pieces: `when` (conditional), `each` (keyed children from a fixed
5//! sequence), `list` (a reactive, diffed collection), and the scoped `environment` context
6//! (`with_environment` / `environment`).
7
8use std::cell::{Cell, RefCell};
9use std::collections::HashSet;
10use std::hash::Hash;
11use std::rc::Rc;
12
13use day_core::*;
14use day_reactive::{AnyBinding, Binding, Scope, Signal, watch};
15use day_spec::props::*;
16
17use crate::{Decorate, Decorated, IntoReactive, IntoText, MenuEntry, Reactive, TextSource};
18use day_spec::{Event, Proposal, Rect, Size, kinds};
19
20// ---------------------------------------------------------------------------
21// Structure: when / each (§5.3–§5.4)
22// ---------------------------------------------------------------------------
23
24/// Reactive conditional subtree. The anchor is a layout-transparent group; the active arm
25/// lives in its own child scope, disposed on switch (§4.3).
26///
27/// A bare `when` builds nothing while the condition is false. Chain
28/// [`otherwise`](When::otherwise) for the either/or case:
29///
30/// ```ignore
31/// when(move || ok.get(), || label("Saved")).otherwise(|| label("Failed"))
32/// ```
33///
34/// Prefer a binding to a flip when both arms are the same widget with different content:
35/// `label(move || if ok.get() { "Saved" } else { "Failed" })` keeps one native label alive and
36/// costs one setter call, where a `when` swap destroys and recreates native widgets.
37pub fn when<P: Piece>(
38    cond: impl Fn() -> bool + 'static,
39    build_arm: impl Fn() -> P + 'static,
40) -> When {
41    When {
42        cond: Rc::new(cond),
43        then: Rc::new(move || AnyPiece::new(build_arm())),
44        otherwise: None,
45    }
46}
47
48/// A conditional subtree, optionally with an else arm. Built by [`when`].
49#[must_use]
50pub struct When {
51    cond: Rc<dyn Fn() -> bool>,
52    then: Rc<dyn Fn() -> AnyPiece>,
53    otherwise: Option<Rc<dyn Fn() -> AnyPiece>>,
54}
55
56#[day_macros::builder(WhenBuilder)]
57impl When {
58    /// The arm built while the condition is false. Without it, false means "no subtree".
59    ///
60    /// The two arms need not return the same `Piece` type; each is erased to [`AnyPiece`] here.
61    /// Exactly one arm is mounted at a time, in its own child scope, so flipping disposes the
62    /// outgoing arm's signals, bindings, and handlers before the incoming arm builds (§4.3).
63    pub fn otherwise<P: Piece>(mut self, build_arm: impl Fn() -> P + 'static) -> Self {
64        self.otherwise = Some(Rc::new(move || AnyPiece::new(build_arm())));
65        self
66    }
67}
68
69impl Piece for When {
70    fn build(self, cx: &mut BuildCx) -> RNode {
71        let anchor = cx.layout_only(
72            Rc::new(PassThrough),
73            Flex {
74                is_group: true,
75                ..Default::default()
76            },
77            Boundary::No,
78        );
79        let state: Rc<RefCell<Option<Scope>>> = Rc::new(RefCell::new(None));
80        // The scope this `when` is built in, captured here because `mount` below runs from a
81        // reaction, and a reaction re-runs with no scope of its own, so `Scope::child()` there
82        // would parent the incoming arm to the root scope. That misplaces the arm in two ways:
83        // it is no longer owned by the subtree it visually belongs to, and an ambient value an
84        // ancestor provided is no longer above it, so `environment`/`Ambient::ambient` inside a
85        // re-mounted arm cannot see it (docs/state.md).
86        let owner = Scope::current();
87        let When {
88            cond,
89            then,
90            otherwise,
91        } = self;
92
93        let mount = {
94            let state = state.clone();
95            move |on: bool| {
96                // Same lifetime hazard as `each`'s sync, and the same answer; see the note there.
97                if !with_tree(|t| t.node_exists(anchor)) {
98                    return;
99                }
100                // Unmount whatever is up before building the incoming arm: with two arms, every
101                // flip is a swap, and the outgoing scope must be disposed before its replacement
102                // builds so a rebuilt arm never observes the old arm's still-live bindings.
103                if let Some(scope) = state.borrow_mut().take() {
104                    scope.dispose();
105                    // Remove everything under the anchor.
106                    while with_tree(|t| t.child_count(anchor)) > 0 {
107                        let child = with_tree(|t| t.first_child(anchor));
108                        match child {
109                            Some(c) => with_tree(|t| t.remove_subtree(c)),
110                            None => break,
111                        }
112                    }
113                }
114                let arm = if on { Some(&then) } else { otherwise.as_ref() };
115                if let Some(arm) = arm {
116                    let scope = owner.enter(Scope::child);
117                    scope.enter(|| {
118                        let mut cx = BuildCx::new(anchor);
119                        let _ = arm().build(&mut cx);
120                    });
121                    *state.borrow_mut() = Some(scope);
122                }
123            }
124        };
125
126        let initial = {
127            let cond = cond.clone();
128            day_reactive::untrack(move || cond())
129        };
130        mount(initial);
131        watch(
132            move || cond(),
133            move |now, old| {
134                if Some(now) != old {
135                    mount(*now);
136                }
137            },
138        );
139        anchor
140    }
141}
142
143/// Build a row's pieces in a scope of their own, inside the scope that owns the row's slot.
144///
145/// Disposal runs children first, and a scope frees its signals before it runs its cleanups. A
146/// row's teardown reaches back through the slot (a text field seals the edit in progress with
147/// `Binding::write_teardown`, and a model slot resolves its row through its key signal), so
148/// the slot has to outlive every cleanup the row registered. With the row one scope down, its
149/// cleanups run while the slot's signals still stand.
150fn in_row_scope<R>(build: impl FnOnce() -> R) -> R {
151    Scope::child().enter(build)
152}
153
154/// A `Copy` handle to one keyed item's state: the unified `each`/`list` contract (§5.4).
155pub struct ItemSlot<T: 'static, K: 'static> {
156    sig: Signal<T>,
157    key: Signal<K>,
158}
159
160impl<T: 'static, K: 'static> Clone for ItemSlot<T, K> {
161    fn clone(&self) -> Self {
162        *self
163    }
164}
165impl<T: 'static, K: 'static> Copy for ItemSlot<T, K> {}
166
167impl<T: Clone + 'static, K: Clone + 'static> ItemSlot<T, K> {
168    /// Tracked whole-item read. **Read it inside a reactive closure**, e.g.
169    /// `label(move || slot.get())`, not eagerly. A recycling [`list()`] rebinds one physical row to
170    /// many items, and only bindings that read the slot reactively update on rebind; an eager
171    /// `let name = slot.get()` freezes the row at its first item.
172    #[must_use]
173    pub fn get(self) -> T {
174        self.sig.get()
175    }
176    /// Tracked read via a projection. Read it inside a reactive closure (see [`get`](Self::get)).
177    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
178        self.sig.with(f)
179    }
180    /// Tracked field projection (equality-gating happens in the binding layer). Read it inside a
181    /// reactive closure (see [`get`](Self::get)) so recycled rows update on rebind.
182    pub fn field<V: Clone>(self, f: impl FnOnce(&T) -> V) -> V {
183        self.sig.with(f)
184    }
185    /// Tracked identity read, so reactive ids and row actions follow cell recycling.
186    /// Read inside a closure, just like [`get`](Self::get).
187    #[must_use]
188    pub fn key(self) -> K {
189        self.key.get()
190    }
191}
192
193// ---------------------------------------------------------------------------
194// keyed / switch / load / adaptive: the structure idioms every app re-derived (§5.3)
195// ---------------------------------------------------------------------------
196
197/// A subtree keyed by a value: rebuilt when the key changes, left alone while it does not
198/// (so focus and local state survive), nothing while it is `None`.
199///
200/// ```ignore
201/// keyed(move || scene.selected.get(), |id| editor(id))
202/// ```
203///
204/// `key` is one tracked read, compared with `PartialEq` on every change. The outgoing subtree's
205/// scope is disposed before the incoming one builds, which aborts its pending tasks and
206/// subscriptions, exactly as [`when`] does. This is what `each` over a one-item list stood in
207/// for; for an either/or on a `bool`, [`when`] reads better.
208pub fn keyed<K, P>(
209    key: impl Fn() -> Option<K> + 'static,
210    build: impl Fn(&K) -> P + 'static,
211) -> Keyed<K>
212where
213    K: PartialEq + Clone + 'static,
214    P: Piece,
215{
216    Keyed {
217        key: Rc::new(key),
218        build: Rc::new(move |k| AnyPiece::new(build(k))),
219    }
220}
221
222/// One tracked read, one arm (docs/state.md): a subtree per value of `selector`, rebuilt when
223/// the value changes. The arm closure usually matches, so its arms erase with `.any()`:
224///
225/// ```ignore
226/// switch(move || tab.get(), |t| match t {
227///     Tab::Body => body_pane().any(),
228///     Tab::Headers => headers_pane().any(),
229/// })
230/// ```
231///
232/// Revisiting a value builds its arm afresh; inactive arms are not kept alive. State that must
233/// survive a switch belongs in the model, not the subtree. Replaces runs of sibling
234/// `when(move || tab.get() == …, …)`.
235pub fn switch<K, P>(selector: impl Fn() -> K + 'static, arm: impl Fn(&K) -> P + 'static) -> Keyed<K>
236where
237    K: PartialEq + Clone + 'static,
238    P: Piece,
239{
240    keyed(move || Some(selector()), arm)
241}
242
243/// The piece [`keyed`] and [`switch`] build: an anchor whose single child subtree follows a key.
244pub struct Keyed<K: 'static> {
245    key: Rc<dyn Fn() -> Option<K>>,
246    build: Rc<dyn Fn(&K) -> AnyPiece>,
247}
248
249impl<K: PartialEq + Clone + 'static> Piece for Keyed<K> {
250    fn build(self, cx: &mut BuildCx) -> RNode {
251        let anchor = cx.layout_only(
252            Rc::new(PassThrough),
253            Flex {
254                is_group: true,
255                ..Default::default()
256            },
257            Boundary::No,
258        );
259        // Captured for the same reason `When::build` captures it: the watch below runs with no
260        // scope of its own, and the incoming subtree must be owned by this piece's subtree and
261        // see its ambient values (docs/state.md).
262        let owner = Scope::current();
263        let Keyed { key, build } = self;
264        let live: Rc<RefCell<Option<Scope>>> = Rc::new(RefCell::new(None));
265        let mount = {
266            let live = live.clone();
267            move |k: &Option<K>| {
268                if !with_tree(|t| t.node_exists(anchor)) {
269                    return;
270                }
271                // The outgoing subtree first, so a rebuilt arm never observes the old arm's
272                // still-live bindings.
273                if let Some(scope) = live.borrow_mut().take() {
274                    scope.dispose();
275                    while with_tree(|t| t.child_count(anchor)) > 0 {
276                        match with_tree(|t| t.first_child(anchor)) {
277                            Some(c) => with_tree(|t| t.remove_subtree(c)),
278                            None => break,
279                        }
280                    }
281                }
282                if let Some(k) = k {
283                    let scope = owner.enter(Scope::child);
284                    scope.enter(|| {
285                        let mut cx = BuildCx::new(anchor);
286                        let _ = build(k).build(&mut cx);
287                    });
288                    *live.borrow_mut() = Some(scope);
289                }
290            }
291        };
292        let initial = {
293            let key = key.clone();
294            day_reactive::untrack(move || key())
295        };
296        mount(&initial);
297        // `watch` compares with `PartialEq`: an unchanged key never reaches `mount`.
298        watch(
299            move || key(),
300            move |now, old| {
301                if Some(now) != old {
302                    mount(now);
303                }
304            },
305        );
306        anchor
307    }
308}
309
310/// Where a [`load`] reads its state: a [`Resource`](day_reactive::Resource), a
311/// `Signal<Load<T>>`, or a closure. The marker is the same E0119 dodge as [`IntoText`].
312pub trait LoadSource<T: 'static, M>: 'static {
313    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>>;
314}
315
316/// Marker for a [`Resource`](day_reactive::Resource).
317pub struct ResourceMark;
318
319impl<T: Clone + 'static> LoadSource<T, ResourceMark> for day_reactive::Resource<T> {
320    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
321        Rc::new(move || self.signal().get())
322    }
323}
324
325impl<T: Clone + 'static> LoadSource<T, crate::SignalMark> for Signal<day_reactive::Load<T>> {
326    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
327        Rc::new(move || self.get())
328    }
329}
330
331impl<T: 'static, F: Fn() -> day_reactive::Load<T> + 'static> LoadSource<T, crate::FnMark> for F {
332    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
333        Rc::new(self)
334    }
335}
336
337/// The loaded value, handed to a [`load`]'s ready arm: `get()` is a tracked read that follows
338/// `Ready(a)` to `Ready(b)` in place, without rebuilding the arm. `Copy`, like a signal.
339pub struct Loaded<T: 'static> {
340    source: Rc<dyn Fn() -> day_reactive::Load<T>>,
341    last: Rc<RefCell<T>>,
342}
343
344impl<T: 'static> Clone for Loaded<T> {
345    fn clone(&self) -> Self {
346        Loaded {
347            source: self.source.clone(),
348            last: self.last.clone(),
349        }
350    }
351}
352
353impl<T: Clone + 'static> Loaded<T> {
354    /// The value, tracked: inside a label or a binding this follows a reload's new value.
355    /// While the state is between values (loading again, or failed) the last ready value is
356    /// returned, so the arm never sees a hole.
357    #[must_use]
358    pub fn get(&self) -> T {
359        if let day_reactive::Load::Ready(v) = (self.source)() {
360            *self.last.borrow_mut() = v.clone();
361            v
362        } else {
363            self.last.borrow().clone()
364        }
365    }
366    /// A tracked read through a projection, without cloning the whole value.
367    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
368        let v = self.get();
369        f(&v)
370    }
371}
372
373/// The three states of an async load as three subtrees (docs/async.md): the ready arm, and
374/// optional [`loading`](LoadPiece::loading) and [`failed`](LoadPiece::failed) arms (nothing is
375/// built for a state without an arm). Arms rebuild only when the *variant* changes; a new
376/// ready value updates the ready arm in place through [`Loaded::get`].
377///
378/// ```ignore
379/// load(stations, |s| station_list(s))
380///     .loading(spinner)
381///     .failed(|e| label(e.to_string()).secondary())
382/// ```
383///
384/// Whether a refetch passes through `Loading` is the [`Resource`](day_reactive::Resource)'s
385/// policy; an app that wants its stale content shown during a refresh keeps the last value in
386/// its own state and the ready arm reads it.
387pub fn load<T, P, M>(
388    state: impl LoadSource<T, M>,
389    ready: impl Fn(Loaded<T>) -> P + 'static,
390) -> LoadPiece<T>
391where
392    T: Clone + 'static,
393    P: Piece,
394{
395    LoadPiece {
396        source: state.into_load_reader(),
397        ready: Rc::new(move |v| AnyPiece::new(ready(v))),
398        loading: None,
399        failed: None,
400    }
401}
402
403/// The piece [`load`] builds.
404#[must_use]
405pub struct LoadPiece<T: 'static> {
406    source: Rc<dyn Fn() -> day_reactive::Load<T>>,
407    ready: Rc<dyn Fn(Loaded<T>) -> AnyPiece>,
408    loading: Option<Rc<dyn Fn() -> AnyPiece>>,
409    failed: Option<FailedArm>,
410}
411
412/// A [`load`]'s failed arm: the error in, the subtree out.
413type FailedArm = Rc<dyn Fn(&(dyn std::error::Error + 'static)) -> AnyPiece>;
414
415impl<T: Clone + 'static> LoadPiece<T> {
416    /// The subtree shown while loading (a spinner, a skeleton).
417    pub fn loading<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
418        self.loading = Some(Rc::new(move || AnyPiece::new(build())));
419        self
420    }
421    /// The subtree shown after a failure, given the error.
422    pub fn failed<P: Piece>(
423        mut self,
424        build: impl Fn(&(dyn std::error::Error + 'static)) -> P + 'static,
425    ) -> Self {
426        self.failed = Some(Rc::new(move |e| AnyPiece::new(build(e))));
427        self
428    }
429}
430
431/// Which arm a [`load`] shows: the variant alone, so a new ready value is an update, not a swap.
432#[derive(Clone, Copy, PartialEq, Eq)]
433enum LoadArm {
434    Loading,
435    Ready,
436    Failed,
437}
438
439impl<T: Clone + 'static> Piece for LoadPiece<T> {
440    fn build(self, cx: &mut BuildCx) -> RNode {
441        let LoadPiece {
442            source,
443            ready,
444            loading,
445            failed,
446        } = self;
447        let arm_source = source.clone();
448        let error_source = source.clone();
449        keyed(
450            move || {
451                Some(match arm_source() {
452                    day_reactive::Load::Loading => LoadArm::Loading,
453                    day_reactive::Load::Ready(_) => LoadArm::Ready,
454                    day_reactive::Load::Failed(_) => LoadArm::Failed,
455                })
456            },
457            move |arm| match arm {
458                LoadArm::Loading => loading.as_ref().map(|f| f()),
459                LoadArm::Failed => {
460                    failed
461                        .as_ref()
462                        .and_then(|f| match day_reactive::untrack(|| error_source()) {
463                            day_reactive::Load::Failed(e) => Some(f(&*e)),
464                            _ => None,
465                        })
466                }
467                LoadArm::Ready => match day_reactive::untrack(|| source()) {
468                    day_reactive::Load::Ready(v) => Some(ready(Loaded {
469                        source: source.clone(),
470                        last: Rc::new(RefCell::new(v)),
471                    })),
472                    _ => None,
473                },
474            },
475        )
476        .build(cx)
477    }
478}
479
480/// A stack that is a row on a regular width and a column on a compact one, re-laid out (never
481/// rebuilt) as the window crosses the breakpoint, so its children keep their state. The
482/// shape a label-plus-control-plus-result line wants, where wrapping members independently
483/// would tear apart what reads as one sentence.
484///
485/// ```ignore
486/// adaptive((label(t), slider(v), label(move || v.get().to_string()))).spacing(Space::S)
487/// ```
488///
489/// Stacked, the children align leading: they read as a control and the line it produced, and
490/// a centered member floats away from what it belongs to. `at` (default
491/// [`WidthClass::Compact`](day_spec::WidthClass::Compact)) is the widest class that stacks.
492pub fn adaptive<C: PieceSeq>(children: C) -> Adaptive<C> {
493    Adaptive {
494        children,
495        spacing: 0.0,
496        at: day_spec::WidthClass::Compact,
497        align: CrossAlign::Center,
498    }
499}
500
501/// The piece [`adaptive`] builds.
502#[must_use]
503pub struct Adaptive<C: PieceSeq> {
504    children: C,
505    spacing: f64,
506    at: day_spec::WidthClass,
507    align: CrossAlign,
508}
509
510#[day_macros::builder(AdaptiveBuilder)]
511impl<C: PieceSeq> Adaptive<C> {
512    /// The gap between children, in either arrangement: a [`Space`](crate::Space) step or points.
513    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
514        self.spacing = s.into();
515        self
516    }
517    /// The widest [`WidthClass`](day_spec::WidthClass) at which the children stack.
518    pub fn stack_at(mut self, at: day_spec::WidthClass) -> Self {
519        self.at = at;
520        self
521    }
522    /// The cross-axis alignment while the children sit in a row (default centered, as a
523    /// [`row`](crate::row)); stacked, they always align leading.
524    pub fn align(mut self, a: crate::VAlign) -> Self {
525        self.align = match a {
526            crate::VAlign::Top => CrossAlign::Leading,
527            crate::VAlign::Center => CrossAlign::Center,
528            crate::VAlign::Bottom => CrossAlign::Trailing,
529            crate::VAlign::FirstBaseline => CrossAlign::FirstBaseline,
530        };
531        self
532    }
533}
534
535/// The adaptive stack's layout: a [`StackLayout`] whose axis is a cell the size-class watch
536/// flips, so a crossing is a relayout of the same nodes.
537struct AdaptiveLayout {
538    axis: std::cell::Cell<Axis>,
539    spacing: f64,
540    row_align: CrossAlign,
541}
542
543impl AdaptiveLayout {
544    fn stack(&self) -> StackLayout {
545        let axis = self.axis.get();
546        StackLayout {
547            axis,
548            spacing: self.spacing,
549            align: match axis {
550                Axis::Vertical => CrossAlign::Leading,
551                Axis::Horizontal => self.row_align,
552            },
553        }
554    }
555}
556
557impl Layout for AdaptiveLayout {
558    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
559        self.stack().measure(cx, children, p)
560    }
561    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
562        self.stack().place(cx, children, bounds);
563    }
564    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
565        self.stack().baseline(cx, children, size)
566    }
567}
568
569impl<C: PieceSeq> Piece for Adaptive<C> {
570    fn build(self, cx: &mut BuildCx) -> RNode {
571        let at = self.at;
572        let stacked = move || size_class().is_some_and(|c| c.width <= at);
573        let layout = Rc::new(AdaptiveLayout {
574            axis: std::cell::Cell::new(if day_reactive::untrack(stacked) {
575                Axis::Vertical
576            } else {
577                Axis::Horizontal
578            }),
579            spacing: self.spacing,
580            row_align: self.align,
581        });
582        let node = cx.native(
583            kinds::CONTAINER,
584            &ContainerProps::default(),
585            layout.clone(),
586            Flex::default(),
587            Boundary::No,
588        );
589        cx.under(node, |cx| self.children.build_each(cx));
590        // Crossing the breakpoint flips the axis and re-lays the same children out.
591        watch(stacked, move |now: &bool, _| {
592            layout.axis.set(if *now {
593                Axis::Vertical
594            } else {
595                Axis::Horizontal
596            });
597            day_core::invalidate_size(node);
598        });
599        node
600    }
601}
602
603// ---------------------------------------------------------------------------
604// Row sources: where `each` and `list` get their rows (§5.4, docs/list.md)
605// ---------------------------------------------------------------------------
606
607/// Where a collection's rows come from. [`each`]`(source, row)` and [`list()`]`(source, row)`
608/// accept anything implementing this: plain data via [`items`]`(closure, key_of)`, or (with
609/// the `model` feature) a day-model store directly (collection order) or
610/// `store.rows(projection)` (a tracked display projection of key ids).
611pub trait RowSource {
612    /// What a row builder receives.
613    type Slot: Copy + 'static;
614    /// What selection callbacks hand the app.
615    type Ref: 'static;
616    type Conn: RowConn<Slot = Self::Slot, Ref = Self::Ref>;
617    fn connect(self) -> Self::Conn;
618}
619
620/// One collection's live connection to its data, held for the life of the `each`/`list` that
621/// [`RowSource::connect`]ed it.
622pub trait RowConn: 'static {
623    type Slot: Copy + 'static;
624    type Ref: 'static;
625
626    /// Refresh the snapshot and return the display rows as identity tokens. A tracked read: the
627    /// enclosing watch re-runs exactly when something this read depends on changes; for a
628    /// store source that is the collection's shape (or the projection's own reads), never the
629    /// fields a row merely displays.
630    fn refresh(&self) -> Vec<u64>;
631    /// Row count of the current snapshot (no tracking).
632    fn len(&self) -> usize;
633    fn is_empty(&self) -> bool {
634        self.len() == 0
635    }
636    /// Identity token of row `index` in the current snapshot.
637    fn token_at(&self, index: usize) -> u64;
638    /// The current tokens, no refresh and no tracking; the reorder/delete echo compares these.
639    fn tokens_now(&self) -> Vec<u64>;
640    /// A fresh slot for row `index` (`None` on a stale mid-animation pull). Call inside the
641    /// row's scope: plain-data slots allocate their signals here.
642    fn slot_at(&self, index: usize) -> Option<Self::Slot>;
643    /// Point an existing slot at row `index`: the recycle write.
644    fn rebind(&self, slot: &Self::Slot, index: usize);
645    /// The selection currency for row `index`.
646    fn select_ref(&self, index: usize) -> Option<Self::Ref>;
647    /// Whether row values reach existing rows only through reload→rebind. Plain-data rows say
648    /// true (their slots hold copies); store rows say false (values flow through the store's
649    /// per-field notifications), which lets `list` skip the native reload entirely when the
650    /// row set is unchanged.
651    fn values_flow_by_reload(&self) -> bool;
652    /// What changed since the last refresh, if the source can say precisely: sequential
653    /// row deltas a host can animate. `None` means unknown: the list reloads, which is
654    /// always correct. Only sources that maintain their set incrementally (a live query)
655    /// answer `Some`.
656    fn take_row_events(&self) -> Option<Vec<day_spec::props::RowDelta>> {
657        None
658    }
659    /// Rotate the snapshot for a committed native move (display indices).
660    fn commit_move(&self, from: usize, to: usize);
661    /// Drop a row from the snapshot for a committed native delete.
662    fn commit_delete(&self, index: usize);
663}
664
665/// Plain-data rows: an items closure plus a key function, as in
666/// `list(items(model::ordered, |i: &Item| i.id), row_view)`.
667pub fn items<T, K>(
668    f: impl Fn() -> Vec<T> + 'static,
669    key_of: impl Fn(&T) -> K + 'static,
670) -> Items<T, K>
671where
672    T: Clone + 'static,
673    K: Clone + Hash + 'static,
674{
675    Items {
676        f: Rc::new(f),
677        key_of: Rc::new(key_of),
678    }
679}
680
681/// The plain-data [`RowSource`] built by [`items`].
682pub struct Items<T: 'static, K: 'static> {
683    f: Rc<dyn Fn() -> Vec<T>>,
684    key_of: Rc<dyn Fn(&T) -> K>,
685}
686
687impl<T: Clone + 'static, K: Clone + Hash + 'static> RowSource for Items<T, K> {
688    type Slot = ItemSlot<T, K>;
689    type Ref = K;
690    type Conn = ItemsConn<T, K>;
691    fn connect(self) -> ItemsConn<T, K> {
692        ItemsConn {
693            f: self.f,
694            key_of: self.key_of,
695            snapshot: RefCell::new(Vec::new()),
696            tokens: RefCell::new(Vec::new()),
697        }
698    }
699}
700
701/// [`Items`]' connection: the current data snapshot the slots read from.
702pub struct ItemsConn<T: 'static, K: 'static> {
703    f: Rc<dyn Fn() -> Vec<T>>,
704    key_of: Rc<dyn Fn(&T) -> K>,
705    snapshot: RefCell<Vec<T>>,
706    tokens: RefCell<Vec<u64>>,
707}
708
709impl<T: Clone + 'static, K: Clone + Hash + 'static> RowConn for ItemsConn<T, K> {
710    type Slot = ItemSlot<T, K>;
711    type Ref = K;
712
713    fn refresh(&self) -> Vec<u64> {
714        let its = (self.f)();
715        let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
716        *self.snapshot.borrow_mut() = its;
717        (*self.tokens.borrow_mut()).clone_from(&toks);
718        toks
719    }
720    fn len(&self) -> usize {
721        self.snapshot.borrow().len()
722    }
723    fn token_at(&self, index: usize) -> u64 {
724        self.tokens.borrow().get(index).copied().unwrap_or(0)
725    }
726    fn tokens_now(&self) -> Vec<u64> {
727        self.tokens.borrow().clone()
728    }
729    fn slot_at(&self, index: usize) -> Option<ItemSlot<T, K>> {
730        let item = self.snapshot.borrow().get(index).cloned()?;
731        let key = (self.key_of)(&item);
732        Some(ItemSlot {
733            sig: Signal::new(item),
734            key: Signal::new(key),
735        })
736    }
737    fn rebind(&self, slot: &ItemSlot<T, K>, index: usize) {
738        let Some(item) = self.snapshot.borrow().get(index).cloned() else {
739            return; // stale recycle index: skip, the next bind corrects it
740        };
741        slot.key.set((self.key_of)(&item));
742        slot.sig.set(item);
743    }
744    fn select_ref(&self, index: usize) -> Option<K> {
745        self.snapshot.borrow().get(index).map(|t| (self.key_of)(t))
746    }
747    fn values_flow_by_reload(&self) -> bool {
748        true
749    }
750    fn commit_move(&self, from: usize, to: usize) {
751        let mut snap = self.snapshot.borrow_mut();
752        let mut toks = self.tokens.borrow_mut();
753        if from >= snap.len() || to >= snap.len() {
754            return;
755        }
756        let item = snap.remove(from);
757        snap.insert(to, item);
758        let tok = toks.remove(from);
759        toks.insert(to, tok);
760    }
761    fn commit_delete(&self, index: usize) {
762        let mut snap = self.snapshot.borrow_mut();
763        let mut toks = self.tokens.borrow_mut();
764        if index >= snap.len() {
765            return;
766        }
767        snap.remove(index);
768        toks.remove(index);
769    }
770}
771
772struct EachRow<S: 'static> {
773    token: u64,
774    slot: S,
775    scope: Scope,
776    root: RNode,
777}
778
779/// Reactive keyed collection (§5.4): keyed diff, per-key child scopes, slot rebinds for
780/// surviving rows, debug key-uniqueness assertion. Takes any [`RowSource`].
781///
782/// # Panics
783///
784/// In debug builds, panics when two rows of one update share a key.
785pub fn each<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> impl Piece
786where
787    S: RowSource + 'static,
788    P: Piece,
789{
790    piece_fn(move |cx| {
791        let anchor = cx.layout_only(
792            Rc::new(PassThrough),
793            Flex {
794                is_group: true,
795                ..Default::default()
796            },
797            Boundary::No,
798        );
799        // The scope this `each` is built in. `sync` below runs from a reaction, where
800        // `Scope::child()` would parent a new row to the root scope instead of to this piece;
801        // see the same capture in `When::build` for why that matters (docs/state.md).
802        let owner = Scope::current();
803        let conn = Rc::new(source.connect());
804        let rows: Rc<RefCell<Vec<EachRow<S::Slot>>>> = Rc::new(RefCell::new(Vec::new()));
805        let build_row = Rc::new(build_row);
806
807        let sync = {
808            let rows = rows.clone();
809            let conn = conn.clone();
810            let build_row = build_row.clone();
811            move |tokens: &Vec<u64>| {
812                // The reaction driving this closure can outlive the subtree it builds into: a
813                // page swapped out of a nav, a `when` arm closed above us, and the anchor is gone
814                // while the reaction is still subscribed. Building into a removed parent panics in
815                // `Tree::attach`, and that panic is contained at the native event boundary, which
816                // abandons the rest of the drain, so every reaction queued behind it is skipped
817                // and the UI stops updating until something rebuilds it. An anchor that is no
818                // longer in the tree has nothing to sync, so leave quietly.
819                if !with_tree(|t| t.node_exists(anchor)) {
820                    return;
821                }
822                if cfg!(debug_assertions) {
823                    let mut seen = HashSet::new();
824                    for k in tokens {
825                        assert!(seen.insert(*k), "day: duplicate key in `each` diff");
826                    }
827                }
828                let mut old = std::mem::take(&mut *rows.borrow_mut());
829                let mut next: Vec<EachRow<S::Slot>> = Vec::with_capacity(tokens.len());
830                for (index, tok) in tokens.iter().enumerate() {
831                    if let Some(pos) = old.iter().position(|r| r.token == *tok) {
832                        let row = old.remove(pos);
833                        // Surviving row: one rebind (plain data refreshes the slot's copy;
834                        // a store slot is a no-op when the key is unchanged).
835                        conn.rebind(&row.slot, index);
836                        next.push(row);
837                    } else {
838                        let scope = owner.enter(Scope::child);
839                        let built = scope.enter(|| {
840                            let slot = conn.slot_at(index)?;
841                            let mut cx = BuildCx::new(anchor);
842                            Some((slot, in_row_scope(|| build_row(slot).build(&mut cx))))
843                        });
844                        match built {
845                            Some((slot, root)) => next.push(EachRow {
846                                token: *tok,
847                                slot,
848                                scope,
849                                root,
850                            }),
851                            None => scope.dispose(),
852                        }
853                    }
854                }
855                // Removals.
856                for row in old {
857                    row.scope.dispose();
858                    with_tree(|t| t.remove_subtree(row.root));
859                }
860                // Order: reattach in the new sequence.
861                let order: Vec<RNode> = next.iter().map(|r| r.root).collect();
862                with_tree(|t| t.reorder_children(anchor, order));
863                *rows.borrow_mut() = next;
864            }
865        };
866
867        let initial = {
868            let conn = conn.clone();
869            day_reactive::untrack(move || conn.refresh())
870        };
871        sync(&initial);
872        let conn2 = conn.clone();
873        watch(move || conn2.refresh(), move |new, _| sync(new));
874        anchor
875    })
876}
877
878// ---------------------------------------------------------------------------
879// `list`: native recycling list (docs/list.md, §10)
880// ---------------------------------------------------------------------------
881
882/// Stable u64 identity token for a key, for the native list's diffing.
883fn key_token<K: Hash>(k: &K) -> u64 {
884    use std::hash::Hasher;
885    let mut h = std::collections::hash_map::DefaultHasher::new();
886    k.hash(&mut h);
887    h.finish()
888}
889
890/// A native recycling list: the platform widget owns scrolling + cell reuse; Day builds each
891/// visible row once and *rebinds* it as cells recycle. Takes any [`RowSource`]; shares the row
892/// contract with [`each`], so migrating a collection between them is a one-word change.
893#[must_use]
894pub struct List<S: RowSource> {
895    source: Option<S>,
896    build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
897    row_height: RowHeight,
898    on_select: Option<Rc<dyn Fn(S::Ref)>>,
899    on_activate: Option<Rc<dyn Fn(S::Ref)>>,
900    on_selection: Option<SelectionFn<S::Ref>>,
901    multi_select: bool,
902    selected_rows: Option<Rc<dyn Fn() -> Vec<usize>>>,
903    selection: Option<ListSelection<S::Ref>>,
904    scroll_to_end: Option<day_reactive::Trigger>,
905    scroll_to_row: Option<RowCommand>,
906    visible_rows: Option<AnyBinding<std::ops::Range<usize>>>,
907    follow_end: Option<f64>,
908    end_reached: Option<(f64, Rc<dyn Fn()>)>,
909    header: Option<SlotBuild>,
910    footer: Option<SlotBuild>,
911    empty: Option<SlotBuild>,
912    content_padding: day_spec::Insets,
913    reorder: Option<Reorder>,
914    delete: Option<Delete>,
915    swipe_leading: Option<SwipeProvider>,
916    swipe_trailing: Option<SwipeProvider>,
917    separators: Option<bool>,
918    inset_grouped: bool,
919    editing: crate::Reactive<bool>,
920    sections: Option<ListSections<S::Slot>>,
921}
922
923/// [`List::sections`]: each item's section key (by index, hashed to a token) and the header
924/// builder, which receives the slot of its section's first item.
925struct ListSections<Slot> {
926    key: Rc<dyn Fn(usize) -> u64>,
927    header: Rc<dyn Fn(Slot) -> AnyPiece>,
928}
929
930/// The full-set selection callback, aliased for the field above.
931type SelectionFn<R> = Rc<dyn Fn(Vec<R>)>;
932
933/// [`List::scroll_to_row`]'s binding, erased over what it holds (a bare index or a
934/// [`RowTarget`]): a tracked read of the pending command, and the write that consumes it.
935struct RowCommand {
936    pending: Rc<dyn Fn() -> Option<RowTarget>>,
937    consume: Rc<dyn Fn()>,
938}
939
940/// A list's header, footer or empty-state builder: called once per cell the host gives it.
941type SlotBuild = Rc<dyn Fn() -> AnyPiece>;
942
943/// One programmatic scroll of a [`list()`], written to its
944/// [`scroll_to_row`](ListBuilder::scroll_to_row) binding: the row, where it lands, and whether
945/// the list animates there (docs/list.md "Programmatic scrolling").
946///
947/// ```ignore
948/// jump.set(Some(RowTarget::new(250)));                               // reveal, animated
949/// jump.set(Some(RowTarget::new(0).align(RowAlign::Start).instant())); // snap to the top
950/// ```
951#[derive(Clone, Copy, Debug, PartialEq, Eq)]
952pub struct RowTarget {
953    row: usize,
954    align: day_spec::RowAlign,
955    animated: bool,
956}
957
958impl RowTarget {
959    /// Scroll to `row` (an item index, clamped to the list) with the least movement that
960    /// shows it, animated.
961    #[must_use]
962    pub fn new(row: usize) -> Self {
963        RowTarget {
964            row,
965            align: day_spec::RowAlign::Nearest,
966            animated: true,
967        }
968    }
969    /// Where the row lands in the viewport (probe `Cap::ListScrollAlign`; where it is
970    /// unsupported the row is revealed where the platform puts it).
971    #[must_use]
972    pub fn align(mut self, align: day_spec::RowAlign) -> Self {
973        self.align = align;
974        self
975    }
976    /// Jump there without the scroll animation.
977    #[must_use]
978    pub fn instant(mut self) -> Self {
979        self.animated = false;
980        self
981    }
982}
983
984impl From<usize> for RowTarget {
985    fn from(row: usize) -> Self {
986        RowTarget::new(row)
987    }
988}
989
990/// A row reference that names its row by a key: what [`List::selection`] binds. A day-model
991/// store's rows (an `Elem`) answer their key, which is also the row's identity token.
992pub trait SelectionKey {
993    fn selection_key(&self) -> u64;
994}
995
996/// [`List::selection`]'s two directions: the key to select (a tracked read) and the write that
997/// reports the user's choice.
998struct ListSelection<R> {
999    key: Rc<dyn Fn() -> Option<u64>>,
1000    write: Rc<dyn Fn(Option<u64>)>,
1001    key_of: Rc<dyn Fn(&R) -> u64>,
1002}
1003
1004// ---------------------------------------------------------------------------
1005// List items (docs/list.md "List items")
1006// ---------------------------------------------------------------------------
1007
1008/// A list item's leading glyph: an app vector, which may follow a signal, or a standard symbol.
1009#[derive(Clone)]
1010enum ItemIcon {
1011    Vector(Reactive<day_spec::VectorName>),
1012    Symbol(day_spec::Symbol),
1013}
1014
1015impl ItemIcon {
1016    /// The glyph as the spec names it; `tracked` subscribes a reactive vector.
1017    fn spec(&self, tracked: bool) -> day_spec::Icon {
1018        match self {
1019            ItemIcon::Vector(r) => {
1020                let name = if tracked { r.get() } else { r.get_untracked() };
1021                day_spec::Icon::Image(name.as_str().to_owned())
1022            }
1023            ItemIcon::Symbol(s) => day_spec::Icon::Symbol(*s),
1024        }
1025    }
1026}
1027
1028/// A list row's standard content, built by [`list_item`] (docs/list.md "List items").
1029#[must_use]
1030pub struct ListItem {
1031    title: TextSource,
1032    subtitle: Option<TextSource>,
1033    detail: Option<TextSource>,
1034    icon: Option<ItemIcon>,
1035    icon_tint: Option<Reactive<day_spec::Ink>>,
1036    checked: Option<Reactive<bool>>,
1037}
1038
1039/// A list row's standard content: a leading icon, a title, an optional subtitle and trailing
1040/// detail, and a check mark, drawn the way the platform draws its own list rows (docs/list.md
1041/// "List items"). UIKit shows it with the cell's default content configuration, Android as a
1042/// Material list item, AppKit as a table cell's image and text, GTK as a row box; elsewhere
1043/// the piece composes the same parts. Each part may follow a signal, and changes in place, so
1044/// a recycled row tracks its item.
1045///
1046/// ```ignore
1047/// list(scene.items.rows(keys), move |slot| {
1048///     list_item(move || slot.name().read())
1049///         .icon(move || slot.kind().read().icon())
1050///         .icon_tint(move || slot.tint().read().color())
1051///         .checked(move || slot.done().read())
1052/// })
1053/// ```
1054pub fn list_item<M>(title: impl IntoText<M>) -> ListItem {
1055    ListItem {
1056        title: title.into_text(),
1057        subtitle: None,
1058        detail: None,
1059        icon: None,
1060        icon_tint: None,
1061        checked: None,
1062    }
1063}
1064
1065#[day_macros::builder(ListItemBuilder)]
1066impl ListItem {
1067    /// A second line under the title, in the platform's secondary style.
1068    pub fn subtitle<M>(mut self, text: impl IntoText<M>) -> Self {
1069        self.subtitle = Some(text.into_text());
1070        self
1071    }
1072    /// Trailing text, such as a count or a value, in the platform's secondary style.
1073    pub fn detail<M>(mut self, text: impl IntoText<M>) -> Self {
1074        self.detail = Some(text.into_text());
1075        self
1076    }
1077    /// The leading glyph: an app vector (`res::vectors::…`), drawn as a template in the
1078    /// foreground color unless [`Self::icon_tint`] names one. A signal or closure swaps it in
1079    /// place.
1080    pub fn icon<M>(mut self, name: impl IntoReactive<day_spec::VectorName, M>) -> Self {
1081        self.icon = Some(ItemIcon::Vector(name.into_reactive()));
1082        self
1083    }
1084    /// The leading glyph as a standard symbol.
1085    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1086        self.icon = Some(ItemIcon::Symbol(symbol));
1087        self
1088    }
1089    /// The leading glyph's color.
1090    pub fn icon_tint<M>(mut self, color: impl IntoReactive<day_spec::Ink, M>) -> Self {
1091        self.icon_tint = Some(color.into_reactive());
1092        self
1093    }
1094    /// A trailing check mark while `on` holds: the platform's mark for a chosen or completed
1095    /// row, announced as selected.
1096    pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
1097        self.checked = Some(on.into_reactive());
1098        self
1099    }
1100}
1101
1102impl Piece for ListItem {
1103    fn build(self, cx: &mut BuildCx) -> RNode {
1104        if day_core::capability(day_spec::Cap::ListItem) == day_spec::Support::Native {
1105            self.build_native(cx)
1106        } else {
1107            self.compose().build(cx)
1108        }
1109    }
1110}
1111
1112impl ListItem {
1113    /// The platform's own row content (`kinds::LIST_ITEM`), each part patched in place.
1114    fn build_native(self, cx: &mut BuildCx) -> RNode {
1115        let text = |t: &Option<TextSource>| t.as_ref().map_or_default(TextSource::initial);
1116        let props = ListItemProps {
1117            title: self.title.initial(),
1118            subtitle: text(&self.subtitle),
1119            detail: text(&self.detail),
1120            icon: self.icon.as_ref().map(|i| i.spec(false)),
1121            icon_tint: self.icon_tint.as_ref().map(Reactive::get_untracked),
1122            checked: self.checked.as_ref().is_some_and(Reactive::get_untracked),
1123        };
1124        // The platform's whole row: it sizes its own height (docs/list.md "Row metrics").
1125        let node = cx.leaf(
1126            kinds::LIST_ITEM,
1127            &props,
1128            Flex {
1129                grow_w: true,
1130                whole_row: true,
1131                ..Default::default()
1132            },
1133        );
1134        let patch = move |p: ListItemPatch, size: bool| {
1135            with_tree(|t| t.patch(node, Box::new(p), size));
1136        };
1137        let bind_text =
1138            |src: Option<TextSource>, seed: String, make: fn(String) -> ListItemPatch| {
1139                if let Some(src @ TextSource::Dyn(_)) = src {
1140                    day_reactive::bind_seeded(
1141                        seed,
1142                        move || src.resolve(),
1143                        move |t: &String| patch(make(t.clone()), true),
1144                    );
1145                }
1146            };
1147        bind_text(Some(self.title), props.title, ListItemPatch::Title);
1148        bind_text(self.subtitle, props.subtitle, ListItemPatch::Subtitle);
1149        bind_text(self.detail, props.detail, ListItemPatch::Detail);
1150        if let Some(icon @ ItemIcon::Vector(Reactive::Dyn(_))) = self.icon {
1151            day_reactive::bind_seeded(
1152                props.icon,
1153                move || Some(icon.spec(true)),
1154                move |i| patch(ListItemPatch::Icon(i.clone()), false),
1155            );
1156        }
1157        if let Some(tint @ Reactive::Dyn(_)) = self.icon_tint {
1158            day_reactive::bind_seeded(
1159                props.icon_tint,
1160                move || Some(tint.get()),
1161                move |c| patch(ListItemPatch::IconTint(*c), false),
1162            );
1163        }
1164        if let Some(on @ Reactive::Dyn(_)) = self.checked {
1165            day_reactive::bind_seeded(
1166                props.checked,
1167                move || on.get(),
1168                move |b: &bool| patch(ListItemPatch::Checked(*b), true),
1169            );
1170        }
1171        node
1172    }
1173
1174    /// The same parts from plain pieces, where the toolkit has no row content of its own.
1175    fn compose(self) -> impl Piece {
1176        use crate::{column, image, label, row, vector, when};
1177        let tint = self.icon_tint;
1178        let leading = self.icon.map(move |icon| match icon {
1179            ItemIcon::Vector(src) => {
1180                let glyph = vector(move || src.get()).template();
1181                match tint {
1182                    Some(t) => glyph
1183                        .tint(move || t.get())
1184                        .decorative()
1185                        .frame(20.0, 20.0)
1186                        .any(),
1187                    None => glyph.decorative().frame(20.0, 20.0).any(),
1188                }
1189            }
1190            ItemIcon::Symbol(sym) => match sym.outline_svg() {
1191                Some(svg) => image(svg.into_bytes()).template().frame(20.0, 20.0).any(),
1192                None => crate::spacer().frame(20.0, 20.0).any(),
1193            },
1194        });
1195        let titles = column((
1196            label(self.title),
1197            self.subtitle
1198                .map(|t| label(t).font(day_spec::Font::Footnote).secondary()),
1199        ))
1200        .spacing(2.0)
1201        .align(crate::HAlign::Leading)
1202        .grow(Dimension::Width);
1203        let detail = self.detail.map(|t| label(t).secondary());
1204        let checked = self.checked.clone();
1205        let mark = checked.map(|on| {
1206            when(
1207                move || on.get(),
1208                || {
1209                    let svg = day_spec::Symbol::Check.outline_svg().unwrap_or_default();
1210                    image(svg.into_bytes())
1211                        .template()
1212                        .decorative()
1213                        .frame(16.0, 16.0)
1214                },
1215            )
1216        });
1217        let selected = self.checked;
1218        row((leading, titles, detail, mark))
1219            .spacing(crate::Space::M)
1220            .align(crate::VAlign::Center)
1221            .grow(Dimension::Width)
1222            .a11y(move |a| match selected {
1223                Some(on) => a.selected(move || on.get()),
1224                None => a,
1225            })
1226    }
1227}
1228
1229/// A row's swipe-action offer, aliased for the fields above: called with the row index at
1230/// gesture time, so the actions reflect the row's current state (docs/list.md).
1231type SwipeProvider = Rc<dyn Fn(usize) -> Vec<SwipeAction>>;
1232
1233/// One button in a row's swipe-action offer (docs/list.md): what the platform reveals as the
1234/// user drags a row aside, built by [`swipe_action`]. Holds the label, the styling hints the
1235/// backend maps onto its own affordance, and the handler the activation runs.
1236#[must_use]
1237pub struct SwipeAction {
1238    label: TextSource,
1239    destructive: bool,
1240    tint: Option<day_spec::Ink>,
1241    symbol: Option<day_spec::Symbol>,
1242    handler: Rc<dyn Fn()>,
1243}
1244
1245/// Build a swipe action with `label` (a literal, a `res::str::…` text, a signal or a closure;
1246/// resolved in the current locale each time the offer is pulled). Chain
1247/// [`destructive`](SwipeAction::destructive) or [`tint`](SwipeAction::tint) for styling and
1248/// [`action`](SwipeAction::action) for the work; an action without a handler still reveals and
1249/// dismisses, but does nothing.
1250pub fn swipe_action<M>(label: impl IntoText<M>) -> SwipeAction {
1251    SwipeAction {
1252        label: label.into_text(),
1253        destructive: false,
1254        tint: None,
1255        symbol: None,
1256        handler: Rc::new(|| {}),
1257    }
1258}
1259
1260impl SwipeAction {
1261    /// Mark the action destructive: the platform styles it as such (red, on the Apple
1262    /// toolkits) and may animate the row away on activation.
1263    pub fn destructive(mut self) -> Self {
1264        self.destructive = true;
1265        self
1266    }
1267    /// The button's background color, where the platform honors one. Left unset, the platform
1268    /// picks its own default (gray, with red for destructive actions, on the Apple toolkits).
1269    pub fn tint(mut self, color: impl Into<day_spec::Ink>) -> Self {
1270        self.tint = Some(color.into());
1271        self
1272    }
1273    /// A glyph for the button where the platform draws one: above the label on macOS, in
1274    /// place of it on iOS (docs/list.md). The label still matters: it is the accessibility
1275    /// name, and the platforms without a glyph slot show it alone.
1276    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1277        self.symbol = Some(symbol);
1278        self
1279    }
1280    /// The work an activation runs. Called on the main thread at the next event drain, never
1281    /// inside the native gesture callback; the row index is the one the offer was pulled for,
1282    /// so capture what the action needs when building it.
1283    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
1284        self.handler = Rc::new(f);
1285        self
1286    }
1287}
1288
1289/// Drag-to-reorder for a [`list()`] (docs/list.md): the handler that applies a committed move,
1290/// an optional guard consulted while the drag is live, and whether the gesture is offered
1291/// right now. A list is reorderable exactly when it carries one of these
1292/// (`list(..).reorderable(Reorder::new(f))`).
1293///
1294/// The platform's own mechanism does the dragging (the macOS drop gap, the iOS long-press
1295/// lift, Android's `ItemTouchHelper`) where the backend supports it (probe `Cap::ListReorder`;
1296/// docs/list.md has the matrix).
1297#[derive(Clone)]
1298#[must_use]
1299pub struct Reorder {
1300    moved: Rc<dyn Fn(usize, usize)>,
1301    guard: Option<Rc<dyn Fn(usize, usize) -> ReorderVerdict>>,
1302    enabled: Reactive<bool>,
1303}
1304
1305impl Reorder {
1306    /// `moved(from, to)` runs after a committed move: row `from` now sits at row `to`. Apply the
1307    /// same rotation to the backing data (`let it = v.remove(from); v.insert(to, it);`), and
1308    /// persist it if the order should survive a relaunch. Runs on the main thread at the next
1309    /// event drain, never inside the native drop callback.
1310    pub fn new(moved: impl Fn(usize, usize) + 'static) -> Reorder {
1311        Reorder {
1312            moved: Rc::new(moved),
1313            guard: None,
1314            enabled: Reactive::Const(true),
1315        }
1316    }
1317    /// Veto or override drops while the drag is live: called synchronously from the native
1318    /// validate hook with `(from, proposed_to)`. Return [`ReorderVerdict::Deny`] to refuse,
1319    /// [`ReorderVerdict::Retarget`] to accept at a different index (a "pinned rows" pattern), or
1320    /// [`ReorderVerdict::Allow`] to accept as proposed (the default without a guard). Keep it
1321    /// pure (read state, decide, return); it runs inside the platform's drag callback.
1322    pub fn guard(mut self, g: impl Fn(usize, usize) -> ReorderVerdict + 'static) -> Reorder {
1323        self.guard = Some(Rc::new(g));
1324        self
1325    }
1326    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
1327    /// `bool`, read when the platform asks whether a drag may begin, so an edit mode or a
1328    /// loading state can withhold it without rebuilding the list.
1329    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Reorder {
1330        self.enabled = on.into_reactive();
1331        self
1332    }
1333}
1334
1335/// Swipe-to-delete for a [`list()`] (docs/list.md): the handler that applies a committed delete,
1336/// the label the platform puts on its affordance, an optional per-row guard, and whether the
1337/// gesture is offered right now. A list is deletable exactly when it carries one of these
1338/// (`list(..).deletable(Delete::new(f))`).
1339///
1340/// The platform's delete gesture does the work (the iOS trailing swipe action, Android's
1341/// `ItemTouchHelper` swipe, ArkUI's `ListItem` swipe action) where the backend supports it
1342/// (probe `Cap::ListDelete`). The desktop toolkits answer `Unsupported`, so a list that must be
1343/// editable everywhere pairs this with an explicit control (a menu item or a button).
1344#[derive(Clone)]
1345#[must_use]
1346pub struct Delete {
1347    deleted: Rc<dyn Fn(usize)>,
1348    label: Option<TextSource>,
1349    guard: Option<Rc<dyn Fn(usize) -> bool>>,
1350    enabled: Reactive<bool>,
1351}
1352
1353impl Delete {
1354    /// `deleted(index)` runs after a committed delete: row `index` is gone. Apply the same
1355    /// removal to the backing data (`v.remove(index)`), and persist it if the change should
1356    /// survive a relaunch. Runs on the main thread at the next event drain, never inside the
1357    /// native swipe callback.
1358    pub fn new(deleted: impl Fn(usize) + 'static) -> Delete {
1359        Delete {
1360            deleted: Rc::new(deleted),
1361            label: None,
1362            guard: None,
1363            enabled: Reactive::Const(true),
1364        }
1365    }
1366    /// The word the platform puts on its delete affordance (`res::str::delete()`). Resolved in
1367    /// the locale current when the list builds. Left unset, each backend falls back to a trash
1368    /// glyph rather than shipping an English word into every locale.
1369    pub fn label<M>(mut self, text: impl IntoText<M>) -> Delete {
1370        self.label = Some(text.into_text());
1371        self
1372    }
1373    /// Protect individual rows: called synchronously before the affordance is offered, so a row
1374    /// that answers `false` shows no delete action rather than one that fails on use. Keep it
1375    /// pure; it runs inside the platform's swipe callback.
1376    pub fn guard(mut self, g: impl Fn(usize) -> bool + 'static) -> Delete {
1377        self.guard = Some(Rc::new(g));
1378        self
1379    }
1380    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
1381    /// `bool`, read when the platform asks whether a row may be deleted.
1382    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Delete {
1383        self.enabled = on.into_reactive();
1384        self
1385    }
1386}
1387
1388/// A reorder guard's verdict on a proposed row move (docs/list.md): consulted synchronously from
1389/// the native drag's validate hook, so the affordance (gap, insertion mark, forbidden cursor)
1390/// reflects the answer while the user is still dragging.
1391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1392pub enum ReorderVerdict {
1393    /// Accept the drop where proposed.
1394    Allow,
1395    /// Refuse the drop (the row springs back; most backends show a forbidden cursor live).
1396    Deny,
1397    /// Accept the drop, but at this row index instead of the proposed one.
1398    Retarget(usize),
1399}
1400
1401/// Build a recycling list from a [`RowSource`] and a row builder:
1402/// `list(items(rows_fn, key_of), row_view)` for plain data, `list(store, row_view)` (or
1403/// `list(store.rows(projection), …)`) for a day-model store.
1404pub fn list<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> List<S>
1405where
1406    S: RowSource + 'static,
1407    P: Piece,
1408{
1409    List {
1410        source: Some(source),
1411        build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
1412        row_height: RowHeight::Automatic,
1413        on_select: None,
1414        on_activate: None,
1415        on_selection: None,
1416        multi_select: false,
1417        selected_rows: None,
1418        selection: None,
1419        scroll_to_end: None,
1420        scroll_to_row: None,
1421        visible_rows: None,
1422        follow_end: None,
1423        end_reached: None,
1424        header: None,
1425        footer: None,
1426        empty: None,
1427        content_padding: day_spec::Insets::ZERO,
1428        reorder: None,
1429        delete: None,
1430        swipe_leading: None,
1431        swipe_trailing: None,
1432        separators: None,
1433        inset_grouped: false,
1434        editing: crate::Reactive::Const(false),
1435        sections: None,
1436    }
1437}
1438
1439#[day_macros::builder(ListBuilder<S>)]
1440impl<S: RowSource + 'static> List<S> {
1441    /// Row sizing: `Uniform(h)` (fastest) or `Automatic` (self-sizing).
1442    pub fn row_height(mut self, h: RowHeight) -> Self {
1443        self.row_height = h;
1444        self
1445    }
1446    /// Open, play, or otherwise activate a row. Desktop lists use double-click or Enter;
1447    /// touch lists use a tap. Selection callbacks remain independent.
1448    pub fn on_activate(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
1449        self.on_activate = Some(Rc::new(f));
1450        self
1451    }
1452
1453    /// Called with the selected row when the native list reports a selection: the key for a
1454    /// plain-data source, the row's `Elem` handle for a store source.
1455    pub fn on_select(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
1456        self.on_select = Some(Rc::new(f));
1457        self
1458    }
1459    /// Allow selecting several rows at once, where the toolkit supports it (docs/list.md has
1460    /// the matrix; single-selection backends fall back to one row at a time). Every selection
1461    /// change calls [`Self::on_selection`] with the full set of selected rows.
1462    pub fn multi_select(mut self) -> Self {
1463        self.multi_select = true;
1464        self
1465    }
1466    /// Called with the full set of selected rows (row order, empty = cleared) whenever the
1467    /// selection changes: the multi-select analogue of [`Self::on_select`]. Also fired by
1468    /// single-selection backends with a one-element (or empty) set.
1469    pub fn on_selection(mut self, f: impl Fn(Vec<S::Ref>) + 'static) -> Self {
1470        self.on_selection = Some(Rc::new(f));
1471        self
1472    }
1473    /// Reactively sync the native selection to `rows` (row indices; empty clears). Re-runs
1474    /// whenever the closure's tracked reads change; the toolkit applies the sync without
1475    /// re-emitting a selection event. Drive it from app state to build "Clear selection".
1476    pub fn selected_rows(mut self, rows: impl Fn() -> Vec<usize> + 'static) -> Self {
1477        self.selected_rows = Some(Rc::new(rows));
1478        self
1479    }
1480    /// Two-way single selection by key, for a list of day-model store rows: `selected` holds
1481    /// the selected row's key (`None` for no selection). A row the user picks writes its key,
1482    /// clearing the selection writes `None`, and a key the app writes selects that row and
1483    /// scrolls it into view, following the row through inserts and moves.
1484    ///
1485    /// ```ignore
1486    /// list(scene.items, row_view).selection(scene.selected)
1487    /// ```
1488    pub fn selection(mut self, selected: impl Binding<Option<u64>>) -> Self
1489    where
1490        S::Ref: SelectionKey,
1491    {
1492        let selected = AnyBinding::new(selected);
1493        self.selection = Some(ListSelection {
1494            key: Rc::new(move || selected.get()),
1495            write: Rc::new(move |key| selected.set_if_changed(key)),
1496            key_of: Rc::new(|row: &S::Ref| row.selection_key()),
1497        });
1498        self
1499    }
1500    /// Scroll the list to its end whenever `trigger` fires, e.g. a "jump to latest" button on a
1501    /// chat timeline. Fire it with [`day_reactive::Trigger::notify`]. No-op while the list is
1502    /// empty. The scroll targets the native list
1503    /// (`NSTableView`/`UITableView`/`GtkListView`/`QListView`/`RecyclerView`), so it respects the
1504    /// platform's own scroll physics. To keep following new rows by itself, see
1505    /// [`Self::follow_end`].
1506    pub fn scroll_to_end(mut self, trigger: day_reactive::Trigger) -> Self {
1507        self.scroll_to_end = Some(trigger);
1508        self
1509    }
1510
1511    /// Follow the end of the list (docs/list.md "Following the end"): when the rows change
1512    /// while the list's end is within `threshold` points of the bottom of the viewport, the
1513    /// list scrolls to its new end, so a chat timeline or a log keeps its newest row in view.
1514    /// A reader who has scrolled further up than `threshold` is left where they are; they
1515    /// rejoin by scrolling back down, or through [`Self::scroll_to_end`].
1516    ///
1517    /// The distance comes from the native list (`Cap::ListViewport`). A toolkit that does
1518    /// not report it follows every change.
1519    ///
1520    /// ```ignore
1521    /// list(items(move || messages.get(), |m| m.id), message_row).follow_end(40.0)
1522    /// ```
1523    pub fn follow_end(mut self, threshold: f64) -> Self {
1524        self.follow_end = Some(threshold.max(0.0));
1525        self
1526    }
1527
1528    /// Call `f` when the user comes within `threshold` points of the end of the list: the
1529    /// moment to load the next page (docs/list.md "Reaching the end"). It fires once on the
1530    /// way in, and again only after the end has left that distance and returned, or after
1531    /// the number of rows changed, so a handler that appends rows is called again when the
1532    /// reader reaches the new end. A page that leaves the end within `threshold` fires it
1533    /// again once its rows are laid out, with no scroll; a call that adds no rows re-arms
1534    /// nothing, so it is never called in a loop. An empty list does not fire it.
1535    /// Needs `Cap::ListViewport`.
1536    ///
1537    /// ```ignore
1538    /// list(rows, row_view).on_end_reached(400.0, move || feed.load_more())
1539    /// ```
1540    pub fn on_end_reached(mut self, threshold: f64, f: impl Fn() + 'static) -> Self {
1541        self.end_reached = Some((threshold.max(0.0), Rc::new(f)));
1542        self
1543    }
1544
1545    /// Programmatic scroll-to-row (docs/list.md "Programmatic scrolling"): each
1546    /// `Some(target)` written to the binding scrolls there, realizing the row if it was
1547    /// virtualized away, and the binding then resets to `None`, so the same row can be sent
1548    /// twice in a row. The same contract as `scroll(..).scroll_target(..)`. A [`RowTarget`]
1549    /// names the row, where it lands and whether the scroll animates; a binding of plain
1550    /// indices works too, each one a `RowTarget::new(row)`.
1551    ///
1552    /// ```ignore
1553    /// let jump = Signal::new(None);
1554    /// list(rows, row_view).scroll_to_row(jump);
1555    /// button(res::str::newest()).action(move || jump.set(Some(0)));
1556    /// // With options:
1557    /// jump.set(Some(RowTarget::new(250).align(RowAlign::Center).instant()));
1558    /// ```
1559    pub fn scroll_to_row<T>(mut self, target: impl Binding<Option<T>>) -> Self
1560    where
1561        T: Into<RowTarget> + Clone + 'static,
1562    {
1563        let target = AnyBinding::new(target);
1564        let consume = target;
1565        self.scroll_to_row = Some(RowCommand {
1566            pending: Rc::new(move || target.get().map(Into::into)),
1567            consume: Rc::new(move || consume.set(None)),
1568        });
1569        self
1570    }
1571
1572    /// The rows in view (docs/list.md "Visible rows"), written to `rows` as the list scrolls:
1573    /// a half-open range of row indices, `rows.start` the first row with any part showing and
1574    /// `rows.end` one past the last, empty while no row is in view. Section headers and the
1575    /// list's own header and footer are not rows. Use `rows.start` with a heading overlay for
1576    /// a floating group header. No periodic timer is used. Where `Cap::ListViewport` is
1577    /// unsupported the range holds the first visible row only.
1578    pub fn visible_rows(mut self, rows: impl Binding<std::ops::Range<usize>>) -> Self {
1579        self.visible_rows = Some(AnyBinding::new(rows));
1580        self
1581    }
1582
1583    /// Content above the first row that scrolls with the rows (docs/list.md "Header, footer
1584    /// and empty state"): a search summary, a hero, a banner. `build` runs when the list
1585    /// first shows it. It is not a row: nothing selects, swipes or counts it.
1586    pub fn header<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
1587        self.header = Some(Rc::new(move || AnyPiece::new(build())));
1588        self
1589    }
1590
1591    /// Content below the last row that scrolls with the rows: a "loading more" spinner, a
1592    /// count, a sign-off. The same contract as [`Self::header`].
1593    pub fn footer<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
1594        self.footer = Some(Rc::new(move || AnyPiece::new(build())));
1595        self
1596    }
1597
1598    /// What the list shows in place of its rows while it has none (docs/list.md "Header,
1599    /// footer and empty state"), centered in the viewport, between the header and the footer
1600    /// if the list has them. It goes when the first row arrives and returns when the last
1601    /// one leaves.
1602    ///
1603    /// ```ignore
1604    /// list(rows, row_view).empty(|| label(res::str::no_messages()).secondary())
1605    /// ```
1606    pub fn empty<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
1607        self.empty = Some(Rc::new(move || {
1608            AnyPiece::new(build().aligned(Alignment::Center).grow(Dimension::Both))
1609        }));
1610        self
1611    }
1612
1613    /// Space around the list's content, inside the scrolling area: the top and bottom
1614    /// scroll with the rows (the last row clears a floating composer or tab bar), the sides
1615    /// inset every row. Takes a number for all four sides or an `Insets`.
1616    pub fn content_padding(mut self, insets: impl Into<day_spec::Insets>) -> Self {
1617        self.content_padding = insets.into();
1618        self
1619    }
1620
1621    /// Let the user drag rows into a new order (docs/list.md): the list is reorderable exactly
1622    /// when it carries a [`Reorder`], whose handler applies the move to the app's data.
1623    ///
1624    /// ```ignore
1625    /// list(rows, row_view)
1626    ///     .reorderable(Reorder::new(move |from, to| scene.move_item(from, to)).guard(keep_pinned))
1627    /// ```
1628    pub fn reorderable(mut self, reorder: Reorder) -> Self {
1629        self.reorder = Some(reorder);
1630        self
1631    }
1632
1633    /// Let the user delete rows with the platform's delete gesture (docs/list.md): the list is
1634    /// deletable exactly when it carries a [`Delete`], whose handler applies the removal to the
1635    /// app's data.
1636    ///
1637    /// ```ignore
1638    /// list(rows, row_view)
1639    ///     .deletable(Delete::new(move |i| scene.remove_at(i)).label(res::str::delete()))
1640    /// ```
1641    pub fn deletable(mut self, delete: Delete) -> Self {
1642        self.delete = Some(delete);
1643        self
1644    }
1645
1646    /// Offer swipe actions on the row's leading edge, the reading-direction start, where the
1647    /// platform reveals them as the user drags the row aside (probe `Cap::ListSwipeActions`;
1648    /// docs/list.md has the matrix; a backend without the affordance shows nothing, so pair
1649    /// each action with an explicit control for the rest). `provider` runs at gesture time
1650    /// with the row index, so the offer can reflect the row's current state ("Mark as Read"
1651    /// vs "Mark as Unread"). Keep it pure and fast; it runs inside the platform's swipe
1652    /// callback; the actions' handlers run later, at the event drain. A full swipe across
1653    /// activates the edge's first action.
1654    pub fn swipe_leading(mut self, provider: impl Fn(usize) -> Vec<SwipeAction> + 'static) -> Self {
1655        self.swipe_leading = Some(Rc::new(provider));
1656        self
1657    }
1658
1659    /// Offer swipe actions on the row's trailing edge, the reading-direction end. Same
1660    /// contract as [`swipe_leading`](Self::swipe_leading).
1661    pub fn swipe_trailing(
1662        mut self,
1663        provider: impl Fn(usize) -> Vec<SwipeAction> + 'static,
1664    ) -> Self {
1665        self.swipe_trailing = Some(Rc::new(provider));
1666        self
1667    }
1668
1669    /// Draw a separator under each row. It is the host's separator, drawn at the row boundary
1670    /// and never by row content (docs/list.md): it aligns with the native selection and stays
1671    /// put while a macOS/iOS swipe slides the row past it, exactly as Mail's separators do.
1672    /// Unset, each platform keeps its default (iOS draws them, the desktops don't); see
1673    /// [`Self::no_separators`] for the other override. A backend without a separator mechanism
1674    /// ignores this (the docs matrix says which); don't re-create the old hand-drawn hairline
1675    /// there. Rows separate by their pitch.
1676    pub fn separators(mut self) -> Self {
1677        self.separators = Some(true);
1678        self
1679    }
1680
1681    /// Draw the list as the platform's inset grouped list: rounded groups of rows set in from
1682    /// the edges, one per section, as iOS Settings and Safari's History do (docs/list.md
1683    /// "Appearance"). iOS and macOS draw it; the other platforms draw their plain list.
1684    pub fn inset_grouped(mut self) -> Self {
1685        self.inset_grouped = true;
1686        self
1687    }
1688
1689    /// Draw no separator between rows, on a platform whose default draws one (iOS).
1690    pub fn no_separators(mut self) -> Self {
1691        self.separators = Some(false);
1692        self
1693    }
1694
1695    /// Group the rows into sections, each opened by a header row (docs/list.md "Sections").
1696    /// `key` runs with each row index when the rows change and names the row's section: a new
1697    /// section, and a header, starts wherever the key differs from the row before, so sort the
1698    /// rows by section first. `header` builds a section's header from the slot of its first
1699    /// row, the same slot a row builder gets, and rebinds it as its cell recycles.
1700    ///
1701    /// Headers are the platform's own: macOS group rows and UIKit section headers, which pin
1702    /// to the top of the list while their section scrolls under them; the other toolkits pin
1703    /// a copy of the current header the same way (`Cap::ListSections`). A header is never
1704    /// selected, activated or swiped, and row indices everywhere (selection, swipe offers,
1705    /// `selected_rows`, `scroll_to_row`, `visible_rows`) still count rows only. A header
1706    /// sizes to its content even when the rows are `Uniform`.
1707    ///
1708    /// A row drags only within its own section, the platforms' rule for grouped tables: a
1709    /// drop past either end of the section lands at that end, and the `reorderable` guard
1710    /// sees row indices. A sectioned list offers no native swipe-to-delete, since deleting a
1711    /// section's last row would take its header with it.
1712    ///
1713    /// ```ignore
1714    /// list(items(move || articles.get(), |a| a.id), article_row)
1715    ///     .sections(
1716    ///         move |i| articles.with(|a| a[i].feed_id),
1717    ///         |slot| label(move || slot.field(|a| a.feed_title.clone())),
1718    ///     )
1719    /// ```
1720    pub fn sections<K: Hash, P: Piece>(
1721        mut self,
1722        key: impl Fn(usize) -> K + 'static,
1723        header: impl Fn(S::Slot) -> P + 'static,
1724    ) -> Self {
1725        self.sections = Some(ListSections {
1726            key: Rc::new(move |i| key_token(&key(i))),
1727            header: Rc::new(move |slot| AnyPiece::new(header(slot))),
1728        });
1729        self
1730    }
1731
1732    /// Put the list in the platform's editing mode (docs/list.md): on iOS, the rows show
1733    /// their delete controls (where a [`Delete`] offers one) and reorder grips (where a
1734    /// [`Reorder`] moves them), and a tap still activates
1735    /// the row. Reactive, so an Edit/Done button can toggle it, and the change animates.
1736    ///
1737    /// Probe `Cap::ListEditing`. The other toolkits have no separate editing mode: their
1738    /// rows drag, swipe and open menus as they are, so the list renders as if this were off.
1739    pub fn editing<M>(mut self, on: impl crate::IntoReactive<bool, M>) -> Self {
1740        self.editing = on.into_reactive();
1741        self
1742    }
1743}
1744
1745/// The driver's build closure for a supplementary row (the list's header, footer or empty
1746/// state): build the piece in a scope of its own, with no item to bind.
1747fn slot_builder_plain(build: SlotBuild) -> day_core::SupplementBuild {
1748    Box::new(move |anchor| {
1749        let scope = Scope::child();
1750        let build = build.clone();
1751        scope.enter(move || {
1752            let mut cx = BuildCx::new(anchor);
1753            build().build(&mut cx);
1754        });
1755        BuiltRow {
1756            scope,
1757            rebind: Rc::new(|_: usize| {}),
1758        }
1759    })
1760}
1761
1762/// The driver's build closure for a row or a section header: build `builder`'s piece from a
1763/// slot for item `index` in its own scope, and rebind that slot as the cell recycles.
1764fn slot_builder<C: RowConn>(
1765    conn: Rc<C>,
1766    builder: Rc<dyn Fn(C::Slot) -> AnyPiece>,
1767) -> Box<dyn Fn(usize, RNode) -> BuiltRow> {
1768    Box::new(move |index, anchor| {
1769        let scope = Scope::child();
1770        let conn = conn.clone();
1771        let builder = builder.clone();
1772        let rebind = scope.enter(move || {
1773            // Native callbacks can deliver a stale index mid-animation; an out-of-range pull
1774            // yields an empty row instead of panicking.
1775            let Some(slot) = conn.slot_at(index) else {
1776                return Rc::new(|_: usize| {}) as Rc<dyn Fn(usize)>;
1777            };
1778            let mut rowcx = BuildCx::new(anchor);
1779            in_row_scope(|| builder(slot).build(&mut rowcx));
1780            // Rebind on recycle: point the slot at the cell's new row.
1781            Rc::new(move |i: usize| conn.rebind(&slot, i)) as Rc<dyn Fn(usize)>
1782        });
1783        BuiltRow { scope, rebind }
1784    })
1785}
1786
1787impl<S: RowSource + 'static> Piece for List<S> {
1788    fn build(mut self, cx: &mut BuildCx) -> RNode {
1789        let props = ListProps {
1790            activatable: self.on_activate.is_some(),
1791            row_height: self.row_height,
1792            selectable: self.on_select.is_some()
1793                || self.on_selection.is_some()
1794                || self.selection.is_some()
1795                || self.on_activate.is_some(),
1796            multi_select: self.multi_select,
1797            // A sectioned list reorders within a section but offers no native delete (see
1798            // `sections`); the scripted path still reaches the driver.
1799            reorderable: self.reorder.is_some(),
1800            deletable: self.delete.is_some() && self.sections.is_none(),
1801            delete_label: self
1802                .delete
1803                .as_ref()
1804                .and_then(|d| d.label.as_ref())
1805                .map_or_default(TextSource::initial),
1806            swipe_actions: self.swipe_leading.is_some() || self.swipe_trailing.is_some(),
1807            separators: self.separators,
1808            editing: self.editing.get_untracked(),
1809            sections: self.sections.is_some(),
1810            inset_grouped: self.inset_grouped,
1811        };
1812        let node = cx.leaf(
1813            kinds::LIST,
1814            &props,
1815            Flex {
1816                grow_w: true,
1817                grow_h: true,
1818                ..Default::default()
1819            },
1820        );
1821
1822        // The source's live connection: the data-source's view of the world, refreshed by the
1823        // watch below. The native host queries it synchronously; the driver's build/rebind
1824        // closures read the same snapshot.
1825        let conn = Rc::new(self.source.take().expect("List built once").connect());
1826        // A sectioned list's keys, one per row of the snapshot: computed with it, and rotated
1827        // with it by a committed move, so day-core's header rows always match the rows.
1828        let section_keys: Rc<RefCell<Vec<u64>>> = Rc::new(RefCell::new(Vec::new()));
1829        let key_of_row = self.sections.as_ref().map(|s| s.key.clone());
1830        let refresh = {
1831            let (conn, keys, key_of_row) = (conn.clone(), section_keys.clone(), key_of_row.clone());
1832            Rc::new(move || {
1833                let tokens = conn.refresh();
1834                if let Some(key) = &key_of_row {
1835                    *keys.borrow_mut() = (0..conn.len()).map(|i| key(i)).collect();
1836                }
1837                (tokens, keys.borrow().clone())
1838            })
1839        };
1840        // After a committed native move/delete, the token order the app's own data update is
1841        // expected to echo back. When the refresh below sees exactly this order, the native rows
1842        // already sit in it (the gesture animated them there): take the data, skip the reload.
1843        let pending_echo: Rc<RefCell<Option<Vec<u64>>>> = Rc::new(RefCell::new(None));
1844
1845        if let Some(activate) = self.on_activate.clone() {
1846            let conn = conn.clone();
1847            cx.on(node, move |event| {
1848                if let Event::ListActivated(row) = event
1849                    && let Some(reference) = conn.select_ref(*row)
1850                {
1851                    activate(reference);
1852                }
1853            });
1854        }
1855
1856        // Selection → refs (translate the native row indices through the snapshot). A
1857        // single-selection report also feeds `on_selection` as a one-element set, so an app
1858        // tracking the full selection works unchanged on single-selection backends.
1859        if self.on_select.is_some() || self.on_selection.is_some() {
1860            let (on_select, on_selection) = (self.on_select.clone(), self.on_selection.clone());
1861            let conn = conn.clone();
1862            cx.on(node, move |ev| match ev {
1863                Event::SelectionChanged(i) => {
1864                    if let Some(f) = &on_select
1865                        && let Some(r) = conn.select_ref(*i as usize)
1866                    {
1867                        f(r);
1868                    }
1869                    if let Some(f) = &on_selection {
1870                        f(conn.select_ref(*i as usize).into_iter().collect());
1871                    }
1872                }
1873                Event::SelectionSet(rows) => {
1874                    if let Some(f) = &on_selection {
1875                        f(rows
1876                            .iter()
1877                            .filter_map(|i| conn.select_ref(*i as usize))
1878                            .collect());
1879                    }
1880                }
1881                _ => {}
1882            });
1883        }
1884
1885        // A `.selection` binding: the user's choice writes the key back. `user_pick` remembers
1886        // it, so the apply below neither re-selects nor scrolls the row the user just chose.
1887        // `apply` selects the bound key's row in the current snapshot (the rows the native list
1888        // shows), and scrolls to it once after the app writes a key; a key whose row has not
1889        // reached the snapshot yet stays pending until the reload that brings it.
1890        let user_pick: Rc<Cell<Option<Option<u64>>>> = Rc::new(Cell::new(None));
1891        let reveal = Rc::new(Cell::new(false));
1892        let apply_selection: Option<Rc<dyn Fn()>> = self.selection.as_ref().map(|sel| {
1893            let (key, conn, reveal) = (sel.key.clone(), conn.clone(), reveal.clone());
1894            Rc::new(move || {
1895                let wanted = day_reactive::untrack(|| key());
1896                let row = wanted.and_then(|k| conn.tokens_now().iter().position(|t| *t == k));
1897                let scroll = row.filter(|_| reveal.replace(false));
1898                // Posted, like `selected_rows`: a toolkit may still be applying the reload
1899                // that brought the row.
1900                day_reactive::on_main(move || {
1901                    day_core::list_set_selected(node, row.into_iter().collect());
1902                    if let Some(row) = scroll {
1903                        list_scroll_to_row(node, row, day_spec::RowAlign::Nearest, true);
1904                    }
1905                });
1906            }) as Rc<dyn Fn()>
1907        });
1908        if let Some(sel) = &self.selection {
1909            let (write, key_of) = (sel.write.clone(), sel.key_of.clone());
1910            let (conn, pick) = (conn.clone(), user_pick.clone());
1911            cx.on(node, move |ev| {
1912                let row = match ev {
1913                    Event::SelectionChanged(i) => conn.select_ref(*i as usize),
1914                    Event::SelectionSet(rows) => {
1915                        rows.first().and_then(|i| conn.select_ref(*i as usize))
1916                    }
1917                    _ => return,
1918                };
1919                let key = row.as_ref().map(|r| key_of(r));
1920                pick.set(Some(key));
1921                write(key);
1922            });
1923        }
1924
1925        // A committed native move, deferred to the event drain (never run inside the platform's
1926        // drop callback): hand the app the same (from, to) the native side animated.
1927        if let Some(on_reorder) = self.reorder.as_ref().map(|r| r.moved.clone()) {
1928            cx.on(node, move |ev| {
1929                if let Event::ListReorder { from, to } = ev {
1930                    on_reorder(*from, *to);
1931                }
1932            });
1933        }
1934
1935        // A committed native delete, deferred to the event drain (never run inside the
1936        // platform's swipe callback): hand the app the row the native side animated away.
1937        if let Some(on_delete) = self.delete.as_ref().map(|d| d.deleted.clone()) {
1938            cx.on(node, move |ev| {
1939                if let Event::ListDelete(index) = ev {
1940                    on_delete(*index);
1941                }
1942            });
1943        }
1944
1945        // An activated swipe action, deferred to the event drain. The handlers live in
1946        // `SwipeAction`s the provider builds fresh per gesture, so re-pull the offer here to
1947        // find the one the user pressed. The provider is the single source of both the offer
1948        // and its handlers, and a state change between reveal and activation resolves to the
1949        // action the row now offers at that position.
1950        if self.swipe_leading.is_some() || self.swipe_trailing.is_some() {
1951            let (leading, trailing) = (self.swipe_leading.clone(), self.swipe_trailing.clone());
1952            cx.on(node, move |ev| {
1953                if let Event::ListSwipe {
1954                    index,
1955                    edge,
1956                    action,
1957                } = ev
1958                {
1959                    let provider = match edge {
1960                        day_spec::SwipeEdge::Leading => leading.as_ref(),
1961                        day_spec::SwipeEdge::Trailing => trailing.as_ref(),
1962                    };
1963                    if let Some(p) = provider
1964                        && let Some(a) = p(*index).get(*action)
1965                    {
1966                        (a.handler)();
1967                    }
1968                }
1969            });
1970        }
1971
1972        // The viewport, as the native list reports it (docs/list.md "Visible rows"): the
1973        // visible range for the app, the distance to the end for `follow_end`, and the
1974        // end-reached edge.
1975        let track_viewport =
1976            self.visible_rows.is_some() || self.follow_end.is_some() || self.end_reached.is_some();
1977        // The last distance from the viewport's end to the content's end; `None` until a host
1978        // says, which a host without `Cap::ListViewport` never does.
1979        let end_distance: Rc<Cell<Option<f64>>> = Rc::new(Cell::new(None));
1980        // `follow_end` scrolled to the end and the list has not reported arriving yet: the
1981        // distances it reports on the way there must not read as the reader leaving.
1982        let following = Rc::new(Cell::new(false));
1983        // `on_end_reached` fires on the way in, then waits for the end to leave or the rows
1984        // to change.
1985        let end_armed = Rc::new(Cell::new(true));
1986        if track_viewport {
1987            let visible = self.visible_rows.take();
1988            let follow = self.follow_end;
1989            let reached = self.end_reached.take();
1990            let (distance, following, armed) =
1991                (end_distance.clone(), following.clone(), end_armed.clone());
1992            let conn = conn.clone();
1993            cx.on(node, move |event| {
1994                let (rows, end_distance) = match event {
1995                    Event::ListViewport { rows, end_distance } => (rows, end_distance),
1996                    // The reader took the list (docs/list.md "Following the end"): a followed
1997                    // scroll they interrupted is over, and until the list says where they
1998                    // stopped they count as away from the end.
1999                    Event::ListReaderScrolled => {
2000                        following.set(false);
2001                        distance.set(Some(f64::INFINITY));
2002                        return;
2003                    }
2004                    _ => return,
2005                };
2006                if let Some(visible) = &visible {
2007                    visible.set_if_changed(rows.clone());
2008                }
2009                let Some(now) = *end_distance else {
2010                    return;
2011                };
2012                let near = follow.is_some_and(|threshold| now <= threshold);
2013                if near {
2014                    following.set(false);
2015                }
2016                if near || !following.get() {
2017                    distance.set(Some(now));
2018                }
2019                if let Some((threshold, reached)) = &reached {
2020                    if now > *threshold {
2021                        armed.set(true);
2022                    } else if !conn.is_empty() && armed.replace(false) {
2023                        reached();
2024                    }
2025                }
2026            });
2027        }
2028        let has_empty = self.empty.is_some();
2029        let driver = ListDriver {
2030            track_viewport,
2031            track_reader: self.follow_end.is_some(),
2032            supplements: day_core::ListSupplements {
2033                header: self.header.take().map(slot_builder_plain),
2034                footer: self.footer.take().map(slot_builder_plain),
2035                empty: self.empty.take().map(slot_builder_plain),
2036                padding: self.content_padding,
2037            },
2038            row_height: self.row_height,
2039            len: {
2040                let conn = conn.clone();
2041                Box::new(move || conn.len())
2042            },
2043            token_at: {
2044                let conn = conn.clone();
2045                Box::new(move |i| conn.token_at(i))
2046            },
2047            build: slot_builder(conn.clone(), self.build_row.clone()),
2048            sections: self.sections.as_ref().map(|sections| ListSectionsDriver {
2049                key_at: {
2050                    let keys = section_keys.clone();
2051                    Box::new(move |i| keys.borrow().get(i).copied().unwrap_or_default())
2052                },
2053                build: slot_builder(conn.clone(), sections.header.clone()),
2054            }),
2055            delete: self.delete.as_ref().map(|delete| ListDeleteDriver {
2056                // Availability first (`Delete::enabled`), then the row's own guard.
2057                can_delete: {
2058                    let (guard, enabled) = (delete.guard.clone(), delete.enabled.clone());
2059                    Box::new(move |i| {
2060                        enabled.get_untracked() && guard.as_ref().is_none_or(|g| g(i))
2061                    })
2062                },
2063                // Commit: drop the row from the snapshot now (subsequent len/token_at/bind_row
2064                // serve the shorter list while the native removal animates), arm the echo skip,
2065                // and defer the app's callback.
2066                deleted: {
2067                    let (conn, echo, keys) =
2068                        (conn.clone(), pending_echo.clone(), section_keys.clone());
2069                    Box::new(move |index| {
2070                        if index >= conn.len() {
2071                            return;
2072                        }
2073                        conn.commit_delete(index);
2074                        if index < keys.borrow().len() {
2075                            keys.borrow_mut().remove(index);
2076                        }
2077                        *echo.borrow_mut() = Some(conn.tokens_now());
2078                        enqueue_event(rnode_to_id(node), Event::ListDelete(index));
2079                    })
2080                },
2081            }),
2082            reorder: self.reorder.as_ref().map(|reorder| ListReorderDriver {
2083                // The guard's verdict, encoded for the synchronous `can_move` callback:
2084                // accepted index or -1. Availability (`Reorder::enabled`) is asked first.
2085                can_move: {
2086                    let (guard, enabled) = (reorder.guard.clone(), reorder.enabled.clone());
2087                    Box::new(move |from, to| {
2088                        if !enabled.get_untracked() {
2089                            return -1;
2090                        }
2091                        match guard.as_ref().map(|g| g(from, to)) {
2092                            None | Some(ReorderVerdict::Allow) => to as i64,
2093                            Some(ReorderVerdict::Deny) => -1,
2094                            Some(ReorderVerdict::Retarget(i)) => i as i64,
2095                        }
2096                    })
2097                },
2098                // Commit: rotate the snapshot now (subsequent len/token_at/bind_row serve the
2099                // new order while the native move animates), arm the echo skip, and defer the
2100                // app's callback through the event queue.
2101                moved: {
2102                    let (conn, echo, keys) =
2103                        (conn.clone(), pending_echo.clone(), section_keys.clone());
2104                    Box::new(move |from, to| {
2105                        if from >= conn.len() || to >= conn.len() {
2106                            return;
2107                        }
2108                        conn.commit_move(from, to);
2109                        {
2110                            let mut keys = keys.borrow_mut();
2111                            if from < keys.len() && to < keys.len() {
2112                                let k = keys.remove(from);
2113                                keys.insert(to, k);
2114                            }
2115                        }
2116                        *echo.borrow_mut() = Some(conn.tokens_now());
2117                        enqueue_event(rnode_to_id(node), Event::ListReorder { from, to });
2118                    })
2119                },
2120            }),
2121            swipe: (self.swipe_leading.is_some() || self.swipe_trailing.is_some()).then(|| {
2122                ListSwipeDriver {
2123                    // The offer, stripped to data: labels + styling go to the toolkit; the
2124                    // handlers stay here, found again by index when the activation drains.
2125                    actions_at: {
2126                        let (leading, trailing) =
2127                            (self.swipe_leading.clone(), self.swipe_trailing.clone());
2128                        Box::new(move |i, edge| {
2129                            let provider = match edge {
2130                                day_spec::SwipeEdge::Leading => leading.as_ref(),
2131                                day_spec::SwipeEdge::Trailing => trailing.as_ref(),
2132                            };
2133                            provider.map_or_else(Vec::new, |p| {
2134                                p(i).iter()
2135                                    .map(|a| day_spec::ListSwipeAction {
2136                                        label: a.label.resolve(),
2137                                        destructive: a.destructive,
2138                                        tint: a.tint,
2139                                        symbol: a.symbol,
2140                                    })
2141                                    .collect()
2142                            })
2143                        })
2144                    },
2145                    // Commit: defer the app's handler through the event queue (never run it
2146                    // inside the native gesture callback).
2147                    performed: {
2148                        let conn = conn.clone();
2149                        Box::new(move |index, edge, action| {
2150                            if index >= conn.len() {
2151                                return;
2152                            }
2153                            enqueue_event(
2154                                rnode_to_id(node),
2155                                Event::ListSwipe {
2156                                    index,
2157                                    edge,
2158                                    action,
2159                                },
2160                            );
2161                        })
2162                    },
2163                }
2164            }),
2165        };
2166        install_list(node, driver);
2167
2168        // With `follow_end`, the explicit jump to the end below is a followed scroll too.
2169        let jump_follows = (self.follow_end.is_some(), following.clone());
2170        // Keep the snapshot current and tell the native host to re-query on changes. The compute
2171        // is the tracked refresh; for a store source whose values flow through per-field
2172        // notifications, an unchanged row set skips the native reload entirely: a field edit
2173        // costs the one control it patched, not a visible-rows rebind.
2174        {
2175            let conn = conn.clone();
2176            let follow = self.follow_end;
2177            let sectioned = self.sections.is_some();
2178            let reselect = apply_selection.clone();
2179            let initial = {
2180                let refresh = refresh.clone();
2181                day_reactive::untrack(move || refresh())
2182            };
2183            // The native host attached against an empty snapshot (install_list ran before this
2184            // prime), so tell it the real row set now: reload, without the scroll a later
2185            // followed change gets. Skipping this rendered every list blank until its first data
2186            // change, while the synthetic rail kept passing: the walkthrough drove the driver
2187            // directly and never noticed.
2188            list_reload(node);
2189            // The rows the native host shows: what the next change is diffed against.
2190            let last: RefCell<(Vec<u64>, Vec<u64>)> = RefCell::new(initial);
2191            watch(
2192                move || refresh(),
2193                move |rows: &(Vec<u64>, Vec<u64>), _| {
2194                    let toks = &rows.0;
2195                    let pending = pending_echo.borrow_mut().take();
2196                    // A native delete that emptied a list with an empty state is no echo: the
2197                    // host has to be told about the row that takes the items' place.
2198                    let is_echo = pending.as_ref().is_some_and(|e| e == toks)
2199                        && !(has_empty && toks.is_empty());
2200                    let old = last.replace(rows.clone());
2201                    // A row moving to another section changes its header rows, not its tokens.
2202                    let unchanged = !conn.values_flow_by_reload() && old == *rows;
2203                    if old.0.len() != toks.len() {
2204                        end_armed.set(true);
2205                    }
2206                    // Where the reader was before this change (`follow_end`): a list that
2207                    // never reported is taken to be at its end.
2208                    let at_end = follow.is_some_and(|threshold| {
2209                        following.get() || end_distance.get().is_none_or(|d| d <= threshold)
2210                    });
2211                    if !is_echo && pending.is_some() {
2212                        // The native rows took a move or delete the app answered with some
2213                        // other order. The source's deltas describe the change from its order
2214                        // before the gesture, not from the rows on screen: reload instead.
2215                        let _ = conn.take_row_events();
2216                        list_reload(node);
2217                        if let Some(apply) = &reselect {
2218                            apply();
2219                        }
2220                    } else if !is_echo && !unchanged {
2221                        // A source that maintains its set incrementally says what changed;
2222                        // for any other, the old and new tokens are diffed into the same
2223                        // deltas (docs/list.md "Keyed updates").
2224                        let sync = match conn.take_row_events() {
2225                            Some(deltas) if !deltas.is_empty() => {
2226                                let count = deltas.len();
2227                                list_splice(node, deltas);
2228                                day_core::ListSync::Spliced(count)
2229                            }
2230                            Some(_) => day_core::ListSync::Unchanged,
2231                            None => day_core::list_sync(
2232                                node,
2233                                day_core::ListRows {
2234                                    tokens: &old.0,
2235                                    sections: sectioned.then_some(&old.1),
2236                                },
2237                                day_core::ListRows {
2238                                    tokens: toks,
2239                                    sections: sectioned.then_some(&rows.1),
2240                                },
2241                            ),
2242                        };
2243                        if at_end {
2244                            // New rows scroll into view; a row that only grew (a streamed
2245                            // reply) is kept in view without an animation per update.
2246                            following.set(true);
2247                            list_scroll_to_end(node, sync != day_core::ListSync::Unchanged);
2248                        }
2249                        // A reload drops the native selection, and a splice may have moved
2250                        // the bound row; put it back.
2251                        if let Some(apply) = &reselect {
2252                            apply();
2253                        }
2254                    } else {
2255                        // Consume events the host must not see twice (its own echo, or a
2256                        // change whose set landed identical).
2257                        let _ = conn.take_row_events();
2258                    }
2259                },
2260            );
2261        }
2262
2263        // Imperative scroll-to-end: each `trigger.notify()` re-runs this watch (the trigger's
2264        // signal is the only tracked dep), whose callback scrolls the native list to its last row.
2265        // `watch` never fires for the initial run, so building the list does not force a scroll.
2266        if let Some(trigger) = self.scroll_to_end {
2267            let (follows, following) = jump_follows;
2268            watch(
2269                move || trigger.track(),
2270                move |(): &(), _| {
2271                    // A row that arrives while the jump is on its way is followed, as it is
2272                    // during a followed scroll: the reader asked for the end.
2273                    if follows {
2274                        following.set(true);
2275                    }
2276                    list_scroll_to_end(node, true);
2277                },
2278            );
2279        }
2280
2281        // Programmatic scroll-to-row: every `Some(target)` write scrolls there and is then
2282        // consumed, the `scroll_target` contract (the initial build never scrolls).
2283        if let Some(command) = self.scroll_to_row {
2284            let RowCommand { pending, consume } = command;
2285            watch(
2286                move || pending(),
2287                move |target: &Option<RowTarget>, _| {
2288                    if let Some(to) = *target {
2289                        // Deferred one main-loop turn, as `scroll_target` is: a row appended
2290                        // in the same batch reaches the host before the scroll does.
2291                        day_reactive::on_main(move || {
2292                            list_scroll_to_row(node, to.row, to.align, to.animated);
2293                        });
2294                        consume(); // ready for the next command
2295                    }
2296                },
2297            );
2298        }
2299
2300        // A reactive editing mode patches on change; the props carried the initial state.
2301        if let editing @ crate::Reactive::Dyn(_) =
2302            std::mem::replace(&mut self.editing, crate::Reactive::Const(false))
2303        {
2304            watch(
2305                move || editing.get(),
2306                move |on: &bool, old| {
2307                    if old.is_some() {
2308                        list_set_editing(node, *on);
2309                    }
2310                },
2311            );
2312        }
2313
2314        // `.selection`: every key the app writes selects its row and scrolls it into view (once
2315        // the row is in the snapshot; see `apply`). The initial key and the user's own pick
2316        // select without scrolling.
2317        if let (Some(sel), Some(apply)) = (self.selection.take(), apply_selection) {
2318            let first = Cell::new(true);
2319            day_reactive::bind(
2320                move || (sel.key)(),
2321                move |key: &Option<u64>| {
2322                    let initial = first.replace(false);
2323                    // The user's own pick is applied too, unscrolled: a list with no selection of
2324                    // its own (Android's RecyclerView) paints only what Day records, and a native
2325                    // list re-selecting the row it shows is a no-op.
2326                    let picked = user_pick.take() == Some(*key);
2327                    reveal.set(!initial && !picked && key.is_some());
2328                    apply();
2329                },
2330            );
2331        }
2332
2333        // An explicit selection binding owns the initial selection too. Reader layouts may
2334        // remount a list with an already-selected model item; skipping the initial apply
2335        // leaves the native table unselected until a later model change.
2336        if let Some(rows) = self.selected_rows {
2337            day_reactive::bind(
2338                move || rows(),
2339                move |rows: &Vec<usize>| {
2340                    // Selection and the row source may depend on the same model signal.
2341                    // Let the source publish/reload its snapshot before selecting its indexes.
2342                    let rows = rows.clone();
2343                    day_reactive::on_main(move || day_core::list_set_selected(node, rows));
2344                },
2345            );
2346        }
2347        node
2348    }
2349}
2350
2351// ---------------------------------------------------------------------------
2352// Model-driven rows (feature "model", docs/model.md): a day-model store as a RowSource
2353// ---------------------------------------------------------------------------
2354
2355#[cfg(feature = "model")]
2356mod model_rows {
2357    use super::*;
2358    use day_model::{Elem, Identified, Keyed, Source, Store};
2359
2360    /// One recycled row's connection to its store: the slot a model list's row builder
2361    /// receives. `Copy`, and a day-model [`Source`], so `#[derive(Observable)]` accessors hang
2362    /// off it. `text_field(slot.name())` binds two-way and follows the slot to its next row
2363    /// when the cell recycles, because the slot resolves its row on every operation.
2364    pub struct ModelSlot<T: 'static> {
2365        store: Store<Keyed<T>>,
2366        cur: Signal<u64>,
2367    }
2368
2369    impl<T> Clone for ModelSlot<T> {
2370        fn clone(&self) -> Self {
2371            *self
2372        }
2373    }
2374    impl<T> Copy for ModelSlot<T> {}
2375
2376    impl<T: Identified + Clone + 'static> ModelSlot<T> {
2377        /// A slot pointed at `key`, for row sources implemented outside this crate (a live
2378        /// query). Application code receives slots from `list`/`each` instead.
2379        pub fn for_key(store: Store<Keyed<T>>, key: u64) -> ModelSlot<T> {
2380            ModelSlot {
2381                store,
2382                cur: Signal::new(key),
2383            }
2384        }
2385        /// The recycle write, for external row sources: point this slot at another key.
2386        pub fn rebind_key(&self, key: u64) {
2387            self.cur.set_if_changed(key);
2388        }
2389    }
2390
2391    impl<T: Identified + 'static> ModelSlot<T> {
2392        /// The row's key right now, tracked, so a closure reading it follows recycling
2393        /// (a context-menu action captures the slot and acts on whichever row the cell shows
2394        /// when it runs).
2395        pub fn key(self) -> u64 {
2396            self.cur.get()
2397        }
2398        /// The current row as a plain element handle, for `exists()` guards or handing to
2399        /// code outside the row. Tracked via the slot, so it follows recycling too.
2400        pub fn item(self) -> Elem<T> {
2401            self.store.elem(self.cur.get())
2402        }
2403        fn elem_now(self) -> Elem<T> {
2404            self.store.elem(self.cur.get_untracked())
2405        }
2406    }
2407
2408    impl<T: Identified + 'static> Source<T> for ModelSlot<T> {
2409        // The slot's location is wherever the cell currently sits, hence `DYNAMIC`.
2410        const DYNAMIC: bool = true;
2411        fn track_extra(self) {
2412            self.cur.track();
2413        }
2414        fn path(self) -> day_model::Path {
2415            self.elem_now().path()
2416        }
2417        fn node(self) -> day_model::NodeId {
2418            self.elem_now().node()
2419        }
2420        fn components(self, out: &mut Vec<u64>) {
2421            self.elem_now().components(out);
2422        }
2423        fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
2424            self.elem_now().with_value_untracked(f)
2425        }
2426        fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
2427            self.elem_now().update_value(f)
2428        }
2429        fn bump_version(self) {
2430            self.elem_now().bump_version();
2431        }
2432    }
2433
2434    /// A store row names itself by its key, so a store list binds [`List::selection`].
2435    impl<T: Identified + 'static> SelectionKey for Elem<T> {
2436        fn selection_key(&self) -> u64 {
2437            self.key()
2438        }
2439    }
2440
2441    /// A store IS a row source: collection order, rows keyed by the store's own keys.
2442    impl<T: Identified + Clone + 'static> RowSource for Store<Keyed<T>> {
2443        type Slot = ModelSlot<T>;
2444        type Ref = Elem<T>;
2445        type Conn = StoreConn<T>;
2446        fn connect(self) -> StoreConn<T> {
2447            StoreConn {
2448                store: self,
2449                rows: None,
2450                keys: RefCell::new(Vec::new()),
2451            }
2452        }
2453    }
2454
2455    /// A display projection over a store: `store.rows(move || ordered_keys())`. The projection
2456    /// is a tracked read of key ids: read only the fields the order depends on, and a write to
2457    /// any other field cannot re-run it.
2458    pub struct Rows<T: 'static> {
2459        store: Store<Keyed<T>>,
2460        f: Rc<dyn Fn() -> Vec<u64>>,
2461    }
2462
2463    impl<T: Identified + Clone + 'static> RowSource for Rows<T> {
2464        type Slot = ModelSlot<T>;
2465        type Ref = Elem<T>;
2466        type Conn = StoreConn<T>;
2467        fn connect(self) -> StoreConn<T> {
2468            StoreConn {
2469                store: self.store,
2470                rows: Some(self.f),
2471                keys: RefCell::new(Vec::new()),
2472            }
2473        }
2474    }
2475
2476    /// `store.rows(projection)`: the display-ordered row source for [`list()`]/[`each`].
2477    pub trait StoreRows<T: 'static> {
2478        fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T>;
2479    }
2480
2481    impl<T: Identified + Clone + 'static> StoreRows<T> for Store<Keyed<T>> {
2482        fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T> {
2483            Rows {
2484                store: self,
2485                f: Rc::new(f),
2486            }
2487        }
2488    }
2489
2490    /// The store connection: its snapshot is the display keys; no item is ever cloned.
2491    pub struct StoreConn<T: 'static> {
2492        store: Store<Keyed<T>>,
2493        rows: Option<Rc<dyn Fn() -> Vec<u64>>>,
2494        keys: RefCell<Vec<u64>>,
2495    }
2496
2497    impl<T: Identified + Clone + 'static> RowConn for StoreConn<T> {
2498        type Slot = ModelSlot<T>;
2499        type Ref = Elem<T>;
2500
2501        fn refresh(&self) -> Vec<u64> {
2502            let keys = match &self.rows {
2503                Some(f) => f(),
2504                None => self.store.keys(),
2505            };
2506            *self.keys.borrow_mut() = keys.clone();
2507            keys
2508        }
2509        fn len(&self) -> usize {
2510            self.keys.borrow().len()
2511        }
2512        fn token_at(&self, index: usize) -> u64 {
2513            self.keys.borrow().get(index).copied().unwrap_or(0)
2514        }
2515        fn tokens_now(&self) -> Vec<u64> {
2516            self.keys.borrow().clone()
2517        }
2518        fn slot_at(&self, index: usize) -> Option<ModelSlot<T>> {
2519            let key = self.keys.borrow().get(index).copied()?;
2520            Some(ModelSlot {
2521                store: self.store,
2522                cur: Signal::new(key),
2523            })
2524        }
2525        fn rebind(&self, slot: &ModelSlot<T>, index: usize) {
2526            if let Some(key) = self.keys.borrow().get(index).copied() {
2527                // Values flow through the store's own notifications; the rebind is only the
2528                // key, and an unchanged key is a no-op.
2529                slot.cur.set_if_changed(key);
2530            }
2531        }
2532        fn select_ref(&self, index: usize) -> Option<Elem<T>> {
2533            let key = self.keys.borrow().get(index).copied()?;
2534            Some(self.store.elem(key))
2535        }
2536        fn values_flow_by_reload(&self) -> bool {
2537            false
2538        }
2539        fn commit_move(&self, from: usize, to: usize) {
2540            let mut keys = self.keys.borrow_mut();
2541            if from >= keys.len() || to >= keys.len() {
2542                return;
2543            }
2544            let k = keys.remove(from);
2545            keys.insert(to, k);
2546        }
2547        fn commit_delete(&self, index: usize) {
2548            let mut keys = self.keys.borrow_mut();
2549            if index >= keys.len() {
2550                return;
2551            }
2552            keys.remove(index);
2553        }
2554    }
2555
2556    /// A hierarchy over a store: `store.tree(children_of)` (docs/tree.md). The projection
2557    /// maps a parent key (`None` = the root) to its ordered child keys, a tracked read, so
2558    /// re-parenting or re-ordering writes re-run it; tokens are the store's keys.
2559    pub struct StoreTree<T: 'static> {
2560        store: Store<Keyed<T>>,
2561        children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
2562    }
2563
2564    /// `store.tree(children_of)`: the hierarchical source for [`super::tree`].
2565    pub trait StoreTrees<T: 'static> {
2566        fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T>;
2567    }
2568
2569    impl<T: Identified + Clone + 'static> StoreTrees<T> for Store<Keyed<T>> {
2570        fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T> {
2571            StoreTree {
2572                store: self,
2573                children: Rc::new(children),
2574            }
2575        }
2576    }
2577
2578    impl<T: Identified + Clone + 'static> super::NodeSource for StoreTree<T> {
2579        type Slot = ModelSlot<T>;
2580        type Key = u64;
2581        type Conn = StoreTreeConn<T>;
2582        fn connect(self) -> StoreTreeConn<T> {
2583            StoreTreeConn {
2584                store: self.store,
2585                children: self.children,
2586                shape: RefCell::new(super::TreeShape::default()),
2587            }
2588        }
2589    }
2590
2591    /// [`StoreTree`]'s connection: the derived shape; values flow through the store's own
2592    /// per-field notifications, so an unchanged shape skips the native reload entirely.
2593    pub struct StoreTreeConn<T: 'static> {
2594        store: Store<Keyed<T>>,
2595        children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
2596        shape: RefCell<super::TreeShape>,
2597    }
2598
2599    impl<T: Identified + Clone + 'static> super::TreeConn for StoreTreeConn<T> {
2600        type Slot = ModelSlot<T>;
2601        type Key = u64;
2602
2603        fn refresh(&self) -> Vec<(u64, Option<u64>)> {
2604            let mut shape = super::TreeShape::default();
2605            let mut seen = HashSet::new();
2606            // Depth-first from the root, children pushed in reverse so walk order is
2607            // display order. `seen` guards a malformed parent graph from looping.
2608            let mut stack: Vec<(Option<u64>, u64)> = (self.children)(None)
2609                .into_iter()
2610                .rev()
2611                .map(|k| (None, k))
2612                .collect();
2613            while let Some((parent, key)) = stack.pop() {
2614                if !seen.insert(key) {
2615                    debug_assert!(false, "day: cycle or duplicate key in store tree");
2616                    continue;
2617                }
2618                shape.tokens.push(key);
2619                shape.parents.insert(key, parent);
2620                shape.children.entry(parent).or_default().push(key);
2621                for child in (self.children)(Some(key)).into_iter().rev() {
2622                    stack.push((Some(key), child));
2623                }
2624            }
2625            let fp = shape.fingerprint();
2626            *self.shape.borrow_mut() = shape;
2627            fp
2628        }
2629        fn tokens_now(&self) -> Vec<u64> {
2630            self.shape.borrow().tokens.clone()
2631        }
2632        fn children_len(&self, parent: Option<u64>) -> usize {
2633            self.shape
2634                .borrow()
2635                .children
2636                .get(&parent)
2637                .map(|v| v.len())
2638                .unwrap_or(0)
2639        }
2640        fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
2641            self.shape
2642                .borrow()
2643                .children
2644                .get(&parent)
2645                .and_then(|v| v.get(index).copied())
2646                .unwrap_or(0)
2647        }
2648        fn parent_of(&self, token: u64) -> Option<Option<u64>> {
2649            self.shape.borrow().parents.get(&token).copied()
2650        }
2651        fn key_of(&self, token: u64) -> Option<u64> {
2652            self.shape
2653                .borrow()
2654                .parents
2655                .contains_key(&token)
2656                .then_some(token)
2657        }
2658        fn token_of(&self, key: &u64) -> u64 {
2659            *key
2660        }
2661        fn slot_for(&self, token: u64) -> Option<ModelSlot<T>> {
2662            self.shape
2663                .borrow()
2664                .parents
2665                .contains_key(&token)
2666                .then(|| ModelSlot::for_key(self.store, token))
2667        }
2668        fn rebind(&self, slot: &ModelSlot<T>, token: u64) {
2669            slot.rebind_key(token);
2670        }
2671        fn values_flow_by_reload(&self) -> bool {
2672            false
2673        }
2674    }
2675}
2676
2677#[cfg(feature = "model")]
2678pub use model_rows::{ModelSlot, Rows, StoreRows, StoreTree, StoreTreeConn, StoreTrees};
2679
2680// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
2681
2682// ---------------------------------------------------------------------------
2683// `tree`: native hierarchical tree (docs/tree.md)
2684// ---------------------------------------------------------------------------
2685
2686pub use day_spec::MoveVerdict;
2687
2688/// A hierarchical row source for [`tree`]: the [`RowSource`] idea grown a parent per row.
2689/// Two implementations: [`branches`] (plain data) and a day-model store's
2690/// `store.tree(children_of)` (feature `model`).
2691pub trait NodeSource {
2692    /// What a row builder receives.
2693    type Slot: Copy + 'static;
2694    /// The app's identity currency: what selection, moves and expansion speak.
2695    type Key: Clone + Hash + Eq + 'static;
2696    type Conn: TreeConn<Slot = Self::Slot, Key = Self::Key>;
2697    fn connect(self) -> Self::Conn;
2698}
2699
2700/// One tree's live connection to its data, held for the life of the [`tree`] that connected
2701/// it. All hierarchy queries are TOKEN-addressed (docs/tree.md): `None` = the root level.
2702pub trait TreeConn: 'static {
2703    type Slot: Copy + 'static;
2704    type Key: Clone + Hash + Eq + 'static;
2705
2706    /// Refresh the snapshot and return the tree's shape: `(token, parent)` pairs in walk
2707    /// order. A tracked read: the enclosing watch re-runs exactly when something this read
2708    /// depends on changes.
2709    fn refresh(&self) -> Vec<(u64, Option<u64>)>;
2710    /// Every token in the current snapshot, walk order, no refresh and no tracking.
2711    fn tokens_now(&self) -> Vec<u64>;
2712    fn children_len(&self, parent: Option<u64>) -> usize;
2713    fn child_token(&self, parent: Option<u64>, index: usize) -> u64;
2714    /// `Some(parent)` for a known token (`Some(None)` = a root row), `None` for an unknown one.
2715    fn parent_of(&self, token: u64) -> Option<Option<u64>>;
2716    fn key_of(&self, token: u64) -> Option<Self::Key>;
2717    /// The token a key maps to (pure: no snapshot lookup).
2718    fn token_of(&self, key: &Self::Key) -> u64;
2719    /// A fresh slot for `token` (`None` on a stale mid-animation pull). Call inside the
2720    /// row's scope: plain-data slots allocate their signals here.
2721    fn slot_for(&self, token: u64) -> Option<Self::Slot>;
2722    /// Point an existing slot at `token`: the recycle write.
2723    fn rebind(&self, slot: &Self::Slot, token: u64);
2724    /// Whether row VALUES reach existing rows only through reload→rebind (see
2725    /// [`RowConn::values_flow_by_reload`]).
2726    fn values_flow_by_reload(&self) -> bool;
2727}
2728
2729/// Plain-data tree rows: a flat items closure, a key per item, and a parent key per item
2730/// (`None` = a root row), as in `tree(branches(model::all, |n| n.id, |n| n.parent), row_view)`.
2731/// Children keep the items' own relative order; an item whose parent key is absent from the
2732/// set is treated as a root row rather than dropped.
2733pub fn branches<T, K>(
2734    f: impl Fn() -> Vec<T> + 'static,
2735    key_of: impl Fn(&T) -> K + 'static,
2736    parent_of: impl Fn(&T) -> Option<K> + 'static,
2737) -> Branches<T, K>
2738where
2739    T: Clone + 'static,
2740    K: Clone + Hash + Eq + 'static,
2741{
2742    Branches {
2743        f: Rc::new(f),
2744        key_of: Rc::new(key_of),
2745        parent_of: Rc::new(parent_of),
2746    }
2747}
2748
2749/// A parent-key extractor (aliased for the fields below; clippy's type-complexity bound).
2750type ParentOf<T, K> = Rc<dyn Fn(&T) -> Option<K>>;
2751
2752/// The plain-data [`NodeSource`] built by [`branches`].
2753pub struct Branches<T: 'static, K: 'static> {
2754    f: Rc<dyn Fn() -> Vec<T>>,
2755    key_of: Rc<dyn Fn(&T) -> K>,
2756    parent_of: ParentOf<T, K>,
2757}
2758
2759impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> NodeSource for Branches<T, K> {
2760    type Slot = ItemSlot<T, K>;
2761    type Key = K;
2762    type Conn = BranchesConn<T, K>;
2763    fn connect(self) -> BranchesConn<T, K> {
2764        BranchesConn {
2765            f: self.f,
2766            key_of: self.key_of,
2767            parent_of: self.parent_of,
2768            snapshot: RefCell::new(Vec::new()),
2769            shape: RefCell::new(TreeShape::default()),
2770        }
2771    }
2772}
2773
2774/// The derived children/parent indexes both connections maintain per refresh.
2775#[derive(Default)]
2776struct TreeShape {
2777    /// Walk-order tokens (parents before their children for a well-formed set).
2778    tokens: Vec<u64>,
2779    children: std::collections::HashMap<Option<u64>, Vec<u64>>,
2780    parents: std::collections::HashMap<u64, Option<u64>>,
2781    /// token → index into the flat snapshot (plain-data sources only).
2782    index_of: std::collections::HashMap<u64, usize>,
2783}
2784
2785impl TreeShape {
2786    fn fingerprint(&self) -> Vec<(u64, Option<u64>)> {
2787        self.tokens
2788            .iter()
2789            .map(|t| (*t, self.parents.get(t).copied().flatten()))
2790            .collect()
2791    }
2792}
2793
2794/// [`Branches`]' connection: the current data snapshot plus its derived shape.
2795pub struct BranchesConn<T: 'static, K: 'static> {
2796    f: Rc<dyn Fn() -> Vec<T>>,
2797    key_of: Rc<dyn Fn(&T) -> K>,
2798    parent_of: ParentOf<T, K>,
2799    snapshot: RefCell<Vec<T>>,
2800    shape: RefCell<TreeShape>,
2801}
2802
2803impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> TreeConn for BranchesConn<T, K> {
2804    type Slot = ItemSlot<T, K>;
2805    type Key = K;
2806
2807    fn refresh(&self) -> Vec<(u64, Option<u64>)> {
2808        let its = (self.f)();
2809        let mut shape = TreeShape::default();
2810        let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
2811        let present: HashSet<u64> = toks.iter().copied().collect();
2812        for (i, item) in its.iter().enumerate() {
2813            let tok = toks[i];
2814            // A parent key outside the set roots the row rather than dropping it.
2815            let parent = (self.parent_of)(item)
2816                .map(|k| key_token(&k))
2817                .filter(|p| present.contains(p));
2818            shape.tokens.push(tok);
2819            shape.parents.insert(tok, parent);
2820            shape.children.entry(parent).or_default().push(tok);
2821            shape.index_of.insert(tok, i);
2822        }
2823        *self.snapshot.borrow_mut() = its;
2824        let fp = shape.fingerprint();
2825        *self.shape.borrow_mut() = shape;
2826        fp
2827    }
2828    fn tokens_now(&self) -> Vec<u64> {
2829        self.shape.borrow().tokens.clone()
2830    }
2831    fn children_len(&self, parent: Option<u64>) -> usize {
2832        self.shape
2833            .borrow()
2834            .children
2835            .get(&parent)
2836            .map_or(0, std::vec::Vec::len)
2837    }
2838    fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
2839        self.shape
2840            .borrow()
2841            .children
2842            .get(&parent)
2843            .and_then(|v| v.get(index).copied())
2844            .unwrap_or(0)
2845    }
2846    fn parent_of(&self, token: u64) -> Option<Option<u64>> {
2847        self.shape.borrow().parents.get(&token).copied()
2848    }
2849    fn key_of(&self, token: u64) -> Option<K> {
2850        let idx = self.shape.borrow().index_of.get(&token).copied()?;
2851        self.snapshot.borrow().get(idx).map(|t| (self.key_of)(t))
2852    }
2853    fn token_of(&self, key: &K) -> u64 {
2854        key_token(key)
2855    }
2856    fn slot_for(&self, token: u64) -> Option<ItemSlot<T, K>> {
2857        let idx = self.shape.borrow().index_of.get(&token).copied()?;
2858        let item = self.snapshot.borrow().get(idx).cloned()?;
2859        let key = (self.key_of)(&item);
2860        Some(ItemSlot {
2861            sig: Signal::new(item),
2862            key: Signal::new(key),
2863        })
2864    }
2865    fn rebind(&self, slot: &ItemSlot<T, K>, token: u64) {
2866        let Some(idx) = self.shape.borrow().index_of.get(&token).copied() else {
2867            return; // stale recycle token: skip, the next bind corrects it
2868        };
2869        let Some(item) = self.snapshot.borrow().get(idx).cloned() else {
2870            return;
2871        };
2872        slot.key.set((self.key_of)(&item));
2873        slot.sig.set(item);
2874    }
2875    fn values_flow_by_reload(&self) -> bool {
2876        true
2877    }
2878}
2879
2880/// A native hierarchical tree (docs/tree.md): rows nest, disclose, and drag to a new parent.
2881/// The platform widget owns scrolling, disclosure and cell reuse; Day builds each visible row
2882/// once and *rebinds* it as cells recycle ([`list()`]'s contract, token-addressed). Gate its UI
2883/// on `Cap::Tree`: a backend without tree support renders nothing.
2884/// Drag-to-move for a [`tree`] (docs/tree.md): the handler that applies a committed
2885/// re-parent, an optional guard consulted while the drag is live, and whether the gesture is
2886/// offered right now. A tree is movable exactly when it carries one of these
2887/// (`tree(..).movable(Move::new(f))`). The [`list()`] counterpart is [`Reorder`].
2888#[must_use]
2889pub struct Move<K: 'static> {
2890    moved: TreeMoveFn<K>,
2891    guard: Option<TreeGuardFn<K>>,
2892    enabled: Reactive<bool>,
2893}
2894
2895impl<K: 'static> Move<K> {
2896    /// `moved(key, parent, index)` runs after a committed move: `key` now sits under `parent`
2897    /// (`None` = the root) at `index` (`None` = dropped onto the parent: append). Apply the
2898    /// same re-parent to the backing data; its refresh reloads the tree. Runs at the next event
2899    /// drain, never inside the native drop callback.
2900    pub fn new(moved: impl Fn(K, Option<K>, Option<usize>) + 'static) -> Move<K> {
2901        Move {
2902            moved: Rc::new(moved),
2903            guard: None,
2904            enabled: Reactive::Const(true),
2905        }
2906    }
2907    /// Veto drops while the drag is live. The structural refusals (a row into itself, into
2908    /// its own descendant, into a leaf) are built in; this guard adds the app's own. Keep it
2909    /// pure: it runs inside the platform's drag callback.
2910    pub fn guard(
2911        mut self,
2912        g: impl Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict + 'static,
2913    ) -> Move<K> {
2914        self.guard = Some(Rc::new(g));
2915        self
2916    }
2917    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
2918    /// `bool`, read when the platform asks whether a drag may begin.
2919    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Move<K> {
2920        self.enabled = on.into_reactive();
2921        self
2922    }
2923}
2924
2925#[must_use]
2926pub struct TreePiece<S: NodeSource> {
2927    source: Option<S>,
2928    build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
2929    row_height: RowHeight,
2930    indent: Option<f64>,
2931    section_headers: bool,
2932    on_expansion: Option<ExpansionFn<S::Key>>,
2933    expanded: Option<AnyBinding<HashSet<S::Key>>>,
2934    expandable: Option<KeyPredicate<S::Key>>,
2935    selected: Option<Rc<dyn Fn() -> Vec<S::Key>>>,
2936    on_selection: Option<SelectionKeysFn<S::Key>>,
2937    multi_select: bool,
2938    movable: bool,
2939    on_move: Option<TreeMoveFn<S::Key>>,
2940    move_guard: Option<TreeGuardFn<S::Key>>,
2941    type_ahead: Option<KeyTextFn<S::Key>>,
2942    reveal: Option<AnyBinding<Option<S::Key>>>,
2943    row_id: Option<KeyIdFn<S::Key>>,
2944    row_menu: Option<RowMenuEntriesFn<S::Key>>,
2945}
2946
2947/// The committed-move callback, aliased for the field above.
2948type ExpansionFn<K> = Rc<dyn Fn(K, bool)>;
2949type TreeMoveFn<K> = Rc<dyn Fn(K, Option<K>, Option<usize>)>;
2950/// The live move guard, aliased for the field above.
2951type TreeGuardFn<K> = Rc<dyn Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict>;
2952/// A per-key yes/no rule (`.expandable`), aliased for the field above.
2953type KeyPredicate<K> = Rc<dyn Fn(&K) -> bool>;
2954/// The full-selection callback (`.on_selection`), aliased for the field above.
2955type SelectionKeysFn<K> = Rc<dyn Fn(Vec<K>)>;
2956/// A per-key string (`.type_ahead`), aliased for the field above.
2957type KeyTextFn<K> = Rc<dyn Fn(&K) -> String>;
2958/// A registered identity per tree row, reevaluated on recycle.
2959type KeyIdFn<K> = Rc<dyn Fn(&K) -> day_core::ElementId>;
2960/// A row's summon-time context-menu builder (`.row_context_menu`), aliased for the field above.
2961type RowMenuEntriesFn<K> = Rc<dyn Fn(&K) -> Vec<MenuEntry>>;
2962
2963/// Build a hierarchical tree from a [`NodeSource`] and a row builder:
2964/// `tree(branches(items_fn, key_of, parent_of), row_view)` for plain data,
2965/// `tree(store.tree(children_of), row_view)` for a day-model store.
2966pub fn tree<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> TreePiece<S>
2967where
2968    S: NodeSource + 'static,
2969    P: Piece,
2970{
2971    TreePiece {
2972        source: Some(source),
2973        build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
2974        row_height: RowHeight::Automatic,
2975        indent: None,
2976        section_headers: false,
2977        on_expansion: None,
2978        expanded: None,
2979        expandable: None,
2980        selected: None,
2981        on_selection: None,
2982        multi_select: false,
2983        movable: false,
2984        on_move: None,
2985        move_guard: None,
2986        type_ahead: None,
2987        reveal: None,
2988        row_id: None,
2989        row_menu: None,
2990    }
2991}
2992
2993#[day_macros::builder(TreeBuilder<S>)]
2994impl<S: NodeSource + 'static> TreePiece<S> {
2995    /// Row sizing: `Uniform(h)` (fastest) or `Automatic` (self-sizing).
2996    pub fn row_height(mut self, h: RowHeight) -> Self {
2997        self.row_height = h;
2998        self
2999    }
3000    /// Indentation per depth level, in points (unset = the platform's default step).
3001    pub fn indent(mut self, pts: f64) -> Self {
3002        self.indent = Some(pts);
3003        self
3004    }
3005    /// Render a two-level source as sections. Root branches are headings and cannot be
3006    /// selected; root leaves remain ordinary rows. Children must be leaves. This enables
3007    /// native `ExpandableListView` on Android, where arbitrary-depth trees are composed.
3008    pub fn section_headers(mut self) -> Self {
3009        self.section_headers = true;
3010        self
3011    }
3012    /// Reports an actual user/scripting disclosure change with the stable application key.
3013    /// Programmatic writes to `expanded` do not echo this callback.
3014    pub fn on_expansion(mut self, f: impl Fn(S::Key, bool) + 'static) -> Self {
3015        self.on_expansion = Some(Rc::new(f));
3016        self
3017    }
3018    /// The app-owned expansion set (docs/tree.md): the user's disclosure clicks update it,
3019    /// and the app writing it discloses/collapses the native rows. Persist it (or don't);
3020    /// it is plain state.
3021    pub fn expanded(mut self, set: impl Binding<HashSet<S::Key>>) -> Self {
3022        self.expanded = Some(AnyBinding::new(set));
3023        self
3024    }
3025    /// Which rows can hold children at all: what draws (or omits) the disclosure, and which
3026    /// rows a drop may land on. Defaults to "has children right now", which draws no
3027    /// disclosure on an empty group; a source with real branch/leaf kinds should say so.
3028    pub fn expandable(mut self, f: impl Fn(&S::Key) -> bool + 'static) -> Self {
3029        self.expandable = Some(Rc::new(f));
3030        self
3031    }
3032    /// Reactively sync the native selection to these keys (empty clears). Point it and
3033    /// [`Self::on_selection`] at one signal and selection is two-way, shared with anything
3034    /// else reading the same state.
3035    pub fn selected(mut self, f: impl Fn() -> Vec<S::Key> + 'static) -> Self {
3036        self.selected = Some(Rc::new(f));
3037        self
3038    }
3039    /// Called with the full selected key set (empty = cleared) whenever the user changes the
3040    /// selection.
3041    pub fn on_selection(mut self, f: impl Fn(Vec<S::Key>) + 'static) -> Self {
3042        self.on_selection = Some(Rc::new(f));
3043        self
3044    }
3045    /// Allow selecting several rows at once, where the toolkit supports it.
3046    pub fn multi_select(mut self) -> Self {
3047        self.multi_select = true;
3048        self
3049    }
3050    /// Let the user drag rows to a new parent/position with the platform's native mechanism,
3051    /// where the backend supports it (probe `Cap::TreeMove`): the tree is movable exactly when
3052    /// it carries a [`Move`], whose handler re-parents the app's data.
3053    ///
3054    /// ```ignore
3055    /// tree(nodes, row_view).movable(Move::new(move |key, parent, index| store.reparent(key, parent, index)))
3056    /// ```
3057    pub fn movable(mut self, mv: Move<S::Key>) -> Self {
3058        self.movable = true;
3059        self.on_move = Some(mv.moved);
3060        // Availability first (`Move::enabled`), then the app's guard, then the structural
3061        // refusals the driver adds.
3062        let enabled = mv.enabled;
3063        let guard = mv.guard;
3064        self.move_guard = Some(Rc::new(move |k: &S::Key, p: Option<&S::Key>, i| {
3065            if !enabled.get_untracked() {
3066                return MoveVerdict::Deny;
3067            }
3068            match &guard {
3069                Some(g) => g(k, p, i),
3070                None => MoveVerdict::Allow,
3071            }
3072        }));
3073        self
3074    }
3075    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
3076    /// Unset rows don't participate.
3077    pub fn type_ahead(mut self, f: impl Fn(&S::Key) -> String + 'static) -> Self {
3078        self.type_ahead = Some(Rc::new(f));
3079        self
3080    }
3081    /// Programmatic reveal: set the signal to `Some(key)` and the row scrolls into view with
3082    /// every ancestor expanded (through [`Self::expanded`], so the app sees the change).
3083    pub fn reveal(mut self, target: impl Binding<Option<S::Key>>) -> Self {
3084        self.reveal = Some(AnyBinding::new(target));
3085        self
3086    }
3087    /// A dayscript element id per row, from its key (docs/tree.md): re-applied on every
3088    /// recycle, so `tap`/`assert_text` address the row wherever its cell currently sits. It
3089    /// is also what the `expand:`/`tree_move:` steps resolve rows by.
3090    pub fn row_id(mut self, f: impl Fn(&S::Key) -> day_core::ElementId + 'static) -> Self {
3091        self.row_id = Some(Rc::new(f));
3092        self
3093    }
3094    /// A per-row context menu, built when the menu is summoned (docs/menus.md "Dynamic context
3095    /// menus"): right-click on desktop, long-press on touch. The closure receives the
3096    /// row's key and returns the menu to show; it may adjust the app's selection first (the
3097    /// convention: a summon outside the current selection selects that row). An empty
3098    /// result shows nothing for that row.
3099    pub fn row_context_menu(mut self, f: impl Fn(&S::Key) -> Vec<MenuEntry> + 'static) -> Self {
3100        self.row_menu = Some(Rc::new(f));
3101        self
3102    }
3103
3104    /// The composed tree (docs/tree.md M2): on a backend without a native tree widget, the
3105    /// same piece flattens its visible rows onto [`list()`]; indentation and the disclosure
3106    /// chevron are day pieces inside each row, and selection rides the list's own machinery.
3107    /// The [`TreeDriver`] still installs on the returned node, so the dayscript
3108    /// `expand:`/`tree_move:` steps drive the composed tree exactly as they drive a native
3109    /// one (`attach_tree` is the no-op default off the native path; nothing pulls cells).
3110    fn build_composed(mut self, cx: &mut BuildCx) -> RNode {
3111        // The visible rows, in display order: a refresh (the tracked shape read) plus a DFS
3112        // that descends only into expanded rows. This is the list's row set.
3113        fn visible<C: TreeConn + ?Sized>(
3114            conn: &C,
3115            is_open: &dyn Fn(u64) -> bool,
3116            parent: Option<u64>,
3117            depth: u16,
3118            out: &mut Vec<(u64, u16)>,
3119        ) {
3120            for i in 0..conn.children_len(parent) {
3121                let t = conn.child_token(parent, i);
3122                out.push((t, depth));
3123                if is_open(t) {
3124                    visible(conn, is_open, Some(t), depth + 1, out);
3125                }
3126            }
3127        }
3128        /// Disclosure column width, and the default per-depth indent where the platform
3129        /// offers no native step to inherit.
3130        const CHEVRON_W: f64 = 18.0;
3131        const DEFAULT_INDENT: f64 = 14.0;
3132
3133        let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
3134        // Expansion state: the app's key set when it owns one, else this token set. Both are
3135        // signals, so the flattener below re-runs on every disclosure however it arrives:
3136        // a chevron tap, the app writing its set, or a synthetic `expand:` step.
3137        let open_sig: Signal<HashSet<u64>> = Signal::new(HashSet::new());
3138        let expanded_sig = self.expanded;
3139
3140        // Tracked when read inside a reactive closure.
3141        let is_open: Rc<dyn Fn(u64) -> bool> = {
3142            let conn = conn.clone();
3143            match expanded_sig {
3144                Some(sig) => Rc::new(move |t| match conn.key_of(t) {
3145                    Some(k) => sig.with(|s| s.contains(&k)),
3146                    None => false,
3147                }),
3148                None => Rc::new(move |t| open_sig.with(|s| s.contains(&t))),
3149            }
3150        };
3151        let set_open: Rc<dyn Fn(u64, bool)> = {
3152            let (conn, is_open, changed) =
3153                (conn.clone(), is_open.clone(), self.on_expansion.clone());
3154            Rc::new(move |t, on| {
3155                if day_reactive::untrack(|| is_open(t)) == on {
3156                    return;
3157                }
3158                let Some(key) = conn.key_of(t) else {
3159                    return;
3160                };
3161                if let Some(sig) = expanded_sig {
3162                    sig.update(|s| {
3163                        if on {
3164                            s.insert(key.clone());
3165                        } else {
3166                            s.remove(&key);
3167                        }
3168                    });
3169                } else {
3170                    open_sig.update(|s| {
3171                        if on {
3172                            s.insert(t);
3173                        } else {
3174                            s.remove(&t);
3175                        }
3176                    });
3177                }
3178                if let Some(f) = &changed {
3179                    f(key, on);
3180                }
3181            })
3182        };
3183
3184        // "Can hold children": the app's branch/leaf rule, or "has children right now".
3185        let expandable_of: Rc<dyn Fn(u64) -> bool> = {
3186            let (conn, f) = (conn.clone(), self.expandable.clone());
3187            Rc::new(move |tok| match &f {
3188                Some(f) => conn.key_of(tok).is_some_and(|k| f(&k)),
3189                None => conn.children_len(Some(tok)) > 0,
3190            })
3191        };
3192
3193        let flatten: Rc<dyn Fn() -> Vec<(u64, u16)>> = {
3194            let (conn, is_open) = (conn.clone(), is_open.clone());
3195            Rc::new(move || {
3196                let _shape = conn.refresh();
3197                let mut rows = Vec::new();
3198                visible(&*conn, &*is_open, None, 0, &mut rows);
3199                rows
3200            })
3201        };
3202
3203        // Each physical row: indent shell → chevron + the user's row content. The rebind
3204        // watch re-points the user's slot, the depth cell, and the dayscript id whenever
3205        // the list recycles this cell onto another row.
3206        let step = self.indent.unwrap_or(DEFAULT_INDENT);
3207        let build_row = {
3208            let (conn, user_row, row_id) =
3209                (conn.clone(), self.build_row.clone(), self.row_id.clone());
3210            let (is_open, expandable_of, set_open) =
3211                (is_open.clone(), expandable_of.clone(), set_open.clone());
3212            let row_menu = self.row_menu.clone();
3213            move |slot: ItemSlot<(u64, u16), u64>| -> AnyPiece {
3214                let (token0, depth0) = day_reactive::untrack(|| slot.get());
3215                let Some(user_slot) = conn.slot_for(token0) else {
3216                    // A stale mid-reload pull: an empty row instead of a panic.
3217                    return AnyPiece::new(crate::spacer());
3218                };
3219                let depth = Rc::new(std::cell::Cell::new(f64::from(depth0)));
3220                let chevron = {
3221                    let (is_open, expandable_of) = (is_open.clone(), expandable_of.clone());
3222                    let (set_open, is_open_tap) = (set_open.clone(), is_open.clone());
3223                    let expandable_tap = expandable_of.clone();
3224                    crate::label(move || {
3225                        let t = slot.get().0;
3226                        // The full-size triangles (U+25BC/25B6), not the small ▾/▸ forms:
3227                        // HarmonyOS Sans ships no glyph for the small ones; they rendered
3228                        // as nothing at all on harmony-arkui.
3229                        if expandable_of(t) {
3230                            if is_open(t) { "▼" } else { "▶" }
3231                        } else {
3232                            ""
3233                        }
3234                        .to_string()
3235                    })
3236                    .align(TextAlign::Center)
3237                    .width(CHEVRON_W)
3238                    .on_tap(move || {
3239                        let t = day_reactive::untrack(|| slot.get().0);
3240                        if expandable_tap(t) {
3241                            set_open(t, !day_reactive::untrack(|| is_open_tap(t)));
3242                        }
3243                    })
3244                };
3245                let content = crate::row((chevron, user_row(user_slot)));
3246                let shell = TreeRowShell {
3247                    depth: depth.clone(),
3248                    step,
3249                    content: AnyPiece::new(content),
3250                }
3251                .tweak({
3252                    let (conn, row_id) = (conn.clone(), row_id.clone());
3253                    move |n| {
3254                        let id_conn = conn.clone();
3255                        let set_ids = move |tok: u64| {
3256                            if let Some(rid) = &row_id
3257                                && let Some(k) = id_conn.key_of(tok)
3258                            {
3259                                with_tree(|t| t.set_id(n, rid(&k).as_str().to_owned()));
3260                            }
3261                        };
3262                        set_ids(token0);
3263                        watch(
3264                            move || slot.get(),
3265                            move |(tok, d), _| {
3266                                conn.rebind(&user_slot, *tok);
3267                                depth.set(f64::from(*d));
3268                                set_ids(*tok);
3269                            },
3270                        );
3271                    }
3272                });
3273                match &row_menu {
3274                    // The ordinary decorator: the dom backend arms its listener, and the
3275                    // composed presenter answers the summon. The key is read when the menu is
3276                    // summoned, so a recycled cell asks about the row it currently shows.
3277                    Some(f) => {
3278                        let (conn, f) = (conn.clone(), f.clone());
3279                        AnyPiece::new(shell.context_menu(move |_p: day_spec::Point| {
3280                            match conn.key_of(day_reactive::untrack(|| slot.get().0)) {
3281                                Some(k) => f(&k),
3282                                None => Vec::new(),
3283                            }
3284                        }))
3285                    }
3286                    None => AnyPiece::new(shell),
3287                }
3288            }
3289        };
3290
3291        let section_header: Rc<dyn Fn(u64) -> bool> = {
3292            let (conn, expandable, sections) =
3293                (conn.clone(), expandable_of.clone(), self.section_headers);
3294            Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
3295        };
3296        let scroll_sig: Signal<Option<usize>> = Signal::new(None);
3297        let mut lst = list(
3298            items(
3299                {
3300                    let flatten = flatten.clone();
3301                    move || flatten()
3302                },
3303                |r: &(u64, u16)| r.0,
3304            ),
3305            build_row,
3306        )
3307        .row_height(self.row_height)
3308        .apply_if(self.multi_select, ListBuilder::multi_select)
3309        .scroll_to_row(scroll_sig);
3310        // A composed list may report a heading click. Reapply the last destination
3311        // selection even when the app's signal did not change, so headers never stay lit.
3312        let selected_tokens = Signal::new(Vec::<u64>::new());
3313        let selection_revision = Signal::new(0u64);
3314        if self.on_selection.is_some() || (self.section_headers && self.selected.is_some()) {
3315            let conn = conn.clone();
3316            let header = section_header.clone();
3317            let callback = self.on_selection.clone();
3318            lst = lst.on_selection(move |toks: Vec<u64>| {
3319                if toks.iter().any(|t| header(*t)) {
3320                    selection_revision.update(|r| *r += 1);
3321                    return;
3322                }
3323                selected_tokens.set(toks.clone());
3324                if let Some(f) = &callback {
3325                    f(toks.iter().filter_map(|t| conn.key_of(*t)).collect());
3326                }
3327            });
3328        }
3329        let mut repair_selection: Option<Rc<dyn Fn() -> Vec<usize>>> = None;
3330        if self.selected.is_some() || (self.section_headers && self.on_selection.is_some()) {
3331            let (conn, flatten, selected) = (conn.clone(), flatten.clone(), self.selected.clone());
3332            let section_header = section_header.clone();
3333            let rows: Rc<dyn Fn() -> Vec<usize>> = Rc::new(move || {
3334                let rows = flatten();
3335                let want: HashSet<u64> = match &selected {
3336                    Some(sel) => sel().iter().map(|k| conn.token_of(k)).collect(),
3337                    None => selected_tokens.get().into_iter().collect(),
3338                };
3339                rows.iter()
3340                    .enumerate()
3341                    .filter(|(_, r)| want.contains(&r.0) && !section_header(r.0))
3342                    .map(|(i, _)| i)
3343                    .collect()
3344            });
3345            repair_selection = Some(rows.clone());
3346            lst = lst.selected_rows(move || rows());
3347        }
3348        let node = lst.build(cx);
3349        if let Some(rows) = repair_selection {
3350            day_reactive::bind(
3351                move || selection_revision.get(),
3352                move |revision| {
3353                    if *revision != 0 {
3354                        let rows = day_reactive::untrack(|| rows());
3355                        day_reactive::on_main(move || day_core::list_set_selected(node, rows));
3356                    }
3357                },
3358            );
3359        }
3360
3361        // Synthetic events (the dayscript `expand:` step, `tree_try_move`'s commit) land on
3362        // this node exactly as native ones land on a native tree.
3363        {
3364            let (on_move, conn_ev, set_open) =
3365                (self.on_move.clone(), conn.clone(), set_open.clone());
3366            cx.on(node, move |ev| match ev {
3367                Event::TreeExpanded { token, expanded } => set_open(*token, *expanded),
3368                Event::TreeMove {
3369                    token,
3370                    parent,
3371                    index,
3372                } => {
3373                    if let Some(f) = &on_move
3374                        && let Some(key) = conn_ev.key_of(*token)
3375                    {
3376                        f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
3377                    }
3378                }
3379                _ => {}
3380            });
3381        }
3382
3383        // The driver: what `expand:`/`tree_move:` resolve rows and route moves through.
3384        let driver = TreeDriver {
3385            section_header: {
3386                let f = section_header.clone();
3387                Box::new(move |t| f(t))
3388            },
3389            row_height: self.row_height,
3390            children_len: {
3391                let conn = conn.clone();
3392                Box::new(move |p| conn.children_len(p))
3393            },
3394            child_token: {
3395                let conn = conn.clone();
3396                Box::new(move |p, i| conn.child_token(p, i))
3397            },
3398            expandable: {
3399                let f = expandable_of.clone();
3400                Box::new(move |t| f(t))
3401            },
3402            expanded: {
3403                let is_open = is_open.clone();
3404                Box::new(move |t| day_reactive::untrack(|| is_open(t)))
3405            },
3406            // Never pulled: no toolkit attaches to the composed tree, so no cell binds
3407            // arrive. The list's own driver owns the physical rows.
3408            build: Box::new(|_tok, _anchor| TreeBuiltRow {
3409                scope: Scope::child(),
3410                rebind: Rc::new(|_| {}),
3411            }),
3412            type_select_text: Box::new(|_| String::new()),
3413            resolve_row: {
3414                let (conn, row_id) = (conn.clone(), self.row_id.clone());
3415                Box::new(move |id| {
3416                    let rid = row_id.as_ref()?;
3417                    conn.tokens_now()
3418                        .into_iter()
3419                        .find(|t| conn.key_of(*t).is_some_and(|k| rid(&k).as_str() == id))
3420                })
3421            },
3422            row_menu: None,
3423            moves: self.movable.then(|| {
3424                let can = {
3425                    let (conn, expandable_of, guard) =
3426                        (conn.clone(), expandable_of.clone(), self.move_guard.clone());
3427                    move |tok: u64, parent: Option<u64>, index: Option<usize>| {
3428                        let Some(key) = conn.key_of(tok) else {
3429                            return MoveVerdict::Deny;
3430                        };
3431                        let parent_key = match parent {
3432                            Some(p) => {
3433                                if p == tok || !expandable_of(p) {
3434                                    return MoveVerdict::Deny;
3435                                }
3436                                let mut cur = Some(p);
3437                                while let Some(c) = cur {
3438                                    if c == tok {
3439                                        return MoveVerdict::Deny;
3440                                    }
3441                                    cur = conn.parent_of(c).flatten();
3442                                }
3443                                match conn.key_of(p) {
3444                                    Some(k) => Some(k),
3445                                    None => return MoveVerdict::Deny,
3446                                }
3447                            }
3448                            None => None,
3449                        };
3450                        match &guard {
3451                            Some(g) => g(&key, parent_key.as_ref(), index),
3452                            None => MoveVerdict::Allow,
3453                        }
3454                    }
3455                };
3456                let can_commit = can.clone();
3457                TreeMovesDriver {
3458                    can_move: Box::new(can),
3459                    moved: Box::new(move |t, p, i| {
3460                        if can_commit(t, p, i) == MoveVerdict::Deny {
3461                            return;
3462                        }
3463                        enqueue_event(
3464                            rnode_to_id(node),
3465                            Event::TreeMove {
3466                                token: t,
3467                                parent: p,
3468                                index: i,
3469                            },
3470                        );
3471                    }),
3472                }
3473            }),
3474        };
3475        install_tree(node, driver);
3476
3477        // Reveal: expand every ancestor through the app-visible state, then scroll the
3478        // list to the row's flattened index.
3479        if let Some(sig) = self.reveal {
3480            let (conn, set_open, flatten) = (conn.clone(), set_open.clone(), flatten.clone());
3481            watch(
3482                move || sig.get(),
3483                move |key: &Option<S::Key>, _| {
3484                    let Some(key) = key else { return };
3485                    let tok = conn.token_of(key);
3486                    let mut cur = conn.parent_of(tok).flatten();
3487                    while let Some(p) = cur {
3488                        set_open(p, true);
3489                        cur = conn.parent_of(p).flatten();
3490                    }
3491                    let row = day_reactive::untrack(|| flatten())
3492                        .iter()
3493                        .position(|r| r.0 == tok);
3494                    if let Some(row) = row {
3495                        scroll_sig.set(Some(row));
3496                    }
3497                },
3498            );
3499        }
3500
3501        node
3502    }
3503}
3504
3505/// The composed tree row's indentation (docs/tree.md M2): offsets its single child by the
3506/// row's current depth × step. Depth lives in a `Cell` the rebind watch writes before the
3507/// cell's relayout, so a recycled row re-indents without rebuilding.
3508struct TreeIndent {
3509    depth: Rc<std::cell::Cell<f64>>,
3510    step: f64,
3511}
3512
3513impl Layout for TreeIndent {
3514    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
3515        let pad = self.depth.get() * self.step;
3516        let child_p = Proposal::new(p.width.map(|w| (w - pad).max(0.0)), p.height);
3517        let s = match children.first() {
3518            Some(&c) => cx.measure_child(c, child_p),
3519            None => Size::ZERO,
3520        };
3521        Size::new(s.width + pad, s.height)
3522    }
3523    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
3524        if let Some(&c) = children.first() {
3525            let pad = (self.depth.get() * self.step).min(bounds.size.width);
3526            let inner = Size::new(bounds.size.width - pad, bounds.size.height);
3527            let _ = cx.measure_child(c, Proposal::exact(inner));
3528            cx.place_child(c, Rect::new(pad, 0.0, inner.width, inner.height));
3529        }
3530    }
3531}
3532
3533/// One composed tree row: the [`TreeIndent`] wrapper around the chevron + user content,
3534/// grown to the cell's width so selection and taps span the row.
3535struct TreeRowShell {
3536    depth: Rc<std::cell::Cell<f64>>,
3537    step: f64,
3538    content: AnyPiece,
3539}
3540
3541impl Piece for TreeRowShell {
3542    fn build(self, cx: &mut BuildCx) -> RNode {
3543        // Native, not layout-only: the row's dayscript id and its `.context_menu_fn` listener
3544        // both need a realized element to land on (a11y identifier; the dom's `contextmenu`
3545        // arm). A transparent container, like the decorators' layer nodes.
3546        let w = cx.native(
3547            kinds::CONTAINER,
3548            &ContainerProps {
3549                corner_radius: 0.0,
3550                clips: false,
3551                role: None,
3552                ..Default::default()
3553            },
3554            Rc::new(TreeIndent {
3555                depth: self.depth,
3556                step: self.step,
3557            }),
3558            Flex {
3559                grow_w: true,
3560                ..Default::default()
3561            },
3562            Boundary::No,
3563        );
3564        cx.under(w, |cx| {
3565            let _ = self.content.build(cx);
3566        });
3567        w
3568    }
3569}
3570
3571impl<S: NodeSource + 'static> Piece for TreePiece<S> {
3572    fn build(mut self, cx: &mut BuildCx) -> RNode {
3573        // No native tree widget → the composed tree: the same piece contract flattened onto
3574        // [`list()`] (docs/tree.md M2). `Emulated` and `Unsupported` both take this path; the
3575        // composition needs nothing beyond the list machinery every backend carries.
3576        // Two-level-only native controls (Android) provide single selection. A
3577        // multi-select section source uses the full-tree path, composed where necessary.
3578        let cap = if self.section_headers && !self.multi_select {
3579            day_spec::Cap::TreeSections
3580        } else {
3581            day_spec::Cap::Tree
3582        };
3583        if day_core::capability(cap) != day_spec::Support::Native {
3584            return self.build_composed(cx);
3585        }
3586        let props = TreeProps {
3587            section_headers: self.section_headers,
3588            row_height: self.row_height,
3589            selectable: self.selected.is_some() || self.on_selection.is_some(),
3590            multi_select: self.multi_select,
3591            movable: self.movable,
3592            indent: self.indent,
3593        };
3594        let node = cx.leaf(
3595            kinds::TREE,
3596            &props,
3597            Flex {
3598                grow_w: true,
3599                grow_h: true,
3600                ..Default::default()
3601            },
3602        );
3603
3604        let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
3605
3606        // The driver's (and flattener's) view of expansion: token-keyed, updated from native
3607        // disclosure events and from every programmatic patch this piece issues, so it is
3608        // right whether or not the app owns an expansion signal.
3609        let open_tokens: Rc<RefCell<HashSet<u64>>> = Rc::new(RefCell::new(HashSet::new()));
3610
3611        // "Can hold children": the app's branch/leaf rule, or "has children right now".
3612        let expandable_of: Rc<dyn Fn(u64) -> bool> = {
3613            let (conn, f) = (conn.clone(), self.expandable.clone());
3614            Rc::new(move |tok| match &f {
3615                Some(f) => conn.key_of(tok).is_some_and(|k| f(&k)),
3616                None => conn.children_len(Some(tok)) > 0,
3617            })
3618        };
3619
3620        let section_header: Rc<dyn Fn(u64) -> bool> = {
3621            let (conn, expandable, sections) =
3622                (conn.clone(), expandable_of.clone(), self.section_headers);
3623            Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
3624        };
3625        // Native events → app state.
3626        {
3627            let (on_selection, expanded_sig) = (self.on_selection.clone(), self.expanded);
3628            let (on_move, conn_ev, open) =
3629                (self.on_move.clone(), conn.clone(), open_tokens.clone());
3630            let changed = self.on_expansion.clone();
3631            let header = section_header.clone();
3632            cx.on(node, move |ev| match ev {
3633                Event::TreeSelection(tokens) => {
3634                    if let Some(f) = &on_selection {
3635                        f(tokens
3636                            .iter()
3637                            .filter(|t| !header(**t))
3638                            .filter_map(|t| conn_ev.key_of(*t))
3639                            .collect());
3640                    }
3641                }
3642                Event::TreeExpanded { token, expanded } => {
3643                    let Some(key) = conn_ev.key_of(*token) else {
3644                        return;
3645                    };
3646                    let was = expanded_sig.map_or_else(
3647                        || open.borrow().contains(token),
3648                        |sig| day_reactive::untrack(|| sig.with(|s| s.contains(&key))),
3649                    );
3650                    if was == *expanded {
3651                        return;
3652                    }
3653                    if let Some(sig) = &expanded_sig {
3654                        // The app's set follows the disclosure, and the expansion watch
3655                        // derives the patch. The record does not move here: for a native
3656                        // click the patch is a redundant no-op, and for a synthetic event
3657                        // (the dayscript `expand:` step) it is the very thing that discloses
3658                        // the row; pre-moving the record swallowed it.
3659                        if let Some(key) = conn_ev.key_of(*token) {
3660                            sig.update(|set| {
3661                                if *expanded {
3662                                    set.insert(key.clone());
3663                                } else {
3664                                    set.remove(&key);
3665                                }
3666                            });
3667                        }
3668                    } else {
3669                        // No app signal: this record IS the expansion state.
3670                        // The native tree is told too: a no-op after a native click, and for a
3671                        // synthetic event (the dayscript `expand:` step) the disclosure itself,
3672                        // which recording alone never showed.
3673                        if *expanded {
3674                            open.borrow_mut().insert(*token);
3675                        } else {
3676                            open.borrow_mut().remove(token);
3677                        }
3678                        day_core::tree_set_expanded(node, *token, *expanded);
3679                    }
3680                    if let Some(f) = &changed {
3681                        f(key, *expanded);
3682                    }
3683                }
3684                Event::TreeMove {
3685                    token,
3686                    parent,
3687                    index,
3688                } => {
3689                    if let Some(f) = &on_move
3690                        && let Some(key) = conn_ev.key_of(*token)
3691                    {
3692                        f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
3693                    }
3694                }
3695                _ => {}
3696            });
3697        }
3698
3699        // The type-erased driver day-core drives on cell pulls (docs/tree.md).
3700        let driver = TreeDriver {
3701            section_header: {
3702                let f = section_header.clone();
3703                Box::new(move |t| f(t))
3704            },
3705            row_height: self.row_height,
3706            children_len: {
3707                let conn = conn.clone();
3708                Box::new(move |p| conn.children_len(p))
3709            },
3710            child_token: {
3711                let conn = conn.clone();
3712                Box::new(move |p, i| conn.child_token(p, i))
3713            },
3714            expandable: {
3715                let f = expandable_of.clone();
3716                Box::new(move |t| f(t))
3717            },
3718            expanded: {
3719                let open = open_tokens.clone();
3720                Box::new(move |t| open.borrow().contains(&t))
3721            },
3722            build: {
3723                let (conn, build_row, row_id) =
3724                    (conn.clone(), self.build_row.clone(), self.row_id.clone());
3725                Box::new(move |token, anchor| {
3726                    let scope = Scope::child();
3727                    let (conn, build_row, row_id) =
3728                        (conn.clone(), build_row.clone(), row_id.clone());
3729                    let rebind = scope.enter(move || {
3730                        // Native callbacks can deliver a stale token mid-animation; an
3731                        // unknown pull yields an empty row instead of panicking.
3732                        let Some(slot) = conn.slot_for(token) else {
3733                            return Rc::new(|_: u64| {}) as Rc<dyn Fn(u64)>;
3734                        };
3735                        let mut rowcx = BuildCx::new(anchor);
3736                        let root = build_row(slot).build(&mut rowcx);
3737                        if let Some(rid) = &row_id
3738                            && let Some(k) = conn.key_of(token)
3739                        {
3740                            with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
3741                        }
3742                        // Rebind on recycle: point the slot (and the row's element id) at
3743                        // the cell's new row.
3744                        Rc::new(move |tok: u64| {
3745                            conn.rebind(&slot, tok);
3746                            if let Some(rid) = &row_id
3747                                && let Some(k) = conn.key_of(tok)
3748                            {
3749                                with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
3750                            }
3751                        }) as Rc<dyn Fn(u64)>
3752                    });
3753                    TreeBuiltRow { scope, rebind }
3754                })
3755            },
3756            type_select_text: {
3757                let (conn, f) = (conn.clone(), self.type_ahead.clone());
3758                Box::new(move |tok| match &f {
3759                    Some(f) => conn.key_of(tok).map_or_default(|k| f(&k)),
3760                    None => String::new(),
3761                })
3762            },
3763            resolve_row: {
3764                let (conn, row_id) = (conn.clone(), self.row_id.clone());
3765                Box::new(move |id| {
3766                    let rid = row_id.as_ref()?;
3767                    conn.tokens_now()
3768                        .into_iter()
3769                        .find(|t| conn.key_of(*t).is_some_and(|k| rid(&k).as_str() == id))
3770                })
3771            },
3772            row_menu: self.row_menu.clone().map(|f| {
3773                // Per-summon lowering in its own scope, disposed when the next summon (or
3774                // the tree's teardown) replaces it: the `context_menu_fn` rule.
3775                let conn = conn.clone();
3776                let last: Rc<RefCell<Option<Scope>>> = Rc::default();
3777                {
3778                    let last = last.clone();
3779                    Scope::current().on_cleanup(move || {
3780                        if let Some(s) = last.borrow_mut().take() {
3781                            s.dispose();
3782                        }
3783                    });
3784                }
3785                Box::new(move |tok: u64| {
3786                    let Some(key) = conn.key_of(tok) else {
3787                        return Vec::new();
3788                    };
3789                    if let Some(s) = last.borrow_mut().take() {
3790                        s.dispose();
3791                    }
3792                    let scope = Scope::child();
3793                    let items = scope.enter(|| crate::menus::lower_menu_scoped(f(&key)));
3794                    *last.borrow_mut() = Some(scope);
3795                    items
3796                }) as day_core::tree_driver::RowMenuFn
3797            }),
3798            moves: self.movable.then(|| {
3799                // The live verdict: structural refusals first (a row into itself, into its
3800                // own descendant, into a leaf, or addressing anything unknown), then the
3801                // app's guard.
3802                let can = {
3803                    let (conn, expandable_of, guard) =
3804                        (conn.clone(), expandable_of.clone(), self.move_guard.clone());
3805                    move |tok: u64, parent: Option<u64>, index: Option<usize>| {
3806                        let Some(key) = conn.key_of(tok) else {
3807                            return MoveVerdict::Deny;
3808                        };
3809                        let parent_key = match parent {
3810                            Some(p) => {
3811                                if p == tok || !expandable_of(p) {
3812                                    return MoveVerdict::Deny;
3813                                }
3814                                // Walk p's ancestors: dropping into one's own subtree.
3815                                let mut cur = Some(p);
3816                                while let Some(c) = cur {
3817                                    if c == tok {
3818                                        return MoveVerdict::Deny;
3819                                    }
3820                                    cur = conn.parent_of(c).flatten();
3821                                }
3822                                match conn.key_of(p) {
3823                                    Some(k) => Some(k),
3824                                    None => return MoveVerdict::Deny,
3825                                }
3826                            }
3827                            None => None,
3828                        };
3829                        match &guard {
3830                            Some(g) => g(&key, parent_key.as_ref(), index),
3831                            None => MoveVerdict::Allow,
3832                        }
3833                    }
3834                };
3835                let can_commit = can.clone();
3836                TreeMovesDriver {
3837                    can_move: Box::new(can),
3838                    // Commit: defer the app's callback through the event queue; its own data
3839                    // write drives the reload (docs/tree.md).
3840                    moved: Box::new(move |t, p, i| {
3841                        if can_commit(t, p, i) == MoveVerdict::Deny {
3842                            return;
3843                        }
3844                        enqueue_event(
3845                            rnode_to_id(node),
3846                            Event::TreeMove {
3847                                token: t,
3848                                parent: p,
3849                                index: i,
3850                            },
3851                        );
3852                    }),
3853                }
3854            }),
3855        };
3856        install_tree(node, driver);
3857
3858        // Prime the snapshot, tell the native host, and re-assert expansion + selection by
3859        // token after every shape change (docs/tree.md: a reload must not silently collapse
3860        // the tree or drop its selection).
3861        let apply_expansion = {
3862            let (conn, open) = (conn.clone(), open_tokens.clone());
3863            let expanded_sig = self.expanded;
3864            move || {
3865                let desired: HashSet<u64> = match &expanded_sig {
3866                    Some(sig) => {
3867                        let conn = &conn;
3868                        sig.get_untracked()
3869                            .iter()
3870                            .map(|k| conn.token_of(k))
3871                            .collect()
3872                    }
3873                    None => open.borrow().clone(),
3874                };
3875                let present: HashSet<u64> = conn.tokens_now().into_iter().collect();
3876                // Parents before children: a backend may not record a disclosure for a row
3877                // whose ancestor is still collapsed.
3878                let mut ordered: Vec<u64> = desired
3879                    .iter()
3880                    .filter(|t| present.contains(t))
3881                    .copied()
3882                    .collect();
3883                let depth_of = |mut t: u64| {
3884                    let mut d = 0usize;
3885                    while let Some(Some(p)) = conn.parent_of(t) {
3886                        d += 1;
3887                        t = p;
3888                    }
3889                    d
3890                };
3891                ordered.sort_by_key(|t| depth_of(*t));
3892                for t in ordered {
3893                    tree_set_expanded(node, t, true);
3894                }
3895                open.borrow_mut().clone_from(&desired);
3896            }
3897        };
3898        let apply_selection = {
3899            let (conn, selected) = (conn.clone(), self.selected.clone());
3900            move || {
3901                if let Some(sel) = &selected {
3902                    let keys = day_reactive::untrack(|| sel());
3903                    let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
3904                    tree_set_selected(node, toks);
3905                }
3906            }
3907        };
3908        {
3909            let conn2 = conn.clone();
3910            let initial = {
3911                let conn = conn.clone();
3912                day_reactive::untrack(move || conn.refresh())
3913            };
3914            // The native host attached against an empty snapshot: tell it the real node set
3915            // now, then disclose the initially-expanded rows (see the list's prime for why
3916            // skipping this renders blank while the synthetic rail keeps passing).
3917            tree_reload(node);
3918            apply_expansion();
3919            apply_selection();
3920            let last: RefCell<Vec<(u64, Option<u64>)>> = RefCell::new(initial);
3921            let (apply_expansion, apply_selection) =
3922                (apply_expansion.clone(), apply_selection.clone());
3923            let conn3 = conn.clone();
3924            watch(
3925                move || conn2.refresh(),
3926                move |shape: &Vec<(u64, Option<u64>)>, _| {
3927                    let unchanged = !conn3.values_flow_by_reload() && *last.borrow() == *shape;
3928                    (*last.borrow_mut()).clone_from(shape);
3929                    if unchanged {
3930                        return;
3931                    }
3932                    tree_reload(node);
3933                    apply_expansion();
3934                    apply_selection();
3935                },
3936            );
3937        }
3938
3939        // App expansion signal → native disclosure (delta patches; redundant ones no-op).
3940        if let Some(sig) = self.expanded {
3941            let (conn, open) = (conn.clone(), open_tokens.clone());
3942            watch(
3943                move || sig.get(),
3944                move |set: &HashSet<S::Key>, _| {
3945                    let desired: HashSet<u64> = set.iter().map(|k| conn.token_of(k)).collect();
3946                    let current = open.borrow().clone();
3947                    for t in desired.difference(&current) {
3948                        tree_set_expanded(node, *t, true);
3949                    }
3950                    for t in current.difference(&desired) {
3951                        tree_set_expanded(node, *t, false);
3952                    }
3953                    open.borrow_mut().clone_from(&desired);
3954                },
3955            );
3956        }
3957
3958        // Programmatic selection sync (`watch`, so the initial build doesn't clobber a
3959        // toolkit-default selection; the prime above already applied it once).
3960        if let Some(sel) = self.selected.clone() {
3961            let conn = conn.clone();
3962            watch(
3963                move || sel(),
3964                move |keys: &Vec<S::Key>, _| {
3965                    let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
3966                    tree_set_selected(node, toks);
3967                },
3968            );
3969        }
3970
3971        // Reveal: expand every ancestor (native + the app's signal), then scroll.
3972        if let Some(sig) = self.reveal {
3973            let (conn, open, expanded_sig) = (conn.clone(), open_tokens.clone(), self.expanded);
3974            watch(
3975                move || sig.get(),
3976                move |key: &Option<S::Key>, _| {
3977                    let Some(key) = key else { return };
3978                    let tok = conn.token_of(key);
3979                    let mut ancestors = Vec::new();
3980                    let mut cur = conn.parent_of(tok).flatten();
3981                    while let Some(p) = cur {
3982                        ancestors.push(p);
3983                        cur = conn.parent_of(p).flatten();
3984                    }
3985                    for p in ancestors.iter().rev() {
3986                        tree_set_expanded(node, *p, true);
3987                        open.borrow_mut().insert(*p);
3988                        if let Some(sig) = &expanded_sig
3989                            && let Some(k) = conn.key_of(*p)
3990                        {
3991                            sig.update(|set| {
3992                                set.insert(k.clone());
3993                            });
3994                        }
3995                    }
3996                    tree_reveal(node, tok);
3997                },
3998            );
3999        }
4000
4001        node
4002    }
4003}
4004
4005// ---------------------------------------------------------------------------
4006// The test host (docs/testing.md)
4007// ---------------------------------------------------------------------------
4008
4009/// The root of an app's test build: `content` normally, and while `day test` drives a GUI
4010/// case, that case's page alone, built fresh for the case and disposed when the next one
4011/// starts. One page mounted at a time is what keeps one case's ids, signals and resident
4012/// native views out of the next one's way.
4013///
4014/// ```ignore
4015/// pub fn root() -> impl Piece {
4016///     day::test_host(|| my_app_root())
4017/// }
4018/// ```
4019///
4020/// A panic while the case's page is built is caught here and reported as the case's failure;
4021/// the host shows the message in its place.
4022pub fn test_host<P: Piece>(content: impl Fn() -> P + 'static) -> impl Piece {
4023    let content = Rc::new(content);
4024    piece_fn(move |cx| {
4025        // Bumped whenever the engine changes the active case: a new key is a new `each` row,
4026        // so the old page's scope is disposed and the new one builds from scratch.
4027        let generation = Signal::new(0u64);
4028        day_core::conformance::set_host(Some(Rc::new(move || generation.update(|g| *g += 1))));
4029        Scope::current().on_cleanup(|| day_core::conformance::set_host(None));
4030        each(
4031            items(move || vec![generation.get()], |g: &u64| *g),
4032            move |_| match day_core::conformance::active() {
4033                Some(case) => guarded_page(case),
4034                None => AnyPiece::new(content()),
4035            },
4036        )
4037        .build(cx)
4038    })
4039}
4040
4041/// A case's page, built with a panic caught and recorded rather than taking the app down.
4042/// Also what a browsing view of the cases shows (the conformance app's navigation).
4043pub fn guarded_page(case: day_core::conformance::Case) -> AnyPiece {
4044    AnyPiece::new(piece_fn(move |cx| {
4045        let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4046            case.build_page().map(|page| page.build(&mut *cx))
4047        }));
4048        match built {
4049            Ok(Some(root)) => root,
4050            Ok(None) => crate::label("").build(cx),
4051            Err(payload) => {
4052                let message = day_core::conformance::panic_message(payload.as_ref());
4053                day_core::conformance::note_page_panic(message.clone());
4054                crate::label(format!("panicked: {message}")).build(cx)
4055            }
4056        }
4057    }))
4058}
4059
4060#[cfg(feature = "conformance")]
4061pub(crate) mod conformance {
4062    use day_core::conformance::{Case, Drive, Fail, FrameExpect};
4063    use day_geometry::Insets;
4064    use day_reactive::Signal;
4065    use day_spec::props::RowHeight;
4066    use day_spec::{Cap, Font, kinds};
4067
4068    use crate::*;
4069
4070    /// A list of the given names, each row a label with the id `row:<name>`.
4071    fn names_list(names: Signal<Vec<String>>) -> List<Items<String, String>> {
4072        list(
4073            items(move || names.get(), |n: &String| n.clone()),
4074            |row: ItemSlot<String, String>| {
4075                // A reactive id, before the padding: a recycled cell rebinds to other rows, and
4076                // the id must name the label rather than its wrapper.
4077                label(move || row.get())
4078                    .id_of(move || day_core::id!(conformance_row, row.get()))
4079                    .padding(Insets::symmetric(12.0, 6.0))
4080            },
4081        )
4082        .row_height(RowHeight::Uniform(32.0))
4083    }
4084
4085    fn names(list: &[&str]) -> Signal<Vec<String>> {
4086        Signal::new(list.iter().map(std::string::ToString::to_string).collect())
4087    }
4088
4089    /// A list item realizes as the platform's own row content (docs/list.md "List items"),
4090    /// and its check mark follows its source in place.
4091    #[day_macros::test(day_core)]
4092    fn list_items_show_their_parts() -> Case {
4093        Case::new()
4094            .proves(kinds::LIST_ITEM)
4095            .proves_cap(Cap::ListItem)
4096            .requires(Cap::ListItem)
4097            .page(|| {
4098                let done = Signal::new(false);
4099                let rows = names(&["Milk", "Bread"]);
4100                column((
4101                    button("Done")
4102                        .action(move || done.update(|d| *d = !*d))
4103                        .id(day_core::id!(toggle_done)),
4104                    list(
4105                        items(move || rows.get(), |n: &String| n.clone()),
4106                        move |row: ItemSlot<String, String>| {
4107                            list_item(move || row.get())
4108                                .subtitle("aisle 4")
4109                                .checked(move || done.get())
4110                                .id_of(move || day_core::id!(conformance_item, row.get()))
4111                        },
4112                    )
4113                    .height(200.0),
4114                ))
4115            })
4116            .drive(|d: Drive| async move {
4117                d.assert_visible("conformance_item:Milk").await?;
4118                d.tap("toggle_done").await?;
4119                d.assert_visible("conformance_item:Bread").await
4120            })
4121    }
4122
4123    /// A list realizes a native cell for each row, showing the row's content.
4124    #[day_macros::test(day_core)]
4125    fn list_rows_realize() -> Case {
4126        Case::new()
4127            .proves_duty("attach_list")
4128            .proves_duty("adopt")
4129            .proves(kinds::LIST)
4130            .proves(kinds::LIST_CELL)
4131            .page(|| {
4132                names_list(names(&["Alpha", "Beta", "Gamma"]))
4133                    .id(day_core::id!(list))
4134                    .height(200.0)
4135            })
4136            .drive(|d: Drive| async move {
4137                d.assert_text("conformance_row:Alpha", "Alpha").await?;
4138                d.assert_text("conformance_row:Gamma", "Gamma").await
4139            })
4140    }
4141
4142    /// A row added to the source appears in the native list; one removed goes away.
4143    #[day_macros::test(day_core)]
4144    fn list_follows_source() -> Case {
4145        Case::new()
4146            .proves_duty("release")
4147            .proves(kinds::LIST)
4148            .page(|| {
4149                let rows = names(&["Alpha", "Beta"]);
4150                column((
4151                    button("Add")
4152                        .action(move || rows.update(|v| v.push("Delta".into())))
4153                        .id(day_core::id!(add)),
4154                    button("Drop")
4155                        .action(move || rows.update(|v| v.retain(|n| n != "Alpha")))
4156                        .id(day_core::id!(drop)),
4157                    names_list(rows).id(day_core::id!(list)).height(200.0),
4158                ))
4159            })
4160            .drive(|d: Drive| async move {
4161                d.assert_missing("conformance_row:Delta").await?;
4162                d.tap("add").await?;
4163                d.assert_text("conformance_row:Delta", "Delta").await?;
4164                d.tap("drop").await?;
4165                d.assert_missing("conformance_row:Alpha").await?;
4166                d.assert_text("conformance_row:Beta", "Beta").await
4167            })
4168    }
4169
4170    /// Synthetic fixture: appending and scrolling in one event must apply the native insert
4171    /// before scrolling. UIKit used to scroll against its old count and throw an exception.
4172    #[day_macros::test(day_core)]
4173    fn list_append_then_scroll() -> Case {
4174        Case::new()
4175            .proves(kinds::LIST)
4176            .page(|| {
4177                let rows = names(&[]);
4178                let scroll = Signal::new(None);
4179                column((
4180                    button("Append").id(day_core::id!(append)).action(move || {
4181                        rows.update(|rows| rows.push(format!("Item {}", rows.len())));
4182                        scroll.set(Some(rows.with(|rows| rows.len() - 1)));
4183                    }),
4184                    names_list(rows)
4185                        .scroll_to_row(scroll)
4186                        .id(day_core::id!(list))
4187                        .height(120.0),
4188                ))
4189            })
4190            .drive(|d: Drive| async move {
4191                // Start empty, then grow past the viewport to prove the scroll actually runs.
4192                for index in 0..8 {
4193                    d.tap("append").await?;
4194                    d.assert_visible(&format!("conformance_row:Item%20{index}"))
4195                        .await?;
4196                }
4197                Ok(())
4198            })
4199    }
4200
4201    /// The rows of the self-sizing fixture, in order: key, font, text.
4202    const SIZED: [(&str, Font, &str); 5] = [
4203        ("small", Font::Caption2, "Small print"),
4204        ("large", Font::LargeTitle, "Large"),
4205        ("body", Font::Body, "Body text"),
4206        (
4207            "wrap",
4208            Font::Footnote,
4209            "A footnote long enough to wrap onto three lines or more in a narrow list, \
4210             whatever the platform's type scale, so its row is several lines tall",
4211        ),
4212        ("end", Font::Body, "End"),
4213    ];
4214
4215    /// The text the `body` row grows to: several lines at any platform's type scale.
4216    const GROWN: &str = "Body text that grew long enough to wrap onto several lines, \
4217        the way a row does when its content changes after it was first sized";
4218
4219    /// A self-sizing list of [`SIZED`] rows, each a bare label with the id `sized:<key>`, so
4220    /// the label's frame is the row's whole height. `grown` swaps the `body` row's text.
4221    fn sized_list(grown: Signal<bool>) -> List<Items<&'static str, &'static str>> {
4222        list(
4223            items(|| SIZED.iter().map(|r| r.0).collect(), |k: &&str| *k),
4224            move |slot: ItemSlot<&'static str, &'static str>| {
4225                // A label's font is fixed at build, and cells recycle: one arm per font, only
4226                // the slot's own one built.
4227                let arm = |key: &'static str, font: Font, text: &'static str| {
4228                    when(
4229                        move || slot.get() == key,
4230                        move || {
4231                            label(move || {
4232                                if key == "body" && grown.get() {
4233                                    GROWN.to_string()
4234                                } else {
4235                                    text.to_string()
4236                                }
4237                            })
4238                            .font(font)
4239                            .id_of(move || day_core::id!(sized, slot.get()))
4240                        },
4241                    )
4242                };
4243                let [a, b, c, d, e] = SIZED;
4244                column((
4245                    arm(a.0, a.1, a.2),
4246                    arm(b.0, b.1, b.2),
4247                    arm(c.0, c.1, c.2),
4248                    arm(d.0, d.1, d.2),
4249                    arm(e.0, e.1, e.2),
4250                ))
4251                .spacing(0.0)
4252            },
4253        )
4254        .row_height(RowHeight::Automatic)
4255        .no_separators()
4256    }
4257
4258    /// One `sized:` row as laid out: its label's Day height, the height Day gave the row around
4259    /// it, and the row's native top, in window points.
4260    struct SizedRow {
4261        key: &'static str,
4262        content: f64,
4263        row: f64,
4264        top: f64,
4265    }
4266
4267    /// Every `sized:` row, in row order.
4268    ///
4269    /// The row's height is its cell anchor's Day frame, not the label's: Day lays a row inside
4270    /// the platform's margins and holds it at the platform's minimum height (docs/list.md "Row
4271    /// metrics"), so a caption row is taller than its text by more than a large-title row is.
4272    fn sized_rows() -> Result<Vec<SizedRow>, Fail> {
4273        day_core::try_with_tree(|t| {
4274            SIZED
4275                .iter()
4276                .map(|(key, ..)| {
4277                    let id = format!("sized:{key}");
4278                    let node = t
4279                        .find_by_id(&id)
4280                        .ok_or_else(|| Fail(format!("no element {id:?}")))?;
4281                    let content = t
4282                        .node_frame(node)
4283                        .ok_or_else(|| Fail(format!("{id:?} has no Day frame")))?;
4284                    let mut anchor = node;
4285                    while t.node_kind(anchor) != Some(kinds::LIST_CELL) {
4286                        anchor = t
4287                            .parent_of(anchor)
4288                            .ok_or_else(|| Fail(format!("{id:?} is not inside a list cell")))?;
4289                    }
4290                    let row = t
4291                        .node_frame(anchor)
4292                        .ok_or_else(|| Fail(format!("{id:?}'s row has no Day frame")))?;
4293                    let native = t
4294                        .read_native(node)
4295                        .and_then(|n| n.frame)
4296                        .ok_or_else(|| Fail(format!("{id:?} has no native frame")))?;
4297                    Ok(SizedRow {
4298                        key,
4299                        content: content.size.height,
4300                        row: row.size.height,
4301                        top: native.origin.y,
4302                    })
4303                })
4304                .collect()
4305        })
4306        .unwrap_or_else(|| Err(Fail("the tree is busy".into())))
4307    }
4308
4309    /// Every row is as tall as Day laid it: the next row's content starts one row height below
4310    /// this one's, give or take a chrome allowance (a GTK row's theme padding) that every row
4311    /// shares. A row the platform held at a fixed height either clips its content (the next row
4312    /// starts too soon) or leaves a gap that differs from row to row.
4313    ///
4314    /// Measured content top to content top, and Day centers content in a row taller than it,
4315    /// so each pitch also carries half the difference between the two rows' spare height.
4316    fn rows_fit() -> Result<Vec<(&'static str, f64)>, Fail> {
4317        let rows = sized_rows()?;
4318        let spare = |r: &SizedRow| (r.row - r.content) / 2.0;
4319        let expected = |a: &SizedRow, b: &SizedRow| a.row - spare(a) + spare(b);
4320        let chrome = (rows[1].top - rows[0].top) - expected(&rows[0], &rows[1]);
4321        for pair in rows.windows(2) {
4322            let (this, next) = (&pair[0], &pair[1]);
4323            let pitch = next.top - this.top;
4324            if pitch + 0.5 < this.content {
4325                return Err(Fail(format!(
4326                    "row {:?} is {:.1} tall but the next row starts {pitch:.1} below it: the \
4327                     native row clips its content",
4328                    this.key, this.content
4329                )));
4330            }
4331            let want = expected(this, next) + chrome;
4332            if (pitch - want).abs() > 1.5 {
4333                return Err(Fail(format!(
4334                    "row {:?} holds {:.1} of content in a {:.1} row, and the next row starts \
4335                     {pitch:.1} below it where {want:.1} was expected (the first row's chrome \
4336                     allowance is {chrome:.1}): the native row did not take its content's height",
4337                    this.key, this.content, this.row
4338                )));
4339            }
4340        }
4341        Ok(rows.into_iter().map(|r| (r.key, r.content)).collect())
4342    }
4343
4344    fn height_of(rows: &[(&str, f64)], key: &str) -> f64 {
4345        rows.iter().find(|r| r.0 == key).map_or(0.0, |r| r.1)
4346    }
4347
4348    /// An `Automatic` list sizes each row to its content: small and large text, a wrapped
4349    /// paragraph, and a row whose text grows and shrinks after it was first sized.
4350    #[day_macros::test(day_core)]
4351    fn list_rows_size_to_content() -> Case {
4352        Case::new()
4353            .proves(kinds::LIST)
4354            .proves(kinds::LIST_CELL)
4355            .page(|| {
4356                let grown = Signal::new(false);
4357                column((
4358                    button("Grow")
4359                        .action(move || grown.update(|g| *g = !*g))
4360                        .id(day_core::id!(grow)),
4361                    sized_list(grown)
4362                        .id(day_core::id!(list))
4363                        .width(240.0)
4364                        .height(480.0),
4365                ))
4366            })
4367            .drive(|d: Drive| async move {
4368                d.assert_visible("sized:end").await?;
4369                d.shot("sized-rows").await?;
4370                let rows = rows_fit()?;
4371                // The fixture means what it says: the type sizes differ, and the paragraph
4372                // wrapped at the list's width.
4373                let (small, large) = (height_of(&rows, "small"), height_of(&rows, "large"));
4374                d.check(
4375                    large > small * 1.5,
4376                    "a large-title row is taller than a caption row",
4377                )?;
4378                let body = height_of(&rows, "body");
4379                d.check(
4380                    height_of(&rows, "wrap") > body * 1.5,
4381                    "the footnote wrapped",
4382                )?;
4383                // A row re-laid at a new height after it was first sized.
4384                d.tap("grow").await?;
4385                d.wait_idle().await?;
4386                d.pause(0.3).await?;
4387                d.shot("sized-rows-grown").await?;
4388                let grew = rows_fit()?;
4389                d.check(height_of(&grew, "body") > body * 1.5, "the body row grew")?;
4390                d.tap("grow").await?;
4391                d.wait_idle().await?;
4392                d.pause(0.3).await?;
4393                let shrank = rows_fit()?;
4394                d.check(
4395                    (height_of(&shrank, "body") - body).abs() < 1.0,
4396                    "the body row shrank back",
4397                )
4398            })
4399    }
4400
4401    /// Selecting a row reports its key; activating one reports its key too.
4402    #[day_macros::test(day_core)]
4403    fn list_select_and_activate() -> Case {
4404        Case::new()
4405            .proves(kinds::LIST)
4406            .page(|| {
4407                let picked = Signal::new(String::new());
4408                let opened = Signal::new(String::new());
4409                column((
4410                    label(move || format!("picked {}", picked.get())).id(day_core::id!(picked)),
4411                    label(move || format!("opened {}", opened.get())).id(day_core::id!(opened)),
4412                    names_list(names(&["Alpha", "Beta", "Gamma"]))
4413                        .on_select(move |k| picked.set(k))
4414                        .on_activate(move |k| opened.set(k))
4415                        .id(day_core::id!(list))
4416                        .height(200.0),
4417                ))
4418            })
4419            .drive(|d: Drive| async move {
4420                d.select("list", 1).await?;
4421                d.assert_text("picked", "picked Beta").await?;
4422                d.activate("list", 2).await?;
4423                d.assert_text("opened", "opened Gamma").await
4424            })
4425    }
4426
4427    /// A committed reorder reaches the app, which moves the row in its source.
4428    #[day_macros::test(day_core)]
4429    fn list_reorder_moves_row() -> Case {
4430        Case::new()
4431            .proves(kinds::LIST)
4432            .page(|| {
4433                let rows = names(&["Alpha", "Beta", "Gamma"]);
4434                column((
4435                    label(move || rows.get().join(",")).id(day_core::id!(order)),
4436                    names_list(rows)
4437                        .reorderable(Reorder::new(move |from, to| {
4438                            rows.update(|v| {
4439                                let item = v.remove(from);
4440                                v.insert(to.min(v.len()), item);
4441                            });
4442                        }))
4443                        .id(day_core::id!(list))
4444                        .height(200.0),
4445                ))
4446            })
4447            .drive(|d: Drive| async move {
4448                d.reorder("list", 0, 2).await?;
4449                d.assert_text("order", "Beta,Gamma,Alpha").await?;
4450                d.assert_text("conformance_row:Alpha", "Alpha").await
4451            })
4452    }
4453
4454    /// A deleted row reaches the app, and the native list drops it.
4455    #[day_macros::test(day_core)]
4456    fn list_delete_row() -> Case {
4457        Case::new()
4458            .proves(kinds::LIST)
4459            .page(|| {
4460                let rows = names(&["Alpha", "Beta", "Gamma"]);
4461                column((
4462                    label(move || rows.get().join(",")).id(day_core::id!(order)),
4463                    names_list(rows)
4464                        .deletable(Delete::new(move |at| {
4465                            rows.update(|v| {
4466                                v.remove(at);
4467                            });
4468                        }))
4469                        .id(day_core::id!(list))
4470                        .height(200.0),
4471                ))
4472            })
4473            .drive(|d: Drive| async move {
4474                d.delete_row("list", 1).await?;
4475                d.assert_text("order", "Alpha,Gamma").await?;
4476                d.assert_missing("conformance_row:Beta").await
4477            })
4478    }
4479
4480    /// A row's trailing swipe action runs its work for that row.
4481    #[day_macros::test(day_core)]
4482    fn list_swipe_action() -> Case {
4483        Case::new()
4484            .proves(kinds::LIST)
4485            .page(|| {
4486                let rows = names(&["Alpha", "Beta", "Gamma"]);
4487                let flagged = Signal::new(String::new());
4488                column((
4489                    label(move || format!("flagged {}", flagged.get())).id(day_core::id!(flagged)),
4490                    names_list(rows)
4491                        .swipe_trailing(move |at| {
4492                            let name = rows.get_untracked()[at].clone();
4493                            vec![swipe_action("Flag").action(move || flagged.set(name.clone()))]
4494                        })
4495                        .id(day_core::id!(list))
4496                        .height(200.0),
4497                ))
4498            })
4499            .drive(|d: Drive| async move {
4500                d.swipe_row("list", 2, false, 0).await?;
4501                d.assert_text("flagged", "flagged Gamma").await
4502            })
4503    }
4504
4505    /// The dayscript `scroll_to` step drives a native list through its row scrolling: `bottom`
4506    /// reaches the last row, `top` the first, and a row's id reveals the row it names.
4507    #[day_macros::test(day_core)]
4508    fn list_scroll_to_edges_and_rows_from_dayscript() -> Case {
4509        Case::new()
4510            .proves(kinds::LIST)
4511            .proves_duty("list_scroll")
4512            .page(|| {
4513                let rows: Signal<Vec<String>> =
4514                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4515                names_list(rows).id(day_core::id!(list)).height(200.0)
4516            })
4517            .drive(|d: Drive| async move {
4518                d.assert_missing("conformance_row:Row%20299").await?;
4519                d.scroll_to("list", "bottom").await?;
4520                d.assert_text("conformance_row:Row%20299", "Row 299")
4521                    .await?;
4522                d.reveal("conformance_row:Row%20297").await?;
4523                d.scroll_to("list", "top").await?;
4524                d.assert_text("conformance_row:Row%200", "Row 0").await?;
4525                d.reveal("conformance_row:Row%202").await?;
4526                d.assert_text("conformance_row:Row%202", "Row 2").await
4527            })
4528    }
4529
4530    /// Scrolling a long list to a row realizes it, even where rows are recycled.
4531    #[day_macros::test(day_core)]
4532    fn list_scroll_to_row() -> Case {
4533        Case::new()
4534            .proves(kinds::LIST)
4535            .page(|| {
4536                let rows: Signal<Vec<String>> =
4537                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4538                let jump: Signal<Option<usize>> = Signal::new(None);
4539                column((
4540                    button("Jump")
4541                        .action(move || jump.set(Some(250)))
4542                        .id(day_core::id!(jump)),
4543                    names_list(rows)
4544                        .scroll_to_row(jump)
4545                        .id(day_core::id!(list))
4546                        .height(200.0),
4547                ))
4548            })
4549            .drive(|d: Drive| async move {
4550                d.assert_missing("conformance_row:Row%20250").await?;
4551                d.tap("jump").await?;
4552                d.assert_text("conformance_row:Row%20250", "Row 250").await
4553            })
4554    }
4555
4556    /// Counts the rows a list has alive: one per row built, one less per row disposed. A
4557    /// guard rides in each row's label closure, which the row's scope owns, so a cell the
4558    /// host merely pooled still counts (its row is intact and rebinds) and a cell the host
4559    /// discarded stops counting once `ListSource::release` disposed its row.
4560    struct RowAlive(std::rc::Rc<std::cell::Cell<usize>>);
4561
4562    impl RowAlive {
4563        fn new(live: &std::rc::Rc<std::cell::Cell<usize>>) -> Self {
4564            live.set(live.get() + 1);
4565            RowAlive(live.clone())
4566        }
4567    }
4568
4569    impl Drop for RowAlive {
4570        fn drop(&mut self) {
4571            self.0.set(self.0.get().saturating_sub(1));
4572        }
4573    }
4574
4575    /// The most rows a five-row viewport may have alive once the host has settled: its own
4576    /// pool and nothing visited earlier. The pools measured: AppKit 5, Qt 21 (the viewport plus
4577    /// two overscans), the mock 20, Android and UIKit a few dozen, and `GtkListView` 205: it
4578    /// keeps up to 200 spare items by design (`GTK_LIST_VIEW_MAX_LIST_ITEMS`) and rebinds them.
4579    /// A leak grows with every row visited instead, and the cases visit many more rows than
4580    /// this, so the bound stays tight against it.
4581    const ROWS_ALIVE_BOUND: usize = 256;
4582
4583    /// Distant jumps keep a bounded number of rows alive and rebind their actions.
4584    #[day_macros::test(day_core)]
4585    fn list_recycles_distant_rows() -> Case {
4586        let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
4587        let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
4588        let (count, alive) = (built.clone(), live.clone());
4589        Case::new()
4590            .proves(kinds::LIST)
4591            .proves_cap(Cap::ListRecycling)
4592            // 180 jumps, each settled by a bounded wait: 5 s on GTK, 19 s on Qt, 57 s on
4593            // the iOS simulator.
4594            .timeout(180.0)
4595            .requires_support("native list recycling", || {
4596                if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
4597                    day_spec::Support::Native
4598                } else {
4599                    day_spec::Support::Unsupported
4600                }
4601            })
4602            .page(move || {
4603                count.set(0);
4604                alive.set(0);
4605                let (count, alive) = (count.clone(), alive.clone());
4606                let rows = Signal::new((0..4000).collect::<Vec<usize>>());
4607                let jump = Signal::new(None);
4608                let next = Signal::new(40usize);
4609                let pressed = Signal::new(String::new());
4610                column((
4611                    button("Far").id(day_core::id!(far)).action(move || {
4612                        jump.set(Some(next.get_untracked()));
4613                        next.update(|n| *n += 40);
4614                    }),
4615                    button("Back")
4616                        .id(day_core::id!(back))
4617                        .action(move || jump.set(Some(0))),
4618                    label(move || pressed.get()).id(day_core::id!(pressed)),
4619                    list(items(move || rows.get(), |n: &usize| *n), move |slot| {
4620                        count.set(count.get() + 1);
4621                        let guard = RowAlive::new(&alive);
4622                        button(move || {
4623                            let _ = &guard;
4624                            format!("Row {}", slot.get())
4625                        })
4626                        .id_of(move || day_core::id!(conformance_row, slot.key()))
4627                        .action(move || pressed.set(format!("Pressed {}", slot.get())))
4628                    })
4629                    .row_height(RowHeight::Uniform(32.0))
4630                    .scroll_to_row(jump)
4631                    .height(160.0),
4632                ))
4633            })
4634            .drive(move |d: Drive| {
4635                let (built, live) = (built.clone(), live.clone());
4636                async move {
4637                    d.assert_text("conformance_row:0", "Row 0").await?;
4638                    // Distinct regions: retaining a cell for every visited index must fail.
4639                    // Row 1, not row 0, is the one that must go: GtkListView keeps its
4640                    // focused item's widget realized wherever the view scrolls, and row 0
4641                    // holds the focus here (the first item at start, then every `back` tap).
4642                    // Ninety regions out and back: some nine hundred rows visited, so a host
4643                    // that keeps a row per visited cell overshoots `ROWS_ALIVE_BOUND` several
4644                    // times over, where every pool measured stays under it.
4645                    for row in (40..=3600).step_by(40) {
4646                        d.tap("far").await?;
4647                        d.assert_text(&format!("conformance_row:{row}"), &format!("Row {row}"))
4648                            .await?;
4649                        d.assert_missing("conformance_row:1").await?;
4650                        d.tap(&format!("conformance_row:{row}")).await?;
4651                        d.assert_text("pressed", &format!("Pressed {row}")).await?;
4652                        d.tap("back").await?;
4653                        d.assert_text("conformance_row:0", "Row 0").await?;
4654                        d.tap("conformance_row:0").await?;
4655                        d.assert_text("pressed", "Pressed 0").await?;
4656                    }
4657                    // Settled: a host that releases discarded cells on a later turn (a
4658                    // posted dealloc, a teardown held for a borrow) has had it.
4659                    d.wait_idle().await?;
4660                    d.pause(0.3).await?;
4661                    d.check(
4662                        live.get() <= ROWS_ALIVE_BOUND,
4663                        &format!(
4664                            "{} rows alive after 180 jumps of a five-row viewport ({} built): \
4665                             discarded cells keep their rows",
4666                            live.get(),
4667                            built.get()
4668                        ),
4669                    )
4670                }
4671            })
4672    }
4673
4674    /// Shrinking, regrowing, reordering and jumping discard cells by every path a host has;
4675    /// the rows built in them go with them, and no row answers for a cell it no longer has.
4676    #[day_macros::test(day_core)]
4677    fn list_releases_discarded_rows() -> Case {
4678        const TOTAL: usize = 3000;
4679        const STRIDE: usize = 1237;
4680        let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
4681        let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
4682        let (count, alive) = (built.clone(), live.clone());
4683        Case::new()
4684            .proves(kinds::LIST)
4685            .proves_cap(Cap::ListRecycling)
4686            .timeout(90.0)
4687            .requires_support("native list recycling", || {
4688                if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
4689                    day_spec::Support::Native
4690                } else {
4691                    day_spec::Support::Unsupported
4692                }
4693            })
4694            .page(move || {
4695                count.set(0);
4696                alive.set(0);
4697                let (count, alive) = (count.clone(), alive.clone());
4698                let rows = Signal::new((0..TOTAL).collect::<Vec<usize>>());
4699                let jump = Signal::new(None);
4700                let at = Signal::new(0usize);
4701                let pressed = Signal::new(String::new());
4702                column((
4703                    // A stride coprime with the count walks the whole list in a scattered
4704                    // order, so consecutive jumps never share a cell.
4705                    button("Far").id(day_core::id!(far)).action(move || {
4706                        let next = (at.get_untracked() + STRIDE) % TOTAL;
4707                        at.set(next);
4708                        jump.set(Some(next));
4709                    }),
4710                    // Five rows fill the viewport exactly, so after the shrink every row is on
4711                    // screen wherever the host clamps its scroll offset.
4712                    button("Shrink")
4713                        .id(day_core::id!(shrink))
4714                        .action(move || rows.set((0..5).collect())),
4715                    button("Regrow")
4716                        .id(day_core::id!(regrow))
4717                        .action(move || rows.set((0..TOTAL).collect())),
4718                    // The same rows in a new order: a reload that keeps every token.
4719                    button("Rotate")
4720                        .id(day_core::id!(rotate))
4721                        .action(move || rows.update(|r| r.rotate_left(7))),
4722                    label(move || pressed.get()).id(day_core::id!(pressed)),
4723                    list(items(move || rows.get(), |n: &usize| *n), move |slot| {
4724                        count.set(count.get() + 1);
4725                        let guard = RowAlive::new(&alive);
4726                        button(move || {
4727                            let _ = &guard;
4728                            format!("Row {}", slot.get())
4729                        })
4730                        .id_of(move || day_core::id!(conformance_row, slot.key()))
4731                        .action(move || pressed.set(format!("Pressed {}", slot.get())))
4732                    })
4733                    .row_height(RowHeight::Uniform(32.0))
4734                    .scroll_to_row(jump)
4735                    .height(160.0),
4736                ))
4737            })
4738            .drive(move |d: Drive| {
4739                let (built, live) = (built.clone(), live.clone());
4740                async move {
4741                    d.assert_text("conformance_row:0", "Row 0").await?;
4742                    let (mut at, mut rotation) = (0usize, 0usize);
4743                    // The key of the row at index `i` after `rotation` left-rotations.
4744                    let key_at = |i: usize, rotation: usize| (i + rotation) % TOTAL;
4745                    for _ in 0..10 {
4746                        // A jump lands, and the row it lands on works.
4747                        at = (at + STRIDE) % TOTAL;
4748                        d.tap("far").await?;
4749                        let key = key_at(at, rotation);
4750                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4751                            .await?;
4752                        d.tap(&format!("conformance_row:{key}")).await?;
4753                        d.assert_text("pressed", &format!("Pressed {key}")).await?;
4754                        // Two jumps back to back: the second one wins.
4755                        d.tap("far").await?;
4756                        d.tap("far").await?;
4757                        at = (at + 2 * STRIDE) % TOTAL;
4758                        let key = key_at(at, rotation);
4759                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4760                            .await?;
4761                        // Shrinking under the viewport discards the rows past the new end;
4762                        // none of them may still answer.
4763                        d.tap("shrink").await?;
4764                        d.assert_text("conformance_row:3", "Row 3").await?;
4765                        if key >= 5 {
4766                            d.assert_missing(&format!("conformance_row:{key}")).await?;
4767                        }
4768                        d.tap("regrow").await?;
4769                        // The same set in a new order (regrowing restored the original one),
4770                        // then a jump into it.
4771                        d.tap("rotate").await?;
4772                        rotation = 7;
4773                        at = (at + STRIDE) % TOTAL;
4774                        d.tap("far").await?;
4775                        let key = key_at(at, rotation);
4776                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4777                            .await?;
4778                    }
4779                    d.wait_idle().await?;
4780                    d.pause(0.3).await?;
4781                    d.check(
4782                        live.get() <= ROWS_ALIVE_BOUND,
4783                        &format!(
4784                            "{} rows alive after the churn ({} built): discarded cells keep \
4785                             their rows",
4786                            live.get(),
4787                            built.get()
4788                        ),
4789                    )
4790                }
4791            })
4792    }
4793
4794    /// Emptying a scrolled list releases old ids; repopulating it can scroll again.
4795    #[day_macros::test(day_core)]
4796    fn list_shrink_and_regrow() -> Case {
4797        Case::new()
4798            .proves(kinds::LIST)
4799            .page(|| {
4800                let rows = Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4801                let jump = Signal::new(None);
4802                column((
4803                    button("Jump")
4804                        .id(day_core::id!(jump))
4805                        .action(move || jump.set(Some(250))),
4806                    button("Clear")
4807                        .id(day_core::id!(clear))
4808                        .action(move || rows.set(Vec::new())),
4809                    button("Restore")
4810                        .id(day_core::id!(restore))
4811                        .action(move || {
4812                            rows.set(vec!["New first".into(), "New last".into()]);
4813                            jump.set(Some(1));
4814                        }),
4815                    names_list(rows).scroll_to_row(jump).height(160.0),
4816                ))
4817            })
4818            .drive(|d: Drive| async move {
4819                d.tap("jump").await?;
4820                d.assert_text("conformance_row:Row%20250", "Row 250")
4821                    .await?;
4822                d.tap("clear").await?;
4823                d.assert_missing("conformance_row:Row%20250").await?;
4824                d.tap("restore").await?;
4825                d.assert_text("conformance_row:New%20first", "New first")
4826                    .await?;
4827                d.assert_text("conformance_row:New%20last", "New last")
4828                    .await
4829            })
4830    }
4831
4832    /// One row of the keyed cases: a key the list tracks and a text it shows.
4833    type Keyed = (u32, String);
4834
4835    /// The swatch a keyed row leads with, by key: how a case reads the order of the rows.
4836    fn key_color(key: u32) -> day_spec::Color {
4837        match key {
4838            1 => day_spec::Color::rgb(1.0, 0.0, 0.0),
4839            2 => day_spec::Color::rgb(0.0, 1.0, 0.0),
4840            3 => day_spec::Color::rgb(0.0, 0.0, 1.0),
4841            _ => day_spec::Color::rgb(1.0, 1.0, 0.0),
4842        }
4843    }
4844
4845    /// A list keyed by number, 240 by 160 points, of rows 32 points tall: a swatch in the
4846    /// key's color, 60 points wide, then a label with the id `keyed:<key>` showing the text;
4847    /// the row itself has the id `keyed_row:<key>`.
4848    fn keyed_list(rows: Signal<Vec<Keyed>>) -> Decorated<List<Items<Keyed, u32>>> {
4849        list(
4850            items(move || rows.get(), |r: &Keyed| r.0),
4851            |slot: ItemSlot<Keyed, u32>| {
4852                row((
4853                    rectangle()
4854                        .fill(move || key_color(slot.field(|r| r.0)))
4855                        .frame(60.0, 24.0),
4856                    label(move || slot.field(|r| r.1.clone()))
4857                        .id_of(move || day_core::id!(keyed, slot.field(|r| r.0))),
4858                ))
4859                .spacing(8.0)
4860                .id_of(move || day_core::id!(keyed_row, slot.field(|r| r.0)))
4861            },
4862        )
4863        .row_height(RowHeight::Uniform(32.0))
4864        .frame(240.0, 160.0)
4865    }
4866
4867    fn keyed(rows: &[(u32, &str)]) -> Signal<Vec<Keyed>> {
4868        Signal::new(rows.iter().map(|(k, t)| (*k, (*t).to_owned())).collect())
4869    }
4870
4871    /// Row `index` of the keyed list `id` shows the swatch `color`: sampled 40 points in,
4872    /// inside the swatch under every platform's row margin, at the row's middle.
4873    async fn row_shows(d: &Drive, id: &str, index: u32, color: &str) -> Result<(), Fail> {
4874        let y = (f64::from(index) + 0.5) * 32.0 / 160.0;
4875        d.sample_pixel(id, 40.0 / 240.0, y, color).await
4876    }
4877
4878    /// A plain items list applies an insert, a move, a removal and a changed value as row
4879    /// deltas (docs/list.md "Keyed updates"): every row ends where the data puts it, showing
4880    /// its own item.
4881    #[day_macros::test(day_core)]
4882    fn list_keyed_changes_land_in_order() -> Case {
4883        Case::new()
4884            .proves(kinds::LIST)
4885            // Twelve whole-window pixel samples: 12 to 19 s on a loaded desktop toolkit.
4886            .timeout(60.0)
4887            .page(|| {
4888                let rows = keyed(&[(1, "One"), (2, "Two"), (3, "Three")]);
4889                column((
4890                    row((
4891                        button("Top")
4892                            .action(move || rows.update(|v| v.insert(0, (9, "Nine".into()))))
4893                            .id(day_core::id!(top)),
4894                        button("Move")
4895                            .action(move || {
4896                                rows.update(|v| {
4897                                    if let Some(last) = v.pop() {
4898                                        v.insert(0, last);
4899                                    }
4900                                });
4901                            })
4902                            .id(day_core::id!(lift)),
4903                        button("Edit")
4904                            .action(move || {
4905                                rows.update(|v| {
4906                                    if let Some(two) = v.iter_mut().find(|r| r.0 == 2) {
4907                                        two.1 = "Deux".into();
4908                                    }
4909                                });
4910                            })
4911                            .id(day_core::id!(edit)),
4912                        button("Drop")
4913                            .action(move || rows.update(|v| v.retain(|r| r.0 != 1)))
4914                            .id(day_core::id!(drop)),
4915                    )),
4916                    keyed_list(rows).id(day_core::id!(list)),
4917                ))
4918            })
4919            .drive(|d: Drive| async move {
4920                d.assert_text("keyed:1", "One").await?;
4921                row_shows(&d, "list", 0, "#ff0000").await?;
4922                row_shows(&d, "list", 2, "#0000ff").await?;
4923                // An insert at the top pushes every row down one.
4924                d.tap("top").await?;
4925                d.assert_text("keyed:9", "Nine").await?;
4926                row_shows(&d, "list", 0, "#ffff00").await?;
4927                row_shows(&d, "list", 1, "#ff0000").await?;
4928                row_shows(&d, "list", 3, "#0000ff").await?;
4929                // The last row moves to the top; the others keep their order under it.
4930                d.tap("lift").await?;
4931                d.wait_idle().await?;
4932                row_shows(&d, "list", 0, "#0000ff").await?;
4933                row_shows(&d, "list", 1, "#ffff00").await?;
4934                row_shows(&d, "list", 3, "#00ff00").await?;
4935                // A changed value with the same key reaches its row in place.
4936                d.tap("edit").await?;
4937                d.assert_text("keyed:2", "Deux").await?;
4938                row_shows(&d, "list", 3, "#00ff00").await?;
4939                // A removal from the middle closes the gap.
4940                d.tap("drop").await?;
4941                d.assert_missing("keyed:1").await?;
4942                d.assert_text("keyed:3", "Three").await?;
4943                row_shows(&d, "list", 0, "#0000ff").await?;
4944                row_shows(&d, "list", 1, "#ffff00").await?;
4945                row_shows(&d, "list", 2, "#00ff00").await
4946            })
4947    }
4948
4949    /// `follow_end` leaves a reader at the top where they are and follows a reader at the end
4950    /// (docs/list.md "Following the end").
4951    #[day_macros::test(day_core)]
4952    fn list_follow_end_follows_only_at_the_end() -> Case {
4953        Case::new()
4954            .proves(kinds::LIST)
4955            .proves_cap(Cap::ListViewport)
4956            .requires(Cap::ListViewport)
4957            .page(|| {
4958                let rows: Signal<Vec<String>> =
4959                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4960                let end = day_reactive::Trigger::new();
4961                column((
4962                    row((
4963                        button("Add")
4964                            .action(move || {
4965                                rows.update(|v| v.push(format!("New {}", v.len() - 300)));
4966                            })
4967                            .id(day_core::id!(add)),
4968                        button("End")
4969                            .action(move || end.notify())
4970                            .id(day_core::id!(end)),
4971                    )),
4972                    names_list(rows)
4973                        .follow_end(40.0)
4974                        .scroll_to_end(end)
4975                        .id(day_core::id!(list))
4976                        .height(200.0),
4977                ))
4978            })
4979            .drive(|d: Drive| async move {
4980                d.assert_text("conformance_row:Row%200", "Row 0").await?;
4981                d.wait_idle().await?;
4982                // At the top, far from the end: the new row arrives out of view.
4983                d.tap("add").await?;
4984                d.wait_idle().await?;
4985                d.assert_missing("conformance_row:New%200").await?;
4986                d.assert_text("conformance_row:Row%200", "Row 0").await?;
4987                // At the end: the next row is followed into view.
4988                d.tap("end").await?;
4989                d.assert_text("conformance_row:New%200", "New 0").await?;
4990                d.wait_idle().await?;
4991                d.tap("add").await?;
4992                d.assert_text("conformance_row:New%201", "New 1").await
4993            })
4994    }
4995
4996    /// Rows arriving while a followed scroll is still on its way are followed too: the list's
4997    /// own scrolls are never taken for the reader's (docs/list.md "Following the end",
4998    /// `Cap::ListReaderScroll`). The reader's own scrolls need real input, which a case cannot
4999    /// make; each backend proves them by hand.
5000    #[day_macros::test(day_core)]
5001    fn list_follow_end_keeps_up_with_rows_in_flight() -> Case {
5002        Case::new()
5003            .proves(kinds::LIST)
5004            .proves_cap(Cap::ListReaderScroll)
5005            .requires(Cap::ListViewport)
5006            .timeout(30.0)
5007            .page(|| {
5008                let rows: Signal<Vec<String>> =
5009                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
5010                let end = day_reactive::Trigger::new();
5011                column((
5012                    row((
5013                        button("Burst")
5014                            .action(move || {
5015                                day_core::task(async move {
5016                                    for n in 0..12 {
5017                                        rows.update(|v| v.push(format!("Burst {n}")));
5018                                        day_core::sleep(40).await;
5019                                    }
5020                                });
5021                            })
5022                            .id(day_core::id!(burst)),
5023                        button("End")
5024                            .action(move || end.notify())
5025                            .id(day_core::id!(end)),
5026                    )),
5027                    names_list(rows)
5028                        .follow_end(40.0)
5029                        .scroll_to_end(end)
5030                        .id(day_core::id!(list))
5031                        .height(200.0),
5032                ))
5033            })
5034            .drive(|d: Drive| async move {
5035                d.assert_text("conformance_row:Row%200", "Row 0").await?;
5036                d.wait_idle().await?;
5037                d.tap("end").await?;
5038                d.assert_text("conformance_row:Row%20299", "Row 299")
5039                    .await?;
5040                d.wait_idle().await?;
5041                // Twelve rows, one every 40 ms: each lands while the scroll to the one before
5042                // is still animating, and the last is in view at the end.
5043                d.tap("burst").await?;
5044                d.assert_text("conformance_row:Burst%2011", "Burst 11")
5045                    .await?;
5046                d.wait_idle().await?;
5047                d.assert_text("conformance_row:Burst%2011", "Burst 11")
5048                    .await
5049            })
5050    }
5051
5052    /// `on_end_reached` fires when the list comes to its end, once, and again at the new end
5053    /// after the handler added rows (docs/list.md "Reaching the end").
5054    #[day_macros::test(day_core)]
5055    fn list_end_reached_fires_once_per_end() -> Case {
5056        Case::new()
5057            .proves(kinds::LIST)
5058            .proves_cap(Cap::ListViewport)
5059            .requires(Cap::ListViewport)
5060            .page(|| {
5061                let rows: Signal<Vec<String>> =
5062                    Signal::new((0..60).map(|n| format!("Row {n}")).collect());
5063                let loads = Signal::new(0_u32);
5064                let end = day_reactive::Trigger::new();
5065                column((
5066                    button("End")
5067                        .action(move || end.notify())
5068                        .id(day_core::id!(end)),
5069                    label(move || format!("loads {}", loads.get())).id(day_core::id!(loads)),
5070                    names_list(rows)
5071                        .on_end_reached(100.0, move || {
5072                            loads.update(|n| *n += 1);
5073                            rows.update(|v| {
5074                                let from = v.len();
5075                                v.extend((from..from + 40).map(|n| format!("Row {n}")));
5076                            });
5077                        })
5078                        .scroll_to_end(end)
5079                        .id(day_core::id!(list))
5080                        .height(200.0),
5081                ))
5082            })
5083            .drive(|d: Drive| async move {
5084                d.assert_text("conformance_row:Row%200", "Row 0").await?;
5085                d.wait_idle().await?;
5086                d.assert_text("loads", "loads 0").await?;
5087                d.tap("end").await?;
5088                d.assert_text("loads", "loads 1").await?;
5089                // The handler's rows moved the end away: it does not fire again by itself.
5090                d.pause(0.3).await?;
5091                d.assert_text("loads", "loads 1").await?;
5092                d.tap("end").await?;
5093                d.assert_text("loads", "loads 2").await
5094            })
5095    }
5096
5097    /// A short first page leaves the end within the threshold: `on_end_reached` fires again
5098    /// once the rows it added are laid out, with no scroll, and a call that adds no rows ends
5099    /// the chain (docs/list.md "Reaching the end").
5100    #[day_macros::test(day_core)]
5101    fn list_end_reached_fills_a_short_list() -> Case {
5102        Case::new()
5103            .proves(kinds::LIST)
5104            .proves_cap(Cap::ListViewport)
5105            .requires(Cap::ListViewport)
5106            .page(|| {
5107                let rows: Signal<Vec<String>> =
5108                    Signal::new((0..4).map(|n| format!("Row {n}")).collect());
5109                let loads = Signal::new(0_u32);
5110                column((
5111                    label(move || format!("loads {}", loads.get())).id(day_core::id!(loads)),
5112                    names_list(rows)
5113                        .on_end_reached(200.0, move || {
5114                            loads.update(|n| *n += 1);
5115                            // A source with 12 rows in all: past them a call adds nothing.
5116                            rows.update(|v| {
5117                                let from = v.len();
5118                                v.extend((from..(from + 4).min(12)).map(|n| format!("Row {n}")));
5119                            });
5120                        })
5121                        .id(day_core::id!(list))
5122                        .height(300.0),
5123                ))
5124            })
5125            .drive(|d: Drive| async move {
5126                // Every page leaves the end within 200 pt of a 300 pt viewport (4 rows fit,
5127                // 8 rows fit, 12 rows are 84 pt past it), so three calls come with no scroll:
5128                // the third adds nothing, and nothing re-arms after it.
5129                d.assert_text("loads", "loads 3").await?;
5130                // A row of the third page, inside the viewport.
5131                d.assert_text("conformance_row:Row%208", "Row 8").await?;
5132                d.pause(0.3).await?;
5133                d.assert_text("loads", "loads 3").await
5134            })
5135    }
5136
5137    /// A row scroll lands where its alignment says, and the visible range follows the
5138    /// viewport (docs/list.md "Visible rows", "Programmatic scrolling").
5139    #[day_macros::test(day_core)]
5140    fn list_visible_rows_follow_an_aligned_scroll() -> Case {
5141        Case::new()
5142            .proves(kinds::LIST)
5143            .proves_cap(Cap::ListViewport)
5144            .proves_cap(Cap::ListScrollAlign)
5145            .proves_duty("list_scroll")
5146            .requires(Cap::ListViewport)
5147            .requires(Cap::ListScrollAlign)
5148            .page(|| {
5149                let rows: Signal<Vec<String>> =
5150                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
5151                let jump: Signal<Option<RowTarget>> = Signal::new(None);
5152                let visible = Signal::new(0_usize..0);
5153                column((
5154                    row((
5155                        button("Start")
5156                            .action(move || {
5157                                jump.set(Some(
5158                                    RowTarget::new(100)
5159                                        .align(day_spec::RowAlign::Start)
5160                                        .instant(),
5161                                ));
5162                            })
5163                            .id(day_core::id!(to_start)),
5164                        button("End")
5165                            .action(move || {
5166                                jump.set(Some(
5167                                    RowTarget::new(200).align(day_spec::RowAlign::End).instant(),
5168                                ));
5169                            })
5170                            .id(day_core::id!(to_end)),
5171                    )),
5172                    label(move || format!("first {}", visible.get().start))
5173                        .id(day_core::id!(first)),
5174                    label(move || format!("last {}", visible.get().end.max(1) - 1))
5175                        .id(day_core::id!(last)),
5176                    label(move || {
5177                        if visible.get().len() > 1 {
5178                            "several"
5179                        } else {
5180                            "one or none"
5181                        }
5182                    })
5183                    .id(day_core::id!(span)),
5184                    names_list(rows)
5185                        .scroll_to_row(jump)
5186                        .visible_rows(visible)
5187                        .id(day_core::id!(list))
5188                        .height(160.0),
5189                ))
5190            })
5191            .drive(|d: Drive| async move {
5192                d.assert_text("first", "first 0").await?;
5193                d.assert_text("span", "several").await?;
5194                // Row 100 at the top of the viewport is the first visible row.
5195                d.tap("to_start").await?;
5196                d.assert_text("first", "first 100").await?;
5197                d.assert_text("conformance_row:Row%20100", "Row 100")
5198                    .await?;
5199                // Row 200 at the bottom of the viewport is the last.
5200                d.tap("to_end").await?;
5201                d.assert_text("last", "last 200").await?;
5202                d.assert_text("conformance_row:Row%20200", "Row 200").await
5203            })
5204    }
5205
5206    /// The list's header and footer scroll with its rows, and the empty state stands in for
5207    /// the rows while there are none (docs/list.md "Header, footer and empty state").
5208    #[day_macros::test(day_core)]
5209    fn list_header_footer_and_empty_state() -> Case {
5210        Case::new()
5211            .proves(kinds::LIST)
5212            .page(|| {
5213                let rows = names(&[]);
5214                column((
5215                    row((
5216                        button("Add")
5217                            .action(move || rows.update(|v| v.push(format!("Item {}", v.len()))))
5218                            .id(day_core::id!(add)),
5219                        button("Clear")
5220                            .action(move || rows.set(Vec::new()))
5221                            .id(day_core::id!(clear)),
5222                    )),
5223                    names_list(rows)
5224                        .header(|| {
5225                            label("Inbox")
5226                                .id(day_core::id!(list_header))
5227                                .padding(Insets::symmetric(12.0, 6.0))
5228                        })
5229                        .footer(|| {
5230                            label("End of list")
5231                                .id(day_core::id!(list_footer))
5232                                .padding(Insets::symmetric(12.0, 6.0))
5233                        })
5234                        .empty(|| label("Nothing yet").id(day_core::id!(list_empty)))
5235                        .id(day_core::id!(list))
5236                        .height(260.0),
5237                ))
5238            })
5239            .drive(|d: Drive| async move {
5240                d.assert_text("list_header", "Inbox").await?;
5241                d.assert_text("list_empty", "Nothing yet").await?;
5242                d.assert_text("list_footer", "End of list").await?;
5243                // The first row takes the empty state's place, under the header.
5244                d.tap("add").await?;
5245                d.assert_text("conformance_row:Item%200", "Item 0").await?;
5246                d.assert_missing("list_empty").await?;
5247                d.assert_text("list_header", "Inbox").await?;
5248                d.tap("add").await?;
5249                d.assert_text("conformance_row:Item%201", "Item 1").await?;
5250                d.assert_text("list_footer", "End of list").await?;
5251                // And it returns when the last row leaves.
5252                d.tap("clear").await?;
5253                d.assert_missing("conformance_row:Item%200").await?;
5254                d.assert_text("list_empty", "Nothing yet").await
5255            })
5256    }
5257
5258    /// The empty state shows when the last row leaves a list scrolled far down, under a header
5259    /// taller than the viewport (docs/list.md "Header, footer and empty state"). A host binds
5260    /// only the rows it shows, and keeps its scroll position or goes back to the top, which
5261    /// here shows the header alone: the list has to bring the empty state into view. Android
5262    /// showed only the header (Day-Showcase's French walkthrough, run 44961147680).
5263    #[day_macros::test(day_core)]
5264    fn list_empty_state_shows_after_the_last_row_leaves() -> Case {
5265        Case::new()
5266            .proves(kinds::LIST)
5267            .page(|| {
5268                let rows: Signal<Vec<String>> =
5269                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
5270                let jump: Signal<Option<RowTarget>> = Signal::new(None);
5271                column((
5272                    row((
5273                        button("Down")
5274                            .action(move || jump.set(Some(RowTarget::new(200).instant())))
5275                            .id(day_core::id!(down)),
5276                        button("Clear")
5277                            .action(move || rows.set(Vec::new()))
5278                            .id(day_core::id!(clear)),
5279                    )),
5280                    names_list(rows)
5281                        .header(|| {
5282                            label("A header taller than the list")
5283                                .id(day_core::id!(list_header))
5284                                .padding(Insets::symmetric(12.0, 6.0))
5285                                .height(160.0)
5286                        })
5287                        .empty(|| label("Nothing here").id(day_core::id!(list_empty)))
5288                        .scroll_to_row(jump)
5289                        .id(day_core::id!(list))
5290                        .height(120.0),
5291                ))
5292            })
5293            .drive(|d: Drive| async move {
5294                d.assert_text("list_header", "A header taller than the list")
5295                    .await?;
5296                d.tap("down").await?;
5297                d.wait_idle().await?;
5298                d.assert_text("conformance_row:Row%20200", "Row 200")
5299                    .await?;
5300                d.tap("clear").await?;
5301                d.wait_idle().await?;
5302                d.assert_missing("conformance_row:Row%20200").await?;
5303                d.assert_text("list_empty", "Nothing here").await
5304            })
5305    }
5306
5307    /// Content padding insets every row from the side, beyond the platform's own margins,
5308    /// and puts its top inset above the first row.
5309    #[day_macros::test(day_core)]
5310    fn list_content_padding_insets_rows() -> Case {
5311        Case::new()
5312            .proves(kinds::LIST)
5313            .page(|| {
5314                let plain = keyed(&[(1, "Plain")]);
5315                let padded = keyed(&[(2, "Padded")]);
5316                column((
5317                    keyed_list(plain),
5318                    keyed_list(padded)
5319                        .content_padding(Insets {
5320                            top: 16.0,
5321                            leading: 24.0,
5322                            bottom: 16.0,
5323                            trailing: 24.0,
5324                        })
5325                        .id(day_core::id!(padded_list)),
5326                ))
5327                .spacing(0.0)
5328                .align(HAlign::Leading)
5329            })
5330            .drive(|d: Drive| async move {
5331                d.assert_text("keyed:1", "Plain").await?;
5332                d.assert_text("keyed:2", "Padded").await?;
5333                // The same row, 24 points further in than the plain list's.
5334                d.assert_frame(
5335                    "keyed_row:2",
5336                    FrameExpect {
5337                        x: Some(24.0),
5338                        relative_to: Some("keyed_row:1".into()),
5339                        ..Default::default()
5340                    },
5341                )
5342                .await?;
5343                // And 16 points down: its middle is at 32, its swatch 24 further in.
5344                d.sample_pixel("padded_list", 64.0 / 240.0, 32.0 / 160.0, "#00ff00")
5345                    .await
5346            })
5347    }
5348
5349    /// The rows of [`list_sectioned_rows_keep_their_height_after_a_splice`] once loaded:
5350    /// `(section, key)`, three sections of three.
5351    const SECTIONED: [(&str, u32); 9] = [
5352        ("A", 1),
5353        ("A", 2),
5354        ("A", 3),
5355        ("B", 4),
5356        ("B", 5),
5357        ("B", 6),
5358        ("C", 7),
5359        ("C", 8),
5360        ("C", 9),
5361    ];
5362
5363    /// The native top of each `sectioned:` row's label, in window points, in row order.
5364    fn sectioned_tops() -> Result<Vec<f64>, Fail> {
5365        day_core::try_with_tree(|t| {
5366            SECTIONED
5367                .iter()
5368                .map(|(_, key)| {
5369                    let id = format!("sectioned:{key}");
5370                    let node = t
5371                        .find_by_id(&id)
5372                        .ok_or_else(|| Fail(format!("no element {id:?}")))?;
5373                    t.read_native(node)
5374                        .and_then(|n| n.frame)
5375                        .map(|f| f.origin.y)
5376                        .ok_or_else(|| Fail(format!("{id:?} has no native frame")))
5377                })
5378                .collect()
5379        })
5380        .unwrap_or_else(|| Err(Fail("the tree is busy".into())))
5381    }
5382
5383    /// A sectioned `Uniform` list that grows by a keyed splice keeps every row at the uniform
5384    /// height and every header at its own (docs/list.md "Sections", "Keyed updates"). The
5385    /// splice inserts rows and headers among the ones shown, so a platform that sizes an
5386    /// inserted row before the splice has finished sizes it as whatever row ends up at that
5387    /// index: an item row the height of a header clips its content.
5388    #[day_macros::test(day_core)]
5389    fn list_sectioned_rows_keep_their_height_after_a_splice() -> Case {
5390        Case::new()
5391            .proves(kinds::LIST)
5392            .page(|| {
5393                let rows = Signal::new(vec![SECTIONED[0], SECTIONED[3]]);
5394                column((
5395                    button("Load")
5396                        .action(move || rows.set(SECTIONED.to_vec()))
5397                        .id(day_core::id!(load)),
5398                    list(
5399                        items(move || rows.get(), |r: &(&str, u32)| r.1),
5400                        |slot: ItemSlot<(&'static str, u32), u32>| {
5401                            label(move || format!("Row {}", slot.field(|r| r.1)))
5402                                .id_of(move || day_core::id!(sectioned, slot.field(|r| r.1)))
5403                                .padding(Insets::symmetric(12.0, 6.0))
5404                        },
5405                    )
5406                    .sections(
5407                        move |i| rows.with(|r| r.get(i).map(|r| r.0)),
5408                        |slot: ItemSlot<(&'static str, u32), u32>| {
5409                            label(move || format!("Section {}", slot.field(|r| r.0)))
5410                                .font(Font::Caption)
5411                                .padding(Insets::symmetric(12.0, 2.0))
5412                        },
5413                    )
5414                    .row_height(RowHeight::Uniform(32.0))
5415                    .id(day_core::id!(list))
5416                    .width(240.0)
5417                    .height(480.0),
5418                ))
5419            })
5420            .drive(|d: Drive| async move {
5421                d.assert_text("sectioned:4", "Row 4").await?;
5422                d.tap("load").await?;
5423                d.assert_text("sectioned:9", "Row 9").await?;
5424                d.wait_idle().await?;
5425                d.pause(0.3).await?;
5426                d.shot("sectioned-splice").await?;
5427                let tops = sectioned_tops()?;
5428                // Rows of one section follow each other at one pitch, at least the row height.
5429                let pitch = tops[1] - tops[0];
5430                d.check(
5431                    pitch >= 31.5,
5432                    &format!("the first row is {pitch:.1} tall, under its 32-point height"),
5433                )?;
5434                let mut step = None;
5435                for (i, pair) in tops.windows(2).enumerate() {
5436                    let gap = pair[1] - pair[0];
5437                    if SECTIONED[i].0 == SECTIONED[i + 1].0 {
5438                        d.check(
5439                            (gap - pitch).abs() <= 1.0,
5440                            &format!(
5441                                "row {} starts {gap:.1} below row {} where every row of a \
5442                                 section is {pitch:.1} below the one before",
5443                                SECTIONED[i + 1].1,
5444                                SECTIONED[i].1
5445                            ),
5446                        )?;
5447                    } else {
5448                        // Across a header: the row plus one header, the same at every header.
5449                        let step = *step.get_or_insert(gap);
5450                        d.check(
5451                            gap > pitch && (gap - step).abs() <= 1.0,
5452                            &format!(
5453                                "row {} starts {gap:.1} below row {} across a header, where \
5454                                 the first header's step was {step:.1}",
5455                                SECTIONED[i + 1].1,
5456                                SECTIONED[i].1
5457                            ),
5458                        )?;
5459                    }
5460                }
5461                Ok(())
5462            })
5463    }
5464
5465    type Node = (String, Option<String>);
5466
5467    /// A tree over `(name, parent)` rows, each row a label with the id `row:<name>`; the tree's
5468    /// own row ids are the names, which `expand` and `tree_move` address.
5469    fn names_tree(rows: Signal<Vec<Node>>) -> TreePiece<Branches<Node, String>> {
5470        tree(
5471            branches(
5472                move || rows.get(),
5473                |n: &Node| n.0.clone(),
5474                |n: &Node| n.1.clone(),
5475            ),
5476            |row: ItemSlot<Node, String>| {
5477                label(move || row.get().0)
5478                    .id_of(move || day_core::id!(conformance_row, row.get().0))
5479                    .padding(Insets::symmetric(8.0, 4.0))
5480            },
5481        )
5482        .row_height(RowHeight::Uniform(28.0))
5483        .row_id(|k: &String| day_core::id!(tree_row, k))
5484    }
5485
5486    fn fruit() -> Signal<Vec<Node>> {
5487        let n = |name: &str, parent: Option<&str>| (name.to_string(), parent.map(str::to_owned));
5488        Signal::new(vec![
5489            n("Fruit", None),
5490            n("Apple", Some("Fruit")),
5491            n("Pear", Some("Fruit")),
5492            n("Nuts", None),
5493        ])
5494    }
5495
5496    /// A tree shows its root rows, and disclosing a row shows its children.
5497    #[day_macros::test(day_core)]
5498    fn tree_rows_disclose() -> Case {
5499        Case::new()
5500            .proves_duty("attach_tree")
5501            .proves_cap(Cap::Tree)
5502            .proves(kinds::TREE)
5503            .requires(Cap::Tree)
5504            .page(|| names_tree(fruit()).id(day_core::id!(tree)).height(240.0))
5505            .drive(|d: Drive| async move {
5506                d.assert_text("conformance_row:Fruit", "Fruit").await?;
5507                d.assert_text("conformance_row:Nuts", "Nuts").await?;
5508                d.assert_missing("conformance_row:Apple").await?;
5509                d.expand("tree", "tree_row:Fruit", true).await?;
5510                d.assert_text("conformance_row:Apple", "Apple").await?;
5511                d.expand("tree", "tree_row:Fruit", false).await?;
5512                d.assert_missing("conformance_row:Apple").await
5513            })
5514    }
5515
5516    /// The expanded set is app state: rows it names start disclosed.
5517    #[day_macros::test(day_core)]
5518    fn tree_expanded_signal() -> Case {
5519        Case::new()
5520            .proves(kinds::TREE)
5521            .requires(Cap::Tree)
5522            .page(|| {
5523                let open = Signal::new(std::collections::HashSet::from(["Fruit".to_string()]));
5524                names_tree(fruit())
5525                    .expanded(open)
5526                    .id(day_core::id!(tree))
5527                    .height(240.0)
5528            })
5529            .drive(|d: Drive| async move { d.assert_text("conformance_row:Pear", "Pear").await })
5530    }
5531
5532    /// Synthetic fixture strings. Restoration has no callback echo; filtering preserves
5533    /// key-based state. This case runs on native and composed section implementations.
5534    #[day_macros::test(day_core)]
5535    fn tree_section_expansion_contract() -> Case {
5536        Case::new()
5537            .proves_duty("attach_tree")
5538            .proves_cap(Cap::TreeSections)
5539            .proves(kinds::TREE)
5540            .requires(Cap::TreeSections)
5541            .page(|| {
5542                let rows = fruit();
5543                let open = Signal::new(std::collections::HashSet::from(["Fruit".to_owned()]));
5544                let changes = Signal::new(0usize);
5545                column((
5546                    label(move || {
5547                        format!("{}:{}", open.with(|s| s.contains("Fruit")), changes.get())
5548                    })
5549                    .id(day_core::id!(state)),
5550                    button("restore")
5551                        .id(day_core::id!(restore))
5552                        .action(move || {
5553                            open.set(std::collections::HashSet::from(["Fruit".to_owned()]));
5554                        }),
5555                    button("filter")
5556                        .id(day_core::id!(filter))
5557                        .action(move || rows.update(|r| r.retain(|n| n.0 != "Apple"))),
5558                    names_tree(rows)
5559                        .section_headers()
5560                        .expanded(open)
5561                        .on_expansion(move |_, _| changes.update(|n| *n += 1))
5562                        .id(day_core::id!(tree))
5563                        .height(240.0),
5564                ))
5565            })
5566            .drive(|d: Drive| async move {
5567                d.assert_text("state", "true:0").await?;
5568                d.assert_text("conformance_row:Apple", "Apple").await?;
5569                d.expand("tree", "tree_row:Fruit", false).await?;
5570                d.assert_text("state", "false:1").await?;
5571                d.assert_missing("conformance_row:Apple").await?;
5572                d.expand("tree", "tree_row:Fruit", false).await?;
5573                d.assert_text("state", "false:1").await?;
5574                d.tap("filter").await?;
5575                d.assert_missing("conformance_row:Pear").await?;
5576                d.tap("restore").await?;
5577                d.assert_text("conformance_row:Pear", "Pear").await?;
5578                d.assert_text("state", "true:1").await
5579            })
5580    }
5581
5582    /// A committed move reaches the app, which re-parents the row in its source.
5583    #[day_macros::test(day_core)]
5584    fn tree_move_reparents() -> Case {
5585        Case::new()
5586            .proves_cap(Cap::TreeMove)
5587            .proves(kinds::TREE)
5588            .requires(Cap::Tree)
5589            .page(|| {
5590                let rows = fruit();
5591                let open = Signal::new(std::collections::HashSet::from([
5592                    "Fruit".to_string(),
5593                    "Nuts".to_string(),
5594                ]));
5595                column((
5596                    label(move || {
5597                        rows.get()
5598                            .iter()
5599                            .map(|(n, p)| format!("{n}<{}", p.clone().unwrap_or_default()))
5600                            .collect::<Vec<_>>()
5601                            .join(",")
5602                    })
5603                    .id(day_core::id!(shape)),
5604                    // "Nuts" has no children, so it takes a dropped row only as a declared folder.
5605                    names_tree(rows)
5606                        .expanded(open)
5607                        .expandable(|k: &String| k == "Fruit" || k == "Nuts")
5608                        .movable(Move::new(move |key, parent, _at| {
5609                            rows.update(|v| {
5610                                if let Some(n) = v.iter_mut().find(|n| n.0 == key) {
5611                                    n.1 = parent;
5612                                }
5613                            });
5614                        }))
5615                        .id(day_core::id!(tree))
5616                        .height(240.0),
5617                ))
5618            })
5619            .drive(|d: Drive| async move {
5620                d.tree_move("tree", "tree_row:Pear", Some("tree_row:Nuts"), None)
5621                    .await?;
5622                d.assert_text("shape", "Fruit<,Apple<Fruit,Pear<Nuts,Nuts<")
5623                    .await?;
5624                d.assert_text("conformance_row:Pear", "Pear").await
5625            })
5626    }
5627}