Skip to main content

day_model/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Per-property observation: a store whose writes wake only the readers of the field that
5//! changed.
6//!
7//! With one `Signal<Vec<Item>>`, every observer of the store re-runs when any field of any
8//! element changes. Day's `bind` equality gate keeps the *native* side precise, so what is wasted
9//! is compute: every row's closures re-run and re-clone on every keystroke, and the waste grows
10//! with the list. Here each (element, field) is its own dependency node, so a write wakes exactly
11//! the readers of that field, plus readers who asked for something coarser by reading something
12//! coarser.
13//!
14//! The pieces:
15//!
16//! - [`Store<T>`]: a `Copy`, process-lifetime handle to one value, like `Signal::global`.
17//! - [`Keyed<T>`]: a collection addressed by stable key, with its own key→index map.
18//! - [`Elem<T>`]: one element of a keyed store; [`Elem::exists`] is the tracked deletion guard.
19//! - [`Field`]: one field projected out of any [`Source`]; `Copy`, itself a `Source` (so fields
20//!   nest to any depth), and a [`Binding`], so every control binds to it directly.
21//! - `#[derive(Observable)]` (in day-macros) generates the typed field accessors, so
22//!   `store.elem(id).name()` is written once per struct, not once per call site.
23//! - The **change log**: every write announces `(path components, field label, operation)`, with
24//!   the slot's prior and new value captured when a consumer asks ([`record_values`]). What the
25//!   tests read today; the persistence layer's input later.
26//!
27//! ## Paths
28//!
29//! A path names one observable slot: a store, one element of it, one field, a field of that
30//! field, to any depth. Each gets its own `Trigger` (day-reactive's data-less dependency node),
31//! created lazily on first observation: a path nobody reads has no trigger and costs nothing to
32//! write. Reads track the most specific path they touched; writes notify that path and its
33//! ancestors. That asymmetry is the entire granularity story.
34//!
35//! A path is a parent (an interned id) plus one component. The leaf component is not interned, so
36//! building a field handle (the thing that happens on every read of every row) costs no lookup.
37//! Interning happens only where a path is used as a *parent*: once per store, once per element
38//! handle, once per nested struct.
39//!
40//! ## Reclamation
41//!
42//! Both tables shrink. Triggers are refcounted by the scopes observing them: a binding's scope
43//! dies (a page popped, a row recycled) and the last watcher out disposes the trigger. Interner
44//! entries are refcounted by their children and their triggers: when the last trigger under an
45//! element is released, the element's entry (and any empty ancestors up to its pinned store root)
46//! is freed. A freed slot's id carries a generation, and every handle validates its cached id
47//! before use, re-interning through its own handle chain when stale, so a `Copy` handle held
48//! across a reclamation heals itself, and everyone converges on the current identity.
49//!
50//! A claim made from inside a reactive computation belongs to that computation's current run,
51//! not to a scope: it is released when the computation re-tracks or dies
52//! ([`day_reactive::on_run_retrack`]), exactly mirroring day-reactive's own per-run source
53//! bookkeeping. This is what keeps a long-lived recycled list cell from accumulating claims for
54//! every row it ever showed: rotate a binding across a million rows and the claim count stays
55//! at one row's worth. Outside any computation (a build seeding an initial value, an event
56//! handler) a tracked read subscribes nothing and therefore claims nothing: no trigger is
57//! created at all, because nothing could ever wake through it.
58//!
59//! ## Threads
60//!
61//! `Store` is `Send + Sync` (when `T` is); the trigger tables are thread-local to the main
62//! thread. A worker edits through [`Store::transact`], naming what it touched as plain path
63//! components; dropping the transaction commits the data and queues the announcements, and
64//! [`Store::pump`], called on the main thread, wakes exactly the paths the worker named. (The
65//! persistence container will schedule the pump itself; a bare store keeps delivery explicit.)
66
67use std::any::Any;
68use std::cell::{Cell, RefCell};
69use std::collections::HashMap;
70use std::fmt;
71use std::marker::PhantomData;
72use std::rc::Rc;
73use std::sync::atomic::{AtomicU64, Ordering};
74use std::sync::{Arc, Mutex, OnceLock, RwLock};
75
76use day_reactive::{Binding, Scope, Trigger};
77
78/// The Uuid key type, re-exported so a model file needs no direct `uuid` dependency:
79/// `#[obs(key)] id: Uuid` beside `Uuid::now_v7()` (generation is native-target only until the
80/// web pipeline's entropy import is wired; the type itself works everywhere).
81#[doc(no_inline)]
82pub use uuid::Uuid;
83
84// ---------------------------------------------------------------------------
85// Paths and the interner
86// ---------------------------------------------------------------------------
87
88/// An interned interior node: a path that something hangs off. Carries a generation so a handle
89/// can tell a live id from one whose slot was reclaimed and reused.
90#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
91pub struct NodeId {
92    idx: u32,
93    generation: u32,
94}
95
96/// The parent of a store's own path.
97const ROOT: NodeId = NodeId {
98    idx: 0,
99    generation: 0,
100};
101
102/// The reserved component naming a collection's shape (which keys, in what order) as opposed to
103/// any element's contents.
104pub const STRUCTURE: u64 = u64::MAX;
105
106/// One observable slot: a parent, and one step down from it.
107#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
108pub struct Path {
109    parent: NodeId,
110    part: u64,
111}
112
113impl Path {
114    /// A store's own path.
115    fn root(id: u64) -> Path {
116        Path {
117            parent: ROOT,
118            part: id,
119        }
120    }
121
122    /// One step down. Cheap: the parent is already interned by whoever handed it over.
123    #[must_use]
124    pub fn under(parent: NodeId, part: u64) -> Path {
125        Path { parent, part }
126    }
127
128    /// The path's components, outermost first, resolved through the interner.
129    #[must_use]
130    pub fn components(self) -> Vec<u64> {
131        let mut out: Vec<u64> = self.chain().iter().map(|p| p.part).collect();
132        out.reverse();
133        out
134    }
135
136    /// This path and every resolvable ancestor, innermost first: exactly what a write wakes.
137    fn chain(self) -> Vec<Path> {
138        let mut out = vec![self];
139        let mut at = self.parent;
140        NODES.with(|n| {
141            let nodes = n.borrow();
142            while at != ROOT {
143                match nodes.get(at) {
144                    Some(p) => {
145                        out.push(p);
146                        at = p.parent;
147                    }
148                    None => break,
149                }
150            }
151        });
152        out
153    }
154}
155
156/// A field's path component, derived from its name at compile time.
157///
158/// Hand-assigned indices are a hazard: two fields given the same number share a trigger, and the
159/// symptom is a wakeup that fires too often, invisible until someone profiles it. A name is
160/// already unique within a struct, so the compiler's own uniqueness rule becomes the path's.
161#[must_use]
162pub const fn field_id(name: &str) -> u64 {
163    let bytes = name.as_bytes();
164    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
165    let mut i = 0;
166    while i < bytes.len() {
167        h ^= bytes[i] as u64;
168        h = h.wrapping_mul(0x1000_0000_01b3);
169        i += 1;
170    }
171    h
172}
173
174struct Slot {
175    path: Path,
176    generation: u32,
177    alive: bool,
178    /// A store root: never reclaimed, because the leaked `Store` handle is forever.
179    pinned: bool,
180    /// Live child slots whose `path.parent` is this id.
181    children: u32,
182    /// Live triggers on paths whose parent is this id.
183    triggers: u32,
184}
185
186#[derive(Default)]
187struct Interner {
188    /// Index 0 is the root sentinel and is never read as a path.
189    slots: Vec<Slot>,
190    free: Vec<u32>,
191    lookup: HashMap<Path, NodeId>,
192}
193
194impl Interner {
195    fn get(&self, id: NodeId) -> Option<Path> {
196        match self.slots.get(id.idx as usize) {
197            Some(s) if s.alive && s.generation == id.generation => Some(s.path),
198            _ => None,
199        }
200    }
201
202    fn is_current(&self, id: NodeId) -> bool {
203        id == ROOT || self.get(id).is_some()
204    }
205
206    /// Free `id` if nothing holds it, then walk up freeing empty ancestors. Stops at pinned
207    /// store roots and at anything still watched or still a parent.
208    fn maybe_free(&mut self, mut id: NodeId) {
209        loop {
210            let Some(s) = self.slots.get(id.idx as usize) else {
211                return;
212            };
213            if !s.alive
214                || s.generation != id.generation
215                || s.pinned
216                || s.children > 0
217                || s.triggers > 0
218            {
219                return;
220            }
221            let path = s.path;
222            self.lookup.remove(&path);
223            let s = &mut self.slots[id.idx as usize];
224            s.alive = false;
225            s.generation = s.generation.wrapping_add(1);
226            self.free.push(id.idx);
227            if path.parent == ROOT {
228                return;
229            }
230            if let Some(ps) = self.slots.get_mut(path.parent.idx as usize)
231                && ps.alive
232                && ps.generation == path.parent.generation
233                && ps.children > 0
234            {
235                ps.children -= 1;
236                id = path.parent;
237                continue;
238            }
239            return;
240        }
241    }
242}
243
244day_reactive::tls_group! {
245    static NODES: RefCell<Interner> = RefCell::new(Interner {
246        slots: vec![Slot {
247            path: Path { parent: ROOT, part: 0 },
248            generation: 0,
249            alive: true,
250            pinned: true,
251            children: 0,
252            triggers: 0,
253        }],
254        free: Vec::new(),
255        lookup: HashMap::new(),
256    });
257
258    /// Path → trigger. Each trigger lives in its own child of the root scope: created inside
259    /// whichever page first observed it, it would be disposed with that page and every later
260    /// read would panic. Its own scope is also what makes reclamation possible.
261    static TRIGGERS: RefCell<HashMap<Path, Entry>> = RefCell::new(HashMap::new());
262
263    /// Every change announced while recording is on: what the tests read and, with a schema
264    /// beside it, the persistence change set.
265    static RECORDER: RefCell<Option<Vec<Change>>> = const { RefCell::new(None) };
266
267    /// Whether writes should capture prior/new values into the change log.
268    static WANT_VALUES: Cell<bool> = const { Cell::new(false) };
269
270    /// Standing want-values consumers (an installed undo stack), refcounted, unlike the
271    /// scoped `RECORDER` flag above.
272    static WANT_VALUES_STANDING: Cell<u32> = const { Cell::new(0) };
273
274    /// True while a preview write applies: triggers wake (the UI follows the drag), but no
275    /// change record is built, so sinks, the recorder, autosave and undo all stay quiet until
276    /// the session commits (docs/model.md).
277    static PREVIEW_WRITE: Cell<bool> = const { Cell::new(false) };
278
279    /// Open preview sessions: field components → the pre-session value. Insert-once per
280    /// session; taken at commit/cancel.
281    static PREVIEWS: RefCell<HashMap<Vec<u64>, Rc<dyn Any>>> = RefCell::new(HashMap::new());
282
283    /// The author tag stamped on changes born while set: "undo"/"redo" during replay, a sync
284    /// engine's name during an import. `None` is the user.
285    static CURRENT_AUTHOR: Cell<Option<&'static str>> = const { Cell::new(None) };
286
287    /// Standing consumers of every announced change: the persistence container's dirty
288    /// tracking. Unlike the scoped `RECORDER`, sinks persist until removed.
289    static SINKS: RefCell<Vec<(u64, ChangeSink)>> = const { RefCell::new(Vec::new()) };
290
291    static NEXT_SINK: Cell<u64> = const { Cell::new(1) };
292}
293
294type ChangeSink = Rc<dyn Fn(&Change)>;
295
296/// Handle for one installed change sink; pass it back to [`remove_change_sink`].
297#[derive(Clone, Copy, PartialEq, Eq, Debug)]
298pub struct ChangeSinkId(u64);
299
300/// Install a standing consumer of every announced change (main thread). Where
301/// [`record_changes`] is scoped to one closure, a sink lives until removed; it is how a
302/// persistence container watches the stores it loaded. Sinks receive the same [`Change`] the
303/// recorder would. A sink may write stores re-entrantly. The pipeline nests: a write made
304/// from inside a sink completes its own announcement (sinks included) before the outer one
305/// resumes, which is how relation maintenance cascades a delete. But a sink that writes owns
306/// its own termination: nothing here bounds the recursion.
307pub fn install_change_sink(f: impl Fn(&Change) + 'static) -> ChangeSinkId {
308    let id = NEXT_SINK.with(|n| {
309        let id = n.get();
310        n.set(id + 1);
311        id
312    });
313    SINKS.with(|s| s.borrow_mut().push((id, Rc::new(f))));
314    ChangeSinkId(id)
315}
316
317pub fn remove_change_sink(id: ChangeSinkId) {
318    // Best-effort on the drop path: a container falling out of a reactive runtime's own
319    // thread-exit teardown may reach here after this TLS is gone, and that must not abort.
320    let _ = SINKS.try_with(|s| s.borrow_mut().retain(|(i, _)| *i != id.0));
321}
322
323fn sinks_active() -> bool {
324    SINKS.with(|s| !s.borrow().is_empty())
325}
326
327/// Deliver to every sink with the registry borrow released, so a sink's bookkeeping can never
328/// collide with sink installation from another callback.
329fn feed_sinks(change: &Change) {
330    let sinks: Vec<ChangeSink> =
331        SINKS.with(|s| s.borrow().iter().map(|(_, f)| f.clone()).collect());
332    for f in sinks {
333        f(change);
334    }
335}
336
337/// A live trigger and who is watching it.
338struct Entry {
339    trigger: Trigger,
340    /// The trigger's own scope, a child of root, so it can be disposed on its own.
341    scope: Scope,
342    /// One claim per observing computation, deduped; when the last one releases (on its
343    /// re-track or death), the trigger goes with it.
344    watchers: Vec<day_reactive::RunId>,
345}
346
347/// Give this path an id, so something can hang off it. Called once per source handle, never on
348/// the per-field read path.
349fn intern(p: Path) -> NodeId {
350    NODES.with(|n| {
351        let mut i = n.borrow_mut();
352        if let Some(id) = i.lookup.get(&p) {
353            return *id;
354        }
355        let id = if let Some(idx) = i.free.pop() {
356            let s = &mut i.slots[idx as usize];
357            s.path = p;
358            s.alive = true;
359            s.pinned = false;
360            s.children = 0;
361            s.triggers = 0;
362            NodeId {
363                idx,
364                generation: s.generation,
365            }
366        } else {
367            let idx = i.slots.len() as u32;
368            i.slots.push(Slot {
369                path: p,
370                generation: 0,
371                alive: true,
372                pinned: false,
373                children: 0,
374                triggers: 0,
375            });
376            NodeId { idx, generation: 0 }
377        };
378        i.lookup.insert(p, id);
379        if p.parent != ROOT
380            && let Some(s) = i.slots.get_mut(p.parent.idx as usize)
381            && s.alive
382            && s.generation == p.parent.generation
383        {
384            s.children += 1;
385        }
386        id
387    })
388}
389
390/// Whether an id still names a live slot. A handle whose cached id fails this re-interns
391/// through its own chain — see the module docs on reclamation.
392fn is_current(id: NodeId) -> bool {
393    NODES.with(|n| n.borrow().is_current(id))
394}
395
396fn path_of(id: NodeId) -> Path {
397    NODES.with(|n| n.borrow().get(id).unwrap_or(Path::root(0)))
398}
399
400fn pin(id: NodeId) {
401    NODES.with(|n| {
402        if let Some(s) = n.borrow_mut().slots.get_mut(id.idx as usize) {
403            s.pinned = true;
404        }
405    });
406}
407
408/// How many interior nodes are currently interned (the sentinel excluded): the cost of
409/// observation's second table, assertable in a test.
410#[must_use]
411pub fn interned_nodes() -> usize {
412    NODES.with(|n| n.borrow().slots.iter().filter(|s| s.alive).count() - 1)
413}
414
415/// Subscribe the current reactive computation to exactly this path, and register the claim so
416/// the trigger can be reclaimed on the computation's next re-track (or death).
417///
418/// Observation belongs to computations: outside any active run (a build seeding an initial
419/// value, an event handler, `untrack`) a tracked read subscribes nothing in day-reactive, so
420/// creating a trigger for it would be dead weight that some scope had to carry. It does
421/// nothing; the read itself proceeds unobserved.
422fn track(p: Path) {
423    let Some(watcher) = day_reactive::active_run() else {
424        return;
425    };
426    let (trigger, created, fresh) = TRIGGERS.with(|t| {
427        let mut map = t.borrow_mut();
428        let mut created = false;
429        let entry = map.entry(p).or_insert_with(|| {
430            created = true;
431            // Its own child of root: outlives every observer, and disposable on its own.
432            let scope = Scope::root().create_child();
433            Entry {
434                trigger: scope.enter(Trigger::new),
435                scope,
436                watchers: Vec::new(),
437            }
438        });
439        let fresh = !entry.watchers.contains(&watcher);
440        if fresh {
441            entry.watchers.push(watcher);
442        }
443        (entry.trigger, created, fresh)
444    });
445    if created && p.parent != ROOT {
446        NODES.with(|n| {
447            let mut i = n.borrow_mut();
448            if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
449                && s.alive
450                && s.generation == p.parent.generation
451            {
452                s.triggers += 1;
453            }
454        });
455    }
456    if fresh {
457        // The claim dies with the run: released when the computation re-tracks (having stopped
458        // reading this path, or about to read it afresh) or is disposed.
459        day_reactive::on_run_retrack(move || release(p, watcher));
460    }
461    trigger.track();
462}
463
464/// Drop one watcher's claim; the last one out disposes the trigger and lets the interner free
465/// the ancestors nothing else holds.
466fn release(p: Path, watcher: day_reactive::RunId) {
467    let removed = TRIGGERS.with(|t| {
468        let mut map = t.borrow_mut();
469        let Some(entry) = map.get_mut(&p) else {
470            return false;
471        };
472        entry.watchers.retain(|w| *w != watcher);
473        if entry.watchers.is_empty() {
474            let scope = entry.scope;
475            map.remove(&p);
476            drop(map);
477            // A trigger holds nothing but a counter, so disposing it loses no state: the next
478            // reader creates a fresh one.
479            scope.dispose();
480            true
481        } else {
482            false
483        }
484    });
485    if removed && p.parent != ROOT {
486        NODES.with(|n| {
487            let mut i = n.borrow_mut();
488            if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
489                && s.alive
490                && s.generation == p.parent.generation
491                && s.triggers > 0
492            {
493                s.triggers -= 1;
494            }
495            i.maybe_free(p.parent);
496        });
497    }
498}
499
500/// How many paths currently have a trigger: the cost of observation, assertable in a test.
501#[must_use]
502pub fn observed_paths() -> usize {
503    TRIGGERS.with(|t| t.borrow().len())
504}
505
506// ---------------------------------------------------------------------------
507// The change log
508// ---------------------------------------------------------------------------
509
510/// What kind of change was announced. A persistence layer needs this to choose between an
511/// INSERT, an UPDATE and a DELETE; the UI does not care, which is why it rides alongside the
512/// path rather than inside it.
513#[derive(Clone, Copy, PartialEq, Eq, Debug)]
514pub enum Op {
515    /// One field was written.
516    Set,
517    /// A row entered the collection.
518    Insert,
519    /// A row left it.
520    Delete,
521    /// The collection's order changed.
522    Move,
523}
524
525/// One announced change, in the form a store outside the UI can consume.
526///
527/// `prior` and `value` are the slot's value before and after the write, captured only while a
528/// consumer that wants them is active ([`record_values`], an [`UndoStack`]). A write with no such
529/// consumer clones nothing. They are type-erased; downcast with [`Change::prior_as`] /
530/// [`Change::value_as`]. A structural change carries positions as well: a `Delete` has the
531/// removed row in `prior` and its index (`usize`) in `value`, an `Insert` the added row in
532/// `value` and its index in `prior`, and a `Move` its index before and after.
533#[derive(Clone)]
534pub struct Change {
535    /// The path's components, outermost first: store, key, field, …
536    pub components: Vec<u64>,
537    /// The field's name, which is also its column name.
538    pub label: &'static str,
539    pub op: Op,
540    pub prior: Option<Rc<dyn Any>>,
541    pub value: Option<Rc<dyn Any>>,
542    /// Who made it: `None` is the user; an undo replay stamps "undo"/"redo"; an importer its
543    /// own name ([`with_author`]). Consumers can decline their own echoes.
544    pub author: Option<&'static str>,
545}
546
547impl Change {
548    /// The value before the write, if captured and of type `T`.
549    #[must_use]
550    pub fn prior_as<T: 'static>(&self) -> Option<&T> {
551        self.prior.as_deref().and_then(|v| v.downcast_ref())
552    }
553
554    /// The value after the write, if captured and of type `T`.
555    #[must_use]
556    pub fn value_as<T: 'static>(&self) -> Option<&T> {
557        self.value.as_deref().and_then(|v| v.downcast_ref())
558    }
559}
560
561impl fmt::Debug for Change {
562    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563        f.debug_struct("Change")
564            .field("components", &self.components)
565            .field("label", &self.label)
566            .field("op", &self.op)
567            .field("prior", &self.prior.as_ref().map(|_| ".."))
568            .field("value", &self.value.as_ref().map(|_| ".."))
569            .field("author", &self.author)
570            .finish()
571    }
572}
573
574fn values_wanted() -> bool {
575    WANT_VALUES.with(std::cell::Cell::get) || WANT_VALUES_STANDING.with(|w| w.get() > 0)
576}
577
578/// Whether any change consumer currently captures prior/new values: a scoped
579/// [`record_values`], or a standing holder like an installed undo stack. A framework layer
580/// (the persistence container) asks this to decide whether a delete must materialize its row
581/// first: a value-free delete cannot be inverted, and capturing costs nothing when nobody
582/// records.
583#[must_use]
584pub fn record_capture_active() -> bool {
585    values_wanted()
586}
587
588/// Keep prior/new values flowing on every change while `on` holders exist: the undo stack's
589/// standing form of what [`record_values`] does for one closure.
590pub fn want_values_standing(on: bool) {
591    WANT_VALUES_STANDING.with(|w| {
592        let v = w.get();
593        w.set(if on { v + 1 } else { v.saturating_sub(1) });
594    });
595}
596
597fn previewing() -> bool {
598    PREVIEW_WRITE.with(std::cell::Cell::get)
599}
600
601/// Run `f` with changes stamped as `author`: how an undo replay or an importer signs its
602/// writes so consumers (a sync engine, a query) can tell them from the user's.
603pub fn with_author<R>(author: &'static str, f: impl FnOnce() -> R) -> R {
604    let previous = CURRENT_AUTHOR.with(|a| a.replace(Some(author)));
605    // Restored on unwind too.
606    let _restore = std::mem::DropGuard::new(previous, |previous| {
607        CURRENT_AUTHOR.with(|a| a.set(previous));
608    });
609    f()
610}
611
612fn current_author() -> Option<&'static str> {
613    CURRENT_AUTHOR.with(std::cell::Cell::get)
614}
615
616/// Record every change announced inside `f`. What the tests read, and the persistence layer's
617/// input.
618pub fn record_changes<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
619    RECORDER.with(|r| *r.borrow_mut() = Some(Vec::new()));
620    let out = f();
621    let log = RECORDER.with(|r| r.borrow_mut().take().unwrap_or_default());
622    (out, log)
623}
624
625/// [`record_changes`], with prior/new values captured on every field write inside `f`: the
626/// form an undo unit needs. Costs one clone per write while active, nothing when not.
627pub fn record_values<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
628    WANT_VALUES.with(|w| w.set(true));
629    let out = record_changes(f);
630    WANT_VALUES.with(|w| w.set(false));
631    out
632}
633
634/// Just the labels, for the tests that only care which fields moved.
635pub fn record<R>(f: impl FnOnce() -> R) -> (R, Vec<&'static str>) {
636    let (out, changes) = record_changes(f);
637    (out, changes.into_iter().map(|c| c.label).collect())
638}
639
640/// Wake the observers of this path and of every ancestor, and nobody else. `components` is
641/// resolved lazily: the change log wants the full path as data, but building the `Vec` is wasted
642/// work when nothing records, which is almost always.
643fn notify_change(
644    p: Path,
645    components: impl FnOnce() -> Vec<u64>,
646    label: &'static str,
647    op: Op,
648    prior: Option<Rc<dyn Any>>,
649    value: Option<Rc<dyn Any>>,
650) {
651    if previewing() {
652        // A preview write: the UI follows, nothing durable hears it.
653        wake(p);
654        return;
655    }
656    let recording = RECORDER.with(|r| r.borrow().is_some());
657    if recording || sinks_active() {
658        let change = Change {
659            components: components(),
660            label,
661            op,
662            prior,
663            value,
664            author: current_author(),
665        };
666        feed_sinks(&change);
667        if recording {
668            RECORDER.with(|r| {
669                if let Some(log) = r.borrow_mut().as_mut() {
670                    log.push(change);
671                }
672            });
673        }
674    }
675    wake(p);
676}
677
678fn wake(p: Path) {
679    let chain = p.chain();
680    let live: Vec<Trigger> = TRIGGERS.with(|t| {
681        let map = t.borrow();
682        chain
683            .iter()
684            .filter_map(|k| map.get(k).map(|e| e.trigger))
685            .collect()
686    });
687    for tr in live {
688        tr.notify();
689    }
690}
691
692/// Announce a change named by plain components: how a background transaction's writes reach
693/// the triggers on the main thread, and what a framework layer calls to wake a path it
694/// maintains for a value that lives elsewhere (a relation index announcing a parent's to-many
695/// field). Wakes the deepest path whose interior steps are interned; anything deeper cannot
696/// have an observer, because observing is what interns. The change feeds sinks and the
697/// recorder with the current author tag and op `Set`, carrying no values.
698pub fn announce(parts: &[u64], label: &'static str) {
699    announce_op(parts, label, Op::Set);
700}
701
702/// [`announce`], with the operation named; what the undo replay calls.
703fn announce_op(parts: &[u64], label: &'static str, op: Op) {
704    let resolved = (|| {
705        let (last, interior) = parts.split_last()?;
706        let mut parent = ROOT;
707        for part in interior {
708            let step = Path::under(parent, *part);
709            match NODES.with(|n| {
710                let i = n.borrow();
711                i.lookup.get(&step).copied().filter(|id| i.is_current(*id))
712            }) {
713                Some(id) => parent = id,
714                // The step was never observed: wake it as a leaf, so coarser observers above
715                // it still hear the change.
716                None => return Some(step),
717            }
718        }
719        Some(Path::under(parent, *last))
720    })();
721    let Some(p) = resolved else { return };
722    let recording = RECORDER.with(|r| r.borrow().is_some());
723    if recording || sinks_active() {
724        let change = Change {
725            components: parts.to_vec(),
726            label,
727            op,
728            prior: None,
729            value: None,
730            author: current_author(),
731        };
732        feed_sinks(&change);
733        if recording {
734            RECORDER.with(|r| {
735                if let Some(log) = r.borrow_mut().as_mut() {
736                    log.push(change);
737                }
738            });
739        }
740    }
741    wake(p);
742}
743
744// ---------------------------------------------------------------------------
745// Source
746// ---------------------------------------------------------------------------
747
748/// Anything a field can be projected out of: the store itself, one element of a keyed
749/// collection, or another field (which is how nesting works).
750///
751/// `with_value_untracked` is the one every projection reads through: a field must subscribe to
752/// its path, not to its parent's, or the granularity is gone.
753pub trait Source<T: 'static>: Copy + 'static {
754    /// Whether this source's location can change over the handle's lifetime: a recycled list
755    /// slot whose current row rotates. Fields projected from a dynamic source resolve their
756    /// path through the source on every operation instead of trusting the one cached at
757    /// projection time, and their tracked reads also run [`Source::track_extra`].
758    const DYNAMIC: bool = false;
759
760    /// Extra tracking a projected field's tracked reads perform. A dynamic source tracks its
761    /// own rebind signal here, so a control bound at build follows the slot to its next row.
762    fn track_extra(self) {}
763
764    /// The path this source occupies. Implementations revalidate against the interner, so the
765    /// result is always current.
766    fn path(self) -> Path;
767    /// This source's interned id, so a child can be built with no lookup of its own.
768    ///
769    /// Ids are minted per thread. They are the fast path for a handle built and used on the main
770    /// thread, and must never cross a thread boundary — see `components`.
771    fn node(self) -> NodeId;
772    /// The path as plain components, resolved by walking the handle chain rather than the
773    /// interner. This is what crosses a thread boundary: a worker names what it changed with
774    /// components, and the main thread re-establishes them on its own side when it announces.
775    fn components(self, out: &mut Vec<u64>);
776    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R;
777    /// Returns false when the value is gone (a deleted row), in which case nothing is
778    /// announced either.
779    fn update_value(self, f: impl FnOnce(&mut T)) -> bool;
780    fn bump_version(self);
781
782    /// Tracked read of the whole value: the coarse subscription.
783    fn with<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
784        self.track_extra();
785        track(self.path());
786        self.with_value_untracked(f)
787    }
788}
789
790/// What a transaction touched, in a form that survives the trip to the main thread: the path's
791/// components, outermost first, plus the label the change log records.
792pub type TxPaths = Vec<(Vec<u64>, &'static str)>;
793
794// ---------------------------------------------------------------------------
795// Store
796// ---------------------------------------------------------------------------
797
798/// A `Copy`, process-lifetime handle to one observable value.
799pub struct Store<T: 'static> {
800    inner: &'static Inner<T>,
801    node: NodeId,
802    root_id: u64,
803}
804
805impl<T> Clone for Store<T> {
806    fn clone(&self) -> Self {
807        *self
808    }
809}
810impl<T> Copy for Store<T> {}
811
812struct Inner<T> {
813    data: RwLock<T>,
814    pending: Mutex<TxPaths>,
815    version: AtomicU64,
816}
817
818/// Store root ids are process-global so two stores can never collide.
819static NEXT_STORE: AtomicU64 = AtomicU64::new(1);
820
821impl<T: 'static> Store<T> {
822    /// A process-lifetime store, leaked so the handle stays `Copy` (the property that makes a
823    /// `Signal` pleasant to pass). Create once (a `thread_local!` + accessor fn is the
824    /// idiom); the scoped owner arrives with the persistence container.
825    pub fn new(value: T) -> Store<T> {
826        let inner: &'static Inner<T> = Box::leak(Box::new(Inner {
827            data: RwLock::new(value),
828            pending: Mutex::new(Vec::new()),
829            version: AtomicU64::new(0),
830        }));
831        let root_id = NEXT_STORE.fetch_add(1, Ordering::Relaxed);
832        let node = intern(Path::root(root_id));
833        pin(node);
834        Store {
835            inner,
836            node,
837            root_id,
838        }
839    }
840
841    /// Read the whole value without subscribing the caller to changes.
842    ///
843    /// # Panics
844    ///
845    /// Panics if a thread panicked while holding the store's lock.
846    pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
847        f(&self.inner.data.read().expect("store poisoned"))
848    }
849
850    /// Mutate the whole value; announces a store-wide change (every reader wakes).
851    ///
852    /// # Panics
853    ///
854    /// Panics if a thread panicked while holding the store's lock.
855    pub fn update(self, label: &'static str, f: impl FnOnce(&mut T)) {
856        {
857            let mut g = self.inner.data.write().expect("store poisoned");
858            f(&mut g);
859        }
860        self.inner.version.fetch_add(1, Ordering::Relaxed);
861        let root_id = self.root_id;
862        notify_change(
863            path_of(self.node),
864            || vec![root_id],
865            label,
866            Op::Set,
867            None,
868            None,
869        );
870    }
871
872    /// Bumped on every write; a cheap way for tests to ask "did anything change".
873    #[must_use]
874    pub fn version(self) -> u64 {
875        self.inner.version.load(Ordering::Relaxed)
876    }
877
878    /// This store's root id, the first component of every path under it. A persistence
879    /// container keys its table map on it.
880    #[must_use]
881    pub fn store_id(self) -> u64 {
882        self.root_id
883    }
884
885    /// Announce everything background transactions committed, returning how many paths were
886    /// queued. An app posts this to the main loop after a worker commits; a test calls it
887    /// directly and asserts what it woke.
888    ///
889    /// # Panics
890    ///
891    /// Panics if a thread panicked while holding the store's pending-announcement queue.
892    #[must_use]
893    pub fn pump(self) -> usize {
894        let drained: TxPaths = {
895            let mut q = self.inner.pending.lock().expect("queue poisoned");
896            std::mem::take(&mut *q)
897        };
898        let n = drained.len();
899        day_reactive::batch(|| {
900            for (parts, label) in drained {
901                announce(&parts, label);
902            }
903        });
904        n
905    }
906}
907
908impl<T: 'static> Source<T> for Store<T> {
909    fn path(self) -> Path {
910        path_of(self.node)
911    }
912    fn node(self) -> NodeId {
913        // Pinned at creation, so always current.
914        self.node
915    }
916    fn components(self, out: &mut Vec<u64>) {
917        out.push(self.root_id);
918    }
919    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
920        f(Some(&self.inner.data.read().expect("store poisoned")))
921    }
922    fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
923        let mut g = self.inner.data.write().expect("store poisoned");
924        f(&mut g);
925        true
926    }
927    fn bump_version(self) {
928        self.inner.version.fetch_add(1, Ordering::Relaxed);
929    }
930}
931
932// SAFETY: the handle is a shared reference to data behind a lock plus Copy ids. The reactive
933// triggers those ids name are touched only on the main thread; writes from other threads go
934// through `transact`, whose announcements are queued and delivered by `pump`.
935unsafe impl<T: Send + Sync> Send for Store<T> {}
936unsafe impl<T: Send + Sync> Sync for Store<T> {}
937
938// ---------------------------------------------------------------------------
939// Transactions
940// ---------------------------------------------------------------------------
941
942impl<T: Send + Sync + 'static> Store<T> {
943    /// Open a write transaction: the way a background thread edits. Holding it holds the
944    /// store's write lock, so a reader never sees half of one; dropping it commits and queues
945    /// the announcements for [`Store::pump`].
946    ///
947    /// # Panics
948    ///
949    /// Panics if a thread panicked while holding the store's lock.
950    #[must_use]
951    pub fn transact(self) -> Tx<T> {
952        Tx {
953            store: self,
954            guard: Some(self.inner.data.write().expect("store poisoned")),
955            touched: Vec::new(),
956        }
957    }
958}
959
960/// An open background transaction. Name what you touch with [`Field::touch`] (or push
961/// components directly); commit by dropping.
962pub struct Tx<T: Send + Sync + 'static> {
963    store: Store<T>,
964    guard: Option<std::sync::RwLockWriteGuard<'static, T>>,
965    touched: TxPaths,
966}
967
968impl<T: Send + Sync + 'static> Tx<T> {
969    #[expect(
970        clippy::missing_panics_doc,
971        reason = "the guard is taken in Drop alone, so the `expect` cannot fail on a live Tx"
972    )]
973    pub fn data(&mut self) -> &mut T {
974        // A Tx is only reachable while uncommitted: the guard is taken in Drop alone.
975        self.guard.as_mut().expect("transaction already committed")
976    }
977    pub fn touched(&mut self, parts: Vec<u64>, label: &'static str) {
978        self.touched.push((parts, label));
979    }
980    pub fn paths(&mut self) -> &mut TxPaths {
981        &mut self.touched
982    }
983}
984
985impl<T: Send + Sync + 'static> Drop for Tx<T> {
986    fn drop(&mut self) {
987        let touched = std::mem::take(&mut self.touched);
988        let store = self.store;
989        // Release the data lock first: the commit is the unlock.
990        drop(self.guard.take());
991        store.inner.version.fetch_add(1, Ordering::Relaxed);
992        store
993            .inner
994            .pending
995            .lock()
996            .expect("queue poisoned")
997            .extend(touched);
998        // Announcing is the main thread's job; see `Store::pump`. (Scheduling the pump
999        // automatically is the persistence container's job later; a bare store keeps delivery
1000        // explicit so a headless test owns its own timing.)
1001    }
1002}
1003
1004// ---------------------------------------------------------------------------
1005// Keys and identity
1006// ---------------------------------------------------------------------------
1007
1008/// The floor of the interned-handle space. Plain `u64` keys pass through as their own handle
1009/// and stay below it; the top bit is what lets [`Key::of_handle`] tell an identity handle
1010/// from an interned one without any lookup. Integer `#[obs(key)]` fields assert the bound in
1011/// debug builds rather than silently colliding.
1012const WIDE_BASE: u64 = 1 << 63;
1013
1014/// One element's key: what its paths, its [`Keyed`] slot, and (under persistence) its stored
1015/// row are addressed by.
1016///
1017/// A `u64` key is its own path handle, with no interner, lock or allocation: exactly the cost
1018/// integer keys always had. The wide forms (`Uuid`, `Str`, `Pair`) intern process-globally to
1019/// a `u64` handle on first use, so paths stay 12 bytes and every collection index stays
1020/// `u64`-keyed. A handle, once minted, is stable for the process's lifetime (undo records
1021/// and long-lived `ModelId`s rely on that) and reverses through [`Key::of_handle`]; the
1022/// interner's size is observable via [`interned_keys`].
1023#[derive(Clone, PartialEq, Eq, Hash, Debug)]
1024pub enum Key {
1025    U64(u64),
1026    /// A UUID, carried as its raw 128 bits (`uuid::Uuid::as_u128`).
1027    Uuid(u128),
1028    /// A natural string key: a slug, an external system's id.
1029    Str(Arc<str>),
1030    /// Two handles as one key: how the persistence layer addresses join rows. Apps rarely
1031    /// construct one directly.
1032    Pair(u64, u64),
1033}
1034
1035impl Key {
1036    /// The key's path handle: identity for `U64`, interned (once, then a read-locked lookup)
1037    /// for the wide forms. Callable from any thread; the interner is process-global.
1038    #[must_use]
1039    pub fn handle(&self) -> u64 {
1040        match self {
1041            Key::U64(k) => *k,
1042            Key::Uuid(u) => intern_wide(WideKey::Uuid(*u)),
1043            Key::Str(s) => intern_wide(WideKey::Str(s.clone())),
1044            Key::Pair(a, b) => intern_wide(WideKey::Pair(*a, *b)),
1045        }
1046    }
1047
1048    /// The key a handle names: identity below the wide floor, the interner's record above
1049    /// it. `None` only for a wide handle nothing ever interned (a forged value).
1050    ///
1051    /// # Panics
1052    ///
1053    /// Panics if a thread panicked while holding the key interner's lock.
1054    #[must_use]
1055    pub fn of_handle(handle: u64) -> Option<Key> {
1056        if handle < WIDE_BASE {
1057            return Some(Key::U64(handle));
1058        }
1059        let idx = (handle - WIDE_BASE) as usize;
1060        wide_keys()
1061            .read()
1062            .expect("key interner poisoned")
1063            .reverse
1064            .get(idx)
1065            .map(|w| match w {
1066                WideKey::Uuid(u) => Key::Uuid(*u),
1067                WideKey::Str(s) => Key::Str(s.clone()),
1068                WideKey::Pair(a, b) => Key::Pair(*a, *b),
1069            })
1070    }
1071
1072    #[must_use]
1073    pub fn as_u64(&self) -> Option<u64> {
1074        match self {
1075            Key::U64(k) => Some(*k),
1076            _ => None,
1077        }
1078    }
1079
1080    #[must_use]
1081    pub fn as_uuid(&self) -> Option<uuid::Uuid> {
1082        match self {
1083            Key::Uuid(u) => Some(uuid::Uuid::from_u128(*u)),
1084            _ => None,
1085        }
1086    }
1087
1088    #[must_use]
1089    pub fn as_str(&self) -> Option<&str> {
1090        match self {
1091            Key::Str(s) => Some(s),
1092            _ => None,
1093        }
1094    }
1095}
1096
1097impl fmt::Display for Key {
1098    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099        match self {
1100            Key::U64(k) => write!(f, "{k}"),
1101            Key::Uuid(u) => write!(f, "{}", uuid::Uuid::from_u128(*u)),
1102            Key::Str(s) => f.write_str(s),
1103            Key::Pair(a, b) => write!(f, "{a}:{b}"),
1104        }
1105    }
1106}
1107
1108/// The wide-key interner's stored form (`U64` never enters it).
1109#[derive(Clone, PartialEq, Eq, Hash)]
1110enum WideKey {
1111    Uuid(u128),
1112    Str(Arc<str>),
1113    Pair(u64, u64),
1114}
1115
1116#[derive(Default)]
1117struct WideKeys {
1118    lookup: HashMap<WideKey, u64>,
1119    reverse: Vec<WideKey>,
1120}
1121
1122/// Process-global, unlike the path interner: handles are embedded in `Keyed` indexes that
1123/// background transactions mutate, so a thread-local table would mint divergent handles, the
1124/// exact bug the path system's `components` method exists to prevent.
1125static WIDE_KEYS: OnceLock<RwLock<WideKeys>> = OnceLock::new();
1126
1127fn wide_keys() -> &'static RwLock<WideKeys> {
1128    WIDE_KEYS.get_or_init(Default::default)
1129}
1130
1131fn intern_wide(k: WideKey) -> u64 {
1132    if let Some(h) = wide_keys()
1133        .read()
1134        .expect("key interner poisoned")
1135        .lookup
1136        .get(&k)
1137    {
1138        return *h;
1139    }
1140    let mut w = wide_keys().write().expect("key interner poisoned");
1141    if let Some(h) = w.lookup.get(&k) {
1142        return *h; // another thread won the race between our two locks
1143    }
1144    let h = WIDE_BASE + w.reverse.len() as u64;
1145    w.reverse.push(k.clone());
1146    w.lookup.insert(k, h);
1147    h
1148}
1149
1150/// How many wide keys the process has interned: the cost of wide-key identity itself,
1151/// assertable in a test. Entries are retained for the process's lifetime.
1152///
1153/// # Panics
1154///
1155/// Panics if a thread panicked while holding the key interner's lock.
1156#[must_use]
1157pub fn interned_keys() -> usize {
1158    wide_keys()
1159        .read()
1160        .expect("key interner poisoned")
1161        .reverse
1162        .len()
1163}
1164
1165/// A value usable as a key: what an `#[obs(key)]` / `#[model(id)]` field's type implements.
1166/// Integer keys reserve the top bit (the interned-handle space); a negative cast or a
1167/// hash-derived id at or above `1 << 63` is refused in debug builds rather than silently
1168/// colliding with an interned handle.
1169pub trait AsKey {
1170    fn as_key(&self) -> Key;
1171}
1172
1173fn int_key(k: u64) -> Key {
1174    debug_assert!(
1175        k < WIDE_BASE,
1176        "u64 keys reserve the top bit for interned handles (got {k:#x})"
1177    );
1178    Key::U64(k)
1179}
1180
1181macro_rules! int_key {
1182    ($($t:ty),*) => {$(
1183        impl AsKey for $t {
1184            fn as_key(&self) -> Key {
1185                int_key(*self as u64)
1186            }
1187        }
1188    )*};
1189}
1190macro_rules! lossless_int_key {
1191    ($($t:ty),*) => {$(
1192        impl AsKey for $t {
1193            fn as_key(&self) -> Key {
1194                int_key(u64::from(*self))
1195            }
1196        }
1197    )*};
1198}
1199lossless_int_key!(u8, u16, u32);
1200int_key!(u64, usize, i8, i16, i32, i64, isize);
1201
1202impl AsKey for String {
1203    fn as_key(&self) -> Key {
1204        Key::Str(Arc::from(self.as_str()))
1205    }
1206}
1207impl AsKey for &str {
1208    fn as_key(&self) -> Key {
1209        Key::Str(Arc::from(*self))
1210    }
1211}
1212impl AsKey for Arc<str> {
1213    fn as_key(&self) -> Key {
1214        Key::Str(self.clone())
1215    }
1216}
1217impl AsKey for uuid::Uuid {
1218    fn as_key(&self) -> Key {
1219        Key::Uuid(self.as_u128())
1220    }
1221}
1222impl AsKey for Key {
1223    fn as_key(&self) -> Key {
1224        self.clone()
1225    }
1226}
1227
1228/// A typed, opaque id for one `M` row: `Copy`, 8 bytes, cheap to pass and compare. It wraps
1229/// the key's path handle: [`Store::elem`], query results, list slots and destinations all
1230/// speak it, and a wrong-model id is a compile error rather than a wrong row. [`ModelId::key`]
1231/// recovers the real key for display, deep links, or the persistence edge.
1232///
1233/// Ordering compares handles: meaningful for integer keys, arbitrary (but stable) for wide
1234/// ones; it exists so ids can live in sorted containers.
1235pub struct ModelId<M: ?Sized> {
1236    handle: u64,
1237    _m: PhantomData<fn() -> M>,
1238}
1239
1240impl<M: ?Sized> Clone for ModelId<M> {
1241    fn clone(&self) -> Self {
1242        *self
1243    }
1244}
1245impl<M: ?Sized> Copy for ModelId<M> {}
1246impl<M: ?Sized> PartialEq for ModelId<M> {
1247    fn eq(&self, other: &Self) -> bool {
1248        self.handle == other.handle
1249    }
1250}
1251impl<M: ?Sized> Eq for ModelId<M> {}
1252impl<M: ?Sized> std::hash::Hash for ModelId<M> {
1253    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1254        self.handle.hash(state);
1255    }
1256}
1257impl<M: ?Sized> PartialOrd for ModelId<M> {
1258    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1259        Some(self.cmp(other))
1260    }
1261}
1262impl<M: ?Sized> Ord for ModelId<M> {
1263    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1264        self.handle.cmp(&other.handle)
1265    }
1266}
1267impl<M: ?Sized> fmt::Debug for ModelId<M> {
1268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1269        match Key::of_handle(self.handle) {
1270            Some(k) => write!(f, "ModelId({k})"),
1271            None => write!(f, "ModelId(#{:x})", self.handle),
1272        }
1273    }
1274}
1275
1276impl<M: ?Sized> ModelId<M> {
1277    /// The id for `key`, interning it if wide.
1278    #[expect(
1279        clippy::needless_pass_by_value,
1280        reason = "public signature; callers pass key literals and owned keys by value"
1281    )]
1282    pub fn of(key: impl AsKey) -> Self {
1283        Self::from_handle(key.as_key().handle())
1284    }
1285    /// Wrap an existing path handle (from [`Store::keys`], a slot token, a change record).
1286    #[must_use]
1287    pub const fn from_handle(handle: u64) -> Self {
1288        ModelId {
1289            handle,
1290            _m: PhantomData,
1291        }
1292    }
1293    #[must_use]
1294    pub fn handle(self) -> u64 {
1295        self.handle
1296    }
1297    /// The real key: identity for integer handles, the interner's record for wide ones.
1298    #[must_use]
1299    pub fn key(self) -> Key {
1300        Key::of_handle(self.handle).unwrap_or(Key::U64(self.handle))
1301    }
1302}
1303
1304/// Integer-keyed ids compare against their key value directly: `assert_eq!(ids, [1, 3])`
1305/// reads the way integer-keyed code always has.
1306impl<M: ?Sized> PartialEq<u64> for ModelId<M> {
1307    fn eq(&self, other: &u64) -> bool {
1308        self.handle == *other
1309    }
1310}
1311impl<M: ?Sized> PartialEq<ModelId<M>> for u64 {
1312    fn eq(&self, other: &ModelId<M>) -> bool {
1313        *self == other.handle
1314    }
1315}
1316
1317/// Raw path handles convert directly; this is how `store.elem(k)` keeps taking the values
1318/// [`Store::keys`] returns, and how integer keys stay literal-friendly.
1319impl<M: ?Sized> From<u64> for ModelId<M> {
1320    fn from(handle: u64) -> Self {
1321        ModelId::from_handle(handle)
1322    }
1323}
1324impl<M: ?Sized> From<u32> for ModelId<M> {
1325    fn from(k: u32) -> Self {
1326        ModelId::of(k)
1327    }
1328}
1329impl<M: ?Sized> From<i32> for ModelId<M> {
1330    fn from(k: i32) -> Self {
1331        ModelId::of(k)
1332    }
1333}
1334impl<M: ?Sized> From<usize> for ModelId<M> {
1335    fn from(k: usize) -> Self {
1336        ModelId::of(k)
1337    }
1338}
1339impl<M: ?Sized> From<uuid::Uuid> for ModelId<M> {
1340    fn from(k: uuid::Uuid) -> Self {
1341        ModelId::of(k)
1342    }
1343}
1344impl<M: ?Sized> From<&str> for ModelId<M> {
1345    fn from(k: &str) -> Self {
1346        ModelId::of(k)
1347    }
1348}
1349impl<M: ?Sized> From<String> for ModelId<M> {
1350    fn from(k: String) -> Self {
1351        ModelId::of(k)
1352    }
1353}
1354impl<M: ?Sized> From<Key> for ModelId<M> {
1355    fn from(k: Key) -> Self {
1356        ModelId::from_handle(k.handle())
1357    }
1358}
1359impl<M: ?Sized> From<&Key> for ModelId<M> {
1360    fn from(k: &Key) -> Self {
1361        ModelId::from_handle(k.handle())
1362    }
1363}
1364
1365// ---------------------------------------------------------------------------
1366// Keyed collections
1367// ---------------------------------------------------------------------------
1368
1369/// Gives an element the stable key its paths are addressed by. Implemented by
1370/// `#[derive(Observable)]` from the `#[obs(key)]` field.
1371pub trait Identified {
1372    /// The element's key, read from the `#[obs(key)]` field.
1373    fn key(&self) -> Key;
1374
1375    /// The key as its path handle: identity for `u64` keys, interned otherwise.
1376    fn handle(&self) -> u64 {
1377        self.key().handle()
1378    }
1379
1380    /// The typed id over the same handle. (Named to stay clear of the generated accessor for
1381    /// an `id` field, which nearly every model has.)
1382    fn model_id(&self) -> ModelId<Self>
1383    where
1384        Self: Sized,
1385    {
1386        ModelId::from_handle(self.handle())
1387    }
1388}
1389
1390/// A keyed collection that keeps its own key→index map, so an element read is O(1) rather than
1391/// a scan, and no caller can forget to maintain the map, because the collection does it.
1392pub struct Keyed<T> {
1393    items: Vec<T>,
1394    index: HashMap<u64, usize>,
1395    /// Set when raw access ([`Keyed::items_mut`]) may have invalidated the map. The mutating
1396    /// methods keep it correct themselves, so the O(n) rebuild happens only where a caller
1397    /// reached past them, which is what keeps a bulk insert O(n) rather than O(n²).
1398    stale: bool,
1399}
1400
1401impl<T: Identified> Default for Keyed<T> {
1402    fn default() -> Self {
1403        Keyed {
1404            items: Vec::new(),
1405            index: HashMap::new(),
1406            stale: false,
1407        }
1408    }
1409}
1410
1411impl<T: Identified> Keyed<T> {
1412    #[must_use]
1413    pub fn new(items: Vec<T>) -> Self {
1414        let mut k = Keyed {
1415            items,
1416            index: HashMap::new(),
1417            stale: false,
1418        };
1419        k.reindex();
1420        k
1421    }
1422
1423    /// Rebuild the map. O(n); integer keys pay no interner cost here, wide keys pay one
1424    /// read-locked lookup per row.
1425    pub fn reindex(&mut self) {
1426        self.index.clear();
1427        for (i, item) in self.items.iter().enumerate() {
1428            self.index.insert(item.handle(), i);
1429        }
1430        self.stale = false;
1431    }
1432
1433    /// Rebuild only if raw access may have invalidated the map: what [`Store::restructure`]
1434    /// calls, so appending a row stays O(1) instead of rebuilding the whole index per insert.
1435    pub fn reindex_if_stale(&mut self) {
1436        if self.stale {
1437            self.reindex();
1438        }
1439    }
1440
1441    #[must_use]
1442    pub fn get(&self, key: u64) -> Option<&T> {
1443        self.index.get(&key).and_then(|i| self.items.get(*i))
1444    }
1445
1446    pub fn get_mut(&mut self, key: u64) -> Option<&mut T> {
1447        match self.index.get(&key) {
1448            Some(i) => self.items.get_mut(*i),
1449            None => None,
1450        }
1451    }
1452
1453    #[must_use]
1454    pub fn keys(&self) -> Vec<u64> {
1455        self.items.iter().map(Identified::handle).collect()
1456    }
1457
1458    #[must_use]
1459    pub fn items(&self) -> &[T] {
1460        &self.items
1461    }
1462
1463    #[must_use]
1464    pub fn len(&self) -> usize {
1465        self.items.len()
1466    }
1467
1468    #[must_use]
1469    pub fn is_empty(&self) -> bool {
1470        self.items.is_empty()
1471    }
1472
1473    /// The next free integer key: one past the largest in use (1 for an empty collection), or
1474    /// the lowest unused key from 1 once that would reach the top bit integer keys reserve
1475    /// (see [`AsKey`]). Interned keys (`Uuid`, `Str`, `Pair`) are not counted.
1476    #[must_use]
1477    pub fn next_key(&self) -> u64 {
1478        let used = || {
1479            self.items
1480                .iter()
1481                .map(Identified::handle)
1482                .filter(|h| (1..WIDE_BASE).contains(h))
1483        };
1484        match used().max() {
1485            None => 1,
1486            Some(max) if max + 1 < WIDE_BASE => max + 1,
1487            Some(_) => {
1488                let mut keys: Vec<u64> = used().collect();
1489                keys.sort_unstable();
1490                // A sorted run of distinct keys from 1 first skips a value where
1491                // `keys[i] != i + 1`.
1492                let gap = keys.iter().zip(1u64..).find(|(k, want)| **k != *want);
1493                gap.map_or(keys.len() as u64 + 1, |(_, want)| want)
1494            }
1495        }
1496    }
1497
1498    // --- structural operations: each leaves the index correct ---------------------------------
1499
1500    pub fn push(&mut self, item: T) {
1501        self.index.insert(item.handle(), self.items.len());
1502        self.items.push(item);
1503    }
1504
1505    pub fn remove(&mut self, key: u64) -> Option<T> {
1506        let i = self.index.remove(&key)?;
1507        let item = self.items.remove(i);
1508        self.reindex();
1509        Some(item)
1510    }
1511
1512    pub fn move_item(&mut self, from: usize, to: usize) {
1513        if from >= self.items.len() || to >= self.items.len() {
1514            return;
1515        }
1516        let item = self.items.remove(from);
1517        self.items.insert(to, item);
1518        self.reindex();
1519    }
1520
1521    /// Remove every row. What a reload wants before pushing the new set, in one call rather
1522    /// than a [`Keyed::remove`] (and a reindex) per key.
1523    pub fn clear(&mut self) {
1524        self.items.clear();
1525        self.index.clear();
1526        self.stale = false;
1527    }
1528
1529    /// The raw list, for a structural edit inside [`Store::restructure`] that the helpers above
1530    /// do not cover. Taking it marks the key map stale, so the store rebuilds it after the
1531    /// caller's closure returns; the helpers above stay index-correct on their own and pay
1532    /// nothing for this.
1533    pub fn items_mut(&mut self) -> &mut Vec<T> {
1534        self.stale = true;
1535        &mut self.items
1536    }
1537}
1538
1539// ---------------------------------------------------------------------------
1540// Elements
1541// ---------------------------------------------------------------------------
1542
1543/// One element of a keyed store, addressed by a key that survives reordering.
1544pub struct Elem<T: 'static> {
1545    store: Store<Keyed<T>>,
1546    key: u64,
1547    /// Interned once per handle, not once per field read; revalidated on use.
1548    node: NodeId,
1549}
1550
1551impl<T> Clone for Elem<T> {
1552    fn clone(&self) -> Self {
1553        *self
1554    }
1555}
1556impl<T> Copy for Elem<T> {}
1557
1558impl<T: Identified + 'static> Store<Keyed<T>> {
1559    /// One element, addressed by its id: a [`ModelId`], a raw handle from [`Store::keys`],
1560    /// an integer key, a `Uuid`, or a string key all convert. O(1), because the collection keeps a
1561    /// handle→index map.
1562    pub fn elem(self, key: impl Into<ModelId<T>>) -> Elem<T> {
1563        let key = key.into().handle();
1564        Elem {
1565            store: self,
1566            key,
1567            node: intern(Path::under(self.node, key)),
1568        }
1569    }
1570
1571    /// Tracked read of the collection's shape (which keys, in what order): what a list widget
1572    /// wants. A field write does not wake it; an insert, a removal or a reorder does.
1573    #[must_use]
1574    pub fn keys(self) -> Vec<u64> {
1575        track(Path::under(self.node, STRUCTURE));
1576        self.with_untracked(|k| k.keys().clone())
1577    }
1578
1579    /// [`Store::keys`], typed — the same tracked read, as [`ModelId`]s.
1580    pub fn ids(self) -> Vec<ModelId<T>> {
1581        self.keys().into_iter().map(ModelId::from_handle).collect()
1582    }
1583
1584    /// Structural change: insert, remove, reorder.
1585    ///
1586    /// The affected key and the operation are announced alongside the shape path, because a
1587    /// persistence layer has to choose between an INSERT and a DELETE and cannot infer it from
1588    /// "the shape changed", while the UI, which only re-reads `keys()`, ignores both.
1589    ///
1590    /// # Panics
1591    ///
1592    /// Panics if a thread panicked while holding the store's lock.
1593    pub fn restructure(
1594        self,
1595        label: &'static str,
1596        op: Op,
1597        key: impl Into<ModelId<T>>,
1598        f: impl FnOnce(&mut Keyed<T>),
1599    ) where
1600        T: Clone,
1601    {
1602        let key = key.into().handle();
1603        // When a values consumer stands by (an undo stack), a Delete carries the row it
1604        // removed and an Insert the row it added, each with its index, and a Move its index
1605        // before and after: the whole of what inversion needs (see `Change`).
1606        let capture = values_wanted();
1607        let mut prior: Option<Rc<dyn Any>> = None;
1608        let mut value: Option<Rc<dyn Any>> = None;
1609        {
1610            let mut g = self.inner.data.write().expect("store poisoned");
1611            let index = |k: &Keyed<T>| k.items().iter().position(|t| t.handle() == key);
1612            let before = if capture { index(&g) } else { None };
1613            if capture && op == Op::Delete {
1614                prior = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
1615            }
1616            f(&mut g);
1617            g.reindex_if_stale();
1618            if capture {
1619                let after = index(&g);
1620                let at = |i: Option<usize>| i.map(|i| Rc::new(i) as Rc<dyn Any>);
1621                match op {
1622                    Op::Insert => {
1623                        value = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
1624                        prior = at(after);
1625                    }
1626                    Op::Delete => value = at(before),
1627                    Op::Move => (prior, value) = (at(before), at(after)),
1628                    Op::Set => {}
1629                }
1630            }
1631        }
1632        self.inner.version.fetch_add(1, Ordering::Relaxed);
1633        let root_id = self.root_id;
1634        notify_change(
1635            Path::under(self.node, key),
1636            || vec![root_id, key],
1637            label,
1638            op,
1639            prior,
1640            value,
1641        );
1642        notify_change(
1643            Path::under(self.node, STRUCTURE),
1644            || vec![root_id, STRUCTURE],
1645            label,
1646            op,
1647            None,
1648            None,
1649        );
1650    }
1651
1652    /// Append `item`: the [`Store::restructure`] insert, announced under its own key.
1653    pub fn push(self, item: T)
1654    where
1655        T: Clone,
1656    {
1657        let key = item.handle();
1658        self.restructure("push", Op::Insert, ModelId::from_handle(key), |k| {
1659            k.push(item);
1660        });
1661    }
1662
1663    /// Remove the row with `key`: the [`Store::restructure`] delete. Returns false, announcing
1664    /// nothing, when no such row exists.
1665    pub fn remove(self, key: impl Into<ModelId<T>>) -> bool
1666    where
1667        T: Clone,
1668    {
1669        let key = key.into().handle();
1670        if self.with_untracked(|k| k.get(key).is_none()) {
1671            return false;
1672        }
1673        self.restructure("remove", Op::Delete, ModelId::from_handle(key), |k| {
1674            k.remove(key);
1675        });
1676        true
1677    }
1678
1679    /// Move the row at index `from` to index `to`, the shape a native list's reorder gesture
1680    /// reports. Returns false, announcing nothing, when the move is out of range or in place.
1681    pub fn move_row(self, from: usize, to: usize) -> bool
1682    where
1683        T: Clone,
1684    {
1685        let key = self.with_untracked(|k| {
1686            if from == to || to >= k.len() {
1687                return None;
1688            }
1689            k.items().get(from).map(Identified::handle)
1690        });
1691        let Some(key) = key else { return false };
1692        self.restructure("move", Op::Move, ModelId::from_handle(key), |k| {
1693            k.move_item(from, to);
1694        });
1695        true
1696    }
1697
1698    /// The next free integer key: one past the largest in use, for a model keyed by a `u64`
1699    /// field. Untracked. See [`Keyed::next_key`].
1700    #[must_use]
1701    pub fn next_key(self) -> u64 {
1702        self.with_untracked(Keyed::next_key)
1703    }
1704
1705    /// Feed one row's new value from outside the app's own editing (another connection's
1706    /// committed write arriving through a persistence container, an import), replacing the
1707    /// stored value and announcing each label in `changed` as that field's `Set`. The
1708    /// announcement is precise: readers of the named fields wake, along with everything
1709    /// coarser, where a wholesale [`Store::update`] wakes only readers of the store itself.
1710    /// The announcements carry no values (a background transaction's shape) and the current
1711    /// author tag; wrap the call in [`with_author`] so consumers can tell the merge from the
1712    /// user's own edits. Returns false, announcing nothing, when the row is absent: an absent
1713    /// row is an insert, which is [`Store::restructure`]'s job.
1714    ///
1715    /// # Panics
1716    ///
1717    /// Panics if a thread panicked while holding the store's lock.
1718    pub fn merge_row(self, key: impl Into<ModelId<T>>, value: T, changed: &[&'static str]) -> bool
1719    where
1720        T: Clone,
1721    {
1722        let key = key.into().handle();
1723        {
1724            let mut g = self.inner.data.write().expect("store poisoned");
1725            match g.get_mut(key) {
1726                Some(slot) => *slot = value,
1727                None => return false,
1728            }
1729        }
1730        self.inner.version.fetch_add(1, Ordering::Relaxed);
1731        let elem = intern(Path::under(self.node, key));
1732        let root_id = self.root_id;
1733        for &label in changed {
1734            notify_change(
1735                Path::under(elem, field_id(label)),
1736                || vec![root_id, key, field_id(label)],
1737                label,
1738                Op::Set,
1739                None,
1740                None,
1741            );
1742        }
1743        true
1744    }
1745
1746    /// Write one field by label: front-door semantics (announced at the field's own path,
1747    /// prior/new values captured while a consumer wants them, undoable, persisted) without
1748    /// the generated accessor in scope. The relation machinery writes foreign keys and order
1749    /// values through this; it is public because any framework-level maintenance faces the
1750    /// same need. Returns false, announcing nothing, when the row is absent or when
1751    /// `label`/`V` name no field of `T` (the [`ApplyField`] downcast refused).
1752    ///
1753    /// # Panics
1754    ///
1755    /// Panics if a thread panicked while holding the store's lock.
1756    pub fn write_field<V: Clone + 'static>(
1757        self,
1758        key: impl Into<ModelId<T>>,
1759        label: &'static str,
1760        value: V,
1761    ) -> bool
1762    where
1763        T: ApplyField,
1764    {
1765        let key = key.into().handle();
1766        let capture = values_wanted() && !previewing();
1767        let mut prior: Option<Rc<dyn Any>> = None;
1768        let ok = {
1769            let mut g = self.inner.data.write().expect("store poisoned");
1770            match g.get_mut(key) {
1771                Some(t) => {
1772                    if capture {
1773                        prior = t.read_field(label);
1774                    }
1775                    t.apply_field(label, &value)
1776                }
1777                None => false,
1778            }
1779        };
1780        if !ok {
1781            return false;
1782        }
1783        self.inner.version.fetch_add(1, Ordering::Relaxed);
1784        let elem = intern(Path::under(self.node, key));
1785        let after: Option<Rc<dyn Any>> = if capture { Some(Rc::new(value)) } else { None };
1786        let root_id = self.root_id;
1787        notify_change(
1788            Path::under(elem, field_id(label)),
1789            || vec![root_id, key, field_id(label)],
1790            label,
1791            Op::Set,
1792            prior,
1793            after,
1794        );
1795        true
1796    }
1797
1798    /// Insert-or-replace rows without announcing: the persistence layer faulting stored rows
1799    /// into its cache. No change record is born (sinks, undo and autosave all stay quiet: the
1800    /// rows are the database's own contents arriving, not edits), and no trigger wakes: a
1801    /// faulting read populates before anything binds, so there is nobody to wake yet. The
1802    /// version still bumps, so version-watching tests see the population.
1803    ///
1804    /// # Panics
1805    ///
1806    /// Panics if a thread panicked while holding the store's lock.
1807    pub fn populate(self, rows: Vec<T>) {
1808        {
1809            let mut g = self.inner.data.write().expect("store poisoned");
1810            for row in rows {
1811                let key = row.handle();
1812                match g.get_mut(key) {
1813                    Some(slot) => *slot = row,
1814                    None => g.push(row),
1815                }
1816            }
1817        }
1818        self.inner.version.fetch_add(1, Ordering::Relaxed);
1819    }
1820
1821    /// Remove one row without announcing: the persistence layer evicting a clean cached row.
1822    /// The row is not deleted anywhere; it stops being resident, and a later fault
1823    /// brings it back. Callers guard with [`Store::is_observed`]: evicting a row something is
1824    /// bound to would flip that binding to its `Default` with no wakeup to correct it.
1825    ///
1826    /// # Panics
1827    ///
1828    /// Panics if a thread panicked while holding the store's lock.
1829    pub fn depopulate(self, key: impl Into<ModelId<T>>) -> bool {
1830        let key = key.into().handle();
1831        let removed = {
1832            let mut g = self.inner.data.write().expect("store poisoned");
1833            g.remove(key).is_some()
1834        };
1835        if removed {
1836            self.inner.version.fetch_add(1, Ordering::Relaxed);
1837        }
1838        removed
1839    }
1840
1841    /// [`Store::depopulate`], batched: One retain and one reindex for the whole set, where
1842    /// per-key removal would rebuild the key map per row, the difference between an eviction
1843    /// pass costing O(cache) and O(cache × evicted). Returns how many rows left.
1844    ///
1845    /// # Panics
1846    ///
1847    /// Panics if a thread panicked while holding the store's lock.
1848    pub fn depopulate_many(self, keys: &[u64]) -> usize {
1849        if keys.is_empty() {
1850            return 0;
1851        }
1852        let set: std::collections::HashSet<u64> = keys.iter().copied().collect();
1853        let removed = {
1854            let mut g = self.inner.data.write().expect("store poisoned");
1855            let before = g.len();
1856            g.items_mut().retain(|item| !set.contains(&item.handle()));
1857            g.reindex_if_stale();
1858            before - g.len()
1859        };
1860        if removed > 0 {
1861            self.inner.version.fetch_add(1, Ordering::Relaxed);
1862        }
1863        removed
1864    }
1865
1866    /// Release all row payloads after an owning database queue has permanently closed.
1867    /// This sends no notifications: callers must first detach every observer and undo history.
1868    /// Handles remain allocated (Store is Copy), but large row data and indexes are reclaimed.
1869    /// Poisoned data is discarded too; a failed worker must never retain its working set.
1870    #[doc(hidden)]
1871    pub fn dispose_contents(self) {
1872        let old = {
1873            let mut data = self
1874                .inner
1875                .data
1876                .write()
1877                .unwrap_or_else(std::sync::PoisonError::into_inner);
1878            std::mem::replace(&mut *data, Keyed::new(Vec::new()))
1879        };
1880        // User row destructors may re-enter other code. Do not run them under the data lock.
1881        drop(old);
1882    }
1883
1884    /// Whether anything currently observes this element: a trigger on the element's own path,
1885    /// or on any path under it (a bound field, a nested struct). The eviction guard: a row
1886    /// nobody observes can leave the cache silently, because the next reader faults it back.
1887    pub fn is_observed(self, key: impl Into<ModelId<T>>) -> bool {
1888        let key = key.into().handle();
1889        let elem = Path::under(self.node, key);
1890        if TRIGGERS.with(|t| t.borrow().contains_key(&elem)) {
1891            return true;
1892        }
1893        NODES.with(|n| {
1894            let i = n.borrow();
1895            match i.lookup.get(&elem) {
1896                Some(id) => match i.slots.get(id.idx as usize) {
1897                    Some(s) if s.alive && s.generation == id.generation => {
1898                        s.triggers > 0 || s.children > 0
1899                    }
1900                    _ => false,
1901                },
1902                None => false,
1903            }
1904        })
1905    }
1906}
1907
1908impl<T: Identified + 'static> Elem<T> {
1909    /// The path handle this element addresses: the raw form of [`Elem::model_id`].
1910    #[must_use]
1911    pub fn key(self) -> u64 {
1912        self.key
1913    }
1914
1915    /// The element's typed id. (Named to stay clear of the `id` field accessor an inherent
1916    /// `id()` would shadow on every model that has one.)
1917    #[must_use]
1918    pub fn model_id(self) -> ModelId<T> {
1919        ModelId::from_handle(self.key)
1920    }
1921
1922    /// Whether the row is (still) present. Tracked, so a guard re-runs when the row is deleted
1923    /// or comes back. This is the deletion story: reads of a gone row return the field's
1924    /// `Default`, and this is the one signal a page needs to degrade instead.
1925    #[must_use]
1926    pub fn exists(self) -> bool {
1927        track(self.path());
1928        self.with_value_untracked(|v| v.is_some())
1929    }
1930
1931    /// The cached id when still live, a fresh interning otherwise: the self-healing described
1932    /// in the module docs.
1933    fn live_node(self) -> NodeId {
1934        if is_current(self.node) {
1935            self.node
1936        } else {
1937            intern(Path::under(self.store.node, self.key))
1938        }
1939    }
1940}
1941
1942impl<T: Identified + 'static> Source<T> for Elem<T> {
1943    fn path(self) -> Path {
1944        // The store root is pinned, so this Path is stable across reclamation.
1945        Path::under(self.store.node, self.key)
1946    }
1947    fn node(self) -> NodeId {
1948        self.live_node()
1949    }
1950    fn components(self, out: &mut Vec<u64>) {
1951        self.store.components(out);
1952        out.push(self.key);
1953    }
1954    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
1955        let g = self.store.inner.data.read().expect("store poisoned");
1956        f(g.get(self.key))
1957    }
1958    fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
1959        let mut g = self.store.inner.data.write().expect("store poisoned");
1960        match g.get_mut(self.key) {
1961            Some(t) => {
1962                f(t);
1963                true
1964            }
1965            None => false,
1966        }
1967    }
1968    fn bump_version(self) {
1969        self.store.inner.version.fetch_add(1, Ordering::Relaxed);
1970    }
1971}
1972
1973// ---------------------------------------------------------------------------
1974// Fields
1975// ---------------------------------------------------------------------------
1976
1977/// One field, projected out of any [`Source`]. `Copy`, itself a `Source` (so fields nest), and a
1978/// [`Binding`] (so every control binds to it).
1979pub struct Field<S, T: 'static, V: 'static> {
1980    src: S,
1981    path: Path,
1982    part: u64,
1983    label: &'static str,
1984    get: fn(&T) -> &V,
1985    get_mut: fn(&mut T) -> &mut V,
1986}
1987
1988impl<S: Copy, T, V> Clone for Field<S, T, V> {
1989    fn clone(&self) -> Self {
1990        *self
1991    }
1992}
1993impl<S: Copy, T, V> Copy for Field<S, T, V> {}
1994
1995/// What the derive calls. Named `project` rather than `field` so a struct may have a field
1996/// called `field` without a collision.
1997pub fn project<S: Source<T>, T: 'static, V: 'static>(
1998    src: S,
1999    label: &'static str,
2000    get: fn(&T) -> &V,
2001    get_mut: fn(&mut T) -> &mut V,
2002) -> Field<S, T, V> {
2003    let part = field_id(label);
2004    Field {
2005        src,
2006        // No interning here: this is the per-read path, and the parent is already an id.
2007        path: Path::under(src.node(), part),
2008        part,
2009        label,
2010        get,
2011        get_mut,
2012    }
2013}
2014
2015impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
2016    /// The cached path when its parent is still live, a rebuilt one otherwise. A dynamic
2017    /// source (a recycled slot) never trusts the cache: its location is wherever the source
2018    /// says it is right now.
2019    fn live_path(self) -> Path {
2020        if !S::DYNAMIC && is_current(self.path.parent) {
2021            self.path
2022        } else {
2023            Path::under(self.src.node(), self.part)
2024        }
2025    }
2026
2027    /// Tracked read of this field only.
2028    pub fn with<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
2029        self.src.track_extra();
2030        track(self.live_path());
2031        self.src.with_value_untracked(|t| f(t.map(self.get)))
2032    }
2033
2034    pub fn with_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
2035        self.src.with_value_untracked(|t| f(t.map(self.get)))
2036    }
2037
2038    /// Write, waking readers of this field and of anything coarser. When a change-log consumer
2039    /// asked for values ([`record_values`]), the slot's prior and new value ride along.
2040    pub fn update(self, f: impl FnOnce(&mut V))
2041    where
2042        V: Clone,
2043    {
2044        let capture = values_wanted() && !previewing();
2045        let mut prior: Option<Rc<dyn Any>> = None;
2046        let mut after: Option<Rc<dyn Any>> = None;
2047        let get_mut = self.get_mut;
2048        let ok = self.src.update_value(|t| {
2049            let slot = get_mut(t);
2050            if capture {
2051                prior = Some(Rc::new(slot.clone()));
2052            }
2053            f(slot);
2054            if capture {
2055                after = Some(Rc::new(slot.clone()));
2056            }
2057        });
2058        if ok {
2059            self.src.bump_version();
2060            notify_change(
2061                self.live_path(),
2062                || {
2063                    let mut parts = Vec::new();
2064                    Source::<V>::components(self, &mut parts);
2065                    parts
2066                },
2067                self.label,
2068                Op::Set,
2069                prior,
2070                after,
2071            );
2072        }
2073    }
2074
2075    /// Name this field inside a background transaction. Portable: what is queued is the path's
2076    /// components, which the main thread re-establishes on its own side when it announces.
2077    pub fn touch(self, tx: &mut TxPaths) {
2078        let mut parts = Vec::new();
2079        Source::<V>::components(self, &mut parts);
2080        tx.push((parts, self.label));
2081    }
2082
2083    pub fn path(self) -> Path {
2084        self.live_path()
2085    }
2086
2087    pub fn label(self) -> &'static str {
2088        self.label
2089    }
2090}
2091
2092/// A field is itself a source, so `item.address().city()` works.
2093impl<S: Source<T>, T: 'static, V: 'static> Source<V> for Field<S, T, V> {
2094    // Nesting inherits the source's dynamism: a field of a slot's struct field still rides the
2095    // slot's current row.
2096    const DYNAMIC: bool = S::DYNAMIC;
2097    fn track_extra(self) {
2098        self.src.track_extra();
2099    }
2100    fn path(self) -> Path {
2101        self.live_path()
2102    }
2103    /// Interning happens here and only here: when a field is used as a parent, which is what
2104    /// nesting one struct inside another means.
2105    fn node(self) -> NodeId {
2106        intern(self.live_path())
2107    }
2108    fn components(self, out: &mut Vec<u64>) {
2109        self.src.components(out);
2110        out.push(self.part);
2111    }
2112    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
2113        self.with_untracked(f)
2114    }
2115    fn update_value(self, f: impl FnOnce(&mut V)) -> bool {
2116        let get_mut = self.get_mut;
2117        self.src.update_value(|t| f(get_mut(t)))
2118    }
2119    fn bump_version(self) {
2120        self.src.bump_version();
2121    }
2122}
2123
2124/// A field is a two-way binding: every control takes one, unchanged.
2125impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Binding<V> for Field<S, T, V> {
2126    fn read(&self) -> V {
2127        self.with(|v| v.cloned().unwrap_or_default())
2128    }
2129    fn peek(&self) -> V {
2130        self.with_untracked(|v| v.cloned().unwrap_or_default())
2131    }
2132    fn write(&self, v: V) {
2133        self.update(move |slot| *slot = v);
2134    }
2135    fn write_preview(&self, v: V) {
2136        Field::write_preview(*self, v);
2137    }
2138    fn write_commit(&self, v: V) {
2139        Field::write_commit(*self, v);
2140    }
2141    fn end_preview(&self) {
2142        Field::end_preview(*self);
2143    }
2144}
2145
2146// ---------------------------------------------------------------------------
2147// Conversions
2148// ---------------------------------------------------------------------------
2149
2150/// A converted view of a field: an ISO string as a date, `#RRGGBB` as a color, an index into a
2151/// table as the value it names. `Copy`, and still a binding, so it goes straight into a control.
2152pub struct Mapped<F, V: 'static, U: 'static> {
2153    inner: F,
2154    to: fn(&V) -> U,
2155    from: fn(&U) -> V,
2156    /// The mapped-over field's own label, so a converted write still names its column in the
2157    /// change log (a literal "mapped" would be invisible to the SQL fold).
2158    label: &'static str,
2159}
2160
2161impl<F: Copy, V, U> Clone for Mapped<F, V, U> {
2162    fn clone(&self) -> Self {
2163        *self
2164    }
2165}
2166impl<F: Copy, V, U> Copy for Mapped<F, V, U> {}
2167
2168impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
2169    /// Read this field through `to`, write it back through `from`. Both are fn pointers, so the
2170    /// result stays `Copy`.
2171    pub fn map<U: 'static>(self, to: fn(&V) -> U, from: fn(&U) -> V) -> Mapped<Self, V, U> {
2172        Mapped {
2173            inner: self,
2174            to,
2175            from,
2176            label: self.label,
2177        }
2178    }
2179}
2180
2181/// The missing case converts the stored type's default rather than requiring the UI type to have
2182/// one: a `Color` has no `Default`, and asking every converted type for one would be a tax paid
2183/// by every caller for a case only a deleted row reaches.
2184impl<F: Source<V>, V: Clone + Default + 'static, U: Clone + 'static> Binding<U>
2185    for Mapped<F, V, U>
2186{
2187    fn read(&self) -> U {
2188        self.inner.track_extra();
2189        track(self.inner.path());
2190        self.peek()
2191    }
2192    fn peek(&self) -> U {
2193        self.inner.with_value_untracked(|v| match v {
2194            Some(v) => (self.to)(v),
2195            None => (self.to)(&V::default()),
2196        })
2197    }
2198    fn write_preview(&self, u: U) {
2199        let v = (self.from)(&u);
2200        let inner = self.inner;
2201        let mut parts = Vec::new();
2202        inner.components(&mut parts);
2203        PREVIEWS.with(|p| {
2204            p.borrow_mut().entry(parts).or_insert_with(|| {
2205                Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()))
2206            });
2207        });
2208        PREVIEW_WRITE.with(|f| f.set(true));
2209        let ok = inner.update_value(|slot| *slot = v);
2210        if ok {
2211            inner.bump_version();
2212            notify_change(inner.path(), Vec::new, self.label, Op::Set, None, None);
2213        }
2214        PREVIEW_WRITE.with(|f| f.set(false));
2215    }
2216    fn end_preview(&self) {
2217        let mut parts = Vec::new();
2218        self.inner.components(&mut parts);
2219        PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2220    }
2221    fn write_commit(&self, u: U) {
2222        let inner = self.inner;
2223        let mut parts = Vec::new();
2224        inner.components(&mut parts);
2225        let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2226        match open {
2227            None => self.write(u),
2228            Some(prior) => {
2229                let v = (self.from)(&u);
2230                PREVIEW_WRITE.with(|f| f.set(true));
2231                let ok = inner.update_value(|slot| *slot = v);
2232                PREVIEW_WRITE.with(|f| f.set(false));
2233                if ok {
2234                    inner.bump_version();
2235                    let after: Rc<dyn Any> =
2236                        Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()));
2237                    notify_change(
2238                        inner.path(),
2239                        || parts,
2240                        self.label,
2241                        Op::Set,
2242                        Some(prior),
2243                        Some(after),
2244                    );
2245                }
2246            }
2247        }
2248    }
2249    fn write(&self, u: U) {
2250        let v = (self.from)(&u);
2251        let inner = self.inner;
2252        let capture = values_wanted();
2253        let mut prior: Option<Rc<dyn Any>> = None;
2254        let mut after: Option<Rc<dyn Any>> = None;
2255        let ok = inner.update_value(|slot| {
2256            if capture {
2257                prior = Some(Rc::new(slot.clone()));
2258            }
2259            *slot = v;
2260            if capture {
2261                after = Some(Rc::new(slot.clone()));
2262            }
2263        });
2264        if ok {
2265            inner.bump_version();
2266            notify_change(
2267                inner.path(),
2268                || {
2269                    let mut parts = Vec::new();
2270                    inner.components(&mut parts);
2271                    parts
2272                },
2273                self.label,
2274                Op::Set,
2275                prior,
2276                after,
2277            );
2278        }
2279    }
2280}
2281
2282impl<F: Source<V> + Copy, V: 'static> Mapped<F, V, usize> {
2283    /// `usize` as the `f64` a slider speaks: the adapter every numeric control needs somewhere.
2284    pub fn map_to_f64(self) -> Numeric<Self> {
2285        Numeric { inner: self }
2286    }
2287}
2288
2289/// `usize` ⇄ `f64`.
2290pub struct Numeric<M> {
2291    inner: M,
2292}
2293
2294#[expect(
2295    clippy::expl_impl_clone_on_copy,
2296    reason = "a derive would widen `Clone` to non-`Copy` bindings; this keeps the public bounds"
2297)]
2298impl<M: Copy> Clone for Numeric<M> {
2299    fn clone(&self) -> Self {
2300        *self
2301    }
2302}
2303impl<M: Copy> Copy for Numeric<M> {}
2304
2305impl<M: Binding<usize> + Copy + 'static> Binding<f64> for Numeric<M> {
2306    fn read(&self) -> f64 {
2307        self.inner.read() as f64
2308    }
2309    fn peek(&self) -> f64 {
2310        self.inner.peek() as f64
2311    }
2312    fn write(&self, v: f64) {
2313        self.inner.write(v.round().max(0.0) as usize);
2314    }
2315}
2316
2317// ---------------------------------------------------------------------------
2318// Preview sessions (docs/model.md): the write-side of ValueChanged / ValueCommitted
2319// ---------------------------------------------------------------------------
2320
2321impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Field<S, T, V> {
2322    /// A live write: the value lands and this field's readers wake (a label tracking a
2323    /// dragged slider follows), but no change record is born, so autosave, the undo stack and
2324    /// every sink stay quiet. The first preview since the last commit captures the
2325    /// pre-session value; [`Field::write_commit`] turns the whole gesture into one record.
2326    pub fn write_preview(self, v: V) {
2327        let mut parts = Vec::new();
2328        Source::<V>::components(self, &mut parts);
2329        PREVIEWS.with(|p| {
2330            p.borrow_mut().entry(parts).or_insert_with(|| {
2331                Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()))
2332            });
2333        });
2334        PREVIEW_WRITE.with(|f| f.set(true));
2335        self.update(move |slot| *slot = v);
2336        PREVIEW_WRITE.with(|f| f.set(false));
2337    }
2338
2339    /// The settled value that ends a preview sequence: applies `v`, then announces one change
2340    /// whose prior is the pre-session value, so sixty thumb positions become one record, one
2341    /// undo unit, one UPDATE. Without an open session this is a plain [`Binding::write`].
2342    pub fn write_commit(self, v: V) {
2343        let mut parts = Vec::new();
2344        Source::<V>::components(self, &mut parts);
2345        let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2346        // A session whose row was deleted meanwhile (a field torn down with its row) ends
2347        // here with nothing to record: there is no value left for the change to describe.
2348        let open = open.filter(|_| self.with_untracked(|s| s.is_some()));
2349        match open {
2350            None => self.update(move |slot| *slot = v),
2351            Some(prior) => {
2352                PREVIEW_WRITE.with(|f| f.set(true));
2353                self.update(move |slot| *slot = v);
2354                PREVIEW_WRITE.with(|f| f.set(false));
2355                let after: Rc<dyn Any> =
2356                    Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()));
2357                notify_change(
2358                    self.live_path(),
2359                    || parts,
2360                    self.label,
2361                    Op::Set,
2362                    Some(prior),
2363                    Some(after),
2364                );
2365            }
2366        }
2367    }
2368
2369    /// Close an open preview session without a record (`Binding::end_preview`): an app write
2370    /// replaced what the gesture previewed and recorded its own change, so the session's
2371    /// pre-gesture value no longer describes the field. The next preview captures the current
2372    /// value as its prior. Without an open session this does nothing.
2373    pub fn end_preview(self) {
2374        let mut parts = Vec::new();
2375        Source::<V>::components(self, &mut parts);
2376        PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2377    }
2378
2379    /// The explicit session handle, for custom pieces and programmatic gestures; bindings
2380    /// drive [`Field::write_preview`]/[`Field::write_commit`] on their own.
2381    pub fn session(self) -> FieldSession<S, T, V> {
2382        FieldSession { field: self }
2383    }
2384}
2385
2386/// An explicit preview session over one field (see [`Field::session`]). `Copy`, like the
2387/// field itself.
2388pub struct FieldSession<S: 'static, T: 'static, V: 'static> {
2389    field: Field<S, T, V>,
2390}
2391
2392impl<S: Copy, T, V> Clone for FieldSession<S, T, V> {
2393    fn clone(&self) -> Self {
2394        *self
2395    }
2396}
2397impl<S: Copy, T, V> Copy for FieldSession<S, T, V> {}
2398
2399impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> FieldSession<S, T, V> {
2400    pub fn preview(self, v: V) {
2401        self.field.write_preview(v);
2402    }
2403    /// Seal the session at the current value.
2404    pub fn commit(self) {
2405        let v = self
2406            .field
2407            .with_untracked(|s| s.cloned().unwrap_or_default());
2408        self.field.write_commit(v);
2409    }
2410    /// Abandon the session: the pre-session value comes back (readers wake), and no record of
2411    /// any of it exists (what Escape does).
2412    pub fn cancel(self) {
2413        let mut parts = Vec::new();
2414        Source::<V>::components(self.field, &mut parts);
2415        if let Some(prior) = PREVIEWS.with(|p| p.borrow_mut().remove(&parts))
2416            && let Ok(prior) = prior.downcast::<V>()
2417        {
2418            self.field.write_preview((*prior).clone());
2419            // The restore write re-opened a session pointing at itself; drop it.
2420            let mut parts = Vec::new();
2421            Source::<V>::components(self.field, &mut parts);
2422            PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2423        }
2424    }
2425}
2426
2427// ---------------------------------------------------------------------------
2428// Undo (docs/model.md): the change log read backward
2429// ---------------------------------------------------------------------------
2430
2431/// Write one captured field value back into a struct, by label. Implemented by
2432/// `#[derive(Observable)]`; this trait is how a type-erased undo unit re-enters the
2433/// store it came from.
2434pub trait ApplyField {
2435    fn apply_field(&mut self, label: &str, value: &dyn Any) -> bool;
2436
2437    /// The field's current value, cloned and type-erased; `None` for an unknown label. The
2438    /// derive implements it; [`Store::write_field`] captures priors through it.
2439    fn read_field(&self, label: &str) -> Option<Rc<dyn Any>> {
2440        let _ = label;
2441        None
2442    }
2443}
2444
2445type SetFieldFn = Rc<dyn Fn(u64, &'static str, &Rc<dyn Any>) -> bool>;
2446type InsertRowFn = Rc<dyn Fn(u64, &Rc<dyn Any>, Option<usize>) -> bool>;
2447
2448struct StoreOps {
2449    set_field: SetFieldFn,
2450    insert_row: InsertRowFn,
2451    remove_row: Rc<dyn Fn(u64) -> bool>,
2452    move_row: Rc<dyn Fn(u64, usize) -> bool>,
2453}
2454
2455#[derive(Clone)]
2456struct UndoUnit {
2457    label: &'static str,
2458    changes: Vec<Change>,
2459    /// Transient UI state as of this unit's seal ([`UndoStack::set_transient_context`]);
2460    /// `None` for a unit sealed with no hook installed. Never persisted.
2461    context: Option<Rc<dyn Any>>,
2462}
2463
2464/// A restore closure over one captured snapshot ([`UndoStack::set_transient_context`]).
2465type ContextRestore = Rc<dyn Fn(&dyn Any)>;
2466
2467/// The app's transient-context hook ([`UndoStack::set_transient_context`]).
2468struct ContextHook {
2469    capture: Rc<dyn Fn() -> Rc<dyn Any>>,
2470    restore: ContextRestore,
2471    /// The state before any unit: what undoing the whole history restores.
2472    base: Rc<dyn Any>,
2473}
2474
2475#[derive(Clone, Copy, PartialEq)]
2476enum Replay {
2477    No,
2478    Undoing,
2479    Redoing,
2480}
2481
2482struct UndoInner {
2483    levels: usize,
2484    undo: RefCell<std::collections::VecDeque<UndoUnit>>,
2485    redo: RefCell<Vec<UndoUnit>>,
2486    open: RefCell<Vec<Change>>,
2487    group_label: Cell<Option<&'static str>>,
2488    grouping: Cell<usize>,
2489    replaying: Cell<Replay>,
2490    ops: RefCell<HashMap<u64, StoreOps>>,
2491    can_undo: day_reactive::Signal<bool>,
2492    can_redo: day_reactive::Signal<bool>,
2493    undo_label: day_reactive::Signal<String>,
2494    redo_label: day_reactive::Signal<String>,
2495    resolver: RefCell<Rc<dyn Fn(&'static str) -> String>>,
2496    sink: Cell<Option<ChangeSinkId>>,
2497    context: RefCell<Option<ContextHook>>,
2498}
2499
2500/// One undo history over the stores it [`UndoStack::watch`]es: units are turns (everything one
2501/// event's dispatch changed), inverted, not snapshots. Enabling it turns on standing value
2502/// capture; drop the stack and the capture stops.
2503#[derive(Clone)]
2504pub struct UndoStack {
2505    inner: Rc<UndoInner>,
2506}
2507
2508/// Queue-confined history checkpoint for a persistence transaction. Restore it only after
2509/// rolling back the corresponding model changes. It does not snapshot the models themselves.
2510pub struct UndoCheckpoint {
2511    undo: std::collections::VecDeque<UndoUnit>,
2512    redo: Vec<UndoUnit>,
2513    open: Vec<Change>,
2514}
2515
2516/// RAII lifetime of an undo group; dropping the last nested guard seals its changes.
2517#[must_use = "keep the group alive until the interaction finishes"]
2518pub struct UndoGroup {
2519    stack: UndoStack,
2520}
2521
2522impl Drop for UndoGroup {
2523    fn drop(&mut self) {
2524        let depth = self.stack.inner.grouping.get() - 1;
2525        self.stack.inner.grouping.set(depth);
2526        if depth == 0 {
2527            self.stack.seal();
2528            // Empty groups must not lend their label to the next unrelated edit.
2529            self.stack.inner.group_label.set(None);
2530        }
2531    }
2532}
2533
2534impl UndoStack {
2535    /// A stack holding at most `levels` units: the bound on what history keeps in RAM.
2536    #[must_use]
2537    pub fn new(levels: usize) -> UndoStack {
2538        let (can_undo, can_redo, undo_label, redo_label) =
2539            day_reactive::Scope::detached().enter(|| {
2540                (
2541                    day_reactive::Signal::new(false),
2542                    day_reactive::Signal::new(false),
2543                    day_reactive::Signal::new(String::new()),
2544                    day_reactive::Signal::new(String::new()),
2545                )
2546            });
2547        let stack = UndoStack {
2548            inner: Rc::new(UndoInner {
2549                levels: levels.max(1),
2550                undo: RefCell::new(std::collections::VecDeque::new()),
2551                redo: RefCell::new(Vec::new()),
2552                open: RefCell::new(Vec::new()),
2553                group_label: Cell::new(None),
2554                grouping: Cell::new(0),
2555                replaying: Cell::new(Replay::No),
2556                ops: RefCell::new(HashMap::new()),
2557                can_undo,
2558                can_redo,
2559                undo_label,
2560                redo_label,
2561                resolver: RefCell::new(Rc::new(|label: &'static str| {
2562                    let mut s: String = label.replace(['_', '-'], " ");
2563                    if let Some(first) = s.get_mut(0..1) {
2564                        first.make_ascii_uppercase();
2565                    }
2566                    s
2567                })),
2568                sink: Cell::new(None),
2569                context: RefCell::new(None),
2570            }),
2571        };
2572        want_values_standing(true);
2573        let weak = Rc::downgrade(&stack.inner);
2574        let sink = install_change_sink(move |change| {
2575            if let Some(inner) = weak.upgrade() {
2576                UndoStack { inner }.capture(change);
2577            }
2578        });
2579        stack.inner.sink.set(Some(sink));
2580        let weak = Rc::downgrade(&stack.inner);
2581        day_reactive::on_turn_end(move || {
2582            if let Some(inner) = weak.upgrade() {
2583                let stack = UndoStack { inner };
2584                if stack.inner.grouping.get() == 0 {
2585                    stack.seal();
2586                }
2587            }
2588        });
2589        stack
2590    }
2591
2592    /// Bring one store under this history. Only watched stores are captured; a change in any
2593    /// other store passes the stack by.
2594    pub fn watch<T: ApplyField + Identified + Clone + 'static>(&self, store: Store<Keyed<T>>) {
2595        let ops = StoreOps {
2596            set_field: {
2597                Rc::new(move |key: u64, label: &'static str, value: &Rc<dyn Any>| {
2598                    let elem = store.elem(key);
2599                    let mut applied = false;
2600                    let ok = elem.update_value(|row| {
2601                        applied = row.apply_field(label, value.as_ref());
2602                    });
2603                    if ok && applied {
2604                        elem.bump_version();
2605                        announce_op(&[store.store_id(), key, field_id(label)], label, Op::Set);
2606                    }
2607                    ok && applied
2608                })
2609            },
2610            insert_row: {
2611                Rc::new(move |key: u64, row: &Rc<dyn Any>, at: Option<usize>| {
2612                    let Some(row) = row.downcast_ref::<T>() else {
2613                        return false;
2614                    };
2615                    let row = row.clone();
2616                    store.restructure("undo", Op::Insert, key, move |k| match at {
2617                        Some(at) if at < k.len() => k.items_mut().insert(at, row),
2618                        _ => k.push(row),
2619                    });
2620                    true
2621                })
2622            },
2623            remove_row: {
2624                Rc::new(move |key: u64| {
2625                    store.restructure("undo", Op::Delete, key, move |k| {
2626                        k.remove(key);
2627                    });
2628                    true
2629                })
2630            },
2631            move_row: {
2632                Rc::new(move |key: u64, to: usize| {
2633                    let from =
2634                        store.with_untracked(|k| k.items().iter().position(|t| t.handle() == key));
2635                    from.is_some_and(|from| store.move_row(from, to))
2636                })
2637            },
2638        };
2639        self.inner.ops.borrow_mut().insert(store.store_id(), ops);
2640    }
2641
2642    fn capture(&self, change: &Change) {
2643        if self.inner.replaying.get() != Replay::No {
2644            return;
2645        }
2646        // Another author's writes (an importer, a sync engine) are not the user's history:
2647        // undoing them from the user's stack would revert work the user never did. Their tag
2648        // is exactly the evidence this decision needs.
2649        if change.author.is_some() {
2650            return;
2651        }
2652        let Some(&store) = change.components.first() else {
2653            return;
2654        };
2655        if !self.inner.ops.borrow().contains_key(&store) {
2656            return;
2657        }
2658        let Some(&key) = change.components.get(1) else {
2659            // A wholesale rewrite: history no longer describes reachable states.
2660            self.clear();
2661            return;
2662        };
2663        if key == STRUCTURE {
2664            return;
2665        }
2666        if change.op == Op::Set && change.components.len() >= 3 && change.prior.is_none() {
2667            // A value-less field Set (an author's announce) cannot invert; skip it.
2668            return;
2669        }
2670        self.inner.open.borrow_mut().push(change.clone());
2671    }
2672
2673    /// Close the open unit (turn end does this; a group does it once at its end).
2674    fn seal(&self) {
2675        let changes = std::mem::take(&mut *self.inner.open.borrow_mut());
2676        if changes.is_empty() {
2677            return;
2678        }
2679        let label = self
2680            .inner
2681            .group_label
2682            .take()
2683            .unwrap_or_else(|| changes.first().map_or("", |c| c.label));
2684        // The unit's transient UI state is the state at seal, the end of the turn (or group),
2685        // after any selection writes the same event made. Selection changes between units are
2686        // not captured anywhere: they are not history.
2687        let context = self.inner.context.borrow().as_ref().map(|h| (h.capture)());
2688        let mut undo = self.inner.undo.borrow_mut();
2689        undo.push_back(UndoUnit {
2690            label,
2691            changes,
2692            context,
2693        });
2694        while undo.len() > self.inner.levels {
2695            undo.pop_front();
2696        }
2697        drop(undo);
2698        // A new user unit forks history: redo is gone.
2699        self.inner.redo.borrow_mut().clear();
2700        self.refresh();
2701    }
2702
2703    /// Everything `f` changes lands as one unit named `label`: a multi-field commit, an
2704    /// inspector applying twelve properties.
2705    pub fn grouped(&self, label: &'static str, f: impl FnOnce()) {
2706        let _group = self.begin_group(label);
2707        f();
2708    }
2709
2710    /// Keep one undo unit open across event turns, until the returned guard is dropped.
2711    /// Nested groups join the outer unit and retain its label. Keep the guard only for the
2712    /// duration of the interaction: all watched edits in that interval belong to the group.
2713    pub fn begin_group(&self, label: &'static str) -> UndoGroup {
2714        if self.inner.grouping.get() == 0 {
2715            self.seal();
2716            self.inner.group_label.set(Some(label));
2717        }
2718        self.inner.grouping.set(self.inner.grouping.get() + 1);
2719        UndoGroup {
2720            stack: self.clone(),
2721        }
2722    }
2723
2724    /// Preserve history before an atomic persistence operation. Failed commits must restore
2725    /// both the database/cache and this checkpoint, including an existing redo branch.
2726    #[must_use]
2727    pub fn checkpoint(&self) -> UndoCheckpoint {
2728        UndoCheckpoint {
2729            undo: self.inner.undo.borrow().clone(),
2730            redo: self.inner.redo.borrow().clone(),
2731            open: self.inner.open.borrow().clone(),
2732        }
2733    }
2734
2735    pub fn restore_checkpoint(&self, checkpoint: UndoCheckpoint) {
2736        *self.inner.undo.borrow_mut() = checkpoint.undo;
2737        *self.inner.redo.borrow_mut() = checkpoint.redo;
2738        *self.inner.open.borrow_mut() = checkpoint.open;
2739        self.refresh();
2740    }
2741
2742    #[must_use]
2743    pub fn can_undo(&self) -> day_reactive::Signal<bool> {
2744        self.inner.can_undo
2745    }
2746    #[must_use]
2747    pub fn can_redo(&self) -> day_reactive::Signal<bool> {
2748        self.inner.can_redo
2749    }
2750    /// The next undo unit's display label ("Name", or whatever the resolver makes of it),
2751    /// empty when there is nothing to undo. What a menu title interpolates.
2752    #[must_use]
2753    pub fn undo_label(&self) -> day_reactive::Signal<String> {
2754        self.inner.undo_label
2755    }
2756    #[must_use]
2757    pub fn redo_label(&self) -> day_reactive::Signal<String> {
2758        self.inner.redo_label
2759    }
2760
2761    /// How unit labels become display text (Fluent lookup, capitalization); the default
2762    /// capitalizes the raw label.
2763    pub fn set_label_resolver(&self, f: impl Fn(&'static str) -> String + 'static) {
2764        *self.inner.resolver.borrow_mut() = Rc::new(f);
2765        self.refresh();
2766    }
2767
2768    /// Ride transient UI state (a selection, a scroll position) along the history: captured,
2769    /// never persisted (docs/model.md "Transient UI state").
2770    ///
2771    /// `capture` runs as each unit seals, so a snapshot is the UI state at that point of
2772    /// document history, including any selection writes the same turn made. Undo restores the
2773    /// snapshot of the unit history lands on: the previous unit's, or the base snapshot
2774    /// (taken here, at install) once the last unit is undone; redo restores the redone unit's
2775    /// own. UI changes between units restore nowhere: they are not history, which is what
2776    /// makes "select A, move it, select B, move it, undo" land on A (the state as it stood
2777    /// when A's move sealed) rather than on B.
2778    ///
2779    /// `restore` must not write a watched store (that would fork history from inside a
2780    /// replay); write plain signals. A unit sealed before this call carries no snapshot and
2781    /// restores nothing.
2782    pub fn set_transient_context(
2783        &self,
2784        capture: impl Fn() -> Rc<dyn Any> + 'static,
2785        restore: impl Fn(&dyn Any) + 'static,
2786    ) {
2787        let base = capture();
2788        *self.inner.context.borrow_mut() = Some(ContextHook {
2789            capture: Rc::new(capture),
2790            restore: Rc::new(restore),
2791            base,
2792        });
2793    }
2794
2795    /// Restore the snapshot history just landed on: the top unit's snapshot slot. A unit that
2796    /// recorded nothing restores nothing; the empty stack restores the base. Every borrow is
2797    /// released before the restore closure runs: it is app code.
2798    fn restore_context(&self) {
2799        let (target, restore) = {
2800            let hook = self.inner.context.borrow();
2801            let Some(h) = hook.as_ref() else { return };
2802            let target = match self.inner.undo.borrow().back() {
2803                Some(unit) => unit.context.clone(),
2804                None => Some(h.base.clone()),
2805            };
2806            (target, h.restore.clone())
2807        };
2808        if let Some(ctx) = target {
2809            restore(&*ctx);
2810        }
2811    }
2812
2813    pub fn undo(&self) -> bool {
2814        // Never replay a partially completed interaction under its live gesture state.
2815        if self.inner.grouping.get() > 0 {
2816            return false;
2817        }
2818        self.seal();
2819        let Some(unit) = self.inner.undo.borrow_mut().pop_back() else {
2820            return false;
2821        };
2822        self.inner.replaying.set(Replay::Undoing);
2823        with_author("undo", || {
2824            day_reactive::batch(|| {
2825                for ch in unit.changes.iter().rev() {
2826                    self.apply(ch, true);
2827                }
2828            });
2829        });
2830        self.inner.replaying.set(Replay::No);
2831        self.inner.redo.borrow_mut().push(unit);
2832        // History landed on the previous unit's point: restore its transient state (base
2833        // when the stack just emptied). After the replay flag drops: restores write plain
2834        // signals, never watched stores.
2835        self.restore_context();
2836        self.refresh();
2837        true
2838    }
2839
2840    pub fn redo(&self) -> bool {
2841        // Never replay a partially completed interaction under its live gesture state.
2842        if self.inner.grouping.get() > 0 {
2843            return false;
2844        }
2845        let Some(unit) = self.inner.redo.borrow_mut().pop() else {
2846            return false;
2847        };
2848        self.inner.replaying.set(Replay::Redoing);
2849        with_author("redo", || {
2850            day_reactive::batch(|| {
2851                for ch in &unit.changes {
2852                    self.apply(ch, false);
2853                }
2854            });
2855        });
2856        self.inner.replaying.set(Replay::No);
2857        self.inner.undo.borrow_mut().push_back(unit);
2858        // History landed back on the redone unit: restore its own transient state.
2859        self.restore_context();
2860        self.refresh();
2861        true
2862    }
2863
2864    /// Drop all history (a schema migration, a wholesale reload).
2865    pub fn clear(&self) {
2866        self.inner.undo.borrow_mut().clear();
2867        self.inner.redo.borrow_mut().clear();
2868        self.inner.open.borrow_mut().clear();
2869        self.refresh();
2870    }
2871
2872    fn apply(&self, ch: &Change, invert: bool) {
2873        let (Some(&store), Some(&key)) = (ch.components.first(), ch.components.get(1)) else {
2874            return;
2875        };
2876        let ops = self.inner.ops.borrow();
2877        let Some(ops) = ops.get(&store) else {
2878            return;
2879        };
2880        let effective = if invert {
2881            match ch.op {
2882                Op::Set => Op::Set,
2883                Op::Insert => Op::Delete,
2884                Op::Delete => Op::Insert,
2885                Op::Move => Op::Move,
2886            }
2887        } else {
2888            ch.op
2889        };
2890        let index = |v: &Option<Rc<dyn Any>>| {
2891            v.as_deref()
2892                .and_then(|v| v.downcast_ref::<usize>().copied())
2893        };
2894        match effective {
2895            Op::Set => {
2896                let v = if invert { &ch.prior } else { &ch.value };
2897                if let Some(v) = v {
2898                    (ops.set_field)(key, ch.label, v);
2899                }
2900            }
2901            Op::Insert => {
2902                // Undoing a Delete puts the row back where it was; redoing an Insert, where it went.
2903                let (row, at) = if invert {
2904                    (&ch.prior, index(&ch.value))
2905                } else {
2906                    (&ch.value, index(&ch.prior))
2907                };
2908                if let Some(row) = row {
2909                    (ops.insert_row)(key, row, at);
2910                }
2911            }
2912            Op::Delete => {
2913                (ops.remove_row)(key);
2914            }
2915            Op::Move => {
2916                let to = if invert { &ch.prior } else { &ch.value };
2917                if let Some(to) = index(to) {
2918                    (ops.move_row)(key, to);
2919                }
2920            }
2921        }
2922    }
2923
2924    fn refresh(&self) {
2925        let resolver = self.inner.resolver.borrow().clone();
2926        let undo = self.inner.undo.borrow();
2927        self.inner.can_undo.set_if_changed(!undo.is_empty());
2928        self.inner
2929            .undo_label
2930            .set_if_changed(undo.back().map_or_default(|u| resolver(u.label)));
2931        drop(undo);
2932        let redo = self.inner.redo.borrow();
2933        self.inner.can_redo.set_if_changed(!redo.is_empty());
2934        self.inner
2935            .redo_label
2936            .set_if_changed(redo.last().map_or_default(|u| resolver(u.label)));
2937    }
2938}
2939
2940impl Drop for UndoInner {
2941    fn drop(&mut self) {
2942        if let Some(sink) = self.sink.take() {
2943            remove_change_sink(sink);
2944        }
2945        // Balance the standing want-values this stack held (best-effort at thread teardown).
2946        let _ = WANT_VALUES_STANDING.try_with(|w| w.set(w.get().saturating_sub(1)));
2947    }
2948}