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<AnyBinding<Option<usize>>>,
906    first_visible_row: Option<AnyBinding<usize>>,
907    stick_to_bottom: bool,
908    reorder: Option<Reorder>,
909    delete: Option<Delete>,
910    swipe_leading: Option<SwipeProvider>,
911    swipe_trailing: Option<SwipeProvider>,
912    separators: Option<bool>,
913    inset_grouped: bool,
914    editing: crate::Reactive<bool>,
915    sections: Option<ListSections<S::Slot>>,
916}
917
918/// [`List::sections`]: each item's section key (by index, hashed to a token) and the header
919/// builder, which receives the slot of its section's first item.
920struct ListSections<Slot> {
921    key: Rc<dyn Fn(usize) -> u64>,
922    header: Rc<dyn Fn(Slot) -> AnyPiece>,
923}
924
925/// The full-set selection callback, aliased for the field above.
926type SelectionFn<R> = Rc<dyn Fn(Vec<R>)>;
927
928/// A row reference that names its row by a key: what [`List::selection`] binds. A day-model
929/// store's rows (an `Elem`) answer their key, which is also the row's identity token.
930pub trait SelectionKey {
931    fn selection_key(&self) -> u64;
932}
933
934/// [`List::selection`]'s two directions: the key to select (a tracked read) and the write that
935/// reports the user's choice.
936struct ListSelection<R> {
937    key: Rc<dyn Fn() -> Option<u64>>,
938    write: Rc<dyn Fn(Option<u64>)>,
939    key_of: Rc<dyn Fn(&R) -> u64>,
940}
941
942// ---------------------------------------------------------------------------
943// List items (docs/list.md "List items")
944// ---------------------------------------------------------------------------
945
946/// A list item's leading glyph: an app vector, which may follow a signal, or a standard symbol.
947#[derive(Clone)]
948enum ItemIcon {
949    Vector(Reactive<day_spec::VectorName>),
950    Symbol(day_spec::Symbol),
951}
952
953impl ItemIcon {
954    /// The glyph as the spec names it; `tracked` subscribes a reactive vector.
955    fn spec(&self, tracked: bool) -> day_spec::Icon {
956        match self {
957            ItemIcon::Vector(r) => {
958                let name = if tracked { r.get() } else { r.get_untracked() };
959                day_spec::Icon::Image(name.as_str().to_owned())
960            }
961            ItemIcon::Symbol(s) => day_spec::Icon::Symbol(*s),
962        }
963    }
964}
965
966/// A list row's standard content, built by [`list_item`] (docs/list.md "List items").
967#[must_use]
968pub struct ListItem {
969    title: TextSource,
970    subtitle: Option<TextSource>,
971    detail: Option<TextSource>,
972    icon: Option<ItemIcon>,
973    icon_tint: Option<Reactive<day_spec::Color>>,
974    checked: Option<Reactive<bool>>,
975}
976
977/// A list row's standard content: a leading icon, a title, an optional subtitle and trailing
978/// detail, and a check mark, drawn the way the platform draws its own list rows (docs/list.md
979/// "List items"). UIKit shows it with the cell's default content configuration, Android as a
980/// Material list item, AppKit as a table cell's image and text, GTK as a row box; elsewhere
981/// the piece composes the same parts. Each part may follow a signal, and changes in place, so
982/// a recycled row tracks its item.
983///
984/// ```ignore
985/// list(scene.items.rows(keys), move |slot| {
986///     list_item(move || slot.name().read())
987///         .icon(move || slot.kind().read().icon())
988///         .icon_tint(move || slot.tint().read().color())
989///         .checked(move || slot.done().read())
990/// })
991/// ```
992pub fn list_item<M>(title: impl IntoText<M>) -> ListItem {
993    ListItem {
994        title: title.into_text(),
995        subtitle: None,
996        detail: None,
997        icon: None,
998        icon_tint: None,
999        checked: None,
1000    }
1001}
1002
1003#[day_macros::builder(ListItemBuilder)]
1004impl ListItem {
1005    /// A second line under the title, in the platform's secondary style.
1006    pub fn subtitle<M>(mut self, text: impl IntoText<M>) -> Self {
1007        self.subtitle = Some(text.into_text());
1008        self
1009    }
1010    /// Trailing text, such as a count or a value, in the platform's secondary style.
1011    pub fn detail<M>(mut self, text: impl IntoText<M>) -> Self {
1012        self.detail = Some(text.into_text());
1013        self
1014    }
1015    /// The leading glyph: an app vector (`res::vectors::…`), drawn as a template in the
1016    /// foreground color unless [`Self::icon_tint`] names one. A signal or closure swaps it in
1017    /// place.
1018    pub fn icon<M>(mut self, name: impl IntoReactive<day_spec::VectorName, M>) -> Self {
1019        self.icon = Some(ItemIcon::Vector(name.into_reactive()));
1020        self
1021    }
1022    /// The leading glyph as a standard symbol.
1023    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1024        self.icon = Some(ItemIcon::Symbol(symbol));
1025        self
1026    }
1027    /// The leading glyph's color.
1028    pub fn icon_tint<M>(mut self, color: impl IntoReactive<day_spec::Color, M>) -> Self {
1029        self.icon_tint = Some(color.into_reactive());
1030        self
1031    }
1032    /// A trailing check mark while `on` holds: the platform's mark for a chosen or completed
1033    /// row, announced as selected.
1034    pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
1035        self.checked = Some(on.into_reactive());
1036        self
1037    }
1038}
1039
1040impl Piece for ListItem {
1041    fn build(self, cx: &mut BuildCx) -> RNode {
1042        if day_core::capability(day_spec::Cap::ListItem) == day_spec::Support::Native {
1043            self.build_native(cx)
1044        } else {
1045            self.compose().build(cx)
1046        }
1047    }
1048}
1049
1050impl ListItem {
1051    /// The platform's own row content (`kinds::LIST_ITEM`), each part patched in place.
1052    fn build_native(self, cx: &mut BuildCx) -> RNode {
1053        let text = |t: &Option<TextSource>| t.as_ref().map_or_default(TextSource::initial);
1054        let props = ListItemProps {
1055            title: self.title.initial(),
1056            subtitle: text(&self.subtitle),
1057            detail: text(&self.detail),
1058            icon: self.icon.as_ref().map(|i| i.spec(false)),
1059            icon_tint: self.icon_tint.as_ref().map(Reactive::get_untracked),
1060            checked: self.checked.as_ref().is_some_and(Reactive::get_untracked),
1061        };
1062        // The platform's whole row: it sizes its own height (docs/list.md "Row metrics").
1063        let node = cx.leaf(
1064            kinds::LIST_ITEM,
1065            &props,
1066            Flex {
1067                grow_w: true,
1068                whole_row: true,
1069                ..Default::default()
1070            },
1071        );
1072        let patch = move |p: ListItemPatch, size: bool| {
1073            with_tree(|t| t.patch(node, Box::new(p), size));
1074        };
1075        let bind_text =
1076            |src: Option<TextSource>, seed: String, make: fn(String) -> ListItemPatch| {
1077                if let Some(src @ TextSource::Dyn(_)) = src {
1078                    day_reactive::bind_seeded(
1079                        seed,
1080                        move || src.resolve(),
1081                        move |t: &String| patch(make(t.clone()), true),
1082                    );
1083                }
1084            };
1085        bind_text(Some(self.title), props.title, ListItemPatch::Title);
1086        bind_text(self.subtitle, props.subtitle, ListItemPatch::Subtitle);
1087        bind_text(self.detail, props.detail, ListItemPatch::Detail);
1088        if let Some(icon @ ItemIcon::Vector(Reactive::Dyn(_))) = self.icon {
1089            day_reactive::bind_seeded(
1090                props.icon,
1091                move || Some(icon.spec(true)),
1092                move |i| patch(ListItemPatch::Icon(i.clone()), false),
1093            );
1094        }
1095        if let Some(tint @ Reactive::Dyn(_)) = self.icon_tint {
1096            day_reactive::bind_seeded(
1097                props.icon_tint,
1098                move || Some(tint.get()),
1099                move |c| patch(ListItemPatch::IconTint(*c), false),
1100            );
1101        }
1102        if let Some(on @ Reactive::Dyn(_)) = self.checked {
1103            day_reactive::bind_seeded(
1104                props.checked,
1105                move || on.get(),
1106                move |b: &bool| patch(ListItemPatch::Checked(*b), true),
1107            );
1108        }
1109        node
1110    }
1111
1112    /// The same parts from plain pieces, where the toolkit has no row content of its own.
1113    fn compose(self) -> impl Piece {
1114        use crate::{column, image, label, row, vector, when};
1115        let tint = self.icon_tint;
1116        let leading = self.icon.map(move |icon| match icon {
1117            ItemIcon::Vector(src) => {
1118                let glyph = vector(move || src.get()).template();
1119                match tint {
1120                    Some(t) => glyph
1121                        .tint(move || t.get())
1122                        .decorative()
1123                        .frame(20.0, 20.0)
1124                        .any(),
1125                    None => glyph.decorative().frame(20.0, 20.0).any(),
1126                }
1127            }
1128            ItemIcon::Symbol(sym) => match sym.outline_svg() {
1129                Some(svg) => image(svg.into_bytes()).template().frame(20.0, 20.0).any(),
1130                None => crate::spacer().frame(20.0, 20.0).any(),
1131            },
1132        });
1133        let titles = column((
1134            label(self.title),
1135            self.subtitle
1136                .map(|t| label(t).font(day_spec::Font::Footnote).secondary()),
1137        ))
1138        .spacing(2.0)
1139        .align(crate::HAlign::Leading)
1140        .grow(Dimension::Width);
1141        let detail = self.detail.map(|t| label(t).secondary());
1142        let checked = self.checked.clone();
1143        let mark = checked.map(|on| {
1144            when(
1145                move || on.get(),
1146                || {
1147                    let svg = day_spec::Symbol::Check.outline_svg().unwrap_or_default();
1148                    image(svg.into_bytes())
1149                        .template()
1150                        .decorative()
1151                        .frame(16.0, 16.0)
1152                },
1153            )
1154        });
1155        let selected = self.checked;
1156        row((leading, titles, detail, mark))
1157            .spacing(crate::Space::M)
1158            .align(crate::VAlign::Center)
1159            .grow(Dimension::Width)
1160            .a11y(move |a| match selected {
1161                Some(on) => a.selected(move || on.get()),
1162                None => a,
1163            })
1164    }
1165}
1166
1167/// A row's swipe-action offer, aliased for the fields above: called with the row index at
1168/// gesture time, so the actions reflect the row's current state (docs/list.md).
1169type SwipeProvider = Rc<dyn Fn(usize) -> Vec<SwipeAction>>;
1170
1171/// One button in a row's swipe-action offer (docs/list.md): what the platform reveals as the
1172/// user drags a row aside, built by [`swipe_action`]. Holds the label, the styling hints the
1173/// backend maps onto its own affordance, and the handler the activation runs.
1174#[must_use]
1175pub struct SwipeAction {
1176    label: TextSource,
1177    destructive: bool,
1178    tint: Option<day_spec::Color>,
1179    symbol: Option<day_spec::Symbol>,
1180    handler: Rc<dyn Fn()>,
1181}
1182
1183/// Build a swipe action with `label` (a literal, a `res::str::…` text, a signal or a closure;
1184/// resolved in the current locale each time the offer is pulled). Chain
1185/// [`destructive`](SwipeAction::destructive) or [`tint`](SwipeAction::tint) for styling and
1186/// [`action`](SwipeAction::action) for the work; an action without a handler still reveals and
1187/// dismisses, but does nothing.
1188pub fn swipe_action<M>(label: impl IntoText<M>) -> SwipeAction {
1189    SwipeAction {
1190        label: label.into_text(),
1191        destructive: false,
1192        tint: None,
1193        symbol: None,
1194        handler: Rc::new(|| {}),
1195    }
1196}
1197
1198impl SwipeAction {
1199    /// Mark the action destructive: the platform styles it as such (red, on the Apple
1200    /// toolkits) and may animate the row away on activation.
1201    pub fn destructive(mut self) -> Self {
1202        self.destructive = true;
1203        self
1204    }
1205    /// The button's background color, where the platform honors one. Left unset, the platform
1206    /// picks its own default (gray, with red for destructive actions, on the Apple toolkits).
1207    pub fn tint(mut self, color: day_spec::Color) -> Self {
1208        self.tint = Some(color);
1209        self
1210    }
1211    /// A glyph for the button where the platform draws one: above the label on macOS, in
1212    /// place of it on iOS (docs/list.md). The label still matters: it is the accessibility
1213    /// name, and the platforms without a glyph slot show it alone.
1214    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1215        self.symbol = Some(symbol);
1216        self
1217    }
1218    /// The work an activation runs. Called on the main thread at the next event drain, never
1219    /// inside the native gesture callback; the row index is the one the offer was pulled for,
1220    /// so capture what the action needs when building it.
1221    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
1222        self.handler = Rc::new(f);
1223        self
1224    }
1225}
1226
1227/// Drag-to-reorder for a [`list()`] (docs/list.md): the handler that applies a committed move,
1228/// an optional guard consulted while the drag is live, and whether the gesture is offered
1229/// right now. A list is reorderable exactly when it carries one of these
1230/// (`list(..).reorderable(Reorder::new(f))`).
1231///
1232/// The platform's own mechanism does the dragging (the macOS drop gap, the iOS long-press
1233/// lift, Android's `ItemTouchHelper`) where the backend supports it (probe `Cap::ListReorder`;
1234/// docs/list.md has the matrix).
1235#[derive(Clone)]
1236#[must_use]
1237pub struct Reorder {
1238    moved: Rc<dyn Fn(usize, usize)>,
1239    guard: Option<Rc<dyn Fn(usize, usize) -> ReorderVerdict>>,
1240    enabled: Reactive<bool>,
1241}
1242
1243impl Reorder {
1244    /// `moved(from, to)` runs after a committed move: row `from` now sits at row `to`. Apply the
1245    /// same rotation to the backing data (`let it = v.remove(from); v.insert(to, it);`), and
1246    /// persist it if the order should survive a relaunch. Runs on the main thread at the next
1247    /// event drain, never inside the native drop callback.
1248    pub fn new(moved: impl Fn(usize, usize) + 'static) -> Reorder {
1249        Reorder {
1250            moved: Rc::new(moved),
1251            guard: None,
1252            enabled: Reactive::Const(true),
1253        }
1254    }
1255    /// Veto or override drops while the drag is live: called synchronously from the native
1256    /// validate hook with `(from, proposed_to)`. Return [`ReorderVerdict::Deny`] to refuse,
1257    /// [`ReorderVerdict::Retarget`] to accept at a different index (a "pinned rows" pattern), or
1258    /// [`ReorderVerdict::Allow`] to accept as proposed (the default without a guard). Keep it
1259    /// pure (read state, decide, return); it runs inside the platform's drag callback.
1260    pub fn guard(mut self, g: impl Fn(usize, usize) -> ReorderVerdict + 'static) -> Reorder {
1261        self.guard = Some(Rc::new(g));
1262        self
1263    }
1264    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
1265    /// `bool`, read when the platform asks whether a drag may begin, so an edit mode or a
1266    /// loading state can withhold it without rebuilding the list.
1267    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Reorder {
1268        self.enabled = on.into_reactive();
1269        self
1270    }
1271}
1272
1273/// Swipe-to-delete for a [`list()`] (docs/list.md): the handler that applies a committed delete,
1274/// the label the platform puts on its affordance, an optional per-row guard, and whether the
1275/// gesture is offered right now. A list is deletable exactly when it carries one of these
1276/// (`list(..).deletable(Delete::new(f))`).
1277///
1278/// The platform's delete gesture does the work (the iOS trailing swipe action, Android's
1279/// `ItemTouchHelper` swipe, ArkUI's `ListItem` swipe action) where the backend supports it
1280/// (probe `Cap::ListDelete`). The desktop toolkits answer `Unsupported`, so a list that must be
1281/// editable everywhere pairs this with an explicit control (a menu item or a button).
1282#[derive(Clone)]
1283#[must_use]
1284pub struct Delete {
1285    deleted: Rc<dyn Fn(usize)>,
1286    label: Option<TextSource>,
1287    guard: Option<Rc<dyn Fn(usize) -> bool>>,
1288    enabled: Reactive<bool>,
1289}
1290
1291impl Delete {
1292    /// `deleted(index)` runs after a committed delete: row `index` is gone. Apply the same
1293    /// removal to the backing data (`v.remove(index)`), and persist it if the change should
1294    /// survive a relaunch. Runs on the main thread at the next event drain, never inside the
1295    /// native swipe callback.
1296    pub fn new(deleted: impl Fn(usize) + 'static) -> Delete {
1297        Delete {
1298            deleted: Rc::new(deleted),
1299            label: None,
1300            guard: None,
1301            enabled: Reactive::Const(true),
1302        }
1303    }
1304    /// The word the platform puts on its delete affordance (`res::str::delete()`). Resolved in
1305    /// the locale current when the list builds. Left unset, each backend falls back to a trash
1306    /// glyph rather than shipping an English word into every locale.
1307    pub fn label<M>(mut self, text: impl IntoText<M>) -> Delete {
1308        self.label = Some(text.into_text());
1309        self
1310    }
1311    /// Protect individual rows: called synchronously before the affordance is offered, so a row
1312    /// that answers `false` shows no delete action rather than one that fails on use. Keep it
1313    /// pure; it runs inside the platform's swipe callback.
1314    pub fn guard(mut self, g: impl Fn(usize) -> bool + 'static) -> Delete {
1315        self.guard = Some(Rc::new(g));
1316        self
1317    }
1318    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
1319    /// `bool`, read when the platform asks whether a row may be deleted.
1320    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Delete {
1321        self.enabled = on.into_reactive();
1322        self
1323    }
1324}
1325
1326/// A reorder guard's verdict on a proposed row move (docs/list.md): consulted synchronously from
1327/// the native drag's validate hook, so the affordance (gap, insertion mark, forbidden cursor)
1328/// reflects the answer while the user is still dragging.
1329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1330pub enum ReorderVerdict {
1331    /// Accept the drop where proposed.
1332    Allow,
1333    /// Refuse the drop (the row springs back; most backends show a forbidden cursor live).
1334    Deny,
1335    /// Accept the drop, but at this row index instead of the proposed one.
1336    Retarget(usize),
1337}
1338
1339/// Build a recycling list from a [`RowSource`] and a row builder:
1340/// `list(items(rows_fn, key_of), row_view)` for plain data, `list(store, row_view)` (or
1341/// `list(store.rows(projection), …)`) for a day-model store.
1342pub fn list<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> List<S>
1343where
1344    S: RowSource + 'static,
1345    P: Piece,
1346{
1347    List {
1348        source: Some(source),
1349        build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
1350        row_height: RowHeight::Automatic,
1351        on_select: None,
1352        on_activate: None,
1353        on_selection: None,
1354        multi_select: false,
1355        selected_rows: None,
1356        selection: None,
1357        scroll_to_end: None,
1358        scroll_to_row: None,
1359        first_visible_row: None,
1360        stick_to_bottom: false,
1361        reorder: None,
1362        delete: None,
1363        swipe_leading: None,
1364        swipe_trailing: None,
1365        separators: None,
1366        inset_grouped: false,
1367        editing: crate::Reactive::Const(false),
1368        sections: None,
1369    }
1370}
1371
1372#[day_macros::builder(ListBuilder<S>)]
1373impl<S: RowSource + 'static> List<S> {
1374    /// Row sizing: `Uniform(h)` (fastest) or `Automatic` (self-sizing).
1375    pub fn row_height(mut self, h: RowHeight) -> Self {
1376        self.row_height = h;
1377        self
1378    }
1379    /// Open, play, or otherwise activate a row. Desktop lists use double-click or Enter;
1380    /// touch lists use a tap. Selection callbacks remain independent.
1381    pub fn on_activate(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
1382        self.on_activate = Some(Rc::new(f));
1383        self
1384    }
1385
1386    /// Called with the selected row when the native list reports a selection: the key for a
1387    /// plain-data source, the row's `Elem` handle for a store source.
1388    pub fn on_select(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
1389        self.on_select = Some(Rc::new(f));
1390        self
1391    }
1392    /// Allow selecting several rows at once, where the toolkit supports it (docs/list.md has
1393    /// the matrix; single-selection backends fall back to one row at a time). Every selection
1394    /// change calls [`Self::on_selection`] with the full set of selected rows.
1395    pub fn multi_select(mut self) -> Self {
1396        self.multi_select = true;
1397        self
1398    }
1399    /// Called with the full set of selected rows (row order, empty = cleared) whenever the
1400    /// selection changes: the multi-select analogue of [`Self::on_select`]. Also fired by
1401    /// single-selection backends with a one-element (or empty) set.
1402    pub fn on_selection(mut self, f: impl Fn(Vec<S::Ref>) + 'static) -> Self {
1403        self.on_selection = Some(Rc::new(f));
1404        self
1405    }
1406    /// Reactively sync the native selection to `rows` (row indices; empty clears). Re-runs
1407    /// whenever the closure's tracked reads change; the toolkit applies the sync without
1408    /// re-emitting a selection event. Drive it from app state to build "Clear selection".
1409    pub fn selected_rows(mut self, rows: impl Fn() -> Vec<usize> + 'static) -> Self {
1410        self.selected_rows = Some(Rc::new(rows));
1411        self
1412    }
1413    /// Two-way single selection by key, for a list of day-model store rows: `selected` holds
1414    /// the selected row's key (`None` for no selection). A row the user picks writes its key,
1415    /// clearing the selection writes `None`, and a key the app writes selects that row and
1416    /// scrolls it into view, following the row through inserts and moves.
1417    ///
1418    /// ```ignore
1419    /// list(scene.items, row_view).selection(scene.selected)
1420    /// ```
1421    pub fn selection(mut self, selected: impl Binding<Option<u64>>) -> Self
1422    where
1423        S::Ref: SelectionKey,
1424    {
1425        let selected = AnyBinding::new(selected);
1426        self.selection = Some(ListSelection {
1427            key: Rc::new(move || selected.get()),
1428            write: Rc::new(move |key| selected.set_if_changed(key)),
1429            key_of: Rc::new(|row: &S::Ref| row.selection_key()),
1430        });
1431        self
1432    }
1433    /// Scroll the list so its last row is fully visible whenever `trigger` fires, e.g. a chat
1434    /// timeline sticking to the newest message. Fire it with [`day_reactive::Trigger::notify`]
1435    /// after appending. No-op while the list is empty. The scroll targets the native list
1436    /// (`NSTableView`/`UITableView`/`GtkListView`/`QListView`/`RecyclerView`), so it respects the
1437    /// platform's own scroll physics.
1438    pub fn scroll_to_end(mut self, trigger: day_reactive::Trigger) -> Self {
1439        self.scroll_to_end = Some(trigger);
1440        self
1441    }
1442    /// Best-effort auto-stick: after a data reload, scroll to the end so freshly appended rows stay
1443    /// visible. Convenience over [`Self::scroll_to_end`] for feeds that always follow the newest
1444    /// row; for finer control (only stick when the user is already near the bottom) drive
1445    /// `scroll_to_end` from your own logic instead. Off by default.
1446    pub fn stick_to_bottom(mut self) -> Self {
1447        self.stick_to_bottom = true;
1448        self
1449    }
1450
1451    /// Programmatic scroll-to-row (docs/list.md): set the signal to `Some(row)` and the native
1452    /// list scrolls that row into view, realizing it if it was virtualized away: the row rail's
1453    /// counterpart to `scroll(...).scroll_target(...)`. The signal is left as written; setting
1454    /// the same row again re-fires. Takes a `Signal<Option<usize>>` or any other binding.
1455    pub fn scroll_to_row(mut self, target: impl Binding<Option<usize>>) -> Self {
1456        self.scroll_to_row = Some(AnyBinding::new(target));
1457        self
1458    }
1459
1460    /// The first actually visible article/item index, reported by native scrolling into
1461    /// `first` (a `Signal<usize>` or any other binding). Use with a heading overlay for
1462    /// floating group headers. No periodic timer is used.
1463    pub fn first_visible_row(mut self, first: impl Binding<usize>) -> Self {
1464        self.first_visible_row = Some(AnyBinding::new(first));
1465        self
1466    }
1467
1468    /// Let the user drag rows into a new order (docs/list.md): the list is reorderable exactly
1469    /// when it carries a [`Reorder`], whose handler applies the move to the app's data.
1470    ///
1471    /// ```ignore
1472    /// list(rows, row_view)
1473    ///     .reorderable(Reorder::new(move |from, to| scene.move_item(from, to)).guard(keep_pinned))
1474    /// ```
1475    pub fn reorderable(mut self, reorder: Reorder) -> Self {
1476        self.reorder = Some(reorder);
1477        self
1478    }
1479
1480    /// Let the user delete rows with the platform's delete gesture (docs/list.md): the list is
1481    /// deletable exactly when it carries a [`Delete`], whose handler applies the removal to the
1482    /// app's data.
1483    ///
1484    /// ```ignore
1485    /// list(rows, row_view)
1486    ///     .deletable(Delete::new(move |i| scene.remove_at(i)).label(res::str::delete()))
1487    /// ```
1488    pub fn deletable(mut self, delete: Delete) -> Self {
1489        self.delete = Some(delete);
1490        self
1491    }
1492
1493    /// Offer swipe actions on the row's leading edge, the reading-direction start, where the
1494    /// platform reveals them as the user drags the row aside (probe `Cap::ListSwipeActions`;
1495    /// docs/list.md has the matrix; a backend without the affordance shows nothing, so pair
1496    /// each action with an explicit control for the rest). `provider` runs at gesture time
1497    /// with the row index, so the offer can reflect the row's current state ("Mark as Read"
1498    /// vs "Mark as Unread"). Keep it pure and fast; it runs inside the platform's swipe
1499    /// callback; the actions' handlers run later, at the event drain. A full swipe across
1500    /// activates the edge's first action.
1501    pub fn swipe_leading(mut self, provider: impl Fn(usize) -> Vec<SwipeAction> + 'static) -> Self {
1502        self.swipe_leading = Some(Rc::new(provider));
1503        self
1504    }
1505
1506    /// Offer swipe actions on the row's trailing edge, the reading-direction end. Same
1507    /// contract as [`swipe_leading`](Self::swipe_leading).
1508    pub fn swipe_trailing(
1509        mut self,
1510        provider: impl Fn(usize) -> Vec<SwipeAction> + 'static,
1511    ) -> Self {
1512        self.swipe_trailing = Some(Rc::new(provider));
1513        self
1514    }
1515
1516    /// Draw a separator under each row. It is the host's separator, drawn at the row boundary
1517    /// and never by row content (docs/list.md): it aligns with the native selection and stays
1518    /// put while a macOS/iOS swipe slides the row past it, exactly as Mail's separators do.
1519    /// Unset, each platform keeps its default (iOS draws them, the desktops don't); see
1520    /// [`Self::no_separators`] for the other override. A backend without a separator mechanism
1521    /// ignores this (the docs matrix says which); don't re-create the old hand-drawn hairline
1522    /// there. Rows separate by their pitch.
1523    pub fn separators(mut self) -> Self {
1524        self.separators = Some(true);
1525        self
1526    }
1527
1528    /// Draw the list as the platform's inset grouped list: rounded groups of rows set in from
1529    /// the edges, one per section, as iOS Settings and Safari's History do (docs/list.md
1530    /// "Appearance"). iOS and macOS draw it; the other platforms draw their plain list.
1531    pub fn inset_grouped(mut self) -> Self {
1532        self.inset_grouped = true;
1533        self
1534    }
1535
1536    /// Draw no separator between rows, on a platform whose default draws one (iOS).
1537    pub fn no_separators(mut self) -> Self {
1538        self.separators = Some(false);
1539        self
1540    }
1541
1542    /// Group the rows into sections, each opened by a header row (docs/list.md "Sections").
1543    /// `key` runs with each row index when the rows change and names the row's section: a new
1544    /// section, and a header, starts wherever the key differs from the row before, so sort the
1545    /// rows by section first. `header` builds a section's header from the slot of its first
1546    /// row, the same slot a row builder gets, and rebinds it as its cell recycles.
1547    ///
1548    /// Headers are the platform's own: macOS group rows and UIKit section headers, which pin
1549    /// to the top of the list while their section scrolls under them; the other toolkits pin
1550    /// a copy of the current header the same way (`Cap::ListSections`). A header is never
1551    /// selected, activated or swiped, and row indices everywhere (selection, swipe offers,
1552    /// `selected_rows`, `scroll_to_row`, `first_visible_row`) still count rows only. A header
1553    /// sizes to its content even when the rows are `Uniform`.
1554    ///
1555    /// A row drags only within its own section, the platforms' rule for grouped tables: a
1556    /// drop past either end of the section lands at that end, and the `reorderable` guard
1557    /// sees row indices. A sectioned list offers no native swipe-to-delete, since deleting a
1558    /// section's last row would take its header with it.
1559    ///
1560    /// ```ignore
1561    /// list(items(move || articles.get(), |a| a.id), article_row)
1562    ///     .sections(
1563    ///         move |i| articles.with(|a| a[i].feed_id),
1564    ///         |slot| label(move || slot.field(|a| a.feed_title.clone())),
1565    ///     )
1566    /// ```
1567    pub fn sections<K: Hash, P: Piece>(
1568        mut self,
1569        key: impl Fn(usize) -> K + 'static,
1570        header: impl Fn(S::Slot) -> P + 'static,
1571    ) -> Self {
1572        self.sections = Some(ListSections {
1573            key: Rc::new(move |i| key_token(&key(i))),
1574            header: Rc::new(move |slot| AnyPiece::new(header(slot))),
1575        });
1576        self
1577    }
1578
1579    /// Put the list in the platform's editing mode (docs/list.md): on iOS, the rows show
1580    /// their delete controls (where a [`Delete`] offers one) and reorder grips (where a
1581    /// [`Reorder`] moves them), and a tap still activates
1582    /// the row. Reactive, so an Edit/Done button can toggle it, and the change animates.
1583    ///
1584    /// Probe `Cap::ListEditing`. The other toolkits have no separate editing mode: their
1585    /// rows drag, swipe and open menus as they are, so the list renders as if this were off.
1586    pub fn editing<M>(mut self, on: impl crate::IntoReactive<bool, M>) -> Self {
1587        self.editing = on.into_reactive();
1588        self
1589    }
1590}
1591
1592/// The driver's build closure for a row or a section header: build `builder`'s piece from a
1593/// slot for item `index` in its own scope, and rebind that slot as the cell recycles.
1594fn slot_builder<C: RowConn>(
1595    conn: Rc<C>,
1596    builder: Rc<dyn Fn(C::Slot) -> AnyPiece>,
1597) -> Box<dyn Fn(usize, RNode) -> BuiltRow> {
1598    Box::new(move |index, anchor| {
1599        let scope = Scope::child();
1600        let conn = conn.clone();
1601        let builder = builder.clone();
1602        let rebind = scope.enter(move || {
1603            // Native callbacks can deliver a stale index mid-animation; an out-of-range pull
1604            // yields an empty row instead of panicking.
1605            let Some(slot) = conn.slot_at(index) else {
1606                return Rc::new(|_: usize| {}) as Rc<dyn Fn(usize)>;
1607            };
1608            let mut rowcx = BuildCx::new(anchor);
1609            in_row_scope(|| builder(slot).build(&mut rowcx));
1610            // Rebind on recycle: point the slot at the cell's new row.
1611            Rc::new(move |i: usize| conn.rebind(&slot, i)) as Rc<dyn Fn(usize)>
1612        });
1613        BuiltRow { scope, rebind }
1614    })
1615}
1616
1617impl<S: RowSource + 'static> Piece for List<S> {
1618    fn build(mut self, cx: &mut BuildCx) -> RNode {
1619        let props = ListProps {
1620            activatable: self.on_activate.is_some(),
1621            row_height: self.row_height,
1622            selectable: self.on_select.is_some()
1623                || self.on_selection.is_some()
1624                || self.selection.is_some()
1625                || self.on_activate.is_some(),
1626            multi_select: self.multi_select,
1627            // A sectioned list reorders within a section but offers no native delete (see
1628            // `sections`); the scripted path still reaches the driver.
1629            reorderable: self.reorder.is_some(),
1630            deletable: self.delete.is_some() && self.sections.is_none(),
1631            delete_label: self
1632                .delete
1633                .as_ref()
1634                .and_then(|d| d.label.as_ref())
1635                .map_or_default(TextSource::initial),
1636            swipe_actions: self.swipe_leading.is_some() || self.swipe_trailing.is_some(),
1637            separators: self.separators,
1638            editing: self.editing.get_untracked(),
1639            sections: self.sections.is_some(),
1640            inset_grouped: self.inset_grouped,
1641        };
1642        let node = cx.leaf(
1643            kinds::LIST,
1644            &props,
1645            Flex {
1646                grow_w: true,
1647                grow_h: true,
1648                ..Default::default()
1649            },
1650        );
1651
1652        // The source's live connection: the data-source's view of the world, refreshed by the
1653        // watch below. The native host queries it synchronously; the driver's build/rebind
1654        // closures read the same snapshot.
1655        let conn = Rc::new(self.source.take().expect("List built once").connect());
1656        // A sectioned list's keys, one per row of the snapshot: computed with it, and rotated
1657        // with it by a committed move, so day-core's header rows always match the rows.
1658        let section_keys: Rc<RefCell<Vec<u64>>> = Rc::new(RefCell::new(Vec::new()));
1659        let key_of_row = self.sections.as_ref().map(|s| s.key.clone());
1660        let refresh = {
1661            let (conn, keys, key_of_row) = (conn.clone(), section_keys.clone(), key_of_row.clone());
1662            Rc::new(move || {
1663                let tokens = conn.refresh();
1664                if let Some(key) = &key_of_row {
1665                    *keys.borrow_mut() = (0..conn.len()).map(|i| key(i)).collect();
1666                }
1667                (tokens, keys.borrow().clone())
1668            })
1669        };
1670        // After a committed native move/delete, the token order the app's own data update is
1671        // expected to echo back. When the refresh below sees exactly this order, the native rows
1672        // already sit in it (the gesture animated them there): take the data, skip the reload.
1673        let pending_echo: Rc<RefCell<Option<Vec<u64>>>> = Rc::new(RefCell::new(None));
1674
1675        if let Some(activate) = self.on_activate.clone() {
1676            let conn = conn.clone();
1677            cx.on(node, move |event| {
1678                if let Event::ListActivated(row) = event
1679                    && let Some(reference) = conn.select_ref(*row)
1680                {
1681                    activate(reference);
1682                }
1683            });
1684        }
1685
1686        // Selection → refs (translate the native row indices through the snapshot). A
1687        // single-selection report also feeds `on_selection` as a one-element set, so an app
1688        // tracking the full selection works unchanged on single-selection backends.
1689        if self.on_select.is_some() || self.on_selection.is_some() {
1690            let (on_select, on_selection) = (self.on_select.clone(), self.on_selection.clone());
1691            let conn = conn.clone();
1692            cx.on(node, move |ev| match ev {
1693                Event::SelectionChanged(i) => {
1694                    if let Some(f) = &on_select
1695                        && let Some(r) = conn.select_ref(*i as usize)
1696                    {
1697                        f(r);
1698                    }
1699                    if let Some(f) = &on_selection {
1700                        f(conn.select_ref(*i as usize).into_iter().collect());
1701                    }
1702                }
1703                Event::SelectionSet(rows) => {
1704                    if let Some(f) = &on_selection {
1705                        f(rows
1706                            .iter()
1707                            .filter_map(|i| conn.select_ref(*i as usize))
1708                            .collect());
1709                    }
1710                }
1711                _ => {}
1712            });
1713        }
1714
1715        // A `.selection` binding: the user's choice writes the key back. `user_pick` remembers
1716        // it, so the apply below neither re-selects nor scrolls the row the user just chose.
1717        // `apply` selects the bound key's row in the current snapshot (the rows the native list
1718        // shows), and scrolls to it once after the app writes a key; a key whose row has not
1719        // reached the snapshot yet stays pending until the reload that brings it.
1720        let user_pick: Rc<Cell<Option<Option<u64>>>> = Rc::new(Cell::new(None));
1721        let reveal = Rc::new(Cell::new(false));
1722        let apply_selection: Option<Rc<dyn Fn()>> = self.selection.as_ref().map(|sel| {
1723            let (key, conn, reveal) = (sel.key.clone(), conn.clone(), reveal.clone());
1724            Rc::new(move || {
1725                let wanted = day_reactive::untrack(|| key());
1726                let row = wanted.and_then(|k| conn.tokens_now().iter().position(|t| *t == k));
1727                let scroll = row.filter(|_| reveal.replace(false));
1728                // Posted, like `selected_rows`: a toolkit may still be applying the reload
1729                // that brought the row.
1730                day_reactive::on_main(move || {
1731                    day_core::list_set_selected(node, row.into_iter().collect());
1732                    if let Some(row) = scroll {
1733                        list_scroll_to_row(node, row);
1734                    }
1735                });
1736            }) as Rc<dyn Fn()>
1737        });
1738        if let Some(sel) = &self.selection {
1739            let (write, key_of) = (sel.write.clone(), sel.key_of.clone());
1740            let (conn, pick) = (conn.clone(), user_pick.clone());
1741            cx.on(node, move |ev| {
1742                let row = match ev {
1743                    Event::SelectionChanged(i) => conn.select_ref(*i as usize),
1744                    Event::SelectionSet(rows) => {
1745                        rows.first().and_then(|i| conn.select_ref(*i as usize))
1746                    }
1747                    _ => return,
1748                };
1749                let key = row.as_ref().map(|r| key_of(r));
1750                pick.set(Some(key));
1751                write(key);
1752            });
1753        }
1754
1755        // A committed native move, deferred to the event drain (never run inside the platform's
1756        // drop callback): hand the app the same (from, to) the native side animated.
1757        if let Some(on_reorder) = self.reorder.as_ref().map(|r| r.moved.clone()) {
1758            cx.on(node, move |ev| {
1759                if let Event::ListReorder { from, to } = ev {
1760                    on_reorder(*from, *to);
1761                }
1762            });
1763        }
1764
1765        // A committed native delete, deferred to the event drain (never run inside the
1766        // platform's swipe callback): hand the app the row the native side animated away.
1767        if let Some(on_delete) = self.delete.as_ref().map(|d| d.deleted.clone()) {
1768            cx.on(node, move |ev| {
1769                if let Event::ListDelete(index) = ev {
1770                    on_delete(*index);
1771                }
1772            });
1773        }
1774
1775        // An activated swipe action, deferred to the event drain. The handlers live in
1776        // `SwipeAction`s the provider builds fresh per gesture, so re-pull the offer here to
1777        // find the one the user pressed. The provider is the single source of both the offer
1778        // and its handlers, and a state change between reveal and activation resolves to the
1779        // action the row now offers at that position.
1780        if self.swipe_leading.is_some() || self.swipe_trailing.is_some() {
1781            let (leading, trailing) = (self.swipe_leading.clone(), self.swipe_trailing.clone());
1782            cx.on(node, move |ev| {
1783                if let Event::ListSwipe {
1784                    index,
1785                    edge,
1786                    action,
1787                } = ev
1788                {
1789                    let provider = match edge {
1790                        day_spec::SwipeEdge::Leading => leading.as_ref(),
1791                        day_spec::SwipeEdge::Trailing => trailing.as_ref(),
1792                    };
1793                    if let Some(p) = provider
1794                        && let Some(a) = p(*index).get(*action)
1795                    {
1796                        (a.handler)();
1797                    }
1798                }
1799            });
1800        }
1801
1802        // The type-erased driver day-core drives on cell pulls.
1803        if let Some(signal) = self.first_visible_row {
1804            cx.on(node, move |event| {
1805                if let Event::Custom { tag, num, text } = event
1806                    && (*tag == "day-list-first-visible"
1807                        || (tag.is_empty() && text == "day-list-first-visible"))
1808                    && num.is_finite()
1809                    && *num >= 0.0
1810                {
1811                    signal.set_if_changed(*num as usize);
1812                }
1813            });
1814        }
1815        let driver = ListDriver {
1816            track_viewport: self.first_visible_row.is_some(),
1817            row_height: self.row_height,
1818            len: {
1819                let conn = conn.clone();
1820                Box::new(move || conn.len())
1821            },
1822            token_at: {
1823                let conn = conn.clone();
1824                Box::new(move |i| conn.token_at(i))
1825            },
1826            build: slot_builder(conn.clone(), self.build_row.clone()),
1827            sections: self.sections.as_ref().map(|sections| ListSectionsDriver {
1828                key_at: {
1829                    let keys = section_keys.clone();
1830                    Box::new(move |i| keys.borrow().get(i).copied().unwrap_or_default())
1831                },
1832                build: slot_builder(conn.clone(), sections.header.clone()),
1833            }),
1834            delete: self.delete.as_ref().map(|delete| ListDeleteDriver {
1835                // Availability first (`Delete::enabled`), then the row's own guard.
1836                can_delete: {
1837                    let (guard, enabled) = (delete.guard.clone(), delete.enabled.clone());
1838                    Box::new(move |i| {
1839                        enabled.get_untracked() && guard.as_ref().is_none_or(|g| g(i))
1840                    })
1841                },
1842                // Commit: drop the row from the snapshot now (subsequent len/token_at/bind_row
1843                // serve the shorter list while the native removal animates), arm the echo skip,
1844                // and defer the app's callback.
1845                deleted: {
1846                    let (conn, echo, keys) =
1847                        (conn.clone(), pending_echo.clone(), section_keys.clone());
1848                    Box::new(move |index| {
1849                        if index >= conn.len() {
1850                            return;
1851                        }
1852                        conn.commit_delete(index);
1853                        if index < keys.borrow().len() {
1854                            keys.borrow_mut().remove(index);
1855                        }
1856                        *echo.borrow_mut() = Some(conn.tokens_now());
1857                        enqueue_event(rnode_to_id(node), Event::ListDelete(index));
1858                    })
1859                },
1860            }),
1861            reorder: self.reorder.as_ref().map(|reorder| ListReorderDriver {
1862                // The guard's verdict, encoded for the synchronous `can_move` callback:
1863                // accepted index or -1. Availability (`Reorder::enabled`) is asked first.
1864                can_move: {
1865                    let (guard, enabled) = (reorder.guard.clone(), reorder.enabled.clone());
1866                    Box::new(move |from, to| {
1867                        if !enabled.get_untracked() {
1868                            return -1;
1869                        }
1870                        match guard.as_ref().map(|g| g(from, to)) {
1871                            None | Some(ReorderVerdict::Allow) => to as i64,
1872                            Some(ReorderVerdict::Deny) => -1,
1873                            Some(ReorderVerdict::Retarget(i)) => i as i64,
1874                        }
1875                    })
1876                },
1877                // Commit: rotate the snapshot now (subsequent len/token_at/bind_row serve the
1878                // new order while the native move animates), arm the echo skip, and defer the
1879                // app's callback through the event queue.
1880                moved: {
1881                    let (conn, echo, keys) =
1882                        (conn.clone(), pending_echo.clone(), section_keys.clone());
1883                    Box::new(move |from, to| {
1884                        if from >= conn.len() || to >= conn.len() {
1885                            return;
1886                        }
1887                        conn.commit_move(from, to);
1888                        {
1889                            let mut keys = keys.borrow_mut();
1890                            if from < keys.len() && to < keys.len() {
1891                                let k = keys.remove(from);
1892                                keys.insert(to, k);
1893                            }
1894                        }
1895                        *echo.borrow_mut() = Some(conn.tokens_now());
1896                        enqueue_event(rnode_to_id(node), Event::ListReorder { from, to });
1897                    })
1898                },
1899            }),
1900            swipe: (self.swipe_leading.is_some() || self.swipe_trailing.is_some()).then(|| {
1901                ListSwipeDriver {
1902                    // The offer, stripped to data: labels + styling go to the toolkit; the
1903                    // handlers stay here, found again by index when the activation drains.
1904                    actions_at: {
1905                        let (leading, trailing) =
1906                            (self.swipe_leading.clone(), self.swipe_trailing.clone());
1907                        Box::new(move |i, edge| {
1908                            let provider = match edge {
1909                                day_spec::SwipeEdge::Leading => leading.as_ref(),
1910                                day_spec::SwipeEdge::Trailing => trailing.as_ref(),
1911                            };
1912                            provider.map_or_else(Vec::new, |p| {
1913                                p(i).iter()
1914                                    .map(|a| day_spec::ListSwipeAction {
1915                                        label: a.label.resolve(),
1916                                        destructive: a.destructive,
1917                                        tint: a.tint,
1918                                        symbol: a.symbol,
1919                                    })
1920                                    .collect()
1921                            })
1922                        })
1923                    },
1924                    // Commit: defer the app's handler through the event queue (never run it
1925                    // inside the native gesture callback).
1926                    performed: {
1927                        let conn = conn.clone();
1928                        Box::new(move |index, edge, action| {
1929                            if index >= conn.len() {
1930                                return;
1931                            }
1932                            enqueue_event(
1933                                rnode_to_id(node),
1934                                Event::ListSwipe {
1935                                    index,
1936                                    edge,
1937                                    action,
1938                                },
1939                            );
1940                        })
1941                    },
1942                }
1943            }),
1944        };
1945        install_list(node, driver);
1946
1947        // Keep the snapshot current and tell the native host to re-query on changes. The compute
1948        // is the tracked refresh; for a store source whose values flow through per-field
1949        // notifications, an unchanged row set skips the native reload entirely: a field edit
1950        // costs the one control it patched, not a visible-rows rebind.
1951        {
1952            let (conn, echo, stick) = (conn.clone(), pending_echo.clone(), self.stick_to_bottom);
1953            let reselect = apply_selection.clone();
1954            let initial = {
1955                let refresh = refresh.clone();
1956                day_reactive::untrack(move || refresh())
1957            };
1958            // The native host attached against an empty snapshot (install_list ran before this
1959            // prime), so tell it the real row set now: reload, without the auto-scroll a later
1960            // sticky change gets. Skipping this rendered every list blank until its first data
1961            // change, while the synthetic rail kept passing: the walkthrough drove the driver
1962            // directly and never noticed.
1963            list_reload(node);
1964            let last: RefCell<(Vec<u64>, Vec<u64>)> = RefCell::new(initial);
1965            watch(
1966                move || refresh(),
1967                move |rows: &(Vec<u64>, Vec<u64>), _| {
1968                    let toks = &rows.0;
1969                    let pending = pending_echo.borrow_mut().take();
1970                    let is_echo = pending.as_ref().is_some_and(|e| e == toks);
1971                    // A row moving to another section changes its header rows, not its tokens.
1972                    let unchanged = !conn.values_flow_by_reload() && *last.borrow() == *rows;
1973                    *last.borrow_mut() = rows.clone();
1974                    if !is_echo && pending.is_some() {
1975                        // The native rows took a move or delete the app answered with some
1976                        // other order. The source's deltas describe the change from its order
1977                        // before the gesture, not from the rows on screen: reload instead.
1978                        let _ = conn.take_row_events();
1979                        list_reload(node);
1980                        if let Some(apply) = &reselect {
1981                            apply();
1982                        }
1983                    } else if !is_echo && !unchanged {
1984                        match conn.take_row_events() {
1985                            Some(deltas) if !deltas.is_empty() => list_splice(node, deltas),
1986                            Some(_) => {}
1987                            None => list_reload(node),
1988                        }
1989                        if stick {
1990                            list_scroll_to_end(node);
1991                        }
1992                        // A reload drops the native selection; put the bound row back.
1993                        if let Some(apply) = &reselect {
1994                            apply();
1995                        }
1996                    } else {
1997                        // Consume events the host must not see twice (its own echo, or a
1998                        // change whose set landed identical).
1999                        let _ = conn.take_row_events();
2000                    }
2001                },
2002            );
2003            let _ = echo;
2004        }
2005
2006        // Imperative scroll-to-end: each `trigger.notify()` re-runs this watch (the trigger's
2007        // signal is the only tracked dep), whose callback scrolls the native list to its last row.
2008        // `watch` never fires for the initial run, so building the list does not force a scroll.
2009        if let Some(trigger) = self.scroll_to_end {
2010            watch(
2011                move || trigger.track(),
2012                move |(): &(), _| list_scroll_to_end(node),
2013            );
2014        }
2015
2016        // Programmatic scroll-to-row: every `Some(row)` write scrolls that row into view
2017        // (`watch` fires per write, so repeats of the same row re-fire; the initial build never
2018        // scrolls).
2019        if let Some(sig) = self.scroll_to_row {
2020            watch(
2021                move || sig.get(),
2022                move |row: &Option<usize>, _| {
2023                    if let Some(row) = row {
2024                        list_scroll_to_row(node, *row);
2025                    }
2026                },
2027            );
2028        }
2029
2030        // A reactive editing mode patches on change; the props carried the initial state.
2031        if let editing @ crate::Reactive::Dyn(_) =
2032            std::mem::replace(&mut self.editing, crate::Reactive::Const(false))
2033        {
2034            watch(
2035                move || editing.get(),
2036                move |on: &bool, old| {
2037                    if old.is_some() {
2038                        list_set_editing(node, *on);
2039                    }
2040                },
2041            );
2042        }
2043
2044        // `.selection`: every key the app writes selects its row and scrolls it into view (once
2045        // the row is in the snapshot; see `apply`). The initial key and the user's own pick
2046        // select without scrolling.
2047        if let (Some(sel), Some(apply)) = (self.selection.take(), apply_selection) {
2048            let first = Cell::new(true);
2049            day_reactive::bind(
2050                move || (sel.key)(),
2051                move |key: &Option<u64>| {
2052                    let initial = first.replace(false);
2053                    // The user's own pick is applied too, unscrolled: a list with no selection of
2054                    // its own (Android's RecyclerView) paints only what Day records, and a native
2055                    // list re-selecting the row it shows is a no-op.
2056                    let picked = user_pick.take() == Some(*key);
2057                    reveal.set(!initial && !picked && key.is_some());
2058                    apply();
2059                },
2060            );
2061        }
2062
2063        // An explicit selection binding owns the initial selection too. Reader layouts may
2064        // remount a list with an already-selected model item; skipping the initial apply
2065        // leaves the native table unselected until a later model change.
2066        if let Some(rows) = self.selected_rows {
2067            day_reactive::bind(
2068                move || rows(),
2069                move |rows: &Vec<usize>| {
2070                    // Selection and the row source may depend on the same model signal.
2071                    // Let the source publish/reload its snapshot before selecting its indexes.
2072                    let rows = rows.clone();
2073                    day_reactive::on_main(move || day_core::list_set_selected(node, rows));
2074                },
2075            );
2076        }
2077        node
2078    }
2079}
2080
2081// ---------------------------------------------------------------------------
2082// Model-driven rows (feature "model", docs/model.md): a day-model store as a RowSource
2083// ---------------------------------------------------------------------------
2084
2085#[cfg(feature = "model")]
2086mod model_rows {
2087    use super::*;
2088    use day_model::{Elem, Identified, Keyed, Source, Store};
2089
2090    /// One recycled row's connection to its store: the slot a model list's row builder
2091    /// receives. `Copy`, and a day-model [`Source`], so `#[derive(Observable)]` accessors hang
2092    /// off it. `text_field(slot.name())` binds two-way and follows the slot to its next row
2093    /// when the cell recycles, because the slot resolves its row on every operation.
2094    pub struct ModelSlot<T: 'static> {
2095        store: Store<Keyed<T>>,
2096        cur: Signal<u64>,
2097    }
2098
2099    impl<T> Clone for ModelSlot<T> {
2100        fn clone(&self) -> Self {
2101            *self
2102        }
2103    }
2104    impl<T> Copy for ModelSlot<T> {}
2105
2106    impl<T: Identified + Clone + 'static> ModelSlot<T> {
2107        /// A slot pointed at `key`, for row sources implemented outside this crate (a live
2108        /// query). Application code receives slots from `list`/`each` instead.
2109        pub fn for_key(store: Store<Keyed<T>>, key: u64) -> ModelSlot<T> {
2110            ModelSlot {
2111                store,
2112                cur: Signal::new(key),
2113            }
2114        }
2115        /// The recycle write, for external row sources: point this slot at another key.
2116        pub fn rebind_key(&self, key: u64) {
2117            self.cur.set_if_changed(key);
2118        }
2119    }
2120
2121    impl<T: Identified + 'static> ModelSlot<T> {
2122        /// The row's key right now, tracked, so a closure reading it follows recycling
2123        /// (a context-menu action captures the slot and acts on whichever row the cell shows
2124        /// when it runs).
2125        pub fn key(self) -> u64 {
2126            self.cur.get()
2127        }
2128        /// The current row as a plain element handle, for `exists()` guards or handing to
2129        /// code outside the row. Tracked via the slot, so it follows recycling too.
2130        pub fn item(self) -> Elem<T> {
2131            self.store.elem(self.cur.get())
2132        }
2133        fn elem_now(self) -> Elem<T> {
2134            self.store.elem(self.cur.get_untracked())
2135        }
2136    }
2137
2138    impl<T: Identified + 'static> Source<T> for ModelSlot<T> {
2139        // The slot's location is wherever the cell currently sits, hence `DYNAMIC`.
2140        const DYNAMIC: bool = true;
2141        fn track_extra(self) {
2142            self.cur.track();
2143        }
2144        fn path(self) -> day_model::Path {
2145            self.elem_now().path()
2146        }
2147        fn node(self) -> day_model::NodeId {
2148            self.elem_now().node()
2149        }
2150        fn components(self, out: &mut Vec<u64>) {
2151            self.elem_now().components(out);
2152        }
2153        fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
2154            self.elem_now().with_value_untracked(f)
2155        }
2156        fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
2157            self.elem_now().update_value(f)
2158        }
2159        fn bump_version(self) {
2160            self.elem_now().bump_version();
2161        }
2162    }
2163
2164    /// A store row names itself by its key, so a store list binds [`List::selection`].
2165    impl<T: Identified + 'static> SelectionKey for Elem<T> {
2166        fn selection_key(&self) -> u64 {
2167            self.key()
2168        }
2169    }
2170
2171    /// A store IS a row source: collection order, rows keyed by the store's own keys.
2172    impl<T: Identified + Clone + 'static> RowSource for Store<Keyed<T>> {
2173        type Slot = ModelSlot<T>;
2174        type Ref = Elem<T>;
2175        type Conn = StoreConn<T>;
2176        fn connect(self) -> StoreConn<T> {
2177            StoreConn {
2178                store: self,
2179                rows: None,
2180                keys: RefCell::new(Vec::new()),
2181            }
2182        }
2183    }
2184
2185    /// A display projection over a store: `store.rows(move || ordered_keys())`. The projection
2186    /// is a tracked read of key ids: read only the fields the order depends on, and a write to
2187    /// any other field cannot re-run it.
2188    pub struct Rows<T: 'static> {
2189        store: Store<Keyed<T>>,
2190        f: Rc<dyn Fn() -> Vec<u64>>,
2191    }
2192
2193    impl<T: Identified + Clone + 'static> RowSource for Rows<T> {
2194        type Slot = ModelSlot<T>;
2195        type Ref = Elem<T>;
2196        type Conn = StoreConn<T>;
2197        fn connect(self) -> StoreConn<T> {
2198            StoreConn {
2199                store: self.store,
2200                rows: Some(self.f),
2201                keys: RefCell::new(Vec::new()),
2202            }
2203        }
2204    }
2205
2206    /// `store.rows(projection)`: the display-ordered row source for [`list()`]/[`each`].
2207    pub trait StoreRows<T: 'static> {
2208        fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T>;
2209    }
2210
2211    impl<T: Identified + Clone + 'static> StoreRows<T> for Store<Keyed<T>> {
2212        fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T> {
2213            Rows {
2214                store: self,
2215                f: Rc::new(f),
2216            }
2217        }
2218    }
2219
2220    /// The store connection: its snapshot is the display keys; no item is ever cloned.
2221    pub struct StoreConn<T: 'static> {
2222        store: Store<Keyed<T>>,
2223        rows: Option<Rc<dyn Fn() -> Vec<u64>>>,
2224        keys: RefCell<Vec<u64>>,
2225    }
2226
2227    impl<T: Identified + Clone + 'static> RowConn for StoreConn<T> {
2228        type Slot = ModelSlot<T>;
2229        type Ref = Elem<T>;
2230
2231        fn refresh(&self) -> Vec<u64> {
2232            let keys = match &self.rows {
2233                Some(f) => f(),
2234                None => self.store.keys(),
2235            };
2236            *self.keys.borrow_mut() = keys.clone();
2237            keys
2238        }
2239        fn len(&self) -> usize {
2240            self.keys.borrow().len()
2241        }
2242        fn token_at(&self, index: usize) -> u64 {
2243            self.keys.borrow().get(index).copied().unwrap_or(0)
2244        }
2245        fn tokens_now(&self) -> Vec<u64> {
2246            self.keys.borrow().clone()
2247        }
2248        fn slot_at(&self, index: usize) -> Option<ModelSlot<T>> {
2249            let key = self.keys.borrow().get(index).copied()?;
2250            Some(ModelSlot {
2251                store: self.store,
2252                cur: Signal::new(key),
2253            })
2254        }
2255        fn rebind(&self, slot: &ModelSlot<T>, index: usize) {
2256            if let Some(key) = self.keys.borrow().get(index).copied() {
2257                // Values flow through the store's own notifications; the rebind is only the
2258                // key, and an unchanged key is a no-op.
2259                slot.cur.set_if_changed(key);
2260            }
2261        }
2262        fn select_ref(&self, index: usize) -> Option<Elem<T>> {
2263            let key = self.keys.borrow().get(index).copied()?;
2264            Some(self.store.elem(key))
2265        }
2266        fn values_flow_by_reload(&self) -> bool {
2267            false
2268        }
2269        fn commit_move(&self, from: usize, to: usize) {
2270            let mut keys = self.keys.borrow_mut();
2271            if from >= keys.len() || to >= keys.len() {
2272                return;
2273            }
2274            let k = keys.remove(from);
2275            keys.insert(to, k);
2276        }
2277        fn commit_delete(&self, index: usize) {
2278            let mut keys = self.keys.borrow_mut();
2279            if index >= keys.len() {
2280                return;
2281            }
2282            keys.remove(index);
2283        }
2284    }
2285
2286    /// A hierarchy over a store: `store.tree(children_of)` (docs/tree.md). The projection
2287    /// maps a parent key (`None` = the root) to its ordered child keys, a tracked read, so
2288    /// re-parenting or re-ordering writes re-run it; tokens are the store's keys.
2289    pub struct StoreTree<T: 'static> {
2290        store: Store<Keyed<T>>,
2291        children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
2292    }
2293
2294    /// `store.tree(children_of)`: the hierarchical source for [`super::tree`].
2295    pub trait StoreTrees<T: 'static> {
2296        fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T>;
2297    }
2298
2299    impl<T: Identified + Clone + 'static> StoreTrees<T> for Store<Keyed<T>> {
2300        fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T> {
2301            StoreTree {
2302                store: self,
2303                children: Rc::new(children),
2304            }
2305        }
2306    }
2307
2308    impl<T: Identified + Clone + 'static> super::NodeSource for StoreTree<T> {
2309        type Slot = ModelSlot<T>;
2310        type Key = u64;
2311        type Conn = StoreTreeConn<T>;
2312        fn connect(self) -> StoreTreeConn<T> {
2313            StoreTreeConn {
2314                store: self.store,
2315                children: self.children,
2316                shape: RefCell::new(super::TreeShape::default()),
2317            }
2318        }
2319    }
2320
2321    /// [`StoreTree`]'s connection: the derived shape; values flow through the store's own
2322    /// per-field notifications, so an unchanged shape skips the native reload entirely.
2323    pub struct StoreTreeConn<T: 'static> {
2324        store: Store<Keyed<T>>,
2325        children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
2326        shape: RefCell<super::TreeShape>,
2327    }
2328
2329    impl<T: Identified + Clone + 'static> super::TreeConn for StoreTreeConn<T> {
2330        type Slot = ModelSlot<T>;
2331        type Key = u64;
2332
2333        fn refresh(&self) -> Vec<(u64, Option<u64>)> {
2334            let mut shape = super::TreeShape::default();
2335            let mut seen = HashSet::new();
2336            // Depth-first from the root, children pushed in reverse so walk order is
2337            // display order. `seen` guards a malformed parent graph from looping.
2338            let mut stack: Vec<(Option<u64>, u64)> = (self.children)(None)
2339                .into_iter()
2340                .rev()
2341                .map(|k| (None, k))
2342                .collect();
2343            while let Some((parent, key)) = stack.pop() {
2344                if !seen.insert(key) {
2345                    debug_assert!(false, "day: cycle or duplicate key in store tree");
2346                    continue;
2347                }
2348                shape.tokens.push(key);
2349                shape.parents.insert(key, parent);
2350                shape.children.entry(parent).or_default().push(key);
2351                for child in (self.children)(Some(key)).into_iter().rev() {
2352                    stack.push((Some(key), child));
2353                }
2354            }
2355            let fp = shape.fingerprint();
2356            *self.shape.borrow_mut() = shape;
2357            fp
2358        }
2359        fn tokens_now(&self) -> Vec<u64> {
2360            self.shape.borrow().tokens.clone()
2361        }
2362        fn children_len(&self, parent: Option<u64>) -> usize {
2363            self.shape
2364                .borrow()
2365                .children
2366                .get(&parent)
2367                .map(|v| v.len())
2368                .unwrap_or(0)
2369        }
2370        fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
2371            self.shape
2372                .borrow()
2373                .children
2374                .get(&parent)
2375                .and_then(|v| v.get(index).copied())
2376                .unwrap_or(0)
2377        }
2378        fn parent_of(&self, token: u64) -> Option<Option<u64>> {
2379            self.shape.borrow().parents.get(&token).copied()
2380        }
2381        fn key_of(&self, token: u64) -> Option<u64> {
2382            self.shape
2383                .borrow()
2384                .parents
2385                .contains_key(&token)
2386                .then_some(token)
2387        }
2388        fn token_of(&self, key: &u64) -> u64 {
2389            *key
2390        }
2391        fn slot_for(&self, token: u64) -> Option<ModelSlot<T>> {
2392            self.shape
2393                .borrow()
2394                .parents
2395                .contains_key(&token)
2396                .then(|| ModelSlot::for_key(self.store, token))
2397        }
2398        fn rebind(&self, slot: &ModelSlot<T>, token: u64) {
2399            slot.rebind_key(token);
2400        }
2401        fn values_flow_by_reload(&self) -> bool {
2402            false
2403        }
2404    }
2405}
2406
2407#[cfg(feature = "model")]
2408pub use model_rows::{ModelSlot, Rows, StoreRows, StoreTree, StoreTreeConn, StoreTrees};
2409
2410// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
2411
2412// ---------------------------------------------------------------------------
2413// `tree`: native hierarchical tree (docs/tree.md)
2414// ---------------------------------------------------------------------------
2415
2416pub use day_spec::MoveVerdict;
2417
2418/// A hierarchical row source for [`tree`]: the [`RowSource`] idea grown a parent per row.
2419/// Two implementations: [`branches`] (plain data) and a day-model store's
2420/// `store.tree(children_of)` (feature `model`).
2421pub trait NodeSource {
2422    /// What a row builder receives.
2423    type Slot: Copy + 'static;
2424    /// The app's identity currency: what selection, moves and expansion speak.
2425    type Key: Clone + Hash + Eq + 'static;
2426    type Conn: TreeConn<Slot = Self::Slot, Key = Self::Key>;
2427    fn connect(self) -> Self::Conn;
2428}
2429
2430/// One tree's live connection to its data, held for the life of the [`tree`] that connected
2431/// it. All hierarchy queries are TOKEN-addressed (docs/tree.md): `None` = the root level.
2432pub trait TreeConn: 'static {
2433    type Slot: Copy + 'static;
2434    type Key: Clone + Hash + Eq + 'static;
2435
2436    /// Refresh the snapshot and return the tree's shape: `(token, parent)` pairs in walk
2437    /// order. A tracked read: the enclosing watch re-runs exactly when something this read
2438    /// depends on changes.
2439    fn refresh(&self) -> Vec<(u64, Option<u64>)>;
2440    /// Every token in the current snapshot, walk order, no refresh and no tracking.
2441    fn tokens_now(&self) -> Vec<u64>;
2442    fn children_len(&self, parent: Option<u64>) -> usize;
2443    fn child_token(&self, parent: Option<u64>, index: usize) -> u64;
2444    /// `Some(parent)` for a known token (`Some(None)` = a root row), `None` for an unknown one.
2445    fn parent_of(&self, token: u64) -> Option<Option<u64>>;
2446    fn key_of(&self, token: u64) -> Option<Self::Key>;
2447    /// The token a key maps to (pure: no snapshot lookup).
2448    fn token_of(&self, key: &Self::Key) -> u64;
2449    /// A fresh slot for `token` (`None` on a stale mid-animation pull). Call inside the
2450    /// row's scope: plain-data slots allocate their signals here.
2451    fn slot_for(&self, token: u64) -> Option<Self::Slot>;
2452    /// Point an existing slot at `token`: the recycle write.
2453    fn rebind(&self, slot: &Self::Slot, token: u64);
2454    /// Whether row VALUES reach existing rows only through reload→rebind (see
2455    /// [`RowConn::values_flow_by_reload`]).
2456    fn values_flow_by_reload(&self) -> bool;
2457}
2458
2459/// Plain-data tree rows: a flat items closure, a key per item, and a parent key per item
2460/// (`None` = a root row), as in `tree(branches(model::all, |n| n.id, |n| n.parent), row_view)`.
2461/// Children keep the items' own relative order; an item whose parent key is absent from the
2462/// set is treated as a root row rather than dropped.
2463pub fn branches<T, K>(
2464    f: impl Fn() -> Vec<T> + 'static,
2465    key_of: impl Fn(&T) -> K + 'static,
2466    parent_of: impl Fn(&T) -> Option<K> + 'static,
2467) -> Branches<T, K>
2468where
2469    T: Clone + 'static,
2470    K: Clone + Hash + Eq + 'static,
2471{
2472    Branches {
2473        f: Rc::new(f),
2474        key_of: Rc::new(key_of),
2475        parent_of: Rc::new(parent_of),
2476    }
2477}
2478
2479/// A parent-key extractor (aliased for the fields below; clippy's type-complexity bound).
2480type ParentOf<T, K> = Rc<dyn Fn(&T) -> Option<K>>;
2481
2482/// The plain-data [`NodeSource`] built by [`branches`].
2483pub struct Branches<T: 'static, K: 'static> {
2484    f: Rc<dyn Fn() -> Vec<T>>,
2485    key_of: Rc<dyn Fn(&T) -> K>,
2486    parent_of: ParentOf<T, K>,
2487}
2488
2489impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> NodeSource for Branches<T, K> {
2490    type Slot = ItemSlot<T, K>;
2491    type Key = K;
2492    type Conn = BranchesConn<T, K>;
2493    fn connect(self) -> BranchesConn<T, K> {
2494        BranchesConn {
2495            f: self.f,
2496            key_of: self.key_of,
2497            parent_of: self.parent_of,
2498            snapshot: RefCell::new(Vec::new()),
2499            shape: RefCell::new(TreeShape::default()),
2500        }
2501    }
2502}
2503
2504/// The derived children/parent indexes both connections maintain per refresh.
2505#[derive(Default)]
2506struct TreeShape {
2507    /// Walk-order tokens (parents before their children for a well-formed set).
2508    tokens: Vec<u64>,
2509    children: std::collections::HashMap<Option<u64>, Vec<u64>>,
2510    parents: std::collections::HashMap<u64, Option<u64>>,
2511    /// token → index into the flat snapshot (plain-data sources only).
2512    index_of: std::collections::HashMap<u64, usize>,
2513}
2514
2515impl TreeShape {
2516    fn fingerprint(&self) -> Vec<(u64, Option<u64>)> {
2517        self.tokens
2518            .iter()
2519            .map(|t| (*t, self.parents.get(t).copied().flatten()))
2520            .collect()
2521    }
2522}
2523
2524/// [`Branches`]' connection: the current data snapshot plus its derived shape.
2525pub struct BranchesConn<T: 'static, K: 'static> {
2526    f: Rc<dyn Fn() -> Vec<T>>,
2527    key_of: Rc<dyn Fn(&T) -> K>,
2528    parent_of: ParentOf<T, K>,
2529    snapshot: RefCell<Vec<T>>,
2530    shape: RefCell<TreeShape>,
2531}
2532
2533impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> TreeConn for BranchesConn<T, K> {
2534    type Slot = ItemSlot<T, K>;
2535    type Key = K;
2536
2537    fn refresh(&self) -> Vec<(u64, Option<u64>)> {
2538        let its = (self.f)();
2539        let mut shape = TreeShape::default();
2540        let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
2541        let present: HashSet<u64> = toks.iter().copied().collect();
2542        for (i, item) in its.iter().enumerate() {
2543            let tok = toks[i];
2544            // A parent key outside the set roots the row rather than dropping it.
2545            let parent = (self.parent_of)(item)
2546                .map(|k| key_token(&k))
2547                .filter(|p| present.contains(p));
2548            shape.tokens.push(tok);
2549            shape.parents.insert(tok, parent);
2550            shape.children.entry(parent).or_default().push(tok);
2551            shape.index_of.insert(tok, i);
2552        }
2553        *self.snapshot.borrow_mut() = its;
2554        let fp = shape.fingerprint();
2555        *self.shape.borrow_mut() = shape;
2556        fp
2557    }
2558    fn tokens_now(&self) -> Vec<u64> {
2559        self.shape.borrow().tokens.clone()
2560    }
2561    fn children_len(&self, parent: Option<u64>) -> usize {
2562        self.shape
2563            .borrow()
2564            .children
2565            .get(&parent)
2566            .map_or(0, std::vec::Vec::len)
2567    }
2568    fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
2569        self.shape
2570            .borrow()
2571            .children
2572            .get(&parent)
2573            .and_then(|v| v.get(index).copied())
2574            .unwrap_or(0)
2575    }
2576    fn parent_of(&self, token: u64) -> Option<Option<u64>> {
2577        self.shape.borrow().parents.get(&token).copied()
2578    }
2579    fn key_of(&self, token: u64) -> Option<K> {
2580        let idx = self.shape.borrow().index_of.get(&token).copied()?;
2581        self.snapshot.borrow().get(idx).map(|t| (self.key_of)(t))
2582    }
2583    fn token_of(&self, key: &K) -> u64 {
2584        key_token(key)
2585    }
2586    fn slot_for(&self, token: u64) -> Option<ItemSlot<T, K>> {
2587        let idx = self.shape.borrow().index_of.get(&token).copied()?;
2588        let item = self.snapshot.borrow().get(idx).cloned()?;
2589        let key = (self.key_of)(&item);
2590        Some(ItemSlot {
2591            sig: Signal::new(item),
2592            key: Signal::new(key),
2593        })
2594    }
2595    fn rebind(&self, slot: &ItemSlot<T, K>, token: u64) {
2596        let Some(idx) = self.shape.borrow().index_of.get(&token).copied() else {
2597            return; // stale recycle token: skip, the next bind corrects it
2598        };
2599        let Some(item) = self.snapshot.borrow().get(idx).cloned() else {
2600            return;
2601        };
2602        slot.key.set((self.key_of)(&item));
2603        slot.sig.set(item);
2604    }
2605    fn values_flow_by_reload(&self) -> bool {
2606        true
2607    }
2608}
2609
2610/// A native hierarchical tree (docs/tree.md): rows nest, disclose, and drag to a new parent.
2611/// The platform widget owns scrolling, disclosure and cell reuse; Day builds each visible row
2612/// once and *rebinds* it as cells recycle ([`list()`]'s contract, token-addressed). Gate its UI
2613/// on `Cap::Tree`: a backend without tree support renders nothing.
2614/// Drag-to-move for a [`tree`] (docs/tree.md): the handler that applies a committed
2615/// re-parent, an optional guard consulted while the drag is live, and whether the gesture is
2616/// offered right now. A tree is movable exactly when it carries one of these
2617/// (`tree(..).movable(Move::new(f))`). The [`list()`] counterpart is [`Reorder`].
2618#[must_use]
2619pub struct Move<K: 'static> {
2620    moved: TreeMoveFn<K>,
2621    guard: Option<TreeGuardFn<K>>,
2622    enabled: Reactive<bool>,
2623}
2624
2625impl<K: 'static> Move<K> {
2626    /// `moved(key, parent, index)` runs after a committed move: `key` now sits under `parent`
2627    /// (`None` = the root) at `index` (`None` = dropped onto the parent: append). Apply the
2628    /// same re-parent to the backing data; its refresh reloads the tree. Runs at the next event
2629    /// drain, never inside the native drop callback.
2630    pub fn new(moved: impl Fn(K, Option<K>, Option<usize>) + 'static) -> Move<K> {
2631        Move {
2632            moved: Rc::new(moved),
2633            guard: None,
2634            enabled: Reactive::Const(true),
2635        }
2636    }
2637    /// Veto drops while the drag is live. The structural refusals (a row into itself, into
2638    /// its own descendant, into a leaf) are built in; this guard adds the app's own. Keep it
2639    /// pure: it runs inside the platform's drag callback.
2640    pub fn guard(
2641        mut self,
2642        g: impl Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict + 'static,
2643    ) -> Move<K> {
2644        self.guard = Some(Rc::new(g));
2645        self
2646    }
2647    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
2648    /// `bool`, read when the platform asks whether a drag may begin.
2649    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Move<K> {
2650        self.enabled = on.into_reactive();
2651        self
2652    }
2653}
2654
2655#[must_use]
2656pub struct TreePiece<S: NodeSource> {
2657    source: Option<S>,
2658    build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
2659    row_height: RowHeight,
2660    indent: Option<f64>,
2661    section_headers: bool,
2662    on_expansion: Option<ExpansionFn<S::Key>>,
2663    expanded: Option<AnyBinding<HashSet<S::Key>>>,
2664    expandable: Option<KeyPredicate<S::Key>>,
2665    selected: Option<Rc<dyn Fn() -> Vec<S::Key>>>,
2666    on_selection: Option<SelectionKeysFn<S::Key>>,
2667    multi_select: bool,
2668    movable: bool,
2669    on_move: Option<TreeMoveFn<S::Key>>,
2670    move_guard: Option<TreeGuardFn<S::Key>>,
2671    type_ahead: Option<KeyTextFn<S::Key>>,
2672    reveal: Option<AnyBinding<Option<S::Key>>>,
2673    row_id: Option<KeyIdFn<S::Key>>,
2674    row_menu: Option<RowMenuEntriesFn<S::Key>>,
2675}
2676
2677/// The committed-move callback, aliased for the field above.
2678type ExpansionFn<K> = Rc<dyn Fn(K, bool)>;
2679type TreeMoveFn<K> = Rc<dyn Fn(K, Option<K>, Option<usize>)>;
2680/// The live move guard, aliased for the field above.
2681type TreeGuardFn<K> = Rc<dyn Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict>;
2682/// A per-key yes/no rule (`.expandable`), aliased for the field above.
2683type KeyPredicate<K> = Rc<dyn Fn(&K) -> bool>;
2684/// The full-selection callback (`.on_selection`), aliased for the field above.
2685type SelectionKeysFn<K> = Rc<dyn Fn(Vec<K>)>;
2686/// A per-key string (`.type_ahead`), aliased for the field above.
2687type KeyTextFn<K> = Rc<dyn Fn(&K) -> String>;
2688/// A registered identity per tree row, reevaluated on recycle.
2689type KeyIdFn<K> = Rc<dyn Fn(&K) -> day_core::ElementId>;
2690/// A row's summon-time context-menu builder (`.row_context_menu`), aliased for the field above.
2691type RowMenuEntriesFn<K> = Rc<dyn Fn(&K) -> Vec<MenuEntry>>;
2692
2693/// Build a hierarchical tree from a [`NodeSource`] and a row builder:
2694/// `tree(branches(items_fn, key_of, parent_of), row_view)` for plain data,
2695/// `tree(store.tree(children_of), row_view)` for a day-model store.
2696pub fn tree<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> TreePiece<S>
2697where
2698    S: NodeSource + 'static,
2699    P: Piece,
2700{
2701    TreePiece {
2702        source: Some(source),
2703        build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
2704        row_height: RowHeight::Automatic,
2705        indent: None,
2706        section_headers: false,
2707        on_expansion: None,
2708        expanded: None,
2709        expandable: None,
2710        selected: None,
2711        on_selection: None,
2712        multi_select: false,
2713        movable: false,
2714        on_move: None,
2715        move_guard: None,
2716        type_ahead: None,
2717        reveal: None,
2718        row_id: None,
2719        row_menu: None,
2720    }
2721}
2722
2723#[day_macros::builder(TreeBuilder<S>)]
2724impl<S: NodeSource + 'static> TreePiece<S> {
2725    /// Row sizing: `Uniform(h)` (fastest) or `Automatic` (self-sizing).
2726    pub fn row_height(mut self, h: RowHeight) -> Self {
2727        self.row_height = h;
2728        self
2729    }
2730    /// Indentation per depth level, in points (unset = the platform's default step).
2731    pub fn indent(mut self, pts: f64) -> Self {
2732        self.indent = Some(pts);
2733        self
2734    }
2735    /// Render a two-level source as sections. Root branches are headings and cannot be
2736    /// selected; root leaves remain ordinary rows. Children must be leaves. This enables
2737    /// native `ExpandableListView` on Android, where arbitrary-depth trees are composed.
2738    pub fn section_headers(mut self) -> Self {
2739        self.section_headers = true;
2740        self
2741    }
2742    /// Reports an actual user/scripting disclosure change with the stable application key.
2743    /// Programmatic writes to `expanded` do not echo this callback.
2744    pub fn on_expansion(mut self, f: impl Fn(S::Key, bool) + 'static) -> Self {
2745        self.on_expansion = Some(Rc::new(f));
2746        self
2747    }
2748    /// The app-owned expansion set (docs/tree.md): the user's disclosure clicks update it,
2749    /// and the app writing it discloses/collapses the native rows. Persist it (or don't);
2750    /// it is plain state.
2751    pub fn expanded(mut self, set: impl Binding<HashSet<S::Key>>) -> Self {
2752        self.expanded = Some(AnyBinding::new(set));
2753        self
2754    }
2755    /// Which rows can hold children at all: what draws (or omits) the disclosure, and which
2756    /// rows a drop may land on. Defaults to "has children right now", which draws no
2757    /// disclosure on an empty group; a source with real branch/leaf kinds should say so.
2758    pub fn expandable(mut self, f: impl Fn(&S::Key) -> bool + 'static) -> Self {
2759        self.expandable = Some(Rc::new(f));
2760        self
2761    }
2762    /// Reactively sync the native selection to these keys (empty clears). Point it and
2763    /// [`Self::on_selection`] at one signal and selection is two-way, shared with anything
2764    /// else reading the same state.
2765    pub fn selected(mut self, f: impl Fn() -> Vec<S::Key> + 'static) -> Self {
2766        self.selected = Some(Rc::new(f));
2767        self
2768    }
2769    /// Called with the full selected key set (empty = cleared) whenever the user changes the
2770    /// selection.
2771    pub fn on_selection(mut self, f: impl Fn(Vec<S::Key>) + 'static) -> Self {
2772        self.on_selection = Some(Rc::new(f));
2773        self
2774    }
2775    /// Allow selecting several rows at once, where the toolkit supports it.
2776    pub fn multi_select(mut self) -> Self {
2777        self.multi_select = true;
2778        self
2779    }
2780    /// Let the user drag rows to a new parent/position with the platform's native mechanism,
2781    /// where the backend supports it (probe `Cap::TreeMove`): the tree is movable exactly when
2782    /// it carries a [`Move`], whose handler re-parents the app's data.
2783    ///
2784    /// ```ignore
2785    /// tree(nodes, row_view).movable(Move::new(move |key, parent, index| store.reparent(key, parent, index)))
2786    /// ```
2787    pub fn movable(mut self, mv: Move<S::Key>) -> Self {
2788        self.movable = true;
2789        self.on_move = Some(mv.moved);
2790        // Availability first (`Move::enabled`), then the app's guard, then the structural
2791        // refusals the driver adds.
2792        let enabled = mv.enabled;
2793        let guard = mv.guard;
2794        self.move_guard = Some(Rc::new(move |k: &S::Key, p: Option<&S::Key>, i| {
2795            if !enabled.get_untracked() {
2796                return MoveVerdict::Deny;
2797            }
2798            match &guard {
2799                Some(g) => g(k, p, i),
2800                None => MoveVerdict::Allow,
2801            }
2802        }));
2803        self
2804    }
2805    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
2806    /// Unset rows don't participate.
2807    pub fn type_ahead(mut self, f: impl Fn(&S::Key) -> String + 'static) -> Self {
2808        self.type_ahead = Some(Rc::new(f));
2809        self
2810    }
2811    /// Programmatic reveal: set the signal to `Some(key)` and the row scrolls into view with
2812    /// every ancestor expanded (through [`Self::expanded`], so the app sees the change).
2813    pub fn reveal(mut self, target: impl Binding<Option<S::Key>>) -> Self {
2814        self.reveal = Some(AnyBinding::new(target));
2815        self
2816    }
2817    /// A dayscript element id per row, from its key (docs/tree.md): re-applied on every
2818    /// recycle, so `tap`/`assert_text` address the row wherever its cell currently sits. It
2819    /// is also what the `expand:`/`tree_move:` steps resolve rows by.
2820    pub fn row_id(mut self, f: impl Fn(&S::Key) -> day_core::ElementId + 'static) -> Self {
2821        self.row_id = Some(Rc::new(f));
2822        self
2823    }
2824    /// A per-row context menu, built when the menu is summoned (docs/menus.md "Dynamic context
2825    /// menus"): right-click on desktop, long-press on touch. The closure receives the
2826    /// row's key and returns the menu to show; it may adjust the app's selection first (the
2827    /// convention: a summon outside the current selection selects that row). An empty
2828    /// result shows nothing for that row.
2829    pub fn row_context_menu(mut self, f: impl Fn(&S::Key) -> Vec<MenuEntry> + 'static) -> Self {
2830        self.row_menu = Some(Rc::new(f));
2831        self
2832    }
2833
2834    /// The composed tree (docs/tree.md M2): on a backend without a native tree widget, the
2835    /// same piece flattens its visible rows onto [`list()`]; indentation and the disclosure
2836    /// chevron are day pieces inside each row, and selection rides the list's own machinery.
2837    /// The [`TreeDriver`] still installs on the returned node, so the dayscript
2838    /// `expand:`/`tree_move:` steps drive the composed tree exactly as they drive a native
2839    /// one (`attach_tree` is the no-op default off the native path; nothing pulls cells).
2840    fn build_composed(mut self, cx: &mut BuildCx) -> RNode {
2841        // The visible rows, in display order: a refresh (the tracked shape read) plus a DFS
2842        // that descends only into expanded rows. This is the list's row set.
2843        fn visible<C: TreeConn + ?Sized>(
2844            conn: &C,
2845            is_open: &dyn Fn(u64) -> bool,
2846            parent: Option<u64>,
2847            depth: u16,
2848            out: &mut Vec<(u64, u16)>,
2849        ) {
2850            for i in 0..conn.children_len(parent) {
2851                let t = conn.child_token(parent, i);
2852                out.push((t, depth));
2853                if is_open(t) {
2854                    visible(conn, is_open, Some(t), depth + 1, out);
2855                }
2856            }
2857        }
2858        /// Disclosure column width, and the default per-depth indent where the platform
2859        /// offers no native step to inherit.
2860        const CHEVRON_W: f64 = 18.0;
2861        const DEFAULT_INDENT: f64 = 14.0;
2862
2863        let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
2864        // Expansion state: the app's key set when it owns one, else this token set. Both are
2865        // signals, so the flattener below re-runs on every disclosure however it arrives:
2866        // a chevron tap, the app writing its set, or a synthetic `expand:` step.
2867        let open_sig: Signal<HashSet<u64>> = Signal::new(HashSet::new());
2868        let expanded_sig = self.expanded;
2869
2870        // Tracked when read inside a reactive closure.
2871        let is_open: Rc<dyn Fn(u64) -> bool> = {
2872            let conn = conn.clone();
2873            match expanded_sig {
2874                Some(sig) => Rc::new(move |t| match conn.key_of(t) {
2875                    Some(k) => sig.with(|s| s.contains(&k)),
2876                    None => false,
2877                }),
2878                None => Rc::new(move |t| open_sig.with(|s| s.contains(&t))),
2879            }
2880        };
2881        let set_open: Rc<dyn Fn(u64, bool)> = {
2882            let (conn, is_open, changed) =
2883                (conn.clone(), is_open.clone(), self.on_expansion.clone());
2884            Rc::new(move |t, on| {
2885                if day_reactive::untrack(|| is_open(t)) == on {
2886                    return;
2887                }
2888                let Some(key) = conn.key_of(t) else {
2889                    return;
2890                };
2891                if let Some(sig) = expanded_sig {
2892                    sig.update(|s| {
2893                        if on {
2894                            s.insert(key.clone());
2895                        } else {
2896                            s.remove(&key);
2897                        }
2898                    });
2899                } else {
2900                    open_sig.update(|s| {
2901                        if on {
2902                            s.insert(t);
2903                        } else {
2904                            s.remove(&t);
2905                        }
2906                    });
2907                }
2908                if let Some(f) = &changed {
2909                    f(key, on);
2910                }
2911            })
2912        };
2913
2914        // "Can hold children": the app's branch/leaf rule, or "has children right now".
2915        let expandable_of: Rc<dyn Fn(u64) -> bool> = {
2916            let (conn, f) = (conn.clone(), self.expandable.clone());
2917            Rc::new(move |tok| match &f {
2918                Some(f) => conn.key_of(tok).is_some_and(|k| f(&k)),
2919                None => conn.children_len(Some(tok)) > 0,
2920            })
2921        };
2922
2923        let flatten: Rc<dyn Fn() -> Vec<(u64, u16)>> = {
2924            let (conn, is_open) = (conn.clone(), is_open.clone());
2925            Rc::new(move || {
2926                let _shape = conn.refresh();
2927                let mut rows = Vec::new();
2928                visible(&*conn, &*is_open, None, 0, &mut rows);
2929                rows
2930            })
2931        };
2932
2933        // Each physical row: indent shell → chevron + the user's row content. The rebind
2934        // watch re-points the user's slot, the depth cell, and the dayscript id whenever
2935        // the list recycles this cell onto another row.
2936        let step = self.indent.unwrap_or(DEFAULT_INDENT);
2937        let build_row = {
2938            let (conn, user_row, row_id) =
2939                (conn.clone(), self.build_row.clone(), self.row_id.clone());
2940            let (is_open, expandable_of, set_open) =
2941                (is_open.clone(), expandable_of.clone(), set_open.clone());
2942            let row_menu = self.row_menu.clone();
2943            move |slot: ItemSlot<(u64, u16), u64>| -> AnyPiece {
2944                let (token0, depth0) = day_reactive::untrack(|| slot.get());
2945                let Some(user_slot) = conn.slot_for(token0) else {
2946                    // A stale mid-reload pull: an empty row instead of a panic.
2947                    return AnyPiece::new(crate::spacer());
2948                };
2949                let depth = Rc::new(std::cell::Cell::new(f64::from(depth0)));
2950                let chevron = {
2951                    let (is_open, expandable_of) = (is_open.clone(), expandable_of.clone());
2952                    let (set_open, is_open_tap) = (set_open.clone(), is_open.clone());
2953                    let expandable_tap = expandable_of.clone();
2954                    crate::label(move || {
2955                        let t = slot.get().0;
2956                        // The full-size triangles (U+25BC/25B6), not the small ▾/▸ forms:
2957                        // HarmonyOS Sans ships no glyph for the small ones; they rendered
2958                        // as nothing at all on harmony-arkui.
2959                        if expandable_of(t) {
2960                            if is_open(t) { "▼" } else { "▶" }
2961                        } else {
2962                            ""
2963                        }
2964                        .to_string()
2965                    })
2966                    .align(TextAlign::Center)
2967                    .width(CHEVRON_W)
2968                    .on_tap(move || {
2969                        let t = day_reactive::untrack(|| slot.get().0);
2970                        if expandable_tap(t) {
2971                            set_open(t, !day_reactive::untrack(|| is_open_tap(t)));
2972                        }
2973                    })
2974                };
2975                let content = crate::row((chevron, user_row(user_slot)));
2976                let shell = TreeRowShell {
2977                    depth: depth.clone(),
2978                    step,
2979                    content: AnyPiece::new(content),
2980                }
2981                .tweak({
2982                    let (conn, row_id) = (conn.clone(), row_id.clone());
2983                    move |n| {
2984                        let id_conn = conn.clone();
2985                        let set_ids = move |tok: u64| {
2986                            if let Some(rid) = &row_id
2987                                && let Some(k) = id_conn.key_of(tok)
2988                            {
2989                                with_tree(|t| t.set_id(n, rid(&k).as_str().to_owned()));
2990                            }
2991                        };
2992                        set_ids(token0);
2993                        watch(
2994                            move || slot.get(),
2995                            move |(tok, d), _| {
2996                                conn.rebind(&user_slot, *tok);
2997                                depth.set(f64::from(*d));
2998                                set_ids(*tok);
2999                            },
3000                        );
3001                    }
3002                });
3003                match &row_menu {
3004                    // The ordinary decorator: the dom backend arms its listener, and the
3005                    // composed presenter answers the summon. The key is read when the menu is
3006                    // summoned, so a recycled cell asks about the row it currently shows.
3007                    Some(f) => {
3008                        let (conn, f) = (conn.clone(), f.clone());
3009                        AnyPiece::new(shell.context_menu(move |_p: day_spec::Point| {
3010                            match conn.key_of(day_reactive::untrack(|| slot.get().0)) {
3011                                Some(k) => f(&k),
3012                                None => Vec::new(),
3013                            }
3014                        }))
3015                    }
3016                    None => AnyPiece::new(shell),
3017                }
3018            }
3019        };
3020
3021        let section_header: Rc<dyn Fn(u64) -> bool> = {
3022            let (conn, expandable, sections) =
3023                (conn.clone(), expandable_of.clone(), self.section_headers);
3024            Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
3025        };
3026        let scroll_sig: Signal<Option<usize>> = Signal::new(None);
3027        let mut lst = list(
3028            items(
3029                {
3030                    let flatten = flatten.clone();
3031                    move || flatten()
3032                },
3033                |r: &(u64, u16)| r.0,
3034            ),
3035            build_row,
3036        )
3037        .row_height(self.row_height)
3038        .apply_if(self.multi_select, ListBuilder::multi_select)
3039        .scroll_to_row(scroll_sig);
3040        // A composed list may report a heading click. Reapply the last destination
3041        // selection even when the app's signal did not change, so headers never stay lit.
3042        let selected_tokens = Signal::new(Vec::<u64>::new());
3043        let selection_revision = Signal::new(0u64);
3044        if self.on_selection.is_some() || (self.section_headers && self.selected.is_some()) {
3045            let conn = conn.clone();
3046            let header = section_header.clone();
3047            let callback = self.on_selection.clone();
3048            lst = lst.on_selection(move |toks: Vec<u64>| {
3049                if toks.iter().any(|t| header(*t)) {
3050                    selection_revision.update(|r| *r += 1);
3051                    return;
3052                }
3053                selected_tokens.set(toks.clone());
3054                if let Some(f) = &callback {
3055                    f(toks.iter().filter_map(|t| conn.key_of(*t)).collect());
3056                }
3057            });
3058        }
3059        let mut repair_selection: Option<Rc<dyn Fn() -> Vec<usize>>> = None;
3060        if self.selected.is_some() || (self.section_headers && self.on_selection.is_some()) {
3061            let (conn, flatten, selected) = (conn.clone(), flatten.clone(), self.selected.clone());
3062            let section_header = section_header.clone();
3063            let rows: Rc<dyn Fn() -> Vec<usize>> = Rc::new(move || {
3064                let rows = flatten();
3065                let want: HashSet<u64> = match &selected {
3066                    Some(sel) => sel().iter().map(|k| conn.token_of(k)).collect(),
3067                    None => selected_tokens.get().into_iter().collect(),
3068                };
3069                rows.iter()
3070                    .enumerate()
3071                    .filter(|(_, r)| want.contains(&r.0) && !section_header(r.0))
3072                    .map(|(i, _)| i)
3073                    .collect()
3074            });
3075            repair_selection = Some(rows.clone());
3076            lst = lst.selected_rows(move || rows());
3077        }
3078        let node = lst.build(cx);
3079        if let Some(rows) = repair_selection {
3080            day_reactive::bind(
3081                move || selection_revision.get(),
3082                move |revision| {
3083                    if *revision != 0 {
3084                        let rows = day_reactive::untrack(|| rows());
3085                        day_reactive::on_main(move || day_core::list_set_selected(node, rows));
3086                    }
3087                },
3088            );
3089        }
3090
3091        // Synthetic events (the dayscript `expand:` step, `tree_try_move`'s commit) land on
3092        // this node exactly as native ones land on a native tree.
3093        {
3094            let (on_move, conn_ev, set_open) =
3095                (self.on_move.clone(), conn.clone(), set_open.clone());
3096            cx.on(node, move |ev| match ev {
3097                Event::TreeExpanded { token, expanded } => set_open(*token, *expanded),
3098                Event::TreeMove {
3099                    token,
3100                    parent,
3101                    index,
3102                } => {
3103                    if let Some(f) = &on_move
3104                        && let Some(key) = conn_ev.key_of(*token)
3105                    {
3106                        f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
3107                    }
3108                }
3109                _ => {}
3110            });
3111        }
3112
3113        // The driver: what `expand:`/`tree_move:` resolve rows and route moves through.
3114        let driver = TreeDriver {
3115            section_header: {
3116                let f = section_header.clone();
3117                Box::new(move |t| f(t))
3118            },
3119            row_height: self.row_height,
3120            children_len: {
3121                let conn = conn.clone();
3122                Box::new(move |p| conn.children_len(p))
3123            },
3124            child_token: {
3125                let conn = conn.clone();
3126                Box::new(move |p, i| conn.child_token(p, i))
3127            },
3128            expandable: {
3129                let f = expandable_of.clone();
3130                Box::new(move |t| f(t))
3131            },
3132            expanded: {
3133                let is_open = is_open.clone();
3134                Box::new(move |t| day_reactive::untrack(|| is_open(t)))
3135            },
3136            // Never pulled: no toolkit attaches to the composed tree, so no cell binds
3137            // arrive. The list's own driver owns the physical rows.
3138            build: Box::new(|_tok, _anchor| TreeBuiltRow {
3139                scope: Scope::child(),
3140                rebind: Rc::new(|_| {}),
3141            }),
3142            type_select_text: Box::new(|_| String::new()),
3143            resolve_row: {
3144                let (conn, row_id) = (conn.clone(), self.row_id.clone());
3145                Box::new(move |id| {
3146                    let rid = row_id.as_ref()?;
3147                    conn.tokens_now()
3148                        .into_iter()
3149                        .find(|t| conn.key_of(*t).is_some_and(|k| rid(&k).as_str() == id))
3150                })
3151            },
3152            row_menu: None,
3153            moves: self.movable.then(|| {
3154                let can = {
3155                    let (conn, expandable_of, guard) =
3156                        (conn.clone(), expandable_of.clone(), self.move_guard.clone());
3157                    move |tok: u64, parent: Option<u64>, index: Option<usize>| {
3158                        let Some(key) = conn.key_of(tok) else {
3159                            return MoveVerdict::Deny;
3160                        };
3161                        let parent_key = match parent {
3162                            Some(p) => {
3163                                if p == tok || !expandable_of(p) {
3164                                    return MoveVerdict::Deny;
3165                                }
3166                                let mut cur = Some(p);
3167                                while let Some(c) = cur {
3168                                    if c == tok {
3169                                        return MoveVerdict::Deny;
3170                                    }
3171                                    cur = conn.parent_of(c).flatten();
3172                                }
3173                                match conn.key_of(p) {
3174                                    Some(k) => Some(k),
3175                                    None => return MoveVerdict::Deny,
3176                                }
3177                            }
3178                            None => None,
3179                        };
3180                        match &guard {
3181                            Some(g) => g(&key, parent_key.as_ref(), index),
3182                            None => MoveVerdict::Allow,
3183                        }
3184                    }
3185                };
3186                let can_commit = can.clone();
3187                TreeMovesDriver {
3188                    can_move: Box::new(can),
3189                    moved: Box::new(move |t, p, i| {
3190                        if can_commit(t, p, i) == MoveVerdict::Deny {
3191                            return;
3192                        }
3193                        enqueue_event(
3194                            rnode_to_id(node),
3195                            Event::TreeMove {
3196                                token: t,
3197                                parent: p,
3198                                index: i,
3199                            },
3200                        );
3201                    }),
3202                }
3203            }),
3204        };
3205        install_tree(node, driver);
3206
3207        // Reveal: expand every ancestor through the app-visible state, then scroll the
3208        // list to the row's flattened index.
3209        if let Some(sig) = self.reveal {
3210            let (conn, set_open, flatten) = (conn.clone(), set_open.clone(), flatten.clone());
3211            watch(
3212                move || sig.get(),
3213                move |key: &Option<S::Key>, _| {
3214                    let Some(key) = key else { return };
3215                    let tok = conn.token_of(key);
3216                    let mut cur = conn.parent_of(tok).flatten();
3217                    while let Some(p) = cur {
3218                        set_open(p, true);
3219                        cur = conn.parent_of(p).flatten();
3220                    }
3221                    let row = day_reactive::untrack(|| flatten())
3222                        .iter()
3223                        .position(|r| r.0 == tok);
3224                    if let Some(row) = row {
3225                        scroll_sig.set(Some(row));
3226                    }
3227                },
3228            );
3229        }
3230
3231        node
3232    }
3233}
3234
3235/// The composed tree row's indentation (docs/tree.md M2): offsets its single child by the
3236/// row's current depth × step. Depth lives in a `Cell` the rebind watch writes before the
3237/// cell's relayout, so a recycled row re-indents without rebuilding.
3238struct TreeIndent {
3239    depth: Rc<std::cell::Cell<f64>>,
3240    step: f64,
3241}
3242
3243impl Layout for TreeIndent {
3244    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
3245        let pad = self.depth.get() * self.step;
3246        let child_p = Proposal::new(p.width.map(|w| (w - pad).max(0.0)), p.height);
3247        let s = match children.first() {
3248            Some(&c) => cx.measure_child(c, child_p),
3249            None => Size::ZERO,
3250        };
3251        Size::new(s.width + pad, s.height)
3252    }
3253    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
3254        if let Some(&c) = children.first() {
3255            let pad = (self.depth.get() * self.step).min(bounds.size.width);
3256            let inner = Size::new(bounds.size.width - pad, bounds.size.height);
3257            let _ = cx.measure_child(c, Proposal::exact(inner));
3258            cx.place_child(c, Rect::new(pad, 0.0, inner.width, inner.height));
3259        }
3260    }
3261}
3262
3263/// One composed tree row: the [`TreeIndent`] wrapper around the chevron + user content,
3264/// grown to the cell's width so selection and taps span the row.
3265struct TreeRowShell {
3266    depth: Rc<std::cell::Cell<f64>>,
3267    step: f64,
3268    content: AnyPiece,
3269}
3270
3271impl Piece for TreeRowShell {
3272    fn build(self, cx: &mut BuildCx) -> RNode {
3273        // Native, not layout-only: the row's dayscript id and its `.context_menu_fn` listener
3274        // both need a realized element to land on (a11y identifier; the dom's `contextmenu`
3275        // arm). A transparent container, like the decorators' layer nodes.
3276        let w = cx.native(
3277            kinds::CONTAINER,
3278            &ContainerProps {
3279                background: None,
3280                corner_radius: 0.0,
3281                clips: false,
3282                role: None,
3283            },
3284            Rc::new(TreeIndent {
3285                depth: self.depth,
3286                step: self.step,
3287            }),
3288            Flex {
3289                grow_w: true,
3290                ..Default::default()
3291            },
3292            Boundary::No,
3293        );
3294        cx.under(w, |cx| {
3295            let _ = self.content.build(cx);
3296        });
3297        w
3298    }
3299}
3300
3301impl<S: NodeSource + 'static> Piece for TreePiece<S> {
3302    fn build(mut self, cx: &mut BuildCx) -> RNode {
3303        // No native tree widget → the composed tree: the same piece contract flattened onto
3304        // [`list()`] (docs/tree.md M2). `Emulated` and `Unsupported` both take this path; the
3305        // composition needs nothing beyond the list machinery every backend carries.
3306        // Two-level-only native controls (Android) provide single selection. A
3307        // multi-select section source uses the full-tree path, composed where necessary.
3308        let cap = if self.section_headers && !self.multi_select {
3309            day_spec::Cap::TreeSections
3310        } else {
3311            day_spec::Cap::Tree
3312        };
3313        if day_core::capability(cap) != day_spec::Support::Native {
3314            return self.build_composed(cx);
3315        }
3316        let props = TreeProps {
3317            section_headers: self.section_headers,
3318            row_height: self.row_height,
3319            selectable: self.selected.is_some() || self.on_selection.is_some(),
3320            multi_select: self.multi_select,
3321            movable: self.movable,
3322            indent: self.indent,
3323        };
3324        let node = cx.leaf(
3325            kinds::TREE,
3326            &props,
3327            Flex {
3328                grow_w: true,
3329                grow_h: true,
3330                ..Default::default()
3331            },
3332        );
3333
3334        let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
3335
3336        // The driver's (and flattener's) view of expansion: token-keyed, updated from native
3337        // disclosure events and from every programmatic patch this piece issues, so it is
3338        // right whether or not the app owns an expansion signal.
3339        let open_tokens: Rc<RefCell<HashSet<u64>>> = Rc::new(RefCell::new(HashSet::new()));
3340
3341        // "Can hold children": the app's branch/leaf rule, or "has children right now".
3342        let expandable_of: Rc<dyn Fn(u64) -> bool> = {
3343            let (conn, f) = (conn.clone(), self.expandable.clone());
3344            Rc::new(move |tok| match &f {
3345                Some(f) => conn.key_of(tok).is_some_and(|k| f(&k)),
3346                None => conn.children_len(Some(tok)) > 0,
3347            })
3348        };
3349
3350        let section_header: Rc<dyn Fn(u64) -> bool> = {
3351            let (conn, expandable, sections) =
3352                (conn.clone(), expandable_of.clone(), self.section_headers);
3353            Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
3354        };
3355        // Native events → app state.
3356        {
3357            let (on_selection, expanded_sig) = (self.on_selection.clone(), self.expanded);
3358            let (on_move, conn_ev, open) =
3359                (self.on_move.clone(), conn.clone(), open_tokens.clone());
3360            let changed = self.on_expansion.clone();
3361            let header = section_header.clone();
3362            cx.on(node, move |ev| match ev {
3363                Event::TreeSelection(tokens) => {
3364                    if let Some(f) = &on_selection {
3365                        f(tokens
3366                            .iter()
3367                            .filter(|t| !header(**t))
3368                            .filter_map(|t| conn_ev.key_of(*t))
3369                            .collect());
3370                    }
3371                }
3372                Event::TreeExpanded { token, expanded } => {
3373                    let Some(key) = conn_ev.key_of(*token) else {
3374                        return;
3375                    };
3376                    let was = expanded_sig.map_or_else(
3377                        || open.borrow().contains(token),
3378                        |sig| day_reactive::untrack(|| sig.with(|s| s.contains(&key))),
3379                    );
3380                    if was == *expanded {
3381                        return;
3382                    }
3383                    if let Some(sig) = &expanded_sig {
3384                        // The app's set follows the disclosure, and the expansion watch
3385                        // derives the patch. The record does not move here: for a native
3386                        // click the patch is a redundant no-op, and for a synthetic event
3387                        // (the dayscript `expand:` step) it is the very thing that discloses
3388                        // the row; pre-moving the record swallowed it.
3389                        if let Some(key) = conn_ev.key_of(*token) {
3390                            sig.update(|set| {
3391                                if *expanded {
3392                                    set.insert(key.clone());
3393                                } else {
3394                                    set.remove(&key);
3395                                }
3396                            });
3397                        }
3398                    } else {
3399                        // No app signal: this record IS the expansion state.
3400                        // The native tree is told too: a no-op after a native click, and for a
3401                        // synthetic event (the dayscript `expand:` step) the disclosure itself,
3402                        // which recording alone never showed.
3403                        if *expanded {
3404                            open.borrow_mut().insert(*token);
3405                        } else {
3406                            open.borrow_mut().remove(token);
3407                        }
3408                        day_core::tree_set_expanded(node, *token, *expanded);
3409                    }
3410                    if let Some(f) = &changed {
3411                        f(key, *expanded);
3412                    }
3413                }
3414                Event::TreeMove {
3415                    token,
3416                    parent,
3417                    index,
3418                } => {
3419                    if let Some(f) = &on_move
3420                        && let Some(key) = conn_ev.key_of(*token)
3421                    {
3422                        f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
3423                    }
3424                }
3425                _ => {}
3426            });
3427        }
3428
3429        // The type-erased driver day-core drives on cell pulls (docs/tree.md).
3430        let driver = TreeDriver {
3431            section_header: {
3432                let f = section_header.clone();
3433                Box::new(move |t| f(t))
3434            },
3435            row_height: self.row_height,
3436            children_len: {
3437                let conn = conn.clone();
3438                Box::new(move |p| conn.children_len(p))
3439            },
3440            child_token: {
3441                let conn = conn.clone();
3442                Box::new(move |p, i| conn.child_token(p, i))
3443            },
3444            expandable: {
3445                let f = expandable_of.clone();
3446                Box::new(move |t| f(t))
3447            },
3448            expanded: {
3449                let open = open_tokens.clone();
3450                Box::new(move |t| open.borrow().contains(&t))
3451            },
3452            build: {
3453                let (conn, build_row, row_id) =
3454                    (conn.clone(), self.build_row.clone(), self.row_id.clone());
3455                Box::new(move |token, anchor| {
3456                    let scope = Scope::child();
3457                    let (conn, build_row, row_id) =
3458                        (conn.clone(), build_row.clone(), row_id.clone());
3459                    let rebind = scope.enter(move || {
3460                        // Native callbacks can deliver a stale token mid-animation; an
3461                        // unknown pull yields an empty row instead of panicking.
3462                        let Some(slot) = conn.slot_for(token) else {
3463                            return Rc::new(|_: u64| {}) as Rc<dyn Fn(u64)>;
3464                        };
3465                        let mut rowcx = BuildCx::new(anchor);
3466                        let root = build_row(slot).build(&mut rowcx);
3467                        if let Some(rid) = &row_id
3468                            && let Some(k) = conn.key_of(token)
3469                        {
3470                            with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
3471                        }
3472                        // Rebind on recycle: point the slot (and the row's element id) at
3473                        // the cell's new row.
3474                        Rc::new(move |tok: u64| {
3475                            conn.rebind(&slot, tok);
3476                            if let Some(rid) = &row_id
3477                                && let Some(k) = conn.key_of(tok)
3478                            {
3479                                with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
3480                            }
3481                        }) as Rc<dyn Fn(u64)>
3482                    });
3483                    TreeBuiltRow { scope, rebind }
3484                })
3485            },
3486            type_select_text: {
3487                let (conn, f) = (conn.clone(), self.type_ahead.clone());
3488                Box::new(move |tok| match &f {
3489                    Some(f) => conn.key_of(tok).map_or_default(|k| f(&k)),
3490                    None => String::new(),
3491                })
3492            },
3493            resolve_row: {
3494                let (conn, row_id) = (conn.clone(), self.row_id.clone());
3495                Box::new(move |id| {
3496                    let rid = row_id.as_ref()?;
3497                    conn.tokens_now()
3498                        .into_iter()
3499                        .find(|t| conn.key_of(*t).is_some_and(|k| rid(&k).as_str() == id))
3500                })
3501            },
3502            row_menu: self.row_menu.clone().map(|f| {
3503                // Per-summon lowering in its own scope, disposed when the next summon (or
3504                // the tree's teardown) replaces it: the `context_menu_fn` rule.
3505                let conn = conn.clone();
3506                let last: Rc<RefCell<Option<Scope>>> = Rc::default();
3507                {
3508                    let last = last.clone();
3509                    Scope::current().on_cleanup(move || {
3510                        if let Some(s) = last.borrow_mut().take() {
3511                            s.dispose();
3512                        }
3513                    });
3514                }
3515                Box::new(move |tok: u64| {
3516                    let Some(key) = conn.key_of(tok) else {
3517                        return Vec::new();
3518                    };
3519                    if let Some(s) = last.borrow_mut().take() {
3520                        s.dispose();
3521                    }
3522                    let scope = Scope::child();
3523                    let items = scope.enter(|| crate::menus::lower_menu_scoped(f(&key)));
3524                    *last.borrow_mut() = Some(scope);
3525                    items
3526                }) as day_core::tree_driver::RowMenuFn
3527            }),
3528            moves: self.movable.then(|| {
3529                // The live verdict: structural refusals first (a row into itself, into its
3530                // own descendant, into a leaf, or addressing anything unknown), then the
3531                // app's guard.
3532                let can = {
3533                    let (conn, expandable_of, guard) =
3534                        (conn.clone(), expandable_of.clone(), self.move_guard.clone());
3535                    move |tok: u64, parent: Option<u64>, index: Option<usize>| {
3536                        let Some(key) = conn.key_of(tok) else {
3537                            return MoveVerdict::Deny;
3538                        };
3539                        let parent_key = match parent {
3540                            Some(p) => {
3541                                if p == tok || !expandable_of(p) {
3542                                    return MoveVerdict::Deny;
3543                                }
3544                                // Walk p's ancestors: dropping into one's own subtree.
3545                                let mut cur = Some(p);
3546                                while let Some(c) = cur {
3547                                    if c == tok {
3548                                        return MoveVerdict::Deny;
3549                                    }
3550                                    cur = conn.parent_of(c).flatten();
3551                                }
3552                                match conn.key_of(p) {
3553                                    Some(k) => Some(k),
3554                                    None => return MoveVerdict::Deny,
3555                                }
3556                            }
3557                            None => None,
3558                        };
3559                        match &guard {
3560                            Some(g) => g(&key, parent_key.as_ref(), index),
3561                            None => MoveVerdict::Allow,
3562                        }
3563                    }
3564                };
3565                let can_commit = can.clone();
3566                TreeMovesDriver {
3567                    can_move: Box::new(can),
3568                    // Commit: defer the app's callback through the event queue; its own data
3569                    // write drives the reload (docs/tree.md).
3570                    moved: Box::new(move |t, p, i| {
3571                        if can_commit(t, p, i) == MoveVerdict::Deny {
3572                            return;
3573                        }
3574                        enqueue_event(
3575                            rnode_to_id(node),
3576                            Event::TreeMove {
3577                                token: t,
3578                                parent: p,
3579                                index: i,
3580                            },
3581                        );
3582                    }),
3583                }
3584            }),
3585        };
3586        install_tree(node, driver);
3587
3588        // Prime the snapshot, tell the native host, and re-assert expansion + selection by
3589        // token after every shape change (docs/tree.md: a reload must not silently collapse
3590        // the tree or drop its selection).
3591        let apply_expansion = {
3592            let (conn, open) = (conn.clone(), open_tokens.clone());
3593            let expanded_sig = self.expanded;
3594            move || {
3595                let desired: HashSet<u64> = match &expanded_sig {
3596                    Some(sig) => {
3597                        let conn = &conn;
3598                        sig.get_untracked()
3599                            .iter()
3600                            .map(|k| conn.token_of(k))
3601                            .collect()
3602                    }
3603                    None => open.borrow().clone(),
3604                };
3605                let present: HashSet<u64> = conn.tokens_now().into_iter().collect();
3606                // Parents before children: a backend may not record a disclosure for a row
3607                // whose ancestor is still collapsed.
3608                let mut ordered: Vec<u64> = desired
3609                    .iter()
3610                    .filter(|t| present.contains(t))
3611                    .copied()
3612                    .collect();
3613                let depth_of = |mut t: u64| {
3614                    let mut d = 0usize;
3615                    while let Some(Some(p)) = conn.parent_of(t) {
3616                        d += 1;
3617                        t = p;
3618                    }
3619                    d
3620                };
3621                ordered.sort_by_key(|t| depth_of(*t));
3622                for t in ordered {
3623                    tree_set_expanded(node, t, true);
3624                }
3625                open.borrow_mut().clone_from(&desired);
3626            }
3627        };
3628        let apply_selection = {
3629            let (conn, selected) = (conn.clone(), self.selected.clone());
3630            move || {
3631                if let Some(sel) = &selected {
3632                    let keys = day_reactive::untrack(|| sel());
3633                    let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
3634                    tree_set_selected(node, toks);
3635                }
3636            }
3637        };
3638        {
3639            let conn2 = conn.clone();
3640            let initial = {
3641                let conn = conn.clone();
3642                day_reactive::untrack(move || conn.refresh())
3643            };
3644            // The native host attached against an empty snapshot: tell it the real node set
3645            // now, then disclose the initially-expanded rows (see the list's prime for why
3646            // skipping this renders blank while the synthetic rail keeps passing).
3647            tree_reload(node);
3648            apply_expansion();
3649            apply_selection();
3650            let last: RefCell<Vec<(u64, Option<u64>)>> = RefCell::new(initial);
3651            let (apply_expansion, apply_selection) =
3652                (apply_expansion.clone(), apply_selection.clone());
3653            let conn3 = conn.clone();
3654            watch(
3655                move || conn2.refresh(),
3656                move |shape: &Vec<(u64, Option<u64>)>, _| {
3657                    let unchanged = !conn3.values_flow_by_reload() && *last.borrow() == *shape;
3658                    (*last.borrow_mut()).clone_from(shape);
3659                    if unchanged {
3660                        return;
3661                    }
3662                    tree_reload(node);
3663                    apply_expansion();
3664                    apply_selection();
3665                },
3666            );
3667        }
3668
3669        // App expansion signal → native disclosure (delta patches; redundant ones no-op).
3670        if let Some(sig) = self.expanded {
3671            let (conn, open) = (conn.clone(), open_tokens.clone());
3672            watch(
3673                move || sig.get(),
3674                move |set: &HashSet<S::Key>, _| {
3675                    let desired: HashSet<u64> = set.iter().map(|k| conn.token_of(k)).collect();
3676                    let current = open.borrow().clone();
3677                    for t in desired.difference(&current) {
3678                        tree_set_expanded(node, *t, true);
3679                    }
3680                    for t in current.difference(&desired) {
3681                        tree_set_expanded(node, *t, false);
3682                    }
3683                    open.borrow_mut().clone_from(&desired);
3684                },
3685            );
3686        }
3687
3688        // Programmatic selection sync (`watch`, so the initial build doesn't clobber a
3689        // toolkit-default selection; the prime above already applied it once).
3690        if let Some(sel) = self.selected.clone() {
3691            let conn = conn.clone();
3692            watch(
3693                move || sel(),
3694                move |keys: &Vec<S::Key>, _| {
3695                    let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
3696                    tree_set_selected(node, toks);
3697                },
3698            );
3699        }
3700
3701        // Reveal: expand every ancestor (native + the app's signal), then scroll.
3702        if let Some(sig) = self.reveal {
3703            let (conn, open, expanded_sig) = (conn.clone(), open_tokens.clone(), self.expanded);
3704            watch(
3705                move || sig.get(),
3706                move |key: &Option<S::Key>, _| {
3707                    let Some(key) = key else { return };
3708                    let tok = conn.token_of(key);
3709                    let mut ancestors = Vec::new();
3710                    let mut cur = conn.parent_of(tok).flatten();
3711                    while let Some(p) = cur {
3712                        ancestors.push(p);
3713                        cur = conn.parent_of(p).flatten();
3714                    }
3715                    for p in ancestors.iter().rev() {
3716                        tree_set_expanded(node, *p, true);
3717                        open.borrow_mut().insert(*p);
3718                        if let Some(sig) = &expanded_sig
3719                            && let Some(k) = conn.key_of(*p)
3720                        {
3721                            sig.update(|set| {
3722                                set.insert(k.clone());
3723                            });
3724                        }
3725                    }
3726                    tree_reveal(node, tok);
3727                },
3728            );
3729        }
3730
3731        node
3732    }
3733}
3734
3735// ---------------------------------------------------------------------------
3736// The test host (docs/testing.md)
3737// ---------------------------------------------------------------------------
3738
3739/// The root of an app's test build: `content` normally, and while `day test` drives a GUI
3740/// case, that case's page alone, built fresh for the case and disposed when the next one
3741/// starts. One page mounted at a time is what keeps one case's ids, signals and resident
3742/// native views out of the next one's way.
3743///
3744/// ```ignore
3745/// pub fn root() -> impl Piece {
3746///     day::test_host(|| my_app_root())
3747/// }
3748/// ```
3749///
3750/// A panic while the case's page is built is caught here and reported as the case's failure;
3751/// the host shows the message in its place.
3752pub fn test_host<P: Piece>(content: impl Fn() -> P + 'static) -> impl Piece {
3753    let content = Rc::new(content);
3754    piece_fn(move |cx| {
3755        // Bumped whenever the engine changes the active case: a new key is a new `each` row,
3756        // so the old page's scope is disposed and the new one builds from scratch.
3757        let generation = Signal::new(0u64);
3758        day_core::conformance::set_host(Some(Rc::new(move || generation.update(|g| *g += 1))));
3759        Scope::current().on_cleanup(|| day_core::conformance::set_host(None));
3760        each(
3761            items(move || vec![generation.get()], |g: &u64| *g),
3762            move |_| match day_core::conformance::active() {
3763                Some(case) => guarded_page(case),
3764                None => AnyPiece::new(content()),
3765            },
3766        )
3767        .build(cx)
3768    })
3769}
3770
3771/// A case's page, built with a panic caught and recorded rather than taking the app down.
3772/// Also what a browsing view of the cases shows (the conformance app's navigation).
3773pub fn guarded_page(case: day_core::conformance::Case) -> AnyPiece {
3774    AnyPiece::new(piece_fn(move |cx| {
3775        let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3776            case.build_page().map(|page| page.build(&mut *cx))
3777        }));
3778        match built {
3779            Ok(Some(root)) => root,
3780            Ok(None) => crate::label("").build(cx),
3781            Err(payload) => {
3782                let message = day_core::conformance::panic_message(payload.as_ref());
3783                day_core::conformance::note_page_panic(message.clone());
3784                crate::label(format!("panicked: {message}")).build(cx)
3785            }
3786        }
3787    }))
3788}
3789
3790#[cfg(feature = "conformance")]
3791pub(crate) mod conformance {
3792    use day_core::conformance::{Case, Drive, Fail};
3793    use day_geometry::Insets;
3794    use day_reactive::Signal;
3795    use day_spec::props::RowHeight;
3796    use day_spec::{Cap, Font, kinds};
3797
3798    use crate::*;
3799
3800    /// A list of the given names, each row a label with the id `row:<name>`.
3801    fn names_list(names: Signal<Vec<String>>) -> List<Items<String, String>> {
3802        list(
3803            items(move || names.get(), |n: &String| n.clone()),
3804            |row: ItemSlot<String, String>| {
3805                // A reactive id, before the padding: a recycled cell rebinds to other rows, and
3806                // the id must name the label rather than its wrapper.
3807                label(move || row.get())
3808                    .id_of(move || day_core::id!(conformance_row, row.get()))
3809                    .padding(Insets::symmetric(12.0, 6.0))
3810            },
3811        )
3812        .row_height(RowHeight::Uniform(32.0))
3813    }
3814
3815    fn names(list: &[&str]) -> Signal<Vec<String>> {
3816        Signal::new(list.iter().map(std::string::ToString::to_string).collect())
3817    }
3818
3819    /// A list item realizes as the platform's own row content (docs/list.md "List items"),
3820    /// and its check mark follows its source in place.
3821    #[day_macros::test(day_core)]
3822    fn list_items_show_their_parts() -> Case {
3823        Case::new()
3824            .proves(kinds::LIST_ITEM)
3825            .proves_cap(Cap::ListItem)
3826            .requires(Cap::ListItem)
3827            .page(|| {
3828                let done = Signal::new(false);
3829                let rows = names(&["Milk", "Bread"]);
3830                column((
3831                    button("Done")
3832                        .action(move || done.update(|d| *d = !*d))
3833                        .id(day_core::id!(toggle_done)),
3834                    list(
3835                        items(move || rows.get(), |n: &String| n.clone()),
3836                        move |row: ItemSlot<String, String>| {
3837                            list_item(move || row.get())
3838                                .subtitle("aisle 4")
3839                                .checked(move || done.get())
3840                                .id_of(move || day_core::id!(conformance_item, row.get()))
3841                        },
3842                    )
3843                    .height(200.0),
3844                ))
3845            })
3846            .drive(|d: Drive| async move {
3847                d.assert_visible("conformance_item:Milk").await?;
3848                d.tap("toggle_done").await?;
3849                d.assert_visible("conformance_item:Bread").await
3850            })
3851    }
3852
3853    /// A list realizes a native cell for each row, showing the row's content.
3854    #[day_macros::test(day_core)]
3855    fn list_rows_realize() -> Case {
3856        Case::new()
3857            .proves_duty("attach_list")
3858            .proves_duty("adopt")
3859            .proves(kinds::LIST)
3860            .proves(kinds::LIST_CELL)
3861            .page(|| {
3862                names_list(names(&["Alpha", "Beta", "Gamma"]))
3863                    .id(day_core::id!(list))
3864                    .height(200.0)
3865            })
3866            .drive(|d: Drive| async move {
3867                d.assert_text("conformance_row:Alpha", "Alpha").await?;
3868                d.assert_text("conformance_row:Gamma", "Gamma").await
3869            })
3870    }
3871
3872    /// A row added to the source appears in the native list; one removed goes away.
3873    #[day_macros::test(day_core)]
3874    fn list_follows_source() -> Case {
3875        Case::new()
3876            .proves_duty("release")
3877            .proves(kinds::LIST)
3878            .page(|| {
3879                let rows = names(&["Alpha", "Beta"]);
3880                column((
3881                    button("Add")
3882                        .action(move || rows.update(|v| v.push("Delta".into())))
3883                        .id(day_core::id!(add)),
3884                    button("Drop")
3885                        .action(move || rows.update(|v| v.retain(|n| n != "Alpha")))
3886                        .id(day_core::id!(drop)),
3887                    names_list(rows).id(day_core::id!(list)).height(200.0),
3888                ))
3889            })
3890            .drive(|d: Drive| async move {
3891                d.assert_missing("conformance_row:Delta").await?;
3892                d.tap("add").await?;
3893                d.assert_text("conformance_row:Delta", "Delta").await?;
3894                d.tap("drop").await?;
3895                d.assert_missing("conformance_row:Alpha").await?;
3896                d.assert_text("conformance_row:Beta", "Beta").await
3897            })
3898    }
3899
3900    /// Synthetic fixture: appending and scrolling in one event must apply the native insert
3901    /// before scrolling. UIKit used to scroll against its old count and throw an exception.
3902    #[day_macros::test(day_core)]
3903    fn list_append_then_scroll() -> Case {
3904        Case::new()
3905            .proves(kinds::LIST)
3906            .page(|| {
3907                let rows = names(&[]);
3908                let scroll = Signal::new(None);
3909                column((
3910                    button("Append").id(day_core::id!(append)).action(move || {
3911                        rows.update(|rows| rows.push(format!("Item {}", rows.len())));
3912                        scroll.set(Some(rows.with(|rows| rows.len() - 1)));
3913                    }),
3914                    names_list(rows)
3915                        .scroll_to_row(scroll)
3916                        .id(day_core::id!(list))
3917                        .height(120.0),
3918                ))
3919            })
3920            .drive(|d: Drive| async move {
3921                // Start empty, then grow past the viewport to prove the scroll actually runs.
3922                for index in 0..8 {
3923                    d.tap("append").await?;
3924                    d.assert_visible(&format!("conformance_row:Item%20{index}"))
3925                        .await?;
3926                }
3927                Ok(())
3928            })
3929    }
3930
3931    /// The rows of the self-sizing fixture, in order: key, font, text.
3932    const SIZED: [(&str, Font, &str); 5] = [
3933        ("small", Font::Caption2, "Small print"),
3934        ("large", Font::LargeTitle, "Large"),
3935        ("body", Font::Body, "Body text"),
3936        (
3937            "wrap",
3938            Font::Footnote,
3939            "A footnote long enough to wrap onto three lines or more in a narrow list, \
3940             whatever the platform's type scale, so its row is several lines tall",
3941        ),
3942        ("end", Font::Body, "End"),
3943    ];
3944
3945    /// The text the `body` row grows to: several lines at any platform's type scale.
3946    const GROWN: &str = "Body text that grew long enough to wrap onto several lines, \
3947        the way a row does when its content changes after it was first sized";
3948
3949    /// A self-sizing list of [`SIZED`] rows, each a bare label with the id `sized:<key>`, so
3950    /// the label's frame is the row's whole height. `grown` swaps the `body` row's text.
3951    fn sized_list(grown: Signal<bool>) -> List<Items<&'static str, &'static str>> {
3952        list(
3953            items(|| SIZED.iter().map(|r| r.0).collect(), |k: &&str| *k),
3954            move |slot: ItemSlot<&'static str, &'static str>| {
3955                // A label's font is fixed at build, and cells recycle: one arm per font, only
3956                // the slot's own one built.
3957                let arm = |key: &'static str, font: Font, text: &'static str| {
3958                    when(
3959                        move || slot.get() == key,
3960                        move || {
3961                            label(move || {
3962                                if key == "body" && grown.get() {
3963                                    GROWN.to_string()
3964                                } else {
3965                                    text.to_string()
3966                                }
3967                            })
3968                            .font(font)
3969                            .id_of(move || day_core::id!(sized, slot.get()))
3970                        },
3971                    )
3972                };
3973                let [a, b, c, d, e] = SIZED;
3974                column((
3975                    arm(a.0, a.1, a.2),
3976                    arm(b.0, b.1, b.2),
3977                    arm(c.0, c.1, c.2),
3978                    arm(d.0, d.1, d.2),
3979                    arm(e.0, e.1, e.2),
3980                ))
3981                .spacing(0.0)
3982            },
3983        )
3984        .row_height(RowHeight::Automatic)
3985        .no_separators()
3986    }
3987
3988    /// One `sized:` row as laid out: its label's Day height, the height Day gave the row around
3989    /// it, and the row's native top, in window points.
3990    struct SizedRow {
3991        key: &'static str,
3992        content: f64,
3993        row: f64,
3994        top: f64,
3995    }
3996
3997    /// Every `sized:` row, in row order.
3998    ///
3999    /// The row's height is its cell anchor's Day frame, not the label's: Day lays a row inside
4000    /// the platform's margins and holds it at the platform's minimum height (docs/list.md "Row
4001    /// metrics"), so a caption row is taller than its text by more than a large-title row is.
4002    fn sized_rows() -> Result<Vec<SizedRow>, Fail> {
4003        day_core::try_with_tree(|t| {
4004            SIZED
4005                .iter()
4006                .map(|(key, ..)| {
4007                    let id = format!("sized:{key}");
4008                    let node = t
4009                        .find_by_id(&id)
4010                        .ok_or_else(|| Fail(format!("no element {id:?}")))?;
4011                    let content = t
4012                        .node_frame(node)
4013                        .ok_or_else(|| Fail(format!("{id:?} has no Day frame")))?;
4014                    let mut anchor = node;
4015                    while t.node_kind(anchor) != Some(kinds::LIST_CELL) {
4016                        anchor = t
4017                            .parent_of(anchor)
4018                            .ok_or_else(|| Fail(format!("{id:?} is not inside a list cell")))?;
4019                    }
4020                    let row = t
4021                        .node_frame(anchor)
4022                        .ok_or_else(|| Fail(format!("{id:?}'s row has no Day frame")))?;
4023                    let native = t
4024                        .read_native(node)
4025                        .and_then(|n| n.frame)
4026                        .ok_or_else(|| Fail(format!("{id:?} has no native frame")))?;
4027                    Ok(SizedRow {
4028                        key,
4029                        content: content.size.height,
4030                        row: row.size.height,
4031                        top: native.origin.y,
4032                    })
4033                })
4034                .collect()
4035        })
4036        .unwrap_or_else(|| Err(Fail("the tree is busy".into())))
4037    }
4038
4039    /// Every row is as tall as Day laid it: the next row's content starts one row height below
4040    /// this one's, give or take a chrome allowance (a GTK row's theme padding) that every row
4041    /// shares. A row the platform held at a fixed height either clips its content (the next row
4042    /// starts too soon) or leaves a gap that differs from row to row.
4043    ///
4044    /// Measured content top to content top, and Day centers content in a row taller than it,
4045    /// so each pitch also carries half the difference between the two rows' spare height.
4046    fn rows_fit() -> Result<Vec<(&'static str, f64)>, Fail> {
4047        let rows = sized_rows()?;
4048        let spare = |r: &SizedRow| (r.row - r.content) / 2.0;
4049        let expected = |a: &SizedRow, b: &SizedRow| a.row - spare(a) + spare(b);
4050        let chrome = (rows[1].top - rows[0].top) - expected(&rows[0], &rows[1]);
4051        for pair in rows.windows(2) {
4052            let (this, next) = (&pair[0], &pair[1]);
4053            let pitch = next.top - this.top;
4054            if pitch + 0.5 < this.content {
4055                return Err(Fail(format!(
4056                    "row {:?} is {:.1} tall but the next row starts {pitch:.1} below it: the \
4057                     native row clips its content",
4058                    this.key, this.content
4059                )));
4060            }
4061            let want = expected(this, next) + chrome;
4062            if (pitch - want).abs() > 1.5 {
4063                return Err(Fail(format!(
4064                    "row {:?} holds {:.1} of content in a {:.1} row, and the next row starts \
4065                     {pitch:.1} below it where {want:.1} was expected (the first row's chrome \
4066                     allowance is {chrome:.1}): the native row did not take its content's height",
4067                    this.key, this.content, this.row
4068                )));
4069            }
4070        }
4071        Ok(rows.into_iter().map(|r| (r.key, r.content)).collect())
4072    }
4073
4074    fn height_of(rows: &[(&str, f64)], key: &str) -> f64 {
4075        rows.iter().find(|r| r.0 == key).map_or(0.0, |r| r.1)
4076    }
4077
4078    /// An `Automatic` list sizes each row to its content: small and large text, a wrapped
4079    /// paragraph, and a row whose text grows and shrinks after it was first sized.
4080    #[day_macros::test(day_core)]
4081    fn list_rows_size_to_content() -> Case {
4082        Case::new()
4083            .proves(kinds::LIST)
4084            .proves(kinds::LIST_CELL)
4085            .page(|| {
4086                let grown = Signal::new(false);
4087                column((
4088                    button("Grow")
4089                        .action(move || grown.update(|g| *g = !*g))
4090                        .id(day_core::id!(grow)),
4091                    sized_list(grown)
4092                        .id(day_core::id!(list))
4093                        .width(240.0)
4094                        .height(480.0),
4095                ))
4096            })
4097            .drive(|d: Drive| async move {
4098                d.assert_visible("sized:end").await?;
4099                d.shot("sized-rows").await?;
4100                let rows = rows_fit()?;
4101                // The fixture means what it says: the type sizes differ, and the paragraph
4102                // wrapped at the list's width.
4103                let (small, large) = (height_of(&rows, "small"), height_of(&rows, "large"));
4104                d.check(
4105                    large > small * 1.5,
4106                    "a large-title row is taller than a caption row",
4107                )?;
4108                let body = height_of(&rows, "body");
4109                d.check(
4110                    height_of(&rows, "wrap") > body * 1.5,
4111                    "the footnote wrapped",
4112                )?;
4113                // A row re-laid at a new height after it was first sized.
4114                d.tap("grow").await?;
4115                d.wait_idle().await?;
4116                d.pause(0.3).await?;
4117                d.shot("sized-rows-grown").await?;
4118                let grew = rows_fit()?;
4119                d.check(height_of(&grew, "body") > body * 1.5, "the body row grew")?;
4120                d.tap("grow").await?;
4121                d.wait_idle().await?;
4122                d.pause(0.3).await?;
4123                let shrank = rows_fit()?;
4124                d.check(
4125                    (height_of(&shrank, "body") - body).abs() < 1.0,
4126                    "the body row shrank back",
4127                )
4128            })
4129    }
4130
4131    /// Selecting a row reports its key; activating one reports its key too.
4132    #[day_macros::test(day_core)]
4133    fn list_select_and_activate() -> Case {
4134        Case::new()
4135            .proves(kinds::LIST)
4136            .page(|| {
4137                let picked = Signal::new(String::new());
4138                let opened = Signal::new(String::new());
4139                column((
4140                    label(move || format!("picked {}", picked.get())).id(day_core::id!(picked)),
4141                    label(move || format!("opened {}", opened.get())).id(day_core::id!(opened)),
4142                    names_list(names(&["Alpha", "Beta", "Gamma"]))
4143                        .on_select(move |k| picked.set(k))
4144                        .on_activate(move |k| opened.set(k))
4145                        .id(day_core::id!(list))
4146                        .height(200.0),
4147                ))
4148            })
4149            .drive(|d: Drive| async move {
4150                d.select("list", 1).await?;
4151                d.assert_text("picked", "picked Beta").await?;
4152                d.activate("list", 2).await?;
4153                d.assert_text("opened", "opened Gamma").await
4154            })
4155    }
4156
4157    /// A committed reorder reaches the app, which moves the row in its source.
4158    #[day_macros::test(day_core)]
4159    fn list_reorder_moves_row() -> Case {
4160        Case::new()
4161            .proves(kinds::LIST)
4162            .page(|| {
4163                let rows = names(&["Alpha", "Beta", "Gamma"]);
4164                column((
4165                    label(move || rows.get().join(",")).id(day_core::id!(order)),
4166                    names_list(rows)
4167                        .reorderable(Reorder::new(move |from, to| {
4168                            rows.update(|v| {
4169                                let item = v.remove(from);
4170                                v.insert(to.min(v.len()), item);
4171                            });
4172                        }))
4173                        .id(day_core::id!(list))
4174                        .height(200.0),
4175                ))
4176            })
4177            .drive(|d: Drive| async move {
4178                d.reorder("list", 0, 2).await?;
4179                d.assert_text("order", "Beta,Gamma,Alpha").await?;
4180                d.assert_text("conformance_row:Alpha", "Alpha").await
4181            })
4182    }
4183
4184    /// A deleted row reaches the app, and the native list drops it.
4185    #[day_macros::test(day_core)]
4186    fn list_delete_row() -> Case {
4187        Case::new()
4188            .proves(kinds::LIST)
4189            .page(|| {
4190                let rows = names(&["Alpha", "Beta", "Gamma"]);
4191                column((
4192                    label(move || rows.get().join(",")).id(day_core::id!(order)),
4193                    names_list(rows)
4194                        .deletable(Delete::new(move |at| {
4195                            rows.update(|v| {
4196                                v.remove(at);
4197                            });
4198                        }))
4199                        .id(day_core::id!(list))
4200                        .height(200.0),
4201                ))
4202            })
4203            .drive(|d: Drive| async move {
4204                d.delete_row("list", 1).await?;
4205                d.assert_text("order", "Alpha,Gamma").await?;
4206                d.assert_missing("conformance_row:Beta").await
4207            })
4208    }
4209
4210    /// A row's trailing swipe action runs its work for that row.
4211    #[day_macros::test(day_core)]
4212    fn list_swipe_action() -> Case {
4213        Case::new()
4214            .proves(kinds::LIST)
4215            .page(|| {
4216                let rows = names(&["Alpha", "Beta", "Gamma"]);
4217                let flagged = Signal::new(String::new());
4218                column((
4219                    label(move || format!("flagged {}", flagged.get())).id(day_core::id!(flagged)),
4220                    names_list(rows)
4221                        .swipe_trailing(move |at| {
4222                            let name = rows.get_untracked()[at].clone();
4223                            vec![swipe_action("Flag").action(move || flagged.set(name.clone()))]
4224                        })
4225                        .id(day_core::id!(list))
4226                        .height(200.0),
4227                ))
4228            })
4229            .drive(|d: Drive| async move {
4230                d.swipe_row("list", 2, false, 0).await?;
4231                d.assert_text("flagged", "flagged Gamma").await
4232            })
4233    }
4234
4235    /// Scrolling a long list to a row realizes it, even where rows are recycled.
4236    #[day_macros::test(day_core)]
4237    fn list_scroll_to_row() -> Case {
4238        Case::new()
4239            .proves(kinds::LIST)
4240            .page(|| {
4241                let rows: Signal<Vec<String>> =
4242                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4243                let jump: Signal<Option<usize>> = Signal::new(None);
4244                column((
4245                    button("Jump")
4246                        .action(move || jump.set(Some(250)))
4247                        .id(day_core::id!(jump)),
4248                    names_list(rows)
4249                        .scroll_to_row(jump)
4250                        .id(day_core::id!(list))
4251                        .height(200.0),
4252                ))
4253            })
4254            .drive(|d: Drive| async move {
4255                d.assert_missing("conformance_row:Row%20250").await?;
4256                d.tap("jump").await?;
4257                d.assert_text("conformance_row:Row%20250", "Row 250").await
4258            })
4259    }
4260
4261    /// Counts the rows a list has alive: one per row built, one less per row disposed. A
4262    /// guard rides in each row's label closure, which the row's scope owns, so a cell the
4263    /// host merely pooled still counts (its row is intact and rebinds) and a cell the host
4264    /// discarded stops counting once `ListSource::release` disposed its row.
4265    struct RowAlive(std::rc::Rc<std::cell::Cell<usize>>);
4266
4267    impl RowAlive {
4268        fn new(live: &std::rc::Rc<std::cell::Cell<usize>>) -> Self {
4269            live.set(live.get() + 1);
4270            RowAlive(live.clone())
4271        }
4272    }
4273
4274    impl Drop for RowAlive {
4275        fn drop(&mut self) {
4276            self.0.set(self.0.get().saturating_sub(1));
4277        }
4278    }
4279
4280    /// The most rows a five-row viewport may have alive once the host has settled: its own
4281    /// pool and nothing visited earlier. The pools measured: AppKit 5, Qt 21 (the viewport plus
4282    /// two overscans), the mock 20, Android and UIKit a few dozen, and `GtkListView` 205: it
4283    /// keeps up to 200 spare items by design (`GTK_LIST_VIEW_MAX_LIST_ITEMS`) and rebinds them.
4284    /// A leak grows with every row visited instead, and the cases visit many more rows than
4285    /// this, so the bound stays tight against it.
4286    const ROWS_ALIVE_BOUND: usize = 256;
4287
4288    /// Distant jumps keep a bounded number of rows alive and rebind their actions.
4289    #[day_macros::test(day_core)]
4290    fn list_recycles_distant_rows() -> Case {
4291        let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
4292        let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
4293        let (count, alive) = (built.clone(), live.clone());
4294        Case::new()
4295            .proves(kinds::LIST)
4296            .proves_cap(Cap::ListRecycling)
4297            // 180 jumps, each settled by a bounded wait: 5 s on GTK, 19 s on Qt, 57 s on
4298            // the iOS simulator.
4299            .timeout(180.0)
4300            .requires_support("native list recycling", || {
4301                if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
4302                    day_spec::Support::Native
4303                } else {
4304                    day_spec::Support::Unsupported
4305                }
4306            })
4307            .page(move || {
4308                count.set(0);
4309                alive.set(0);
4310                let (count, alive) = (count.clone(), alive.clone());
4311                let rows = Signal::new((0..4000).collect::<Vec<usize>>());
4312                let jump = Signal::new(None);
4313                let next = Signal::new(40usize);
4314                let pressed = Signal::new(String::new());
4315                column((
4316                    button("Far").id(day_core::id!(far)).action(move || {
4317                        jump.set(Some(next.get_untracked()));
4318                        next.update(|n| *n += 40);
4319                    }),
4320                    button("Back")
4321                        .id(day_core::id!(back))
4322                        .action(move || jump.set(Some(0))),
4323                    label(move || pressed.get()).id(day_core::id!(pressed)),
4324                    list(items(move || rows.get(), |n: &usize| *n), move |slot| {
4325                        count.set(count.get() + 1);
4326                        let guard = RowAlive::new(&alive);
4327                        button(move || {
4328                            let _ = &guard;
4329                            format!("Row {}", slot.get())
4330                        })
4331                        .id_of(move || day_core::id!(conformance_row, slot.key()))
4332                        .action(move || pressed.set(format!("Pressed {}", slot.get())))
4333                    })
4334                    .row_height(RowHeight::Uniform(32.0))
4335                    .scroll_to_row(jump)
4336                    .height(160.0),
4337                ))
4338            })
4339            .drive(move |d: Drive| {
4340                let (built, live) = (built.clone(), live.clone());
4341                async move {
4342                    d.assert_text("conformance_row:0", "Row 0").await?;
4343                    // Distinct regions: retaining a cell for every visited index must fail.
4344                    // Row 1, not row 0, is the one that must go: GtkListView keeps its
4345                    // focused item's widget realized wherever the view scrolls, and row 0
4346                    // holds the focus here (the first item at start, then every `back` tap).
4347                    // Ninety regions out and back: some nine hundred rows visited, so a host
4348                    // that keeps a row per visited cell overshoots `ROWS_ALIVE_BOUND` several
4349                    // times over, where every pool measured stays under it.
4350                    for row in (40..=3600).step_by(40) {
4351                        d.tap("far").await?;
4352                        d.assert_text(&format!("conformance_row:{row}"), &format!("Row {row}"))
4353                            .await?;
4354                        d.assert_missing("conformance_row:1").await?;
4355                        d.tap(&format!("conformance_row:{row}")).await?;
4356                        d.assert_text("pressed", &format!("Pressed {row}")).await?;
4357                        d.tap("back").await?;
4358                        d.assert_text("conformance_row:0", "Row 0").await?;
4359                        d.tap("conformance_row:0").await?;
4360                        d.assert_text("pressed", "Pressed 0").await?;
4361                    }
4362                    // Settled: a host that releases discarded cells on a later turn (a
4363                    // posted dealloc, a teardown held for a borrow) has had it.
4364                    d.wait_idle().await?;
4365                    d.pause(0.3).await?;
4366                    d.check(
4367                        live.get() <= ROWS_ALIVE_BOUND,
4368                        &format!(
4369                            "{} rows alive after 180 jumps of a five-row viewport ({} built): \
4370                             discarded cells keep their rows",
4371                            live.get(),
4372                            built.get()
4373                        ),
4374                    )
4375                }
4376            })
4377    }
4378
4379    /// Shrinking, regrowing, reordering and jumping discard cells by every path a host has;
4380    /// the rows built in them go with them, and no row answers for a cell it no longer has.
4381    #[day_macros::test(day_core)]
4382    fn list_releases_discarded_rows() -> Case {
4383        const TOTAL: usize = 3000;
4384        const STRIDE: usize = 1237;
4385        let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
4386        let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
4387        let (count, alive) = (built.clone(), live.clone());
4388        Case::new()
4389            .proves(kinds::LIST)
4390            .proves_cap(Cap::ListRecycling)
4391            .timeout(90.0)
4392            .requires_support("native list recycling", || {
4393                if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
4394                    day_spec::Support::Native
4395                } else {
4396                    day_spec::Support::Unsupported
4397                }
4398            })
4399            .page(move || {
4400                count.set(0);
4401                alive.set(0);
4402                let (count, alive) = (count.clone(), alive.clone());
4403                let rows = Signal::new((0..TOTAL).collect::<Vec<usize>>());
4404                let jump = Signal::new(None);
4405                let at = Signal::new(0usize);
4406                let pressed = Signal::new(String::new());
4407                column((
4408                    // A stride coprime with the count walks the whole list in a scattered
4409                    // order, so consecutive jumps never share a cell.
4410                    button("Far").id(day_core::id!(far)).action(move || {
4411                        let next = (at.get_untracked() + STRIDE) % TOTAL;
4412                        at.set(next);
4413                        jump.set(Some(next));
4414                    }),
4415                    // Five rows fill the viewport exactly, so after the shrink every row is on
4416                    // screen wherever the host clamps its scroll offset.
4417                    button("Shrink")
4418                        .id(day_core::id!(shrink))
4419                        .action(move || rows.set((0..5).collect())),
4420                    button("Regrow")
4421                        .id(day_core::id!(regrow))
4422                        .action(move || rows.set((0..TOTAL).collect())),
4423                    // The same rows in a new order: a reload that keeps every token.
4424                    button("Rotate")
4425                        .id(day_core::id!(rotate))
4426                        .action(move || rows.update(|r| r.rotate_left(7))),
4427                    label(move || pressed.get()).id(day_core::id!(pressed)),
4428                    list(items(move || rows.get(), |n: &usize| *n), move |slot| {
4429                        count.set(count.get() + 1);
4430                        let guard = RowAlive::new(&alive);
4431                        button(move || {
4432                            let _ = &guard;
4433                            format!("Row {}", slot.get())
4434                        })
4435                        .id_of(move || day_core::id!(conformance_row, slot.key()))
4436                        .action(move || pressed.set(format!("Pressed {}", slot.get())))
4437                    })
4438                    .row_height(RowHeight::Uniform(32.0))
4439                    .scroll_to_row(jump)
4440                    .height(160.0),
4441                ))
4442            })
4443            .drive(move |d: Drive| {
4444                let (built, live) = (built.clone(), live.clone());
4445                async move {
4446                    d.assert_text("conformance_row:0", "Row 0").await?;
4447                    let (mut at, mut rotation) = (0usize, 0usize);
4448                    // The key of the row at index `i` after `rotation` left-rotations.
4449                    let key_at = |i: usize, rotation: usize| (i + rotation) % TOTAL;
4450                    for _ in 0..10 {
4451                        // A jump lands, and the row it lands on works.
4452                        at = (at + STRIDE) % TOTAL;
4453                        d.tap("far").await?;
4454                        let key = key_at(at, rotation);
4455                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4456                            .await?;
4457                        d.tap(&format!("conformance_row:{key}")).await?;
4458                        d.assert_text("pressed", &format!("Pressed {key}")).await?;
4459                        // Two jumps back to back: the second one wins.
4460                        d.tap("far").await?;
4461                        d.tap("far").await?;
4462                        at = (at + 2 * STRIDE) % TOTAL;
4463                        let key = key_at(at, rotation);
4464                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4465                            .await?;
4466                        // Shrinking under the viewport discards the rows past the new end;
4467                        // none of them may still answer.
4468                        d.tap("shrink").await?;
4469                        d.assert_text("conformance_row:3", "Row 3").await?;
4470                        if key >= 5 {
4471                            d.assert_missing(&format!("conformance_row:{key}")).await?;
4472                        }
4473                        d.tap("regrow").await?;
4474                        // The same set in a new order (regrowing restored the original one),
4475                        // then a jump into it.
4476                        d.tap("rotate").await?;
4477                        rotation = 7;
4478                        at = (at + STRIDE) % TOTAL;
4479                        d.tap("far").await?;
4480                        let key = key_at(at, rotation);
4481                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
4482                            .await?;
4483                    }
4484                    d.wait_idle().await?;
4485                    d.pause(0.3).await?;
4486                    d.check(
4487                        live.get() <= ROWS_ALIVE_BOUND,
4488                        &format!(
4489                            "{} rows alive after the churn ({} built): discarded cells keep \
4490                             their rows",
4491                            live.get(),
4492                            built.get()
4493                        ),
4494                    )
4495                }
4496            })
4497    }
4498
4499    /// Emptying a scrolled list releases old ids; repopulating it can scroll again.
4500    #[day_macros::test(day_core)]
4501    fn list_shrink_and_regrow() -> Case {
4502        Case::new()
4503            .proves(kinds::LIST)
4504            .page(|| {
4505                let rows = Signal::new((0..300).map(|n| format!("Row {n}")).collect());
4506                let jump = Signal::new(None);
4507                column((
4508                    button("Jump")
4509                        .id(day_core::id!(jump))
4510                        .action(move || jump.set(Some(250))),
4511                    button("Clear")
4512                        .id(day_core::id!(clear))
4513                        .action(move || rows.set(Vec::new())),
4514                    button("Restore")
4515                        .id(day_core::id!(restore))
4516                        .action(move || {
4517                            rows.set(vec!["New first".into(), "New last".into()]);
4518                            jump.set(Some(1));
4519                        }),
4520                    names_list(rows).scroll_to_row(jump).height(160.0),
4521                ))
4522            })
4523            .drive(|d: Drive| async move {
4524                d.tap("jump").await?;
4525                d.assert_text("conformance_row:Row%20250", "Row 250")
4526                    .await?;
4527                d.tap("clear").await?;
4528                d.assert_missing("conformance_row:Row%20250").await?;
4529                d.tap("restore").await?;
4530                d.assert_text("conformance_row:New%20first", "New first")
4531                    .await?;
4532                d.assert_text("conformance_row:New%20last", "New last")
4533                    .await
4534            })
4535    }
4536
4537    type Node = (String, Option<String>);
4538
4539    /// A tree over `(name, parent)` rows, each row a label with the id `row:<name>`; the tree's
4540    /// own row ids are the names, which `expand` and `tree_move` address.
4541    fn names_tree(rows: Signal<Vec<Node>>) -> TreePiece<Branches<Node, String>> {
4542        tree(
4543            branches(
4544                move || rows.get(),
4545                |n: &Node| n.0.clone(),
4546                |n: &Node| n.1.clone(),
4547            ),
4548            |row: ItemSlot<Node, String>| {
4549                label(move || row.get().0)
4550                    .id_of(move || day_core::id!(conformance_row, row.get().0))
4551                    .padding(Insets::symmetric(8.0, 4.0))
4552            },
4553        )
4554        .row_height(RowHeight::Uniform(28.0))
4555        .row_id(|k: &String| day_core::id!(tree_row, k))
4556    }
4557
4558    fn fruit() -> Signal<Vec<Node>> {
4559        let n = |name: &str, parent: Option<&str>| (name.to_string(), parent.map(str::to_owned));
4560        Signal::new(vec![
4561            n("Fruit", None),
4562            n("Apple", Some("Fruit")),
4563            n("Pear", Some("Fruit")),
4564            n("Nuts", None),
4565        ])
4566    }
4567
4568    /// A tree shows its root rows, and disclosing a row shows its children.
4569    #[day_macros::test(day_core)]
4570    fn tree_rows_disclose() -> Case {
4571        Case::new()
4572            .proves_duty("attach_tree")
4573            .proves_cap(Cap::Tree)
4574            .proves(kinds::TREE)
4575            .requires(Cap::Tree)
4576            .page(|| names_tree(fruit()).id(day_core::id!(tree)).height(240.0))
4577            .drive(|d: Drive| async move {
4578                d.assert_text("conformance_row:Fruit", "Fruit").await?;
4579                d.assert_text("conformance_row:Nuts", "Nuts").await?;
4580                d.assert_missing("conformance_row:Apple").await?;
4581                d.expand("tree", "tree_row:Fruit", true).await?;
4582                d.assert_text("conformance_row:Apple", "Apple").await?;
4583                d.expand("tree", "tree_row:Fruit", false).await?;
4584                d.assert_missing("conformance_row:Apple").await
4585            })
4586    }
4587
4588    /// The expanded set is app state: rows it names start disclosed.
4589    #[day_macros::test(day_core)]
4590    fn tree_expanded_signal() -> Case {
4591        Case::new()
4592            .proves(kinds::TREE)
4593            .requires(Cap::Tree)
4594            .page(|| {
4595                let open = Signal::new(std::collections::HashSet::from(["Fruit".to_string()]));
4596                names_tree(fruit())
4597                    .expanded(open)
4598                    .id(day_core::id!(tree))
4599                    .height(240.0)
4600            })
4601            .drive(|d: Drive| async move { d.assert_text("conformance_row:Pear", "Pear").await })
4602    }
4603
4604    /// Synthetic fixture strings. Restoration has no callback echo; filtering preserves
4605    /// key-based state. This case runs on native and composed section implementations.
4606    #[day_macros::test(day_core)]
4607    fn tree_section_expansion_contract() -> Case {
4608        Case::new()
4609            .proves_duty("attach_tree")
4610            .proves_cap(Cap::TreeSections)
4611            .proves(kinds::TREE)
4612            .requires(Cap::TreeSections)
4613            .page(|| {
4614                let rows = fruit();
4615                let open = Signal::new(std::collections::HashSet::from(["Fruit".to_owned()]));
4616                let changes = Signal::new(0usize);
4617                column((
4618                    label(move || {
4619                        format!("{}:{}", open.with(|s| s.contains("Fruit")), changes.get())
4620                    })
4621                    .id(day_core::id!(state)),
4622                    button("restore")
4623                        .id(day_core::id!(restore))
4624                        .action(move || {
4625                            open.set(std::collections::HashSet::from(["Fruit".to_owned()]));
4626                        }),
4627                    button("filter")
4628                        .id(day_core::id!(filter))
4629                        .action(move || rows.update(|r| r.retain(|n| n.0 != "Apple"))),
4630                    names_tree(rows)
4631                        .section_headers()
4632                        .expanded(open)
4633                        .on_expansion(move |_, _| changes.update(|n| *n += 1))
4634                        .id(day_core::id!(tree))
4635                        .height(240.0),
4636                ))
4637            })
4638            .drive(|d: Drive| async move {
4639                d.assert_text("state", "true:0").await?;
4640                d.assert_text("conformance_row:Apple", "Apple").await?;
4641                d.expand("tree", "tree_row:Fruit", false).await?;
4642                d.assert_text("state", "false:1").await?;
4643                d.assert_missing("conformance_row:Apple").await?;
4644                d.expand("tree", "tree_row:Fruit", false).await?;
4645                d.assert_text("state", "false:1").await?;
4646                d.tap("filter").await?;
4647                d.assert_missing("conformance_row:Pear").await?;
4648                d.tap("restore").await?;
4649                d.assert_text("conformance_row:Pear", "Pear").await?;
4650                d.assert_text("state", "true:1").await
4651            })
4652    }
4653
4654    /// A committed move reaches the app, which re-parents the row in its source.
4655    #[day_macros::test(day_core)]
4656    fn tree_move_reparents() -> Case {
4657        Case::new()
4658            .proves_cap(Cap::TreeMove)
4659            .proves(kinds::TREE)
4660            .requires(Cap::Tree)
4661            .page(|| {
4662                let rows = fruit();
4663                let open = Signal::new(std::collections::HashSet::from([
4664                    "Fruit".to_string(),
4665                    "Nuts".to_string(),
4666                ]));
4667                column((
4668                    label(move || {
4669                        rows.get()
4670                            .iter()
4671                            .map(|(n, p)| format!("{n}<{}", p.clone().unwrap_or_default()))
4672                            .collect::<Vec<_>>()
4673                            .join(",")
4674                    })
4675                    .id(day_core::id!(shape)),
4676                    // "Nuts" has no children, so it takes a dropped row only as a declared folder.
4677                    names_tree(rows)
4678                        .expanded(open)
4679                        .expandable(|k: &String| k == "Fruit" || k == "Nuts")
4680                        .movable(Move::new(move |key, parent, _at| {
4681                            rows.update(|v| {
4682                                if let Some(n) = v.iter_mut().find(|n| n.0 == key) {
4683                                    n.1 = parent;
4684                                }
4685                            });
4686                        }))
4687                        .id(day_core::id!(tree))
4688                        .height(240.0),
4689                ))
4690            })
4691            .drive(|d: Drive| async move {
4692                d.tree_move("tree", "tree_row:Pear", Some("tree_row:Nuts"), None)
4693                    .await?;
4694                d.assert_text("shape", "Fruit<,Apple<Fruit,Pear<Nuts,Nuts<")
4695                    .await?;
4696                d.assert_text("conformance_row:Pear", "Pear").await
4697            })
4698    }
4699}