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