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