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    fn end_preview(&self) {
2039        Field::end_preview(*self);
2040    }
2041}
2042
2043// ---------------------------------------------------------------------------
2044// Conversions
2045// ---------------------------------------------------------------------------
2046
2047/// A converted view of a field: an ISO string as a date, `#RRGGBB` as a color, an index into a
2048/// table as the value it names. `Copy`, and still a binding, so it goes straight into a control.
2049pub struct Mapped<F, V: 'static, U: 'static> {
2050    inner: F,
2051    to: fn(&V) -> U,
2052    from: fn(&U) -> V,
2053    /// The mapped-over field's own label, so a converted write still names its column in the
2054    /// change log (a literal "mapped" would be invisible to the SQL fold).
2055    label: &'static str,
2056}
2057
2058impl<F: Copy, V, U> Clone for Mapped<F, V, U> {
2059    fn clone(&self) -> Self {
2060        *self
2061    }
2062}
2063impl<F: Copy, V, U> Copy for Mapped<F, V, U> {}
2064
2065impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
2066    /// Read this field through `to`, write it back through `from`. Both are fn pointers, so the
2067    /// result stays `Copy`.
2068    pub fn map<U: 'static>(self, to: fn(&V) -> U, from: fn(&U) -> V) -> Mapped<Self, V, U> {
2069        Mapped {
2070            inner: self,
2071            to,
2072            from,
2073            label: self.label,
2074        }
2075    }
2076}
2077
2078/// The missing case converts the stored type's default rather than requiring the UI type to have
2079/// one: a `Color` has no `Default`, and asking every converted type for one would be a tax paid
2080/// by every caller for a case only a deleted row reaches.
2081impl<F: Source<V>, V: Clone + Default + 'static, U: Clone + 'static> Binding<U>
2082    for Mapped<F, V, U>
2083{
2084    fn read(&self) -> U {
2085        self.inner.track_extra();
2086        track(self.inner.path());
2087        self.peek()
2088    }
2089    fn peek(&self) -> U {
2090        self.inner.with_value_untracked(|v| match v {
2091            Some(v) => (self.to)(v),
2092            None => (self.to)(&V::default()),
2093        })
2094    }
2095    fn write_preview(&self, u: U) {
2096        let v = (self.from)(&u);
2097        let inner = self.inner;
2098        let mut parts = Vec::new();
2099        inner.components(&mut parts);
2100        PREVIEWS.with(|p| {
2101            p.borrow_mut().entry(parts).or_insert_with(|| {
2102                Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()))
2103            });
2104        });
2105        PREVIEW_WRITE.with(|f| f.set(true));
2106        let ok = inner.update_value(|slot| *slot = v);
2107        if ok {
2108            inner.bump_version();
2109            notify_change(inner.path(), Vec::new, self.label, Op::Set, None, None);
2110        }
2111        PREVIEW_WRITE.with(|f| f.set(false));
2112    }
2113    fn end_preview(&self) {
2114        let mut parts = Vec::new();
2115        self.inner.components(&mut parts);
2116        PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2117    }
2118    fn write_commit(&self, u: U) {
2119        let inner = self.inner;
2120        let mut parts = Vec::new();
2121        inner.components(&mut parts);
2122        let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2123        match open {
2124            None => self.write(u),
2125            Some(prior) => {
2126                let v = (self.from)(&u);
2127                PREVIEW_WRITE.with(|f| f.set(true));
2128                let ok = inner.update_value(|slot| *slot = v);
2129                PREVIEW_WRITE.with(|f| f.set(false));
2130                if ok {
2131                    inner.bump_version();
2132                    let after: Rc<dyn Any> =
2133                        Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()));
2134                    notify_change(
2135                        inner.path(),
2136                        || parts,
2137                        self.label,
2138                        Op::Set,
2139                        Some(prior),
2140                        Some(after),
2141                    );
2142                }
2143            }
2144        }
2145    }
2146    fn write(&self, u: U) {
2147        let v = (self.from)(&u);
2148        let inner = self.inner;
2149        let capture = values_wanted();
2150        let mut prior: Option<Rc<dyn Any>> = None;
2151        let mut after: Option<Rc<dyn Any>> = None;
2152        let ok = inner.update_value(|slot| {
2153            if capture {
2154                prior = Some(Rc::new(slot.clone()));
2155            }
2156            *slot = v;
2157            if capture {
2158                after = Some(Rc::new(slot.clone()));
2159            }
2160        });
2161        if ok {
2162            inner.bump_version();
2163            notify_change(
2164                inner.path(),
2165                || {
2166                    let mut parts = Vec::new();
2167                    inner.components(&mut parts);
2168                    parts
2169                },
2170                self.label,
2171                Op::Set,
2172                prior,
2173                after,
2174            );
2175        }
2176    }
2177}
2178
2179impl<F: Source<V> + Copy, V: 'static> Mapped<F, V, usize> {
2180    /// `usize` as the `f64` a slider speaks: the adapter every numeric control needs somewhere.
2181    pub fn map_to_f64(self) -> Numeric<Self> {
2182        Numeric { inner: self }
2183    }
2184}
2185
2186/// `usize` ⇄ `f64`.
2187pub struct Numeric<M> {
2188    inner: M,
2189}
2190
2191impl<M: Copy> Clone for Numeric<M> {
2192    fn clone(&self) -> Self {
2193        *self
2194    }
2195}
2196impl<M: Copy> Copy for Numeric<M> {}
2197
2198impl<M: Binding<usize> + Copy + 'static> Binding<f64> for Numeric<M> {
2199    fn read(&self) -> f64 {
2200        self.inner.read() as f64
2201    }
2202    fn peek(&self) -> f64 {
2203        self.inner.peek() as f64
2204    }
2205    fn write(&self, v: f64) {
2206        self.inner.write(v.round().max(0.0) as usize);
2207    }
2208}
2209
2210// ---------------------------------------------------------------------------
2211// Preview sessions (docs/model.md): the write-side of ValueChanged / ValueCommitted
2212// ---------------------------------------------------------------------------
2213
2214impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Field<S, T, V> {
2215    /// A live write: the value lands and this field's readers wake (a label tracking a
2216    /// dragged slider follows), but no change record is born, so autosave, the undo stack and
2217    /// every sink stay quiet. The first preview since the last commit captures the
2218    /// pre-session value; [`Field::write_commit`] turns the whole gesture into one record.
2219    pub fn write_preview(self, v: V) {
2220        let mut parts = Vec::new();
2221        Source::<V>::components(self, &mut parts);
2222        PREVIEWS.with(|p| {
2223            p.borrow_mut().entry(parts).or_insert_with(|| {
2224                Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()))
2225            });
2226        });
2227        PREVIEW_WRITE.with(|f| f.set(true));
2228        self.update(move |slot| *slot = v);
2229        PREVIEW_WRITE.with(|f| f.set(false));
2230    }
2231
2232    /// The settled value that ends a preview sequence: applies `v`, then announces one change
2233    /// whose prior is the pre-session value, so sixty thumb positions become one record, one
2234    /// undo unit, one UPDATE. Without an open session this is a plain [`Binding::write`].
2235    pub fn write_commit(self, v: V) {
2236        let mut parts = Vec::new();
2237        Source::<V>::components(self, &mut parts);
2238        let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2239        // A session whose row was deleted meanwhile (a field torn down with its row) ends
2240        // here with nothing to record: there is no value left for the change to describe.
2241        let open = open.filter(|_| self.with_untracked(|s| s.is_some()));
2242        match open {
2243            None => self.update(move |slot| *slot = v),
2244            Some(prior) => {
2245                PREVIEW_WRITE.with(|f| f.set(true));
2246                self.update(move |slot| *slot = v);
2247                PREVIEW_WRITE.with(|f| f.set(false));
2248                let after: Rc<dyn Any> =
2249                    Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()));
2250                notify_change(
2251                    self.live_path(),
2252                    || parts,
2253                    self.label,
2254                    Op::Set,
2255                    Some(prior),
2256                    Some(after),
2257                );
2258            }
2259        }
2260    }
2261
2262    /// Close an open preview session without a record (`Binding::end_preview`): an app write
2263    /// replaced what the gesture previewed and recorded its own change, so the session's
2264    /// pre-gesture value no longer describes the field. The next preview captures the current
2265    /// value as its prior. Without an open session this does nothing.
2266    pub fn end_preview(self) {
2267        let mut parts = Vec::new();
2268        Source::<V>::components(self, &mut parts);
2269        PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2270    }
2271
2272    /// The explicit session handle, for custom pieces and programmatic gestures; bindings
2273    /// drive [`Field::write_preview`]/[`Field::write_commit`] on their own.
2274    pub fn session(self) -> FieldSession<S, T, V> {
2275        FieldSession { field: self }
2276    }
2277}
2278
2279/// An explicit preview session over one field (see [`Field::session`]). `Copy`, like the
2280/// field itself.
2281pub struct FieldSession<S: 'static, T: 'static, V: 'static> {
2282    field: Field<S, T, V>,
2283}
2284
2285impl<S: Copy, T, V> Clone for FieldSession<S, T, V> {
2286    fn clone(&self) -> Self {
2287        *self
2288    }
2289}
2290impl<S: Copy, T, V> Copy for FieldSession<S, T, V> {}
2291
2292impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> FieldSession<S, T, V> {
2293    pub fn preview(self, v: V) {
2294        self.field.write_preview(v);
2295    }
2296    /// Seal the session at the current value.
2297    pub fn commit(self) {
2298        let v = self
2299            .field
2300            .with_untracked(|s| s.cloned().unwrap_or_default());
2301        self.field.write_commit(v);
2302    }
2303    /// Abandon the session: the pre-session value comes back (readers wake), and no record of
2304    /// any of it exists (what Escape does).
2305    pub fn cancel(self) {
2306        let mut parts = Vec::new();
2307        Source::<V>::components(self.field, &mut parts);
2308        if let Some(prior) = PREVIEWS.with(|p| p.borrow_mut().remove(&parts))
2309            && let Ok(prior) = prior.downcast::<V>()
2310        {
2311            self.field.write_preview((*prior).clone());
2312            // The restore write re-opened a session pointing at itself; drop it.
2313            let mut parts = Vec::new();
2314            Source::<V>::components(self.field, &mut parts);
2315            PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2316        }
2317    }
2318}
2319
2320// ---------------------------------------------------------------------------
2321// Undo (docs/model.md): the change log read backward
2322// ---------------------------------------------------------------------------
2323
2324/// Write one captured field value back into a struct, by label. Implemented by
2325/// `#[derive(Observable)]`; this trait is how a type-erased undo unit re-enters the
2326/// store it came from.
2327pub trait ApplyField {
2328    fn apply_field(&mut self, label: &str, value: &dyn Any) -> bool;
2329
2330    /// The field's current value, cloned and type-erased; `None` for an unknown label. The
2331    /// derive implements it; [`Store::write_field`] captures priors through it.
2332    fn read_field(&self, label: &str) -> Option<Rc<dyn Any>> {
2333        let _ = label;
2334        None
2335    }
2336}
2337
2338type SetFieldFn = Rc<dyn Fn(u64, &'static str, &Rc<dyn Any>) -> bool>;
2339type InsertRowFn = Rc<dyn Fn(u64, &Rc<dyn Any>, Option<usize>) -> bool>;
2340
2341struct StoreOps {
2342    set_field: SetFieldFn,
2343    insert_row: InsertRowFn,
2344    remove_row: Rc<dyn Fn(u64) -> bool>,
2345    move_row: Rc<dyn Fn(u64, usize) -> bool>,
2346}
2347
2348#[derive(Clone)]
2349struct UndoUnit {
2350    label: &'static str,
2351    changes: Vec<Change>,
2352    /// Transient UI state as of this unit's seal ([`UndoStack::set_transient_context`]);
2353    /// `None` for a unit sealed with no hook installed. Never persisted.
2354    context: Option<Rc<dyn Any>>,
2355}
2356
2357/// A restore closure over one captured snapshot ([`UndoStack::set_transient_context`]).
2358type ContextRestore = Rc<dyn Fn(&dyn Any)>;
2359
2360/// The app's transient-context hook ([`UndoStack::set_transient_context`]).
2361struct ContextHook {
2362    capture: Rc<dyn Fn() -> Rc<dyn Any>>,
2363    restore: ContextRestore,
2364    /// The state before any unit: what undoing the whole history restores.
2365    base: Rc<dyn Any>,
2366}
2367
2368#[derive(Clone, Copy, PartialEq)]
2369enum Replay {
2370    No,
2371    Undoing,
2372    Redoing,
2373}
2374
2375struct UndoInner {
2376    levels: usize,
2377    undo: RefCell<std::collections::VecDeque<UndoUnit>>,
2378    redo: RefCell<Vec<UndoUnit>>,
2379    open: RefCell<Vec<Change>>,
2380    group_label: Cell<Option<&'static str>>,
2381    grouping: Cell<usize>,
2382    replaying: Cell<Replay>,
2383    ops: RefCell<HashMap<u64, StoreOps>>,
2384    can_undo: day_reactive::Signal<bool>,
2385    can_redo: day_reactive::Signal<bool>,
2386    undo_label: day_reactive::Signal<String>,
2387    redo_label: day_reactive::Signal<String>,
2388    resolver: RefCell<Rc<dyn Fn(&'static str) -> String>>,
2389    sink: Cell<Option<ChangeSinkId>>,
2390    context: RefCell<Option<ContextHook>>,
2391}
2392
2393/// One undo history over the stores it [`UndoStack::watch`]es: units are turns (everything one
2394/// event's dispatch changed), inverted, not snapshots. Enabling it turns on standing value
2395/// capture; drop the stack and the capture stops.
2396#[derive(Clone)]
2397pub struct UndoStack {
2398    inner: Rc<UndoInner>,
2399}
2400
2401/// Queue-confined history checkpoint for a persistence transaction. Restore it only after
2402/// rolling back the corresponding model changes. It does not snapshot the models themselves.
2403pub struct UndoCheckpoint {
2404    undo: std::collections::VecDeque<UndoUnit>,
2405    redo: Vec<UndoUnit>,
2406    open: Vec<Change>,
2407}
2408
2409/// RAII lifetime of an undo group; dropping the last nested guard seals its changes.
2410#[must_use = "keep the group alive until the interaction finishes"]
2411pub struct UndoGroup {
2412    stack: UndoStack,
2413}
2414
2415impl Drop for UndoGroup {
2416    fn drop(&mut self) {
2417        let depth = self.stack.inner.grouping.get() - 1;
2418        self.stack.inner.grouping.set(depth);
2419        if depth == 0 {
2420            self.stack.seal();
2421            // Empty groups must not lend their label to the next unrelated edit.
2422            self.stack.inner.group_label.set(None);
2423        }
2424    }
2425}
2426
2427impl UndoStack {
2428    /// A stack holding at most `levels` units: the bound on what history keeps in RAM.
2429    pub fn new(levels: usize) -> UndoStack {
2430        let (can_undo, can_redo, undo_label, redo_label) =
2431            day_reactive::Scope::detached().enter(|| {
2432                (
2433                    day_reactive::Signal::new(false),
2434                    day_reactive::Signal::new(false),
2435                    day_reactive::Signal::new(String::new()),
2436                    day_reactive::Signal::new(String::new()),
2437                )
2438            });
2439        let stack = UndoStack {
2440            inner: Rc::new(UndoInner {
2441                levels: levels.max(1),
2442                undo: RefCell::new(std::collections::VecDeque::new()),
2443                redo: RefCell::new(Vec::new()),
2444                open: RefCell::new(Vec::new()),
2445                group_label: Cell::new(None),
2446                grouping: Cell::new(0),
2447                replaying: Cell::new(Replay::No),
2448                ops: RefCell::new(HashMap::new()),
2449                can_undo,
2450                can_redo,
2451                undo_label,
2452                redo_label,
2453                resolver: RefCell::new(Rc::new(|label: &'static str| {
2454                    let mut s: String = label.replace(['_', '-'], " ");
2455                    if let Some(first) = s.get_mut(0..1) {
2456                        first.make_ascii_uppercase();
2457                    }
2458                    s
2459                })),
2460                sink: Cell::new(None),
2461                context: RefCell::new(None),
2462            }),
2463        };
2464        want_values_standing(true);
2465        let weak = Rc::downgrade(&stack.inner);
2466        let sink = install_change_sink(move |change| {
2467            if let Some(inner) = weak.upgrade() {
2468                UndoStack { inner }.capture(change);
2469            }
2470        });
2471        stack.inner.sink.set(Some(sink));
2472        let weak = Rc::downgrade(&stack.inner);
2473        day_reactive::on_turn_end(move || {
2474            if let Some(inner) = weak.upgrade() {
2475                let stack = UndoStack { inner };
2476                if stack.inner.grouping.get() == 0 {
2477                    stack.seal();
2478                }
2479            }
2480        });
2481        stack
2482    }
2483
2484    /// Bring one store under this history. Only watched stores are captured; a change in any
2485    /// other store passes the stack by.
2486    pub fn watch<T: ApplyField + Identified + Clone + 'static>(&self, store: Store<Keyed<T>>) {
2487        let ops = StoreOps {
2488            set_field: {
2489                Rc::new(move |key: u64, label: &'static str, value: &Rc<dyn Any>| {
2490                    let elem = store.elem(key);
2491                    let mut applied = false;
2492                    let ok = elem.update_value(|row| {
2493                        applied = row.apply_field(label, value.as_ref());
2494                    });
2495                    if ok && applied {
2496                        elem.bump_version();
2497                        announce_op(&[store.store_id(), key, field_id(label)], label, Op::Set);
2498                    }
2499                    ok && applied
2500                })
2501            },
2502            insert_row: {
2503                Rc::new(move |key: u64, row: &Rc<dyn Any>, at: Option<usize>| {
2504                    let Some(row) = row.downcast_ref::<T>() else {
2505                        return false;
2506                    };
2507                    let row = row.clone();
2508                    store.restructure("undo", Op::Insert, key, move |k| match at {
2509                        Some(at) if at < k.len() => k.items_mut().insert(at, row),
2510                        _ => k.push(row),
2511                    });
2512                    true
2513                })
2514            },
2515            remove_row: {
2516                Rc::new(move |key: u64| {
2517                    store.restructure("undo", Op::Delete, key, move |k| {
2518                        k.remove(key);
2519                    });
2520                    true
2521                })
2522            },
2523            move_row: {
2524                Rc::new(move |key: u64, to: usize| {
2525                    let from =
2526                        store.with_untracked(|k| k.items().iter().position(|t| t.handle() == key));
2527                    from.is_some_and(|from| store.move_row(from, to))
2528                })
2529            },
2530        };
2531        self.inner.ops.borrow_mut().insert(store.store_id(), ops);
2532    }
2533
2534    fn capture(&self, change: &Change) {
2535        if self.inner.replaying.get() != Replay::No {
2536            return;
2537        }
2538        // Another author's writes (an importer, a sync engine) are not the user's history:
2539        // undoing them from the user's stack would revert work the user never did. Their tag
2540        // is exactly the evidence this decision needs.
2541        if change.author.is_some() {
2542            return;
2543        }
2544        let Some(&store) = change.components.first() else {
2545            return;
2546        };
2547        if !self.inner.ops.borrow().contains_key(&store) {
2548            return;
2549        }
2550        let Some(&key) = change.components.get(1) else {
2551            // A wholesale rewrite: history no longer describes reachable states.
2552            self.clear();
2553            return;
2554        };
2555        if key == STRUCTURE {
2556            return;
2557        }
2558        if change.op == Op::Set && change.components.len() >= 3 && change.prior.is_none() {
2559            // A value-less field Set (an author's announce) cannot invert; skip it.
2560            return;
2561        }
2562        self.inner.open.borrow_mut().push(change.clone());
2563    }
2564
2565    /// Close the open unit (turn end does this; a group does it once at its end).
2566    fn seal(&self) {
2567        let changes = std::mem::take(&mut *self.inner.open.borrow_mut());
2568        if changes.is_empty() {
2569            return;
2570        }
2571        let label = self
2572            .inner
2573            .group_label
2574            .take()
2575            .unwrap_or_else(|| changes.first().map(|c| c.label).unwrap_or(""));
2576        // The unit's transient UI state is the state at seal, the end of the turn (or group),
2577        // after any selection writes the same event made. Selection changes between units are
2578        // not captured anywhere: they are not history.
2579        let context = self.inner.context.borrow().as_ref().map(|h| (h.capture)());
2580        let mut undo = self.inner.undo.borrow_mut();
2581        undo.push_back(UndoUnit {
2582            label,
2583            changes,
2584            context,
2585        });
2586        while undo.len() > self.inner.levels {
2587            undo.pop_front();
2588        }
2589        drop(undo);
2590        // A new user unit forks history: redo is gone.
2591        self.inner.redo.borrow_mut().clear();
2592        self.refresh();
2593    }
2594
2595    /// Everything `f` changes lands as one unit named `label`: a multi-field commit, an
2596    /// inspector applying twelve properties.
2597    pub fn grouped(&self, label: &'static str, f: impl FnOnce()) {
2598        let _group = self.begin_group(label);
2599        f();
2600    }
2601
2602    /// Keep one undo unit open across event turns, until the returned guard is dropped.
2603    /// Nested groups join the outer unit and retain its label. Keep the guard only for the
2604    /// duration of the interaction: all watched edits in that interval belong to the group.
2605    pub fn begin_group(&self, label: &'static str) -> UndoGroup {
2606        if self.inner.grouping.get() == 0 {
2607            self.seal();
2608            self.inner.group_label.set(Some(label));
2609        }
2610        self.inner.grouping.set(self.inner.grouping.get() + 1);
2611        UndoGroup {
2612            stack: self.clone(),
2613        }
2614    }
2615
2616    /// Preserve history before an atomic persistence operation. Failed commits must restore
2617    /// both the database/cache and this checkpoint, including an existing redo branch.
2618    pub fn checkpoint(&self) -> UndoCheckpoint {
2619        UndoCheckpoint {
2620            undo: self.inner.undo.borrow().clone(),
2621            redo: self.inner.redo.borrow().clone(),
2622            open: self.inner.open.borrow().clone(),
2623        }
2624    }
2625
2626    pub fn restore_checkpoint(&self, checkpoint: UndoCheckpoint) {
2627        *self.inner.undo.borrow_mut() = checkpoint.undo;
2628        *self.inner.redo.borrow_mut() = checkpoint.redo;
2629        *self.inner.open.borrow_mut() = checkpoint.open;
2630        self.refresh();
2631    }
2632
2633    pub fn can_undo(&self) -> day_reactive::Signal<bool> {
2634        self.inner.can_undo
2635    }
2636    pub fn can_redo(&self) -> day_reactive::Signal<bool> {
2637        self.inner.can_redo
2638    }
2639    /// The next undo unit's display label ("Name", or whatever the resolver makes of it),
2640    /// empty when there is nothing to undo. What a menu title interpolates.
2641    pub fn undo_label(&self) -> day_reactive::Signal<String> {
2642        self.inner.undo_label
2643    }
2644    pub fn redo_label(&self) -> day_reactive::Signal<String> {
2645        self.inner.redo_label
2646    }
2647
2648    /// How unit labels become display text (Fluent lookup, capitalization); the default
2649    /// capitalizes the raw label.
2650    pub fn set_label_resolver(&self, f: impl Fn(&'static str) -> String + 'static) {
2651        *self.inner.resolver.borrow_mut() = Rc::new(f);
2652        self.refresh();
2653    }
2654
2655    /// Ride transient UI state (a selection, a scroll position) along the history: captured,
2656    /// never persisted (docs/model.md "Transient UI state").
2657    ///
2658    /// `capture` runs as each unit seals, so a snapshot is the UI state at that point of
2659    /// document history, including any selection writes the same turn made. Undo restores the
2660    /// snapshot of the unit history lands on: the previous unit's, or the base snapshot
2661    /// (taken here, at install) once the last unit is undone; redo restores the redone unit's
2662    /// own. UI changes between units restore nowhere: they are not history, which is what
2663    /// makes "select A, move it, select B, move it, undo" land on A (the state as it stood
2664    /// when A's move sealed) rather than on B.
2665    ///
2666    /// `restore` must not write a watched store (that would fork history from inside a
2667    /// replay); write plain signals. A unit sealed before this call carries no snapshot and
2668    /// restores nothing.
2669    pub fn set_transient_context(
2670        &self,
2671        capture: impl Fn() -> Rc<dyn Any> + 'static,
2672        restore: impl Fn(&dyn Any) + 'static,
2673    ) {
2674        let base = capture();
2675        *self.inner.context.borrow_mut() = Some(ContextHook {
2676            capture: Rc::new(capture),
2677            restore: Rc::new(restore),
2678            base,
2679        });
2680    }
2681
2682    /// Restore the snapshot history just landed on. `landed` is the top unit's snapshot slot:
2683    /// `Some(None)` is a unit that recorded nothing (restore nothing), outer `None` the empty
2684    /// stack, whose state is the base. Every borrow is released before the restore closure
2685    /// runs: it is app code.
2686    fn restore_context(&self, landed: Option<Option<Rc<dyn Any>>>) {
2687        let (target, restore) = {
2688            let hook = self.inner.context.borrow();
2689            let Some(h) = hook.as_ref() else { return };
2690            let target = match landed {
2691                Some(ctx) => ctx,
2692                None => Some(h.base.clone()),
2693            };
2694            (target, h.restore.clone())
2695        };
2696        if let Some(ctx) = target {
2697            restore(&*ctx);
2698        }
2699    }
2700
2701    pub fn undo(&self) -> bool {
2702        // Never replay a partially completed interaction under its live gesture state.
2703        if self.inner.grouping.get() > 0 {
2704            return false;
2705        }
2706        self.seal();
2707        let Some(unit) = self.inner.undo.borrow_mut().pop_back() else {
2708            return false;
2709        };
2710        self.inner.replaying.set(Replay::Undoing);
2711        with_author("undo", || {
2712            day_reactive::batch(|| {
2713                for ch in unit.changes.iter().rev() {
2714                    self.apply(ch, true);
2715                }
2716            });
2717        });
2718        self.inner.replaying.set(Replay::No);
2719        self.inner.redo.borrow_mut().push(unit);
2720        // History landed on the previous unit's point: restore its transient state (base
2721        // when the stack just emptied). After the replay flag drops: restores write plain
2722        // signals, never watched stores.
2723        let landed = self.inner.undo.borrow().back().map(|u| u.context.clone());
2724        self.restore_context(landed);
2725        self.refresh();
2726        true
2727    }
2728
2729    pub fn redo(&self) -> bool {
2730        // Never replay a partially completed interaction under its live gesture state.
2731        if self.inner.grouping.get() > 0 {
2732            return false;
2733        }
2734        let Some(unit) = self.inner.redo.borrow_mut().pop() else {
2735            return false;
2736        };
2737        self.inner.replaying.set(Replay::Redoing);
2738        with_author("redo", || {
2739            day_reactive::batch(|| {
2740                for ch in &unit.changes {
2741                    self.apply(ch, false);
2742                }
2743            });
2744        });
2745        self.inner.replaying.set(Replay::No);
2746        self.inner.undo.borrow_mut().push_back(unit);
2747        // History landed back on the redone unit: restore its own transient state.
2748        let landed = self.inner.undo.borrow().back().map(|u| u.context.clone());
2749        self.restore_context(landed);
2750        self.refresh();
2751        true
2752    }
2753
2754    /// Drop all history (a schema migration, a wholesale reload).
2755    pub fn clear(&self) {
2756        self.inner.undo.borrow_mut().clear();
2757        self.inner.redo.borrow_mut().clear();
2758        self.inner.open.borrow_mut().clear();
2759        self.refresh();
2760    }
2761
2762    fn apply(&self, ch: &Change, invert: bool) {
2763        let (Some(&store), Some(&key)) = (ch.components.first(), ch.components.get(1)) else {
2764            return;
2765        };
2766        let ops = self.inner.ops.borrow();
2767        let Some(ops) = ops.get(&store) else {
2768            return;
2769        };
2770        let effective = if invert {
2771            match ch.op {
2772                Op::Set => Op::Set,
2773                Op::Insert => Op::Delete,
2774                Op::Delete => Op::Insert,
2775                Op::Move => Op::Move,
2776            }
2777        } else {
2778            ch.op
2779        };
2780        let index = |v: &Option<Rc<dyn Any>>| {
2781            v.as_deref()
2782                .and_then(|v| v.downcast_ref::<usize>().copied())
2783        };
2784        match effective {
2785            Op::Set => {
2786                let v = if invert { &ch.prior } else { &ch.value };
2787                if let Some(v) = v {
2788                    (ops.set_field)(key, ch.label, v);
2789                }
2790            }
2791            Op::Insert => {
2792                // Undoing a Delete puts the row back where it was; redoing an Insert, where it went.
2793                let (row, at) = if invert {
2794                    (&ch.prior, index(&ch.value))
2795                } else {
2796                    (&ch.value, index(&ch.prior))
2797                };
2798                if let Some(row) = row {
2799                    (ops.insert_row)(key, row, at);
2800                }
2801            }
2802            Op::Delete => {
2803                (ops.remove_row)(key);
2804            }
2805            Op::Move => {
2806                let to = if invert { &ch.prior } else { &ch.value };
2807                if let Some(to) = index(to) {
2808                    (ops.move_row)(key, to);
2809                }
2810            }
2811        }
2812    }
2813
2814    fn refresh(&self) {
2815        let resolver = self.inner.resolver.borrow().clone();
2816        let undo = self.inner.undo.borrow();
2817        self.inner.can_undo.set_if_changed(!undo.is_empty());
2818        self.inner
2819            .undo_label
2820            .set_if_changed(undo.back().map(|u| resolver(u.label)).unwrap_or_default());
2821        drop(undo);
2822        let redo = self.inner.redo.borrow();
2823        self.inner.can_redo.set_if_changed(!redo.is_empty());
2824        self.inner
2825            .redo_label
2826            .set_if_changed(redo.last().map(|u| resolver(u.label)).unwrap_or_default());
2827    }
2828}
2829
2830impl Drop for UndoInner {
2831    fn drop(&mut self) {
2832        if let Some(sink) = self.sink.take() {
2833            remove_change_sink(sink);
2834        }
2835        // Balance the standing want-values this stack held (best-effort at thread teardown).
2836        let _ = WANT_VALUES_STANDING.try_with(|w| w.set(w.get().saturating_sub(1)));
2837    }
2838}