1use 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#[doc(no_inline)]
82pub use uuid::Uuid;
83
84#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
91pub struct NodeId {
92 idx: u32,
93 generation: u32,
94}
95
96const ROOT: NodeId = NodeId {
98 idx: 0,
99 generation: 0,
100};
101
102pub const STRUCTURE: u64 = u64::MAX;
105
106#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
108pub struct Path {
109 parent: NodeId,
110 part: u64,
111}
112
113impl Path {
114 fn root(id: u64) -> Path {
116 Path {
117 parent: ROOT,
118 part: id,
119 }
120 }
121
122 #[must_use]
124 pub fn under(parent: NodeId, part: u64) -> Path {
125 Path { parent, part }
126 }
127
128 #[must_use]
130 pub fn components(self) -> Vec<u64> {
131 let mut out: Vec<u64> = self.chain().iter().map(|p| p.part).collect();
132 out.reverse();
133 out
134 }
135
136 fn chain(self) -> Vec<Path> {
138 let mut out = vec![self];
139 let mut at = self.parent;
140 NODES.with(|n| {
141 let nodes = n.borrow();
142 while at != ROOT {
143 match nodes.get(at) {
144 Some(p) => {
145 out.push(p);
146 at = p.parent;
147 }
148 None => break,
149 }
150 }
151 });
152 out
153 }
154}
155
156#[must_use]
162pub const fn field_id(name: &str) -> u64 {
163 let bytes = name.as_bytes();
164 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
165 let mut i = 0;
166 while i < bytes.len() {
167 h ^= bytes[i] as u64;
168 h = h.wrapping_mul(0x1000_0000_01b3);
169 i += 1;
170 }
171 h
172}
173
174struct Slot {
175 path: Path,
176 generation: u32,
177 alive: bool,
178 pinned: bool,
180 children: u32,
182 triggers: u32,
184}
185
186#[derive(Default)]
187struct Interner {
188 slots: Vec<Slot>,
190 free: Vec<u32>,
191 lookup: HashMap<Path, NodeId>,
192}
193
194impl Interner {
195 fn get(&self, id: NodeId) -> Option<Path> {
196 match self.slots.get(id.idx as usize) {
197 Some(s) if s.alive && s.generation == id.generation => Some(s.path),
198 _ => None,
199 }
200 }
201
202 fn is_current(&self, id: NodeId) -> bool {
203 id == ROOT || self.get(id).is_some()
204 }
205
206 fn maybe_free(&mut self, mut id: NodeId) {
209 loop {
210 let Some(s) = self.slots.get(id.idx as usize) else {
211 return;
212 };
213 if !s.alive
214 || s.generation != id.generation
215 || s.pinned
216 || s.children > 0
217 || s.triggers > 0
218 {
219 return;
220 }
221 let path = s.path;
222 self.lookup.remove(&path);
223 let s = &mut self.slots[id.idx as usize];
224 s.alive = false;
225 s.generation = s.generation.wrapping_add(1);
226 self.free.push(id.idx);
227 if path.parent == ROOT {
228 return;
229 }
230 if let Some(ps) = self.slots.get_mut(path.parent.idx as usize)
231 && ps.alive
232 && ps.generation == path.parent.generation
233 && ps.children > 0
234 {
235 ps.children -= 1;
236 id = path.parent;
237 continue;
238 }
239 return;
240 }
241 }
242}
243
244day_reactive::tls_group! {
245 static NODES: RefCell<Interner> = RefCell::new(Interner {
246 slots: vec![Slot {
247 path: Path { parent: ROOT, part: 0 },
248 generation: 0,
249 alive: true,
250 pinned: true,
251 children: 0,
252 triggers: 0,
253 }],
254 free: Vec::new(),
255 lookup: HashMap::new(),
256 });
257
258 static TRIGGERS: RefCell<HashMap<Path, Entry>> = RefCell::new(HashMap::new());
262
263 static RECORDER: RefCell<Option<Vec<Change>>> = const { RefCell::new(None) };
266
267 static WANT_VALUES: Cell<bool> = const { Cell::new(false) };
269
270 static WANT_VALUES_STANDING: Cell<u32> = const { Cell::new(0) };
273
274 static PREVIEW_WRITE: Cell<bool> = const { Cell::new(false) };
278
279 static PREVIEWS: RefCell<HashMap<Vec<u64>, Rc<dyn Any>>> = RefCell::new(HashMap::new());
282
283 static CURRENT_AUTHOR: Cell<Option<&'static str>> = const { Cell::new(None) };
286
287 static SINKS: RefCell<Vec<(u64, ChangeSink)>> = const { RefCell::new(Vec::new()) };
290
291 static NEXT_SINK: Cell<u64> = const { Cell::new(1) };
292}
293
294type ChangeSink = Rc<dyn Fn(&Change)>;
295
296#[derive(Clone, Copy, PartialEq, Eq, Debug)]
298pub struct ChangeSinkId(u64);
299
300pub fn install_change_sink(f: impl Fn(&Change) + 'static) -> ChangeSinkId {
308 let id = NEXT_SINK.with(|n| {
309 let id = n.get();
310 n.set(id + 1);
311 id
312 });
313 SINKS.with(|s| s.borrow_mut().push((id, Rc::new(f))));
314 ChangeSinkId(id)
315}
316
317pub fn remove_change_sink(id: ChangeSinkId) {
318 let _ = SINKS.try_with(|s| s.borrow_mut().retain(|(i, _)| *i != id.0));
321}
322
323fn sinks_active() -> bool {
324 SINKS.with(|s| !s.borrow().is_empty())
325}
326
327fn feed_sinks(change: &Change) {
330 let sinks: Vec<ChangeSink> =
331 SINKS.with(|s| s.borrow().iter().map(|(_, f)| f.clone()).collect());
332 for f in sinks {
333 f(change);
334 }
335}
336
337struct Entry {
339 trigger: Trigger,
340 scope: Scope,
342 watchers: Vec<day_reactive::RunId>,
345}
346
347fn intern(p: Path) -> NodeId {
350 NODES.with(|n| {
351 let mut i = n.borrow_mut();
352 if let Some(id) = i.lookup.get(&p) {
353 return *id;
354 }
355 let id = if let Some(idx) = i.free.pop() {
356 let s = &mut i.slots[idx as usize];
357 s.path = p;
358 s.alive = true;
359 s.pinned = false;
360 s.children = 0;
361 s.triggers = 0;
362 NodeId {
363 idx,
364 generation: s.generation,
365 }
366 } else {
367 let idx = i.slots.len() as u32;
368 i.slots.push(Slot {
369 path: p,
370 generation: 0,
371 alive: true,
372 pinned: false,
373 children: 0,
374 triggers: 0,
375 });
376 NodeId { idx, generation: 0 }
377 };
378 i.lookup.insert(p, id);
379 if p.parent != ROOT
380 && let Some(s) = i.slots.get_mut(p.parent.idx as usize)
381 && s.alive
382 && s.generation == p.parent.generation
383 {
384 s.children += 1;
385 }
386 id
387 })
388}
389
390fn 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#[must_use]
411pub fn interned_nodes() -> usize {
412 NODES.with(|n| n.borrow().slots.iter().filter(|s| s.alive).count() - 1)
413}
414
415fn track(p: Path) {
423 let Some(watcher) = day_reactive::active_run() else {
424 return;
425 };
426 let (trigger, created, fresh) = TRIGGERS.with(|t| {
427 let mut map = t.borrow_mut();
428 let mut created = false;
429 let entry = map.entry(p).or_insert_with(|| {
430 created = true;
431 let scope = Scope::root().create_child();
433 Entry {
434 trigger: scope.enter(Trigger::new),
435 scope,
436 watchers: Vec::new(),
437 }
438 });
439 let fresh = !entry.watchers.contains(&watcher);
440 if fresh {
441 entry.watchers.push(watcher);
442 }
443 (entry.trigger, created, fresh)
444 });
445 if created && p.parent != ROOT {
446 NODES.with(|n| {
447 let mut i = n.borrow_mut();
448 if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
449 && s.alive
450 && s.generation == p.parent.generation
451 {
452 s.triggers += 1;
453 }
454 });
455 }
456 if fresh {
457 day_reactive::on_run_retrack(move || release(p, watcher));
460 }
461 trigger.track();
462}
463
464fn release(p: Path, watcher: day_reactive::RunId) {
467 let removed = TRIGGERS.with(|t| {
468 let mut map = t.borrow_mut();
469 let Some(entry) = map.get_mut(&p) else {
470 return false;
471 };
472 entry.watchers.retain(|w| *w != watcher);
473 if entry.watchers.is_empty() {
474 let scope = entry.scope;
475 map.remove(&p);
476 drop(map);
477 scope.dispose();
480 true
481 } else {
482 false
483 }
484 });
485 if removed && p.parent != ROOT {
486 NODES.with(|n| {
487 let mut i = n.borrow_mut();
488 if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
489 && s.alive
490 && s.generation == p.parent.generation
491 && s.triggers > 0
492 {
493 s.triggers -= 1;
494 }
495 i.maybe_free(p.parent);
496 });
497 }
498}
499
500#[must_use]
502pub fn observed_paths() -> usize {
503 TRIGGERS.with(|t| t.borrow().len())
504}
505
506#[derive(Clone, Copy, PartialEq, Eq, Debug)]
514pub enum Op {
515 Set,
517 Insert,
519 Delete,
521 Move,
523}
524
525#[derive(Clone)]
534pub struct Change {
535 pub components: Vec<u64>,
537 pub label: &'static str,
539 pub op: Op,
540 pub prior: Option<Rc<dyn Any>>,
541 pub value: Option<Rc<dyn Any>>,
542 pub author: Option<&'static str>,
545}
546
547impl Change {
548 #[must_use]
550 pub fn prior_as<T: 'static>(&self) -> Option<&T> {
551 self.prior.as_deref().and_then(|v| v.downcast_ref())
552 }
553
554 #[must_use]
556 pub fn value_as<T: 'static>(&self) -> Option<&T> {
557 self.value.as_deref().and_then(|v| v.downcast_ref())
558 }
559}
560
561impl fmt::Debug for Change {
562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 f.debug_struct("Change")
564 .field("components", &self.components)
565 .field("label", &self.label)
566 .field("op", &self.op)
567 .field("prior", &self.prior.as_ref().map(|_| ".."))
568 .field("value", &self.value.as_ref().map(|_| ".."))
569 .field("author", &self.author)
570 .finish()
571 }
572}
573
574fn values_wanted() -> bool {
575 WANT_VALUES.with(std::cell::Cell::get) || WANT_VALUES_STANDING.with(|w| w.get() > 0)
576}
577
578#[must_use]
584pub fn record_capture_active() -> bool {
585 values_wanted()
586}
587
588pub fn want_values_standing(on: bool) {
591 WANT_VALUES_STANDING.with(|w| {
592 let v = w.get();
593 w.set(if on { v + 1 } else { v.saturating_sub(1) });
594 });
595}
596
597fn previewing() -> bool {
598 PREVIEW_WRITE.with(std::cell::Cell::get)
599}
600
601pub fn with_author<R>(author: &'static str, f: impl FnOnce() -> R) -> R {
604 let previous = CURRENT_AUTHOR.with(|a| a.replace(Some(author)));
605 let _restore = std::mem::DropGuard::new(previous, |previous| {
607 CURRENT_AUTHOR.with(|a| a.set(previous));
608 });
609 f()
610}
611
612fn current_author() -> Option<&'static str> {
613 CURRENT_AUTHOR.with(std::cell::Cell::get)
614}
615
616pub fn record_changes<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
619 RECORDER.with(|r| *r.borrow_mut() = Some(Vec::new()));
620 let out = f();
621 let log = RECORDER.with(|r| r.borrow_mut().take().unwrap_or_default());
622 (out, log)
623}
624
625pub fn record_values<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
628 WANT_VALUES.with(|w| w.set(true));
629 let out = record_changes(f);
630 WANT_VALUES.with(|w| w.set(false));
631 out
632}
633
634pub fn record<R>(f: impl FnOnce() -> R) -> (R, Vec<&'static str>) {
636 let (out, changes) = record_changes(f);
637 (out, changes.into_iter().map(|c| c.label).collect())
638}
639
640fn notify_change(
644 p: Path,
645 components: impl FnOnce() -> Vec<u64>,
646 label: &'static str,
647 op: Op,
648 prior: Option<Rc<dyn Any>>,
649 value: Option<Rc<dyn Any>>,
650) {
651 if previewing() {
652 wake(p);
654 return;
655 }
656 let recording = RECORDER.with(|r| r.borrow().is_some());
657 if recording || sinks_active() {
658 let change = Change {
659 components: components(),
660 label,
661 op,
662 prior,
663 value,
664 author: current_author(),
665 };
666 feed_sinks(&change);
667 if recording {
668 RECORDER.with(|r| {
669 if let Some(log) = r.borrow_mut().as_mut() {
670 log.push(change);
671 }
672 });
673 }
674 }
675 wake(p);
676}
677
678fn wake(p: Path) {
679 let chain = p.chain();
680 let live: Vec<Trigger> = TRIGGERS.with(|t| {
681 let map = t.borrow();
682 chain
683 .iter()
684 .filter_map(|k| map.get(k).map(|e| e.trigger))
685 .collect()
686 });
687 for tr in live {
688 tr.notify();
689 }
690}
691
692pub fn announce(parts: &[u64], label: &'static str) {
699 announce_op(parts, label, Op::Set);
700}
701
702fn announce_op(parts: &[u64], label: &'static str, op: Op) {
704 let resolved = (|| {
705 let (last, interior) = parts.split_last()?;
706 let mut parent = ROOT;
707 for part in interior {
708 let step = Path::under(parent, *part);
709 match NODES.with(|n| {
710 let i = n.borrow();
711 i.lookup.get(&step).copied().filter(|id| i.is_current(*id))
712 }) {
713 Some(id) => parent = id,
714 None => return Some(step),
717 }
718 }
719 Some(Path::under(parent, *last))
720 })();
721 let Some(p) = resolved else { return };
722 let recording = RECORDER.with(|r| r.borrow().is_some());
723 if recording || sinks_active() {
724 let change = Change {
725 components: parts.to_vec(),
726 label,
727 op,
728 prior: None,
729 value: None,
730 author: current_author(),
731 };
732 feed_sinks(&change);
733 if recording {
734 RECORDER.with(|r| {
735 if let Some(log) = r.borrow_mut().as_mut() {
736 log.push(change);
737 }
738 });
739 }
740 }
741 wake(p);
742}
743
744pub trait Source<T: 'static>: Copy + 'static {
754 const DYNAMIC: bool = false;
759
760 fn track_extra(self) {}
763
764 fn path(self) -> Path;
767 fn node(self) -> NodeId;
772 fn components(self, out: &mut Vec<u64>);
776 fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R;
777 fn update_value(self, f: impl FnOnce(&mut T)) -> bool;
780 fn bump_version(self);
781
782 fn with<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
784 self.track_extra();
785 track(self.path());
786 self.with_value_untracked(f)
787 }
788}
789
790pub type TxPaths = Vec<(Vec<u64>, &'static str)>;
793
794pub struct Store<T: 'static> {
800 inner: &'static Inner<T>,
801 node: NodeId,
802 root_id: u64,
803}
804
805impl<T> Clone for Store<T> {
806 fn clone(&self) -> Self {
807 *self
808 }
809}
810impl<T> Copy for Store<T> {}
811
812struct Inner<T> {
813 data: RwLock<T>,
814 pending: Mutex<TxPaths>,
815 version: AtomicU64,
816}
817
818static NEXT_STORE: AtomicU64 = AtomicU64::new(1);
820
821impl<T: 'static> Store<T> {
822 pub fn new(value: T) -> Store<T> {
826 let inner: &'static Inner<T> = Box::leak(Box::new(Inner {
827 data: RwLock::new(value),
828 pending: Mutex::new(Vec::new()),
829 version: AtomicU64::new(0),
830 }));
831 let root_id = NEXT_STORE.fetch_add(1, Ordering::Relaxed);
832 let node = intern(Path::root(root_id));
833 pin(node);
834 Store {
835 inner,
836 node,
837 root_id,
838 }
839 }
840
841 pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
847 f(&self.inner.data.read().expect("store poisoned"))
848 }
849
850 pub fn update(self, label: &'static str, f: impl FnOnce(&mut T)) {
856 {
857 let mut g = self.inner.data.write().expect("store poisoned");
858 f(&mut g);
859 }
860 self.inner.version.fetch_add(1, Ordering::Relaxed);
861 let root_id = self.root_id;
862 notify_change(
863 path_of(self.node),
864 || vec![root_id],
865 label,
866 Op::Set,
867 None,
868 None,
869 );
870 }
871
872 #[must_use]
874 pub fn version(self) -> u64 {
875 self.inner.version.load(Ordering::Relaxed)
876 }
877
878 #[must_use]
881 pub fn store_id(self) -> u64 {
882 self.root_id
883 }
884
885 #[must_use]
893 pub fn pump(self) -> usize {
894 let drained: TxPaths = {
895 let mut q = self.inner.pending.lock().expect("queue poisoned");
896 std::mem::take(&mut *q)
897 };
898 let n = drained.len();
899 day_reactive::batch(|| {
900 for (parts, label) in drained {
901 announce(&parts, label);
902 }
903 });
904 n
905 }
906}
907
908impl<T: 'static> Source<T> for Store<T> {
909 fn path(self) -> Path {
910 path_of(self.node)
911 }
912 fn node(self) -> NodeId {
913 self.node
915 }
916 fn components(self, out: &mut Vec<u64>) {
917 out.push(self.root_id);
918 }
919 fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
920 f(Some(&self.inner.data.read().expect("store poisoned")))
921 }
922 fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
923 let mut g = self.inner.data.write().expect("store poisoned");
924 f(&mut g);
925 true
926 }
927 fn bump_version(self) {
928 self.inner.version.fetch_add(1, Ordering::Relaxed);
929 }
930}
931
932unsafe impl<T: Send + Sync> Send for Store<T> {}
936unsafe impl<T: Send + Sync> Sync for Store<T> {}
937
938impl<T: Send + Sync + 'static> Store<T> {
943 #[must_use]
951 pub fn transact(self) -> Tx<T> {
952 Tx {
953 store: self,
954 guard: Some(self.inner.data.write().expect("store poisoned")),
955 touched: Vec::new(),
956 }
957 }
958}
959
960pub struct Tx<T: Send + Sync + 'static> {
963 store: Store<T>,
964 guard: Option<std::sync::RwLockWriteGuard<'static, T>>,
965 touched: TxPaths,
966}
967
968impl<T: Send + Sync + 'static> Tx<T> {
969 #[expect(
970 clippy::missing_panics_doc,
971 reason = "the guard is taken in Drop alone, so the `expect` cannot fail on a live Tx"
972 )]
973 pub fn data(&mut self) -> &mut T {
974 self.guard.as_mut().expect("transaction already committed")
976 }
977 pub fn touched(&mut self, parts: Vec<u64>, label: &'static str) {
978 self.touched.push((parts, label));
979 }
980 pub fn paths(&mut self) -> &mut TxPaths {
981 &mut self.touched
982 }
983}
984
985impl<T: Send + Sync + 'static> Drop for Tx<T> {
986 fn drop(&mut self) {
987 let touched = std::mem::take(&mut self.touched);
988 let store = self.store;
989 drop(self.guard.take());
991 store.inner.version.fetch_add(1, Ordering::Relaxed);
992 store
993 .inner
994 .pending
995 .lock()
996 .expect("queue poisoned")
997 .extend(touched);
998 }
1002}
1003
1004const WIDE_BASE: u64 = 1 << 63;
1013
1014#[derive(Clone, PartialEq, Eq, Hash, Debug)]
1024pub enum Key {
1025 U64(u64),
1026 Uuid(u128),
1028 Str(Arc<str>),
1030 Pair(u64, u64),
1033}
1034
1035impl Key {
1036 #[must_use]
1039 pub fn handle(&self) -> u64 {
1040 match self {
1041 Key::U64(k) => *k,
1042 Key::Uuid(u) => intern_wide(WideKey::Uuid(*u)),
1043 Key::Str(s) => intern_wide(WideKey::Str(s.clone())),
1044 Key::Pair(a, b) => intern_wide(WideKey::Pair(*a, *b)),
1045 }
1046 }
1047
1048 #[must_use]
1055 pub fn of_handle(handle: u64) -> Option<Key> {
1056 if handle < WIDE_BASE {
1057 return Some(Key::U64(handle));
1058 }
1059 let idx = (handle - WIDE_BASE) as usize;
1060 wide_keys()
1061 .read()
1062 .expect("key interner poisoned")
1063 .reverse
1064 .get(idx)
1065 .map(|w| match w {
1066 WideKey::Uuid(u) => Key::Uuid(*u),
1067 WideKey::Str(s) => Key::Str(s.clone()),
1068 WideKey::Pair(a, b) => Key::Pair(*a, *b),
1069 })
1070 }
1071
1072 #[must_use]
1073 pub fn as_u64(&self) -> Option<u64> {
1074 match self {
1075 Key::U64(k) => Some(*k),
1076 _ => None,
1077 }
1078 }
1079
1080 #[must_use]
1081 pub fn as_uuid(&self) -> Option<uuid::Uuid> {
1082 match self {
1083 Key::Uuid(u) => Some(uuid::Uuid::from_u128(*u)),
1084 _ => None,
1085 }
1086 }
1087
1088 #[must_use]
1089 pub fn as_str(&self) -> Option<&str> {
1090 match self {
1091 Key::Str(s) => Some(s),
1092 _ => None,
1093 }
1094 }
1095}
1096
1097impl fmt::Display for Key {
1098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099 match self {
1100 Key::U64(k) => write!(f, "{k}"),
1101 Key::Uuid(u) => write!(f, "{}", uuid::Uuid::from_u128(*u)),
1102 Key::Str(s) => f.write_str(s),
1103 Key::Pair(a, b) => write!(f, "{a}:{b}"),
1104 }
1105 }
1106}
1107
1108#[derive(Clone, PartialEq, Eq, Hash)]
1110enum WideKey {
1111 Uuid(u128),
1112 Str(Arc<str>),
1113 Pair(u64, u64),
1114}
1115
1116#[derive(Default)]
1117struct WideKeys {
1118 lookup: HashMap<WideKey, u64>,
1119 reverse: Vec<WideKey>,
1120}
1121
1122static WIDE_KEYS: OnceLock<RwLock<WideKeys>> = OnceLock::new();
1126
1127fn wide_keys() -> &'static RwLock<WideKeys> {
1128 WIDE_KEYS.get_or_init(Default::default)
1129}
1130
1131fn intern_wide(k: WideKey) -> u64 {
1132 if let Some(h) = wide_keys()
1133 .read()
1134 .expect("key interner poisoned")
1135 .lookup
1136 .get(&k)
1137 {
1138 return *h;
1139 }
1140 let mut w = wide_keys().write().expect("key interner poisoned");
1141 if let Some(h) = w.lookup.get(&k) {
1142 return *h; }
1144 let h = WIDE_BASE + w.reverse.len() as u64;
1145 w.reverse.push(k.clone());
1146 w.lookup.insert(k, h);
1147 h
1148}
1149
1150#[must_use]
1157pub fn interned_keys() -> usize {
1158 wide_keys()
1159 .read()
1160 .expect("key interner poisoned")
1161 .reverse
1162 .len()
1163}
1164
1165pub trait AsKey {
1170 fn as_key(&self) -> Key;
1171}
1172
1173fn int_key(k: u64) -> Key {
1174 debug_assert!(
1175 k < WIDE_BASE,
1176 "u64 keys reserve the top bit for interned handles (got {k:#x})"
1177 );
1178 Key::U64(k)
1179}
1180
1181macro_rules! int_key {
1182 ($($t:ty),*) => {$(
1183 impl AsKey for $t {
1184 fn as_key(&self) -> Key {
1185 int_key(*self as u64)
1186 }
1187 }
1188 )*};
1189}
1190macro_rules! lossless_int_key {
1191 ($($t:ty),*) => {$(
1192 impl AsKey for $t {
1193 fn as_key(&self) -> Key {
1194 int_key(u64::from(*self))
1195 }
1196 }
1197 )*};
1198}
1199lossless_int_key!(u8, u16, u32);
1200int_key!(u64, usize, i8, i16, i32, i64, isize);
1201
1202impl AsKey for String {
1203 fn as_key(&self) -> Key {
1204 Key::Str(Arc::from(self.as_str()))
1205 }
1206}
1207impl AsKey for &str {
1208 fn as_key(&self) -> Key {
1209 Key::Str(Arc::from(*self))
1210 }
1211}
1212impl AsKey for Arc<str> {
1213 fn as_key(&self) -> Key {
1214 Key::Str(self.clone())
1215 }
1216}
1217impl AsKey for uuid::Uuid {
1218 fn as_key(&self) -> Key {
1219 Key::Uuid(self.as_u128())
1220 }
1221}
1222impl AsKey for Key {
1223 fn as_key(&self) -> Key {
1224 self.clone()
1225 }
1226}
1227
1228pub struct ModelId<M: ?Sized> {
1236 handle: u64,
1237 _m: PhantomData<fn() -> M>,
1238}
1239
1240impl<M: ?Sized> Clone for ModelId<M> {
1241 fn clone(&self) -> Self {
1242 *self
1243 }
1244}
1245impl<M: ?Sized> Copy for ModelId<M> {}
1246impl<M: ?Sized> PartialEq for ModelId<M> {
1247 fn eq(&self, other: &Self) -> bool {
1248 self.handle == other.handle
1249 }
1250}
1251impl<M: ?Sized> Eq for ModelId<M> {}
1252impl<M: ?Sized> std::hash::Hash for ModelId<M> {
1253 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1254 self.handle.hash(state);
1255 }
1256}
1257impl<M: ?Sized> PartialOrd for ModelId<M> {
1258 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1259 Some(self.cmp(other))
1260 }
1261}
1262impl<M: ?Sized> Ord for ModelId<M> {
1263 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1264 self.handle.cmp(&other.handle)
1265 }
1266}
1267impl<M: ?Sized> fmt::Debug for ModelId<M> {
1268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1269 match Key::of_handle(self.handle) {
1270 Some(k) => write!(f, "ModelId({k})"),
1271 None => write!(f, "ModelId(#{:x})", self.handle),
1272 }
1273 }
1274}
1275
1276impl<M: ?Sized> ModelId<M> {
1277 #[expect(
1279 clippy::needless_pass_by_value,
1280 reason = "public signature; callers pass key literals and owned keys by value"
1281 )]
1282 pub fn of(key: impl AsKey) -> Self {
1283 Self::from_handle(key.as_key().handle())
1284 }
1285 #[must_use]
1287 pub const fn from_handle(handle: u64) -> Self {
1288 ModelId {
1289 handle,
1290 _m: PhantomData,
1291 }
1292 }
1293 #[must_use]
1294 pub fn handle(self) -> u64 {
1295 self.handle
1296 }
1297 #[must_use]
1299 pub fn key(self) -> Key {
1300 Key::of_handle(self.handle).unwrap_or(Key::U64(self.handle))
1301 }
1302}
1303
1304impl<M: ?Sized> PartialEq<u64> for ModelId<M> {
1307 fn eq(&self, other: &u64) -> bool {
1308 self.handle == *other
1309 }
1310}
1311impl<M: ?Sized> PartialEq<ModelId<M>> for u64 {
1312 fn eq(&self, other: &ModelId<M>) -> bool {
1313 *self == other.handle
1314 }
1315}
1316
1317impl<M: ?Sized> From<u64> for ModelId<M> {
1320 fn from(handle: u64) -> Self {
1321 ModelId::from_handle(handle)
1322 }
1323}
1324impl<M: ?Sized> From<u32> for ModelId<M> {
1325 fn from(k: u32) -> Self {
1326 ModelId::of(k)
1327 }
1328}
1329impl<M: ?Sized> From<i32> for ModelId<M> {
1330 fn from(k: i32) -> Self {
1331 ModelId::of(k)
1332 }
1333}
1334impl<M: ?Sized> From<usize> for ModelId<M> {
1335 fn from(k: usize) -> Self {
1336 ModelId::of(k)
1337 }
1338}
1339impl<M: ?Sized> From<uuid::Uuid> for ModelId<M> {
1340 fn from(k: uuid::Uuid) -> Self {
1341 ModelId::of(k)
1342 }
1343}
1344impl<M: ?Sized> From<&str> for ModelId<M> {
1345 fn from(k: &str) -> Self {
1346 ModelId::of(k)
1347 }
1348}
1349impl<M: ?Sized> From<String> for ModelId<M> {
1350 fn from(k: String) -> Self {
1351 ModelId::of(k)
1352 }
1353}
1354impl<M: ?Sized> From<Key> for ModelId<M> {
1355 fn from(k: Key) -> Self {
1356 ModelId::from_handle(k.handle())
1357 }
1358}
1359impl<M: ?Sized> From<&Key> for ModelId<M> {
1360 fn from(k: &Key) -> Self {
1361 ModelId::from_handle(k.handle())
1362 }
1363}
1364
1365pub trait Identified {
1372 fn key(&self) -> Key;
1374
1375 fn handle(&self) -> u64 {
1377 self.key().handle()
1378 }
1379
1380 fn model_id(&self) -> ModelId<Self>
1383 where
1384 Self: Sized,
1385 {
1386 ModelId::from_handle(self.handle())
1387 }
1388}
1389
1390pub struct Keyed<T> {
1393 items: Vec<T>,
1394 index: HashMap<u64, usize>,
1395 stale: bool,
1399}
1400
1401impl<T: Identified> Default for Keyed<T> {
1402 fn default() -> Self {
1403 Keyed {
1404 items: Vec::new(),
1405 index: HashMap::new(),
1406 stale: false,
1407 }
1408 }
1409}
1410
1411impl<T: Identified> Keyed<T> {
1412 #[must_use]
1413 pub fn new(items: Vec<T>) -> Self {
1414 let mut k = Keyed {
1415 items,
1416 index: HashMap::new(),
1417 stale: false,
1418 };
1419 k.reindex();
1420 k
1421 }
1422
1423 pub fn reindex(&mut self) {
1426 self.index.clear();
1427 for (i, item) in self.items.iter().enumerate() {
1428 self.index.insert(item.handle(), i);
1429 }
1430 self.stale = false;
1431 }
1432
1433 pub fn reindex_if_stale(&mut self) {
1436 if self.stale {
1437 self.reindex();
1438 }
1439 }
1440
1441 #[must_use]
1442 pub fn get(&self, key: u64) -> Option<&T> {
1443 self.index.get(&key).and_then(|i| self.items.get(*i))
1444 }
1445
1446 pub fn get_mut(&mut self, key: u64) -> Option<&mut T> {
1447 match self.index.get(&key) {
1448 Some(i) => self.items.get_mut(*i),
1449 None => None,
1450 }
1451 }
1452
1453 #[must_use]
1454 pub fn keys(&self) -> Vec<u64> {
1455 self.items.iter().map(Identified::handle).collect()
1456 }
1457
1458 #[must_use]
1459 pub fn items(&self) -> &[T] {
1460 &self.items
1461 }
1462
1463 #[must_use]
1464 pub fn len(&self) -> usize {
1465 self.items.len()
1466 }
1467
1468 #[must_use]
1469 pub fn is_empty(&self) -> bool {
1470 self.items.is_empty()
1471 }
1472
1473 #[must_use]
1477 pub fn next_key(&self) -> u64 {
1478 let used = || {
1479 self.items
1480 .iter()
1481 .map(Identified::handle)
1482 .filter(|h| (1..WIDE_BASE).contains(h))
1483 };
1484 match used().max() {
1485 None => 1,
1486 Some(max) if max + 1 < WIDE_BASE => max + 1,
1487 Some(_) => {
1488 let mut keys: Vec<u64> = used().collect();
1489 keys.sort_unstable();
1490 let gap = keys.iter().zip(1u64..).find(|(k, want)| **k != *want);
1493 gap.map_or(keys.len() as u64 + 1, |(_, want)| want)
1494 }
1495 }
1496 }
1497
1498 pub fn push(&mut self, item: T) {
1501 self.index.insert(item.handle(), self.items.len());
1502 self.items.push(item);
1503 }
1504
1505 pub fn remove(&mut self, key: u64) -> Option<T> {
1506 let i = self.index.remove(&key)?;
1507 let item = self.items.remove(i);
1508 self.reindex();
1509 Some(item)
1510 }
1511
1512 pub fn move_item(&mut self, from: usize, to: usize) {
1513 if from >= self.items.len() || to >= self.items.len() {
1514 return;
1515 }
1516 let item = self.items.remove(from);
1517 self.items.insert(to, item);
1518 self.reindex();
1519 }
1520
1521 pub fn clear(&mut self) {
1524 self.items.clear();
1525 self.index.clear();
1526 self.stale = false;
1527 }
1528
1529 pub fn items_mut(&mut self) -> &mut Vec<T> {
1534 self.stale = true;
1535 &mut self.items
1536 }
1537}
1538
1539pub struct Elem<T: 'static> {
1545 store: Store<Keyed<T>>,
1546 key: u64,
1547 node: NodeId,
1549}
1550
1551impl<T> Clone for Elem<T> {
1552 fn clone(&self) -> Self {
1553 *self
1554 }
1555}
1556impl<T> Copy for Elem<T> {}
1557
1558impl<T: Identified + 'static> Store<Keyed<T>> {
1559 pub fn elem(self, key: impl Into<ModelId<T>>) -> Elem<T> {
1563 let key = key.into().handle();
1564 Elem {
1565 store: self,
1566 key,
1567 node: intern(Path::under(self.node, key)),
1568 }
1569 }
1570
1571 #[must_use]
1574 pub fn keys(self) -> Vec<u64> {
1575 track(Path::under(self.node, STRUCTURE));
1576 self.with_untracked(|k| k.keys().clone())
1577 }
1578
1579 pub fn ids(self) -> Vec<ModelId<T>> {
1581 self.keys().into_iter().map(ModelId::from_handle).collect()
1582 }
1583
1584 pub fn restructure(
1594 self,
1595 label: &'static str,
1596 op: Op,
1597 key: impl Into<ModelId<T>>,
1598 f: impl FnOnce(&mut Keyed<T>),
1599 ) where
1600 T: Clone,
1601 {
1602 let key = key.into().handle();
1603 let capture = values_wanted();
1607 let mut prior: Option<Rc<dyn Any>> = None;
1608 let mut value: Option<Rc<dyn Any>> = None;
1609 {
1610 let mut g = self.inner.data.write().expect("store poisoned");
1611 let index = |k: &Keyed<T>| k.items().iter().position(|t| t.handle() == key);
1612 let before = if capture { index(&g) } else { None };
1613 if capture && op == Op::Delete {
1614 prior = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
1615 }
1616 f(&mut g);
1617 g.reindex_if_stale();
1618 if capture {
1619 let after = index(&g);
1620 let at = |i: Option<usize>| i.map(|i| Rc::new(i) as Rc<dyn Any>);
1621 match op {
1622 Op::Insert => {
1623 value = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
1624 prior = at(after);
1625 }
1626 Op::Delete => value = at(before),
1627 Op::Move => (prior, value) = (at(before), at(after)),
1628 Op::Set => {}
1629 }
1630 }
1631 }
1632 self.inner.version.fetch_add(1, Ordering::Relaxed);
1633 let root_id = self.root_id;
1634 notify_change(
1635 Path::under(self.node, key),
1636 || vec![root_id, key],
1637 label,
1638 op,
1639 prior,
1640 value,
1641 );
1642 notify_change(
1643 Path::under(self.node, STRUCTURE),
1644 || vec![root_id, STRUCTURE],
1645 label,
1646 op,
1647 None,
1648 None,
1649 );
1650 }
1651
1652 pub fn push(self, item: T)
1654 where
1655 T: Clone,
1656 {
1657 let key = item.handle();
1658 self.restructure("push", Op::Insert, ModelId::from_handle(key), |k| {
1659 k.push(item);
1660 });
1661 }
1662
1663 pub fn remove(self, key: impl Into<ModelId<T>>) -> bool
1666 where
1667 T: Clone,
1668 {
1669 let key = key.into().handle();
1670 if self.with_untracked(|k| k.get(key).is_none()) {
1671 return false;
1672 }
1673 self.restructure("remove", Op::Delete, ModelId::from_handle(key), |k| {
1674 k.remove(key);
1675 });
1676 true
1677 }
1678
1679 pub fn move_row(self, from: usize, to: usize) -> bool
1682 where
1683 T: Clone,
1684 {
1685 let key = self.with_untracked(|k| {
1686 if from == to || to >= k.len() {
1687 return None;
1688 }
1689 k.items().get(from).map(Identified::handle)
1690 });
1691 let Some(key) = key else { return false };
1692 self.restructure("move", Op::Move, ModelId::from_handle(key), |k| {
1693 k.move_item(from, to);
1694 });
1695 true
1696 }
1697
1698 #[must_use]
1701 pub fn next_key(self) -> u64 {
1702 self.with_untracked(Keyed::next_key)
1703 }
1704
1705 pub fn merge_row(self, key: impl Into<ModelId<T>>, value: T, changed: &[&'static str]) -> bool
1719 where
1720 T: Clone,
1721 {
1722 let key = key.into().handle();
1723 {
1724 let mut g = self.inner.data.write().expect("store poisoned");
1725 match g.get_mut(key) {
1726 Some(slot) => *slot = value,
1727 None => return false,
1728 }
1729 }
1730 self.inner.version.fetch_add(1, Ordering::Relaxed);
1731 let elem = intern(Path::under(self.node, key));
1732 let root_id = self.root_id;
1733 for &label in changed {
1734 notify_change(
1735 Path::under(elem, field_id(label)),
1736 || vec![root_id, key, field_id(label)],
1737 label,
1738 Op::Set,
1739 None,
1740 None,
1741 );
1742 }
1743 true
1744 }
1745
1746 pub fn write_field<V: Clone + 'static>(
1757 self,
1758 key: impl Into<ModelId<T>>,
1759 label: &'static str,
1760 value: V,
1761 ) -> bool
1762 where
1763 T: ApplyField,
1764 {
1765 let key = key.into().handle();
1766 let capture = values_wanted() && !previewing();
1767 let mut prior: Option<Rc<dyn Any>> = None;
1768 let ok = {
1769 let mut g = self.inner.data.write().expect("store poisoned");
1770 match g.get_mut(key) {
1771 Some(t) => {
1772 if capture {
1773 prior = t.read_field(label);
1774 }
1775 t.apply_field(label, &value)
1776 }
1777 None => false,
1778 }
1779 };
1780 if !ok {
1781 return false;
1782 }
1783 self.inner.version.fetch_add(1, Ordering::Relaxed);
1784 let elem = intern(Path::under(self.node, key));
1785 let after: Option<Rc<dyn Any>> = if capture { Some(Rc::new(value)) } else { None };
1786 let root_id = self.root_id;
1787 notify_change(
1788 Path::under(elem, field_id(label)),
1789 || vec![root_id, key, field_id(label)],
1790 label,
1791 Op::Set,
1792 prior,
1793 after,
1794 );
1795 true
1796 }
1797
1798 pub fn populate(self, rows: Vec<T>) {
1808 {
1809 let mut g = self.inner.data.write().expect("store poisoned");
1810 for row in rows {
1811 let key = row.handle();
1812 match g.get_mut(key) {
1813 Some(slot) => *slot = row,
1814 None => g.push(row),
1815 }
1816 }
1817 }
1818 self.inner.version.fetch_add(1, Ordering::Relaxed);
1819 }
1820
1821 pub fn depopulate(self, key: impl Into<ModelId<T>>) -> bool {
1830 let key = key.into().handle();
1831 let removed = {
1832 let mut g = self.inner.data.write().expect("store poisoned");
1833 g.remove(key).is_some()
1834 };
1835 if removed {
1836 self.inner.version.fetch_add(1, Ordering::Relaxed);
1837 }
1838 removed
1839 }
1840
1841 pub fn depopulate_many(self, keys: &[u64]) -> usize {
1849 if keys.is_empty() {
1850 return 0;
1851 }
1852 let set: std::collections::HashSet<u64> = keys.iter().copied().collect();
1853 let removed = {
1854 let mut g = self.inner.data.write().expect("store poisoned");
1855 let before = g.len();
1856 g.items_mut().retain(|item| !set.contains(&item.handle()));
1857 g.reindex_if_stale();
1858 before - g.len()
1859 };
1860 if removed > 0 {
1861 self.inner.version.fetch_add(1, Ordering::Relaxed);
1862 }
1863 removed
1864 }
1865
1866 #[doc(hidden)]
1871 pub fn dispose_contents(self) {
1872 let old = {
1873 let mut data = self
1874 .inner
1875 .data
1876 .write()
1877 .unwrap_or_else(std::sync::PoisonError::into_inner);
1878 std::mem::replace(&mut *data, Keyed::new(Vec::new()))
1879 };
1880 drop(old);
1882 }
1883
1884 pub fn is_observed(self, key: impl Into<ModelId<T>>) -> bool {
1888 let key = key.into().handle();
1889 let elem = Path::under(self.node, key);
1890 if TRIGGERS.with(|t| t.borrow().contains_key(&elem)) {
1891 return true;
1892 }
1893 NODES.with(|n| {
1894 let i = n.borrow();
1895 match i.lookup.get(&elem) {
1896 Some(id) => match i.slots.get(id.idx as usize) {
1897 Some(s) if s.alive && s.generation == id.generation => {
1898 s.triggers > 0 || s.children > 0
1899 }
1900 _ => false,
1901 },
1902 None => false,
1903 }
1904 })
1905 }
1906}
1907
1908impl<T: Identified + 'static> Elem<T> {
1909 #[must_use]
1911 pub fn key(self) -> u64 {
1912 self.key
1913 }
1914
1915 #[must_use]
1918 pub fn model_id(self) -> ModelId<T> {
1919 ModelId::from_handle(self.key)
1920 }
1921
1922 #[must_use]
1926 pub fn exists(self) -> bool {
1927 track(self.path());
1928 self.with_value_untracked(|v| v.is_some())
1929 }
1930
1931 fn live_node(self) -> NodeId {
1934 if is_current(self.node) {
1935 self.node
1936 } else {
1937 intern(Path::under(self.store.node, self.key))
1938 }
1939 }
1940}
1941
1942impl<T: Identified + 'static> Source<T> for Elem<T> {
1943 fn path(self) -> Path {
1944 Path::under(self.store.node, self.key)
1946 }
1947 fn node(self) -> NodeId {
1948 self.live_node()
1949 }
1950 fn components(self, out: &mut Vec<u64>) {
1951 self.store.components(out);
1952 out.push(self.key);
1953 }
1954 fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
1955 let g = self.store.inner.data.read().expect("store poisoned");
1956 f(g.get(self.key))
1957 }
1958 fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
1959 let mut g = self.store.inner.data.write().expect("store poisoned");
1960 match g.get_mut(self.key) {
1961 Some(t) => {
1962 f(t);
1963 true
1964 }
1965 None => false,
1966 }
1967 }
1968 fn bump_version(self) {
1969 self.store.inner.version.fetch_add(1, Ordering::Relaxed);
1970 }
1971}
1972
1973pub struct Field<S, T: 'static, V: 'static> {
1980 src: S,
1981 path: Path,
1982 part: u64,
1983 label: &'static str,
1984 get: fn(&T) -> &V,
1985 get_mut: fn(&mut T) -> &mut V,
1986}
1987
1988impl<S: Copy, T, V> Clone for Field<S, T, V> {
1989 fn clone(&self) -> Self {
1990 *self
1991 }
1992}
1993impl<S: Copy, T, V> Copy for Field<S, T, V> {}
1994
1995pub fn project<S: Source<T>, T: 'static, V: 'static>(
1998 src: S,
1999 label: &'static str,
2000 get: fn(&T) -> &V,
2001 get_mut: fn(&mut T) -> &mut V,
2002) -> Field<S, T, V> {
2003 let part = field_id(label);
2004 Field {
2005 src,
2006 path: Path::under(src.node(), part),
2008 part,
2009 label,
2010 get,
2011 get_mut,
2012 }
2013}
2014
2015impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
2016 fn live_path(self) -> Path {
2020 if !S::DYNAMIC && is_current(self.path.parent) {
2021 self.path
2022 } else {
2023 Path::under(self.src.node(), self.part)
2024 }
2025 }
2026
2027 pub fn with<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
2029 self.src.track_extra();
2030 track(self.live_path());
2031 self.src.with_value_untracked(|t| f(t.map(self.get)))
2032 }
2033
2034 pub fn with_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
2035 self.src.with_value_untracked(|t| f(t.map(self.get)))
2036 }
2037
2038 pub fn update(self, f: impl FnOnce(&mut V))
2041 where
2042 V: Clone,
2043 {
2044 let capture = values_wanted() && !previewing();
2045 let mut prior: Option<Rc<dyn Any>> = None;
2046 let mut after: Option<Rc<dyn Any>> = None;
2047 let get_mut = self.get_mut;
2048 let ok = self.src.update_value(|t| {
2049 let slot = get_mut(t);
2050 if capture {
2051 prior = Some(Rc::new(slot.clone()));
2052 }
2053 f(slot);
2054 if capture {
2055 after = Some(Rc::new(slot.clone()));
2056 }
2057 });
2058 if ok {
2059 self.src.bump_version();
2060 notify_change(
2061 self.live_path(),
2062 || {
2063 let mut parts = Vec::new();
2064 Source::<V>::components(self, &mut parts);
2065 parts
2066 },
2067 self.label,
2068 Op::Set,
2069 prior,
2070 after,
2071 );
2072 }
2073 }
2074
2075 pub fn touch(self, tx: &mut TxPaths) {
2078 let mut parts = Vec::new();
2079 Source::<V>::components(self, &mut parts);
2080 tx.push((parts, self.label));
2081 }
2082
2083 pub fn path(self) -> Path {
2084 self.live_path()
2085 }
2086
2087 pub fn label(self) -> &'static str {
2088 self.label
2089 }
2090}
2091
2092impl<S: Source<T>, T: 'static, V: 'static> Source<V> for Field<S, T, V> {
2094 const DYNAMIC: bool = S::DYNAMIC;
2097 fn track_extra(self) {
2098 self.src.track_extra();
2099 }
2100 fn path(self) -> Path {
2101 self.live_path()
2102 }
2103 fn node(self) -> NodeId {
2106 intern(self.live_path())
2107 }
2108 fn components(self, out: &mut Vec<u64>) {
2109 self.src.components(out);
2110 out.push(self.part);
2111 }
2112 fn with_value_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
2113 self.with_untracked(f)
2114 }
2115 fn update_value(self, f: impl FnOnce(&mut V)) -> bool {
2116 let get_mut = self.get_mut;
2117 self.src.update_value(|t| f(get_mut(t)))
2118 }
2119 fn bump_version(self) {
2120 self.src.bump_version();
2121 }
2122}
2123
2124impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Binding<V> for Field<S, T, V> {
2126 fn read(&self) -> V {
2127 self.with(|v| v.cloned().unwrap_or_default())
2128 }
2129 fn peek(&self) -> V {
2130 self.with_untracked(|v| v.cloned().unwrap_or_default())
2131 }
2132 fn write(&self, v: V) {
2133 self.update(move |slot| *slot = v);
2134 }
2135 fn write_preview(&self, v: V) {
2136 Field::write_preview(*self, v);
2137 }
2138 fn write_commit(&self, v: V) {
2139 Field::write_commit(*self, v);
2140 }
2141 fn end_preview(&self) {
2142 Field::end_preview(*self);
2143 }
2144}
2145
2146pub struct Mapped<F, V: 'static, U: 'static> {
2153 inner: F,
2154 to: fn(&V) -> U,
2155 from: fn(&U) -> V,
2156 label: &'static str,
2159}
2160
2161impl<F: Copy, V, U> Clone for Mapped<F, V, U> {
2162 fn clone(&self) -> Self {
2163 *self
2164 }
2165}
2166impl<F: Copy, V, U> Copy for Mapped<F, V, U> {}
2167
2168impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
2169 pub fn map<U: 'static>(self, to: fn(&V) -> U, from: fn(&U) -> V) -> Mapped<Self, V, U> {
2172 Mapped {
2173 inner: self,
2174 to,
2175 from,
2176 label: self.label,
2177 }
2178 }
2179}
2180
2181impl<F: Source<V>, V: Clone + Default + 'static, U: Clone + 'static> Binding<U>
2185 for Mapped<F, V, U>
2186{
2187 fn read(&self) -> U {
2188 self.inner.track_extra();
2189 track(self.inner.path());
2190 self.peek()
2191 }
2192 fn peek(&self) -> U {
2193 self.inner.with_value_untracked(|v| match v {
2194 Some(v) => (self.to)(v),
2195 None => (self.to)(&V::default()),
2196 })
2197 }
2198 fn write_preview(&self, u: U) {
2199 let v = (self.from)(&u);
2200 let inner = self.inner;
2201 let mut parts = Vec::new();
2202 inner.components(&mut parts);
2203 PREVIEWS.with(|p| {
2204 p.borrow_mut().entry(parts).or_insert_with(|| {
2205 Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()))
2206 });
2207 });
2208 PREVIEW_WRITE.with(|f| f.set(true));
2209 let ok = inner.update_value(|slot| *slot = v);
2210 if ok {
2211 inner.bump_version();
2212 notify_change(inner.path(), Vec::new, self.label, Op::Set, None, None);
2213 }
2214 PREVIEW_WRITE.with(|f| f.set(false));
2215 }
2216 fn end_preview(&self) {
2217 let mut parts = Vec::new();
2218 self.inner.components(&mut parts);
2219 PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2220 }
2221 fn write_commit(&self, u: U) {
2222 let inner = self.inner;
2223 let mut parts = Vec::new();
2224 inner.components(&mut parts);
2225 let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2226 match open {
2227 None => self.write(u),
2228 Some(prior) => {
2229 let v = (self.from)(&u);
2230 PREVIEW_WRITE.with(|f| f.set(true));
2231 let ok = inner.update_value(|slot| *slot = v);
2232 PREVIEW_WRITE.with(|f| f.set(false));
2233 if ok {
2234 inner.bump_version();
2235 let after: Rc<dyn Any> =
2236 Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()));
2237 notify_change(
2238 inner.path(),
2239 || parts,
2240 self.label,
2241 Op::Set,
2242 Some(prior),
2243 Some(after),
2244 );
2245 }
2246 }
2247 }
2248 }
2249 fn write(&self, u: U) {
2250 let v = (self.from)(&u);
2251 let inner = self.inner;
2252 let capture = values_wanted();
2253 let mut prior: Option<Rc<dyn Any>> = None;
2254 let mut after: Option<Rc<dyn Any>> = None;
2255 let ok = inner.update_value(|slot| {
2256 if capture {
2257 prior = Some(Rc::new(slot.clone()));
2258 }
2259 *slot = v;
2260 if capture {
2261 after = Some(Rc::new(slot.clone()));
2262 }
2263 });
2264 if ok {
2265 inner.bump_version();
2266 notify_change(
2267 inner.path(),
2268 || {
2269 let mut parts = Vec::new();
2270 inner.components(&mut parts);
2271 parts
2272 },
2273 self.label,
2274 Op::Set,
2275 prior,
2276 after,
2277 );
2278 }
2279 }
2280}
2281
2282impl<F: Source<V> + Copy, V: 'static> Mapped<F, V, usize> {
2283 pub fn map_to_f64(self) -> Numeric<Self> {
2285 Numeric { inner: self }
2286 }
2287}
2288
2289pub struct Numeric<M> {
2291 inner: M,
2292}
2293
2294#[expect(
2295 clippy::expl_impl_clone_on_copy,
2296 reason = "a derive would widen `Clone` to non-`Copy` bindings; this keeps the public bounds"
2297)]
2298impl<M: Copy> Clone for Numeric<M> {
2299 fn clone(&self) -> Self {
2300 *self
2301 }
2302}
2303impl<M: Copy> Copy for Numeric<M> {}
2304
2305impl<M: Binding<usize> + Copy + 'static> Binding<f64> for Numeric<M> {
2306 fn read(&self) -> f64 {
2307 self.inner.read() as f64
2308 }
2309 fn peek(&self) -> f64 {
2310 self.inner.peek() as f64
2311 }
2312 fn write(&self, v: f64) {
2313 self.inner.write(v.round().max(0.0) as usize);
2314 }
2315}
2316
2317impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Field<S, T, V> {
2322 pub fn write_preview(self, v: V) {
2327 let mut parts = Vec::new();
2328 Source::<V>::components(self, &mut parts);
2329 PREVIEWS.with(|p| {
2330 p.borrow_mut().entry(parts).or_insert_with(|| {
2331 Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()))
2332 });
2333 });
2334 PREVIEW_WRITE.with(|f| f.set(true));
2335 self.update(move |slot| *slot = v);
2336 PREVIEW_WRITE.with(|f| f.set(false));
2337 }
2338
2339 pub fn write_commit(self, v: V) {
2343 let mut parts = Vec::new();
2344 Source::<V>::components(self, &mut parts);
2345 let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2346 let open = open.filter(|_| self.with_untracked(|s| s.is_some()));
2349 match open {
2350 None => self.update(move |slot| *slot = v),
2351 Some(prior) => {
2352 PREVIEW_WRITE.with(|f| f.set(true));
2353 self.update(move |slot| *slot = v);
2354 PREVIEW_WRITE.with(|f| f.set(false));
2355 let after: Rc<dyn Any> =
2356 Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()));
2357 notify_change(
2358 self.live_path(),
2359 || parts,
2360 self.label,
2361 Op::Set,
2362 Some(prior),
2363 Some(after),
2364 );
2365 }
2366 }
2367 }
2368
2369 pub fn end_preview(self) {
2374 let mut parts = Vec::new();
2375 Source::<V>::components(self, &mut parts);
2376 PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2377 }
2378
2379 pub fn session(self) -> FieldSession<S, T, V> {
2382 FieldSession { field: self }
2383 }
2384}
2385
2386pub struct FieldSession<S: 'static, T: 'static, V: 'static> {
2389 field: Field<S, T, V>,
2390}
2391
2392impl<S: Copy, T, V> Clone for FieldSession<S, T, V> {
2393 fn clone(&self) -> Self {
2394 *self
2395 }
2396}
2397impl<S: Copy, T, V> Copy for FieldSession<S, T, V> {}
2398
2399impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> FieldSession<S, T, V> {
2400 pub fn preview(self, v: V) {
2401 self.field.write_preview(v);
2402 }
2403 pub fn commit(self) {
2405 let v = self
2406 .field
2407 .with_untracked(|s| s.cloned().unwrap_or_default());
2408 self.field.write_commit(v);
2409 }
2410 pub fn cancel(self) {
2413 let mut parts = Vec::new();
2414 Source::<V>::components(self.field, &mut parts);
2415 if let Some(prior) = PREVIEWS.with(|p| p.borrow_mut().remove(&parts))
2416 && let Ok(prior) = prior.downcast::<V>()
2417 {
2418 self.field.write_preview((*prior).clone());
2419 let mut parts = Vec::new();
2421 Source::<V>::components(self.field, &mut parts);
2422 PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2423 }
2424 }
2425}
2426
2427pub trait ApplyField {
2435 fn apply_field(&mut self, label: &str, value: &dyn Any) -> bool;
2436
2437 fn read_field(&self, label: &str) -> Option<Rc<dyn Any>> {
2440 let _ = label;
2441 None
2442 }
2443}
2444
2445type SetFieldFn = Rc<dyn Fn(u64, &'static str, &Rc<dyn Any>) -> bool>;
2446type InsertRowFn = Rc<dyn Fn(u64, &Rc<dyn Any>, Option<usize>) -> bool>;
2447
2448struct StoreOps {
2449 set_field: SetFieldFn,
2450 insert_row: InsertRowFn,
2451 remove_row: Rc<dyn Fn(u64) -> bool>,
2452 move_row: Rc<dyn Fn(u64, usize) -> bool>,
2453}
2454
2455#[derive(Clone)]
2456struct UndoUnit {
2457 label: &'static str,
2458 changes: Vec<Change>,
2459 context: Option<Rc<dyn Any>>,
2462}
2463
2464type ContextRestore = Rc<dyn Fn(&dyn Any)>;
2466
2467struct ContextHook {
2469 capture: Rc<dyn Fn() -> Rc<dyn Any>>,
2470 restore: ContextRestore,
2471 base: Rc<dyn Any>,
2473}
2474
2475#[derive(Clone, Copy, PartialEq)]
2476enum Replay {
2477 No,
2478 Undoing,
2479 Redoing,
2480}
2481
2482struct UndoInner {
2483 levels: usize,
2484 undo: RefCell<std::collections::VecDeque<UndoUnit>>,
2485 redo: RefCell<Vec<UndoUnit>>,
2486 open: RefCell<Vec<Change>>,
2487 group_label: Cell<Option<&'static str>>,
2488 grouping: Cell<usize>,
2489 replaying: Cell<Replay>,
2490 ops: RefCell<HashMap<u64, StoreOps>>,
2491 can_undo: day_reactive::Signal<bool>,
2492 can_redo: day_reactive::Signal<bool>,
2493 undo_label: day_reactive::Signal<String>,
2494 redo_label: day_reactive::Signal<String>,
2495 resolver: RefCell<Rc<dyn Fn(&'static str) -> String>>,
2496 sink: Cell<Option<ChangeSinkId>>,
2497 context: RefCell<Option<ContextHook>>,
2498}
2499
2500#[derive(Clone)]
2504pub struct UndoStack {
2505 inner: Rc<UndoInner>,
2506}
2507
2508pub struct UndoCheckpoint {
2511 undo: std::collections::VecDeque<UndoUnit>,
2512 redo: Vec<UndoUnit>,
2513 open: Vec<Change>,
2514}
2515
2516#[must_use = "keep the group alive until the interaction finishes"]
2518pub struct UndoGroup {
2519 stack: UndoStack,
2520}
2521
2522impl Drop for UndoGroup {
2523 fn drop(&mut self) {
2524 let depth = self.stack.inner.grouping.get() - 1;
2525 self.stack.inner.grouping.set(depth);
2526 if depth == 0 {
2527 self.stack.seal();
2528 self.stack.inner.group_label.set(None);
2530 }
2531 }
2532}
2533
2534impl UndoStack {
2535 #[must_use]
2537 pub fn new(levels: usize) -> UndoStack {
2538 let (can_undo, can_redo, undo_label, redo_label) =
2539 day_reactive::Scope::detached().enter(|| {
2540 (
2541 day_reactive::Signal::new(false),
2542 day_reactive::Signal::new(false),
2543 day_reactive::Signal::new(String::new()),
2544 day_reactive::Signal::new(String::new()),
2545 )
2546 });
2547 let stack = UndoStack {
2548 inner: Rc::new(UndoInner {
2549 levels: levels.max(1),
2550 undo: RefCell::new(std::collections::VecDeque::new()),
2551 redo: RefCell::new(Vec::new()),
2552 open: RefCell::new(Vec::new()),
2553 group_label: Cell::new(None),
2554 grouping: Cell::new(0),
2555 replaying: Cell::new(Replay::No),
2556 ops: RefCell::new(HashMap::new()),
2557 can_undo,
2558 can_redo,
2559 undo_label,
2560 redo_label,
2561 resolver: RefCell::new(Rc::new(|label: &'static str| {
2562 let mut s: String = label.replace(['_', '-'], " ");
2563 if let Some(first) = s.get_mut(0..1) {
2564 first.make_ascii_uppercase();
2565 }
2566 s
2567 })),
2568 sink: Cell::new(None),
2569 context: RefCell::new(None),
2570 }),
2571 };
2572 want_values_standing(true);
2573 let weak = Rc::downgrade(&stack.inner);
2574 let sink = install_change_sink(move |change| {
2575 if let Some(inner) = weak.upgrade() {
2576 UndoStack { inner }.capture(change);
2577 }
2578 });
2579 stack.inner.sink.set(Some(sink));
2580 let weak = Rc::downgrade(&stack.inner);
2581 day_reactive::on_turn_end(move || {
2582 if let Some(inner) = weak.upgrade() {
2583 let stack = UndoStack { inner };
2584 if stack.inner.grouping.get() == 0 {
2585 stack.seal();
2586 }
2587 }
2588 });
2589 stack
2590 }
2591
2592 pub fn watch<T: ApplyField + Identified + Clone + 'static>(&self, store: Store<Keyed<T>>) {
2595 let ops = StoreOps {
2596 set_field: {
2597 Rc::new(move |key: u64, label: &'static str, value: &Rc<dyn Any>| {
2598 let elem = store.elem(key);
2599 let mut applied = false;
2600 let ok = elem.update_value(|row| {
2601 applied = row.apply_field(label, value.as_ref());
2602 });
2603 if ok && applied {
2604 elem.bump_version();
2605 announce_op(&[store.store_id(), key, field_id(label)], label, Op::Set);
2606 }
2607 ok && applied
2608 })
2609 },
2610 insert_row: {
2611 Rc::new(move |key: u64, row: &Rc<dyn Any>, at: Option<usize>| {
2612 let Some(row) = row.downcast_ref::<T>() else {
2613 return false;
2614 };
2615 let row = row.clone();
2616 store.restructure("undo", Op::Insert, key, move |k| match at {
2617 Some(at) if at < k.len() => k.items_mut().insert(at, row),
2618 _ => k.push(row),
2619 });
2620 true
2621 })
2622 },
2623 remove_row: {
2624 Rc::new(move |key: u64| {
2625 store.restructure("undo", Op::Delete, key, move |k| {
2626 k.remove(key);
2627 });
2628 true
2629 })
2630 },
2631 move_row: {
2632 Rc::new(move |key: u64, to: usize| {
2633 let from =
2634 store.with_untracked(|k| k.items().iter().position(|t| t.handle() == key));
2635 from.is_some_and(|from| store.move_row(from, to))
2636 })
2637 },
2638 };
2639 self.inner.ops.borrow_mut().insert(store.store_id(), ops);
2640 }
2641
2642 fn capture(&self, change: &Change) {
2643 if self.inner.replaying.get() != Replay::No {
2644 return;
2645 }
2646 if change.author.is_some() {
2650 return;
2651 }
2652 let Some(&store) = change.components.first() else {
2653 return;
2654 };
2655 if !self.inner.ops.borrow().contains_key(&store) {
2656 return;
2657 }
2658 let Some(&key) = change.components.get(1) else {
2659 self.clear();
2661 return;
2662 };
2663 if key == STRUCTURE {
2664 return;
2665 }
2666 if change.op == Op::Set && change.components.len() >= 3 && change.prior.is_none() {
2667 return;
2669 }
2670 self.inner.open.borrow_mut().push(change.clone());
2671 }
2672
2673 fn seal(&self) {
2675 let changes = std::mem::take(&mut *self.inner.open.borrow_mut());
2676 if changes.is_empty() {
2677 return;
2678 }
2679 let label = self
2680 .inner
2681 .group_label
2682 .take()
2683 .unwrap_or_else(|| changes.first().map_or("", |c| c.label));
2684 let context = self.inner.context.borrow().as_ref().map(|h| (h.capture)());
2688 let mut undo = self.inner.undo.borrow_mut();
2689 undo.push_back(UndoUnit {
2690 label,
2691 changes,
2692 context,
2693 });
2694 while undo.len() > self.inner.levels {
2695 undo.pop_front();
2696 }
2697 drop(undo);
2698 self.inner.redo.borrow_mut().clear();
2700 self.refresh();
2701 }
2702
2703 pub fn grouped(&self, label: &'static str, f: impl FnOnce()) {
2706 let _group = self.begin_group(label);
2707 f();
2708 }
2709
2710 pub fn begin_group(&self, label: &'static str) -> UndoGroup {
2714 if self.inner.grouping.get() == 0 {
2715 self.seal();
2716 self.inner.group_label.set(Some(label));
2717 }
2718 self.inner.grouping.set(self.inner.grouping.get() + 1);
2719 UndoGroup {
2720 stack: self.clone(),
2721 }
2722 }
2723
2724 #[must_use]
2727 pub fn checkpoint(&self) -> UndoCheckpoint {
2728 UndoCheckpoint {
2729 undo: self.inner.undo.borrow().clone(),
2730 redo: self.inner.redo.borrow().clone(),
2731 open: self.inner.open.borrow().clone(),
2732 }
2733 }
2734
2735 pub fn restore_checkpoint(&self, checkpoint: UndoCheckpoint) {
2736 *self.inner.undo.borrow_mut() = checkpoint.undo;
2737 *self.inner.redo.borrow_mut() = checkpoint.redo;
2738 *self.inner.open.borrow_mut() = checkpoint.open;
2739 self.refresh();
2740 }
2741
2742 #[must_use]
2743 pub fn can_undo(&self) -> day_reactive::Signal<bool> {
2744 self.inner.can_undo
2745 }
2746 #[must_use]
2747 pub fn can_redo(&self) -> day_reactive::Signal<bool> {
2748 self.inner.can_redo
2749 }
2750 #[must_use]
2753 pub fn undo_label(&self) -> day_reactive::Signal<String> {
2754 self.inner.undo_label
2755 }
2756 #[must_use]
2757 pub fn redo_label(&self) -> day_reactive::Signal<String> {
2758 self.inner.redo_label
2759 }
2760
2761 pub fn set_label_resolver(&self, f: impl Fn(&'static str) -> String + 'static) {
2764 *self.inner.resolver.borrow_mut() = Rc::new(f);
2765 self.refresh();
2766 }
2767
2768 pub fn set_transient_context(
2783 &self,
2784 capture: impl Fn() -> Rc<dyn Any> + 'static,
2785 restore: impl Fn(&dyn Any) + 'static,
2786 ) {
2787 let base = capture();
2788 *self.inner.context.borrow_mut() = Some(ContextHook {
2789 capture: Rc::new(capture),
2790 restore: Rc::new(restore),
2791 base,
2792 });
2793 }
2794
2795 fn restore_context(&self) {
2799 let (target, restore) = {
2800 let hook = self.inner.context.borrow();
2801 let Some(h) = hook.as_ref() else { return };
2802 let target = match self.inner.undo.borrow().back() {
2803 Some(unit) => unit.context.clone(),
2804 None => Some(h.base.clone()),
2805 };
2806 (target, h.restore.clone())
2807 };
2808 if let Some(ctx) = target {
2809 restore(&*ctx);
2810 }
2811 }
2812
2813 pub fn undo(&self) -> bool {
2814 if self.inner.grouping.get() > 0 {
2816 return false;
2817 }
2818 self.seal();
2819 let Some(unit) = self.inner.undo.borrow_mut().pop_back() else {
2820 return false;
2821 };
2822 self.inner.replaying.set(Replay::Undoing);
2823 with_author("undo", || {
2824 day_reactive::batch(|| {
2825 for ch in unit.changes.iter().rev() {
2826 self.apply(ch, true);
2827 }
2828 });
2829 });
2830 self.inner.replaying.set(Replay::No);
2831 self.inner.redo.borrow_mut().push(unit);
2832 self.restore_context();
2836 self.refresh();
2837 true
2838 }
2839
2840 pub fn redo(&self) -> bool {
2841 if self.inner.grouping.get() > 0 {
2843 return false;
2844 }
2845 let Some(unit) = self.inner.redo.borrow_mut().pop() else {
2846 return false;
2847 };
2848 self.inner.replaying.set(Replay::Redoing);
2849 with_author("redo", || {
2850 day_reactive::batch(|| {
2851 for ch in &unit.changes {
2852 self.apply(ch, false);
2853 }
2854 });
2855 });
2856 self.inner.replaying.set(Replay::No);
2857 self.inner.undo.borrow_mut().push_back(unit);
2858 self.restore_context();
2860 self.refresh();
2861 true
2862 }
2863
2864 pub fn clear(&self) {
2866 self.inner.undo.borrow_mut().clear();
2867 self.inner.redo.borrow_mut().clear();
2868 self.inner.open.borrow_mut().clear();
2869 self.refresh();
2870 }
2871
2872 fn apply(&self, ch: &Change, invert: bool) {
2873 let (Some(&store), Some(&key)) = (ch.components.first(), ch.components.get(1)) else {
2874 return;
2875 };
2876 let ops = self.inner.ops.borrow();
2877 let Some(ops) = ops.get(&store) else {
2878 return;
2879 };
2880 let effective = if invert {
2881 match ch.op {
2882 Op::Set => Op::Set,
2883 Op::Insert => Op::Delete,
2884 Op::Delete => Op::Insert,
2885 Op::Move => Op::Move,
2886 }
2887 } else {
2888 ch.op
2889 };
2890 let index = |v: &Option<Rc<dyn Any>>| {
2891 v.as_deref()
2892 .and_then(|v| v.downcast_ref::<usize>().copied())
2893 };
2894 match effective {
2895 Op::Set => {
2896 let v = if invert { &ch.prior } else { &ch.value };
2897 if let Some(v) = v {
2898 (ops.set_field)(key, ch.label, v);
2899 }
2900 }
2901 Op::Insert => {
2902 let (row, at) = if invert {
2904 (&ch.prior, index(&ch.value))
2905 } else {
2906 (&ch.value, index(&ch.prior))
2907 };
2908 if let Some(row) = row {
2909 (ops.insert_row)(key, row, at);
2910 }
2911 }
2912 Op::Delete => {
2913 (ops.remove_row)(key);
2914 }
2915 Op::Move => {
2916 let to = if invert { &ch.prior } else { &ch.value };
2917 if let Some(to) = index(to) {
2918 (ops.move_row)(key, to);
2919 }
2920 }
2921 }
2922 }
2923
2924 fn refresh(&self) {
2925 let resolver = self.inner.resolver.borrow().clone();
2926 let undo = self.inner.undo.borrow();
2927 self.inner.can_undo.set_if_changed(!undo.is_empty());
2928 self.inner
2929 .undo_label
2930 .set_if_changed(undo.back().map_or_default(|u| resolver(u.label)));
2931 drop(undo);
2932 let redo = self.inner.redo.borrow();
2933 self.inner.can_redo.set_if_changed(!redo.is_empty());
2934 self.inner
2935 .redo_label
2936 .set_if_changed(redo.last().map_or_default(|u| resolver(u.label)));
2937 }
2938}
2939
2940impl Drop for UndoInner {
2941 fn drop(&mut self) {
2942 if let Some(sink) = self.sink.take() {
2943 remove_change_sink(sink);
2944 }
2945 let _ = WANT_VALUES_STANDING.try_with(|w| w.set(w.get().saturating_sub(1)));
2947 }
2948}