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