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 pub fn under(parent: NodeId, part: u64) -> Path {
124 Path { parent, part }
125 }
126
127 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 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
154pub 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 pinned: bool,
177 children: u32,
179 triggers: u32,
181}
182
183#[derive(Default)]
184struct Interner {
185 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 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 static TRIGGERS: RefCell<HashMap<Path, Entry>> = RefCell::new(HashMap::new());
259
260 static RECORDER: RefCell<Option<Vec<Change>>> = const { RefCell::new(None) };
263
264 static WANT_VALUES: Cell<bool> = const { Cell::new(false) };
266
267 static WANT_VALUES_STANDING: Cell<u32> = const { Cell::new(0) };
270
271 static PREVIEW_WRITE: Cell<bool> = const { Cell::new(false) };
275
276 static PREVIEWS: RefCell<HashMap<Vec<u64>, Rc<dyn Any>>> = RefCell::new(HashMap::new());
279
280 static CURRENT_AUTHOR: Cell<Option<&'static str>> = const { Cell::new(None) };
283
284 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
295pub struct ChangeSinkId(u64);
296
297pub 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 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
324fn 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
334struct Entry {
336 trigger: Trigger,
337 scope: Scope,
339 watchers: Vec<day_reactive::RunId>,
342}
343
344fn 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
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
408pub fn interned_nodes() -> usize {
411 NODES.with(|n| n.borrow().slots.iter().filter(|s| s.alive).count() - 1)
412}
413
414fn 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 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 day_reactive::on_run_retrack(move || release(p, watcher));
459 }
460 trigger.track();
461}
462
463fn 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 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
499pub fn observed_paths() -> usize {
501 TRIGGERS.with(|t| t.borrow().len())
502}
503
504#[derive(Clone, Copy, PartialEq, Eq, Debug)]
512pub enum Op {
513 Set,
515 Insert,
517 Delete,
519 Move,
521}
522
523#[derive(Clone)]
532pub struct Change {
533 pub components: Vec<u64>,
535 pub label: &'static str,
537 pub op: Op,
538 pub prior: Option<Rc<dyn Any>>,
539 pub value: Option<Rc<dyn Any>>,
540 pub author: Option<&'static str>,
543}
544
545impl Change {
546 pub fn prior_as<T: 'static>(&self) -> Option<&T> {
548 self.prior.as_deref().and_then(|v| v.downcast_ref())
549 }
550
551 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
573pub fn record_capture_active() -> bool {
579 values_wanted()
580}
581
582pub 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
595pub 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
612pub 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
621pub 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
630pub 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
636fn 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 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
688pub fn announce(parts: &[u64], label: &'static str) {
695 announce_op(parts, label, Op::Set);
696}
697
698fn 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 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
740pub trait Source<T: 'static>: Copy + 'static {
750 const DYNAMIC: bool = false;
755
756 fn track_extra(self) {}
759
760 fn path(self) -> Path;
763 fn node(self) -> NodeId;
768 fn components(self, out: &mut Vec<u64>);
772 fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R;
773 fn update_value(self, f: impl FnOnce(&mut T)) -> bool;
776 fn bump_version(self);
777
778 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
786pub type TxPaths = Vec<(Vec<u64>, &'static str)>;
789
790pub 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
814static NEXT_STORE: AtomicU64 = AtomicU64::new(1);
816
817impl<T: 'static> Store<T> {
818 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 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 pub fn version(self) -> u64 {
861 self.inner.version.load(Ordering::Relaxed)
862 }
863
864 pub fn store_id(self) -> u64 {
867 self.root_id
868 }
869
870 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 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
912unsafe impl<T: Send + Sync> Send for Store<T> {}
916unsafe impl<T: Send + Sync> Sync for Store<T> {}
917
918impl<T: Send + Sync + 'static> Store<T> {
923 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
935pub 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 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 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 }
973}
974
975const WIDE_BASE: u64 = 1 << 63;
984
985#[derive(Clone, PartialEq, Eq, Hash, Debug)]
995pub enum Key {
996 U64(u64),
997 Uuid(u128),
999 Str(Arc<str>),
1001 Pair(u64, u64),
1004}
1005
1006impl Key {
1007 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 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#[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
1084static 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; }
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
1112pub fn interned_keys() -> usize {
1115 wide_keys()
1116 .read()
1117 .expect("key interner poisoned")
1118 .reverse
1119 .len()
1120}
1121
1122pub 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
1172pub 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 pub fn of(key: impl AsKey) -> Self {
1223 Self::from_handle(key.as_key().handle())
1224 }
1225 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 pub fn key(self) -> Key {
1237 Key::of_handle(self.handle).unwrap_or(Key::U64(self.handle))
1238 }
1239}
1240
1241impl<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
1254impl<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
1302pub trait Identified {
1309 fn key(&self) -> Key;
1311
1312 fn handle(&self) -> u64 {
1314 self.key().handle()
1315 }
1316
1317 fn model_id(&self) -> ModelId<Self>
1320 where
1321 Self: Sized,
1322 {
1323 ModelId::from_handle(self.handle())
1324 }
1325}
1326
1327pub struct Keyed<T> {
1330 items: Vec<T>,
1331 index: HashMap<u64, usize>,
1332 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 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 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 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 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 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 pub fn clear(&mut self) {
1454 self.items.clear();
1455 self.index.clear();
1456 self.stale = false;
1457 }
1458
1459 pub fn items_mut(&mut self) -> &mut Vec<T> {
1464 self.stale = true;
1465 &mut self.items
1466 }
1467}
1468
1469pub struct Elem<T: 'static> {
1475 store: Store<Keyed<T>>,
1476 key: u64,
1477 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 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 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 pub fn ids(self) -> Vec<ModelId<T>> {
1510 self.keys().into_iter().map(ModelId::from_handle).collect()
1511 }
1512
1513 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 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 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 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 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 pub fn next_key(self) -> u64 {
1626 self.with_untracked(|k| k.next_key())
1627 }
1628
1629 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 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 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 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 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 #[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 drop(old);
1782 }
1783
1784 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 pub fn key(self) -> u64 {
1811 self.key
1812 }
1813
1814 pub fn model_id(self) -> ModelId<T> {
1817 ModelId::from_handle(self.key)
1818 }
1819
1820 pub fn exists(self) -> bool {
1824 track(self.path());
1825 self.with_value_untracked(|v| v.is_some())
1826 }
1827
1828 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 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
1870pub 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
1892pub 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 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 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 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 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 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
1989impl<S: Source<T>, T: 'static, V: 'static> Source<V> for Field<S, T, V> {
1991 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 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
2021impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Binding<V> for Field<S, T, V> {
2023 fn read(&self) -> V {
2024 self.with(|v| v.cloned().unwrap_or_default())
2025 }
2026 fn peek(&self) -> V {
2027 self.with_untracked(|v| v.cloned().unwrap_or_default())
2028 }
2029 fn write(&self, v: V) {
2030 self.update(move |slot| *slot = v);
2031 }
2032 fn write_preview(&self, v: V) {
2033 Field::write_preview(*self, v);
2034 }
2035 fn write_commit(&self, v: V) {
2036 Field::write_commit(*self, v);
2037 }
2038}
2039
2040pub struct Mapped<F, V: 'static, U: 'static> {
2047 inner: F,
2048 to: fn(&V) -> U,
2049 from: fn(&U) -> V,
2050 label: &'static str,
2053}
2054
2055impl<F: Copy, V, U> Clone for Mapped<F, V, U> {
2056 fn clone(&self) -> Self {
2057 *self
2058 }
2059}
2060impl<F: Copy, V, U> Copy for Mapped<F, V, U> {}
2061
2062impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
2063 pub fn map<U: 'static>(self, to: fn(&V) -> U, from: fn(&U) -> V) -> Mapped<Self, V, U> {
2066 Mapped {
2067 inner: self,
2068 to,
2069 from,
2070 label: self.label,
2071 }
2072 }
2073}
2074
2075impl<F: Source<V>, V: Clone + Default + 'static, U: Clone + 'static> Binding<U>
2079 for Mapped<F, V, U>
2080{
2081 fn read(&self) -> U {
2082 self.inner.track_extra();
2083 track(self.inner.path());
2084 self.peek()
2085 }
2086 fn peek(&self) -> U {
2087 self.inner.with_value_untracked(|v| match v {
2088 Some(v) => (self.to)(v),
2089 None => (self.to)(&V::default()),
2090 })
2091 }
2092 fn write_preview(&self, u: U) {
2093 let v = (self.from)(&u);
2094 let inner = self.inner;
2095 let mut parts = Vec::new();
2096 inner.components(&mut parts);
2097 PREVIEWS.with(|p| {
2098 p.borrow_mut().entry(parts).or_insert_with(|| {
2099 Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()))
2100 });
2101 });
2102 PREVIEW_WRITE.with(|f| f.set(true));
2103 let ok = inner.update_value(|slot| *slot = v);
2104 if ok {
2105 inner.bump_version();
2106 notify_change(inner.path(), Vec::new, self.label, Op::Set, None, None);
2107 }
2108 PREVIEW_WRITE.with(|f| f.set(false));
2109 }
2110 fn write_commit(&self, u: U) {
2111 let inner = self.inner;
2112 let mut parts = Vec::new();
2113 inner.components(&mut parts);
2114 let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2115 match open {
2116 None => self.write(u),
2117 Some(prior) => {
2118 let v = (self.from)(&u);
2119 PREVIEW_WRITE.with(|f| f.set(true));
2120 let ok = inner.update_value(|slot| *slot = v);
2121 PREVIEW_WRITE.with(|f| f.set(false));
2122 if ok {
2123 inner.bump_version();
2124 let after: Rc<dyn Any> =
2125 Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()));
2126 notify_change(
2127 inner.path(),
2128 || parts,
2129 self.label,
2130 Op::Set,
2131 Some(prior),
2132 Some(after),
2133 );
2134 }
2135 }
2136 }
2137 }
2138 fn write(&self, u: U) {
2139 let v = (self.from)(&u);
2140 let inner = self.inner;
2141 let capture = values_wanted();
2142 let mut prior: Option<Rc<dyn Any>> = None;
2143 let mut after: Option<Rc<dyn Any>> = None;
2144 let ok = inner.update_value(|slot| {
2145 if capture {
2146 prior = Some(Rc::new(slot.clone()));
2147 }
2148 *slot = v;
2149 if capture {
2150 after = Some(Rc::new(slot.clone()));
2151 }
2152 });
2153 if ok {
2154 inner.bump_version();
2155 notify_change(
2156 inner.path(),
2157 || {
2158 let mut parts = Vec::new();
2159 inner.components(&mut parts);
2160 parts
2161 },
2162 self.label,
2163 Op::Set,
2164 prior,
2165 after,
2166 );
2167 }
2168 }
2169}
2170
2171impl<F: Source<V> + Copy, V: 'static> Mapped<F, V, usize> {
2172 pub fn map_to_f64(self) -> Numeric<Self> {
2174 Numeric { inner: self }
2175 }
2176}
2177
2178pub struct Numeric<M> {
2180 inner: M,
2181}
2182
2183impl<M: Copy> Clone for Numeric<M> {
2184 fn clone(&self) -> Self {
2185 *self
2186 }
2187}
2188impl<M: Copy> Copy for Numeric<M> {}
2189
2190impl<M: Binding<usize> + Copy + 'static> Binding<f64> for Numeric<M> {
2191 fn read(&self) -> f64 {
2192 self.inner.read() as f64
2193 }
2194 fn peek(&self) -> f64 {
2195 self.inner.peek() as f64
2196 }
2197 fn write(&self, v: f64) {
2198 self.inner.write(v.round().max(0.0) as usize);
2199 }
2200}
2201
2202impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Field<S, T, V> {
2207 pub fn write_preview(self, v: V) {
2212 let mut parts = Vec::new();
2213 Source::<V>::components(self, &mut parts);
2214 PREVIEWS.with(|p| {
2215 p.borrow_mut().entry(parts).or_insert_with(|| {
2216 Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()))
2217 });
2218 });
2219 PREVIEW_WRITE.with(|f| f.set(true));
2220 self.update(move |slot| *slot = v);
2221 PREVIEW_WRITE.with(|f| f.set(false));
2222 }
2223
2224 pub fn write_commit(self, v: V) {
2228 let mut parts = Vec::new();
2229 Source::<V>::components(self, &mut parts);
2230 let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2231 let open = open.filter(|_| self.with_untracked(|s| s.is_some()));
2234 match open {
2235 None => self.update(move |slot| *slot = v),
2236 Some(prior) => {
2237 PREVIEW_WRITE.with(|f| f.set(true));
2238 self.update(move |slot| *slot = v);
2239 PREVIEW_WRITE.with(|f| f.set(false));
2240 let after: Rc<dyn Any> =
2241 Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()));
2242 notify_change(
2243 self.live_path(),
2244 || parts,
2245 self.label,
2246 Op::Set,
2247 Some(prior),
2248 Some(after),
2249 );
2250 }
2251 }
2252 }
2253
2254 pub fn session(self) -> FieldSession<S, T, V> {
2257 FieldSession { field: self }
2258 }
2259}
2260
2261pub struct FieldSession<S: 'static, T: 'static, V: 'static> {
2264 field: Field<S, T, V>,
2265}
2266
2267impl<S: Copy, T, V> Clone for FieldSession<S, T, V> {
2268 fn clone(&self) -> Self {
2269 *self
2270 }
2271}
2272impl<S: Copy, T, V> Copy for FieldSession<S, T, V> {}
2273
2274impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> FieldSession<S, T, V> {
2275 pub fn preview(self, v: V) {
2276 self.field.write_preview(v);
2277 }
2278 pub fn commit(self) {
2280 let v = self
2281 .field
2282 .with_untracked(|s| s.cloned().unwrap_or_default());
2283 self.field.write_commit(v);
2284 }
2285 pub fn cancel(self) {
2288 let mut parts = Vec::new();
2289 Source::<V>::components(self.field, &mut parts);
2290 if let Some(prior) = PREVIEWS.with(|p| p.borrow_mut().remove(&parts))
2291 && let Ok(prior) = prior.downcast::<V>()
2292 {
2293 self.field.write_preview((*prior).clone());
2294 let mut parts = Vec::new();
2296 Source::<V>::components(self.field, &mut parts);
2297 PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
2298 }
2299 }
2300}
2301
2302pub trait ApplyField {
2310 fn apply_field(&mut self, label: &str, value: &dyn Any) -> bool;
2311
2312 fn read_field(&self, label: &str) -> Option<Rc<dyn Any>> {
2315 let _ = label;
2316 None
2317 }
2318}
2319
2320type SetFieldFn = Rc<dyn Fn(u64, &'static str, &Rc<dyn Any>) -> bool>;
2321type InsertRowFn = Rc<dyn Fn(u64, &Rc<dyn Any>, Option<usize>) -> bool>;
2322
2323struct StoreOps {
2324 set_field: SetFieldFn,
2325 insert_row: InsertRowFn,
2326 remove_row: Rc<dyn Fn(u64) -> bool>,
2327 move_row: Rc<dyn Fn(u64, usize) -> bool>,
2328}
2329
2330#[derive(Clone)]
2331struct UndoUnit {
2332 label: &'static str,
2333 changes: Vec<Change>,
2334 context: Option<Rc<dyn Any>>,
2337}
2338
2339type ContextRestore = Rc<dyn Fn(&dyn Any)>;
2341
2342struct ContextHook {
2344 capture: Rc<dyn Fn() -> Rc<dyn Any>>,
2345 restore: ContextRestore,
2346 base: Rc<dyn Any>,
2348}
2349
2350#[derive(Clone, Copy, PartialEq)]
2351enum Replay {
2352 No,
2353 Undoing,
2354 Redoing,
2355}
2356
2357struct UndoInner {
2358 levels: usize,
2359 undo: RefCell<std::collections::VecDeque<UndoUnit>>,
2360 redo: RefCell<Vec<UndoUnit>>,
2361 open: RefCell<Vec<Change>>,
2362 group_label: Cell<Option<&'static str>>,
2363 grouping: Cell<usize>,
2364 replaying: Cell<Replay>,
2365 ops: RefCell<HashMap<u64, StoreOps>>,
2366 can_undo: day_reactive::Signal<bool>,
2367 can_redo: day_reactive::Signal<bool>,
2368 undo_label: day_reactive::Signal<String>,
2369 redo_label: day_reactive::Signal<String>,
2370 resolver: RefCell<Rc<dyn Fn(&'static str) -> String>>,
2371 sink: Cell<Option<ChangeSinkId>>,
2372 context: RefCell<Option<ContextHook>>,
2373}
2374
2375#[derive(Clone)]
2379pub struct UndoStack {
2380 inner: Rc<UndoInner>,
2381}
2382
2383pub struct UndoCheckpoint {
2386 undo: std::collections::VecDeque<UndoUnit>,
2387 redo: Vec<UndoUnit>,
2388 open: Vec<Change>,
2389}
2390
2391#[must_use = "keep the group alive until the interaction finishes"]
2393pub struct UndoGroup {
2394 stack: UndoStack,
2395}
2396
2397impl Drop for UndoGroup {
2398 fn drop(&mut self) {
2399 let depth = self.stack.inner.grouping.get() - 1;
2400 self.stack.inner.grouping.set(depth);
2401 if depth == 0 {
2402 self.stack.seal();
2403 self.stack.inner.group_label.set(None);
2405 }
2406 }
2407}
2408
2409impl UndoStack {
2410 pub fn new(levels: usize) -> UndoStack {
2412 let (can_undo, can_redo, undo_label, redo_label) =
2413 day_reactive::Scope::detached().enter(|| {
2414 (
2415 day_reactive::Signal::new(false),
2416 day_reactive::Signal::new(false),
2417 day_reactive::Signal::new(String::new()),
2418 day_reactive::Signal::new(String::new()),
2419 )
2420 });
2421 let stack = UndoStack {
2422 inner: Rc::new(UndoInner {
2423 levels: levels.max(1),
2424 undo: RefCell::new(std::collections::VecDeque::new()),
2425 redo: RefCell::new(Vec::new()),
2426 open: RefCell::new(Vec::new()),
2427 group_label: Cell::new(None),
2428 grouping: Cell::new(0),
2429 replaying: Cell::new(Replay::No),
2430 ops: RefCell::new(HashMap::new()),
2431 can_undo,
2432 can_redo,
2433 undo_label,
2434 redo_label,
2435 resolver: RefCell::new(Rc::new(|label: &'static str| {
2436 let mut s: String = label.replace(['_', '-'], " ");
2437 if let Some(first) = s.get_mut(0..1) {
2438 first.make_ascii_uppercase();
2439 }
2440 s
2441 })),
2442 sink: Cell::new(None),
2443 context: RefCell::new(None),
2444 }),
2445 };
2446 want_values_standing(true);
2447 let weak = Rc::downgrade(&stack.inner);
2448 let sink = install_change_sink(move |change| {
2449 if let Some(inner) = weak.upgrade() {
2450 UndoStack { inner }.capture(change);
2451 }
2452 });
2453 stack.inner.sink.set(Some(sink));
2454 let weak = Rc::downgrade(&stack.inner);
2455 day_reactive::on_turn_end(move || {
2456 if let Some(inner) = weak.upgrade() {
2457 let stack = UndoStack { inner };
2458 if stack.inner.grouping.get() == 0 {
2459 stack.seal();
2460 }
2461 }
2462 });
2463 stack
2464 }
2465
2466 pub fn watch<T: ApplyField + Identified + Clone + 'static>(&self, store: Store<Keyed<T>>) {
2469 let ops = StoreOps {
2470 set_field: {
2471 Rc::new(move |key: u64, label: &'static str, value: &Rc<dyn Any>| {
2472 let elem = store.elem(key);
2473 let mut applied = false;
2474 let ok = elem.update_value(|row| {
2475 applied = row.apply_field(label, value.as_ref());
2476 });
2477 if ok && applied {
2478 elem.bump_version();
2479 announce_op(&[store.store_id(), key, field_id(label)], label, Op::Set);
2480 }
2481 ok && applied
2482 })
2483 },
2484 insert_row: {
2485 Rc::new(move |key: u64, row: &Rc<dyn Any>, at: Option<usize>| {
2486 let Some(row) = row.downcast_ref::<T>() else {
2487 return false;
2488 };
2489 let row = row.clone();
2490 store.restructure("undo", Op::Insert, key, move |k| match at {
2491 Some(at) if at < k.len() => k.items_mut().insert(at, row),
2492 _ => k.push(row),
2493 });
2494 true
2495 })
2496 },
2497 remove_row: {
2498 Rc::new(move |key: u64| {
2499 store.restructure("undo", Op::Delete, key, move |k| {
2500 k.remove(key);
2501 });
2502 true
2503 })
2504 },
2505 move_row: {
2506 Rc::new(move |key: u64, to: usize| {
2507 let from =
2508 store.with_untracked(|k| k.items().iter().position(|t| t.handle() == key));
2509 from.is_some_and(|from| store.move_row(from, to))
2510 })
2511 },
2512 };
2513 self.inner.ops.borrow_mut().insert(store.store_id(), ops);
2514 }
2515
2516 fn capture(&self, change: &Change) {
2517 if self.inner.replaying.get() != Replay::No {
2518 return;
2519 }
2520 if change.author.is_some() {
2524 return;
2525 }
2526 let Some(&store) = change.components.first() else {
2527 return;
2528 };
2529 if !self.inner.ops.borrow().contains_key(&store) {
2530 return;
2531 }
2532 let Some(&key) = change.components.get(1) else {
2533 self.clear();
2535 return;
2536 };
2537 if key == STRUCTURE {
2538 return;
2539 }
2540 if change.op == Op::Set && change.components.len() >= 3 && change.prior.is_none() {
2541 return;
2543 }
2544 self.inner.open.borrow_mut().push(change.clone());
2545 }
2546
2547 fn seal(&self) {
2549 let changes = std::mem::take(&mut *self.inner.open.borrow_mut());
2550 if changes.is_empty() {
2551 return;
2552 }
2553 let label = self
2554 .inner
2555 .group_label
2556 .take()
2557 .unwrap_or_else(|| changes.first().map(|c| c.label).unwrap_or(""));
2558 let context = self.inner.context.borrow().as_ref().map(|h| (h.capture)());
2562 let mut undo = self.inner.undo.borrow_mut();
2563 undo.push_back(UndoUnit {
2564 label,
2565 changes,
2566 context,
2567 });
2568 while undo.len() > self.inner.levels {
2569 undo.pop_front();
2570 }
2571 drop(undo);
2572 self.inner.redo.borrow_mut().clear();
2574 self.refresh();
2575 }
2576
2577 pub fn grouped(&self, label: &'static str, f: impl FnOnce()) {
2580 let _group = self.begin_group(label);
2581 f();
2582 }
2583
2584 pub fn begin_group(&self, label: &'static str) -> UndoGroup {
2588 if self.inner.grouping.get() == 0 {
2589 self.seal();
2590 self.inner.group_label.set(Some(label));
2591 }
2592 self.inner.grouping.set(self.inner.grouping.get() + 1);
2593 UndoGroup {
2594 stack: self.clone(),
2595 }
2596 }
2597
2598 pub fn checkpoint(&self) -> UndoCheckpoint {
2601 UndoCheckpoint {
2602 undo: self.inner.undo.borrow().clone(),
2603 redo: self.inner.redo.borrow().clone(),
2604 open: self.inner.open.borrow().clone(),
2605 }
2606 }
2607
2608 pub fn restore_checkpoint(&self, checkpoint: UndoCheckpoint) {
2609 *self.inner.undo.borrow_mut() = checkpoint.undo;
2610 *self.inner.redo.borrow_mut() = checkpoint.redo;
2611 *self.inner.open.borrow_mut() = checkpoint.open;
2612 self.refresh();
2613 }
2614
2615 pub fn can_undo(&self) -> day_reactive::Signal<bool> {
2616 self.inner.can_undo
2617 }
2618 pub fn can_redo(&self) -> day_reactive::Signal<bool> {
2619 self.inner.can_redo
2620 }
2621 pub fn undo_label(&self) -> day_reactive::Signal<String> {
2624 self.inner.undo_label
2625 }
2626 pub fn redo_label(&self) -> day_reactive::Signal<String> {
2627 self.inner.redo_label
2628 }
2629
2630 pub fn set_label_resolver(&self, f: impl Fn(&'static str) -> String + 'static) {
2633 *self.inner.resolver.borrow_mut() = Rc::new(f);
2634 self.refresh();
2635 }
2636
2637 pub fn set_transient_context(
2652 &self,
2653 capture: impl Fn() -> Rc<dyn Any> + 'static,
2654 restore: impl Fn(&dyn Any) + 'static,
2655 ) {
2656 let base = capture();
2657 *self.inner.context.borrow_mut() = Some(ContextHook {
2658 capture: Rc::new(capture),
2659 restore: Rc::new(restore),
2660 base,
2661 });
2662 }
2663
2664 fn restore_context(&self, landed: Option<Option<Rc<dyn Any>>>) {
2669 let (target, restore) = {
2670 let hook = self.inner.context.borrow();
2671 let Some(h) = hook.as_ref() else { return };
2672 let target = match landed {
2673 Some(ctx) => ctx,
2674 None => Some(h.base.clone()),
2675 };
2676 (target, h.restore.clone())
2677 };
2678 if let Some(ctx) = target {
2679 restore(&*ctx);
2680 }
2681 }
2682
2683 pub fn undo(&self) -> bool {
2684 if self.inner.grouping.get() > 0 {
2686 return false;
2687 }
2688 self.seal();
2689 let Some(unit) = self.inner.undo.borrow_mut().pop_back() else {
2690 return false;
2691 };
2692 self.inner.replaying.set(Replay::Undoing);
2693 with_author("undo", || {
2694 day_reactive::batch(|| {
2695 for ch in unit.changes.iter().rev() {
2696 self.apply(ch, true);
2697 }
2698 });
2699 });
2700 self.inner.replaying.set(Replay::No);
2701 self.inner.redo.borrow_mut().push(unit);
2702 let landed = self.inner.undo.borrow().back().map(|u| u.context.clone());
2706 self.restore_context(landed);
2707 self.refresh();
2708 true
2709 }
2710
2711 pub fn redo(&self) -> bool {
2712 if self.inner.grouping.get() > 0 {
2714 return false;
2715 }
2716 let Some(unit) = self.inner.redo.borrow_mut().pop() else {
2717 return false;
2718 };
2719 self.inner.replaying.set(Replay::Redoing);
2720 with_author("redo", || {
2721 day_reactive::batch(|| {
2722 for ch in &unit.changes {
2723 self.apply(ch, false);
2724 }
2725 });
2726 });
2727 self.inner.replaying.set(Replay::No);
2728 self.inner.undo.borrow_mut().push_back(unit);
2729 let landed = self.inner.undo.borrow().back().map(|u| u.context.clone());
2731 self.restore_context(landed);
2732 self.refresh();
2733 true
2734 }
2735
2736 pub fn clear(&self) {
2738 self.inner.undo.borrow_mut().clear();
2739 self.inner.redo.borrow_mut().clear();
2740 self.inner.open.borrow_mut().clear();
2741 self.refresh();
2742 }
2743
2744 fn apply(&self, ch: &Change, invert: bool) {
2745 let (Some(&store), Some(&key)) = (ch.components.first(), ch.components.get(1)) else {
2746 return;
2747 };
2748 let ops = self.inner.ops.borrow();
2749 let Some(ops) = ops.get(&store) else {
2750 return;
2751 };
2752 let effective = if invert {
2753 match ch.op {
2754 Op::Set => Op::Set,
2755 Op::Insert => Op::Delete,
2756 Op::Delete => Op::Insert,
2757 Op::Move => Op::Move,
2758 }
2759 } else {
2760 ch.op
2761 };
2762 let index = |v: &Option<Rc<dyn Any>>| {
2763 v.as_deref()
2764 .and_then(|v| v.downcast_ref::<usize>().copied())
2765 };
2766 match effective {
2767 Op::Set => {
2768 let v = if invert { &ch.prior } else { &ch.value };
2769 if let Some(v) = v {
2770 (ops.set_field)(key, ch.label, v);
2771 }
2772 }
2773 Op::Insert => {
2774 let (row, at) = if invert {
2776 (&ch.prior, index(&ch.value))
2777 } else {
2778 (&ch.value, index(&ch.prior))
2779 };
2780 if let Some(row) = row {
2781 (ops.insert_row)(key, row, at);
2782 }
2783 }
2784 Op::Delete => {
2785 (ops.remove_row)(key);
2786 }
2787 Op::Move => {
2788 let to = if invert { &ch.prior } else { &ch.value };
2789 if let Some(to) = index(to) {
2790 (ops.move_row)(key, to);
2791 }
2792 }
2793 }
2794 }
2795
2796 fn refresh(&self) {
2797 let resolver = self.inner.resolver.borrow().clone();
2798 let undo = self.inner.undo.borrow();
2799 self.inner.can_undo.set_if_changed(!undo.is_empty());
2800 self.inner
2801 .undo_label
2802 .set_if_changed(undo.back().map(|u| resolver(u.label)).unwrap_or_default());
2803 drop(undo);
2804 let redo = self.inner.redo.borrow();
2805 self.inner.can_redo.set_if_changed(!redo.is_empty());
2806 self.inner
2807 .redo_label
2808 .set_if_changed(redo.last().map(|u| resolver(u.label)).unwrap_or_default());
2809 }
2810}
2811
2812impl Drop for UndoInner {
2813 fn drop(&mut self) {
2814 if let Some(sink) = self.sink.take() {
2815 remove_change_sink(sink);
2816 }
2817 let _ = WANT_VALUES_STANDING.try_with(|w| w.set(w.get().saturating_sub(1)));
2819 }
2820}