use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};
use day_reactive::{Binding, Scope, Trigger};
#[doc(no_inline)]
pub use uuid::Uuid;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NodeId {
idx: u32,
generation: u32,
}
const ROOT: NodeId = NodeId {
idx: 0,
generation: 0,
};
pub const STRUCTURE: u64 = u64::MAX;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Path {
parent: NodeId,
part: u64,
}
impl Path {
fn root(id: u64) -> Path {
Path {
parent: ROOT,
part: id,
}
}
#[must_use]
pub fn under(parent: NodeId, part: u64) -> Path {
Path { parent, part }
}
#[must_use]
pub fn components(self) -> Vec<u64> {
let mut out: Vec<u64> = self.chain().iter().map(|p| p.part).collect();
out.reverse();
out
}
fn chain(self) -> Vec<Path> {
let mut out = vec![self];
let mut at = self.parent;
NODES.with(|n| {
let nodes = n.borrow();
while at != ROOT {
match nodes.get(at) {
Some(p) => {
out.push(p);
at = p.parent;
}
None => break,
}
}
});
out
}
}
#[must_use]
pub const fn field_id(name: &str) -> u64 {
let bytes = name.as_bytes();
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut i = 0;
while i < bytes.len() {
h ^= bytes[i] as u64;
h = h.wrapping_mul(0x1000_0000_01b3);
i += 1;
}
h
}
struct Slot {
path: Path,
generation: u32,
alive: bool,
pinned: bool,
children: u32,
triggers: u32,
}
#[derive(Default)]
struct Interner {
slots: Vec<Slot>,
free: Vec<u32>,
lookup: HashMap<Path, NodeId>,
}
impl Interner {
fn get(&self, id: NodeId) -> Option<Path> {
match self.slots.get(id.idx as usize) {
Some(s) if s.alive && s.generation == id.generation => Some(s.path),
_ => None,
}
}
fn is_current(&self, id: NodeId) -> bool {
id == ROOT || self.get(id).is_some()
}
fn maybe_free(&mut self, mut id: NodeId) {
loop {
let Some(s) = self.slots.get(id.idx as usize) else {
return;
};
if !s.alive
|| s.generation != id.generation
|| s.pinned
|| s.children > 0
|| s.triggers > 0
{
return;
}
let path = s.path;
self.lookup.remove(&path);
let s = &mut self.slots[id.idx as usize];
s.alive = false;
s.generation = s.generation.wrapping_add(1);
self.free.push(id.idx);
if path.parent == ROOT {
return;
}
if let Some(ps) = self.slots.get_mut(path.parent.idx as usize)
&& ps.alive
&& ps.generation == path.parent.generation
&& ps.children > 0
{
ps.children -= 1;
id = path.parent;
continue;
}
return;
}
}
}
day_reactive::tls_group! {
static NODES: RefCell<Interner> = RefCell::new(Interner {
slots: vec![Slot {
path: Path { parent: ROOT, part: 0 },
generation: 0,
alive: true,
pinned: true,
children: 0,
triggers: 0,
}],
free: Vec::new(),
lookup: HashMap::new(),
});
static TRIGGERS: RefCell<HashMap<Path, Entry>> = RefCell::new(HashMap::new());
static RECORDER: RefCell<Option<Vec<Change>>> = const { RefCell::new(None) };
static WANT_VALUES: Cell<bool> = const { Cell::new(false) };
static WANT_VALUES_STANDING: Cell<u32> = const { Cell::new(0) };
static PREVIEW_WRITE: Cell<bool> = const { Cell::new(false) };
static PREVIEWS: RefCell<HashMap<Vec<u64>, Rc<dyn Any>>> = RefCell::new(HashMap::new());
static CURRENT_AUTHOR: Cell<Option<&'static str>> = const { Cell::new(None) };
static SINKS: RefCell<Vec<(u64, ChangeSink)>> = const { RefCell::new(Vec::new()) };
static NEXT_SINK: Cell<u64> = const { Cell::new(1) };
}
type ChangeSink = Rc<dyn Fn(&Change)>;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ChangeSinkId(u64);
pub fn install_change_sink(f: impl Fn(&Change) + 'static) -> ChangeSinkId {
let id = NEXT_SINK.with(|n| {
let id = n.get();
n.set(id + 1);
id
});
SINKS.with(|s| s.borrow_mut().push((id, Rc::new(f))));
ChangeSinkId(id)
}
pub fn remove_change_sink(id: ChangeSinkId) {
let _ = SINKS.try_with(|s| s.borrow_mut().retain(|(i, _)| *i != id.0));
}
fn sinks_active() -> bool {
SINKS.with(|s| !s.borrow().is_empty())
}
fn feed_sinks(change: &Change) {
let sinks: Vec<ChangeSink> =
SINKS.with(|s| s.borrow().iter().map(|(_, f)| f.clone()).collect());
for f in sinks {
f(change);
}
}
struct Entry {
trigger: Trigger,
scope: Scope,
watchers: Vec<day_reactive::RunId>,
}
fn intern(p: Path) -> NodeId {
NODES.with(|n| {
let mut i = n.borrow_mut();
if let Some(id) = i.lookup.get(&p) {
return *id;
}
let id = if let Some(idx) = i.free.pop() {
let s = &mut i.slots[idx as usize];
s.path = p;
s.alive = true;
s.pinned = false;
s.children = 0;
s.triggers = 0;
NodeId {
idx,
generation: s.generation,
}
} else {
let idx = i.slots.len() as u32;
i.slots.push(Slot {
path: p,
generation: 0,
alive: true,
pinned: false,
children: 0,
triggers: 0,
});
NodeId { idx, generation: 0 }
};
i.lookup.insert(p, id);
if p.parent != ROOT
&& let Some(s) = i.slots.get_mut(p.parent.idx as usize)
&& s.alive
&& s.generation == p.parent.generation
{
s.children += 1;
}
id
})
}
fn is_current(id: NodeId) -> bool {
NODES.with(|n| n.borrow().is_current(id))
}
fn path_of(id: NodeId) -> Path {
NODES.with(|n| n.borrow().get(id).unwrap_or(Path::root(0)))
}
fn pin(id: NodeId) {
NODES.with(|n| {
if let Some(s) = n.borrow_mut().slots.get_mut(id.idx as usize) {
s.pinned = true;
}
});
}
#[must_use]
pub fn interned_nodes() -> usize {
NODES.with(|n| n.borrow().slots.iter().filter(|s| s.alive).count() - 1)
}
fn track(p: Path) {
let Some(watcher) = day_reactive::active_run() else {
return;
};
let (trigger, created, fresh) = TRIGGERS.with(|t| {
let mut map = t.borrow_mut();
let mut created = false;
let entry = map.entry(p).or_insert_with(|| {
created = true;
let scope = Scope::root().create_child();
Entry {
trigger: scope.enter(Trigger::new),
scope,
watchers: Vec::new(),
}
});
let fresh = !entry.watchers.contains(&watcher);
if fresh {
entry.watchers.push(watcher);
}
(entry.trigger, created, fresh)
});
if created && p.parent != ROOT {
NODES.with(|n| {
let mut i = n.borrow_mut();
if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
&& s.alive
&& s.generation == p.parent.generation
{
s.triggers += 1;
}
});
}
if fresh {
day_reactive::on_run_retrack(move || release(p, watcher));
}
trigger.track();
}
fn release(p: Path, watcher: day_reactive::RunId) {
let removed = TRIGGERS.with(|t| {
let mut map = t.borrow_mut();
let Some(entry) = map.get_mut(&p) else {
return false;
};
entry.watchers.retain(|w| *w != watcher);
if entry.watchers.is_empty() {
let scope = entry.scope;
map.remove(&p);
drop(map);
scope.dispose();
true
} else {
false
}
});
if removed && p.parent != ROOT {
NODES.with(|n| {
let mut i = n.borrow_mut();
if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
&& s.alive
&& s.generation == p.parent.generation
&& s.triggers > 0
{
s.triggers -= 1;
}
i.maybe_free(p.parent);
});
}
}
#[must_use]
pub fn observed_paths() -> usize {
TRIGGERS.with(|t| t.borrow().len())
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Op {
Set,
Insert,
Delete,
Move,
}
#[derive(Clone)]
pub struct Change {
pub components: Vec<u64>,
pub label: &'static str,
pub op: Op,
pub prior: Option<Rc<dyn Any>>,
pub value: Option<Rc<dyn Any>>,
pub author: Option<&'static str>,
}
impl Change {
#[must_use]
pub fn prior_as<T: 'static>(&self) -> Option<&T> {
self.prior.as_deref().and_then(|v| v.downcast_ref())
}
#[must_use]
pub fn value_as<T: 'static>(&self) -> Option<&T> {
self.value.as_deref().and_then(|v| v.downcast_ref())
}
}
impl fmt::Debug for Change {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Change")
.field("components", &self.components)
.field("label", &self.label)
.field("op", &self.op)
.field("prior", &self.prior.as_ref().map(|_| ".."))
.field("value", &self.value.as_ref().map(|_| ".."))
.field("author", &self.author)
.finish()
}
}
fn values_wanted() -> bool {
WANT_VALUES.with(std::cell::Cell::get) || WANT_VALUES_STANDING.with(|w| w.get() > 0)
}
#[must_use]
pub fn record_capture_active() -> bool {
values_wanted()
}
pub fn want_values_standing(on: bool) {
WANT_VALUES_STANDING.with(|w| {
let v = w.get();
w.set(if on { v + 1 } else { v.saturating_sub(1) });
});
}
fn previewing() -> bool {
PREVIEW_WRITE.with(std::cell::Cell::get)
}
pub fn with_author<R>(author: &'static str, f: impl FnOnce() -> R) -> R {
let previous = CURRENT_AUTHOR.with(|a| a.replace(Some(author)));
let _restore = std::mem::DropGuard::new(previous, |previous| {
CURRENT_AUTHOR.with(|a| a.set(previous));
});
f()
}
fn current_author() -> Option<&'static str> {
CURRENT_AUTHOR.with(std::cell::Cell::get)
}
pub fn record_changes<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
RECORDER.with(|r| *r.borrow_mut() = Some(Vec::new()));
let out = f();
let log = RECORDER.with(|r| r.borrow_mut().take().unwrap_or_default());
(out, log)
}
pub fn record_values<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
WANT_VALUES.with(|w| w.set(true));
let out = record_changes(f);
WANT_VALUES.with(|w| w.set(false));
out
}
pub fn record<R>(f: impl FnOnce() -> R) -> (R, Vec<&'static str>) {
let (out, changes) = record_changes(f);
(out, changes.into_iter().map(|c| c.label).collect())
}
fn notify_change(
p: Path,
components: impl FnOnce() -> Vec<u64>,
label: &'static str,
op: Op,
prior: Option<Rc<dyn Any>>,
value: Option<Rc<dyn Any>>,
) {
if previewing() {
wake(p);
return;
}
let recording = RECORDER.with(|r| r.borrow().is_some());
if recording || sinks_active() {
let change = Change {
components: components(),
label,
op,
prior,
value,
author: current_author(),
};
feed_sinks(&change);
if recording {
RECORDER.with(|r| {
if let Some(log) = r.borrow_mut().as_mut() {
log.push(change);
}
});
}
}
wake(p);
}
fn wake(p: Path) {
let chain = p.chain();
let live: Vec<Trigger> = TRIGGERS.with(|t| {
let map = t.borrow();
chain
.iter()
.filter_map(|k| map.get(k).map(|e| e.trigger))
.collect()
});
for tr in live {
tr.notify();
}
}
pub fn announce(parts: &[u64], label: &'static str) {
announce_op(parts, label, Op::Set);
}
fn announce_op(parts: &[u64], label: &'static str, op: Op) {
let resolved = (|| {
let (last, interior) = parts.split_last()?;
let mut parent = ROOT;
for part in interior {
let step = Path::under(parent, *part);
match NODES.with(|n| {
let i = n.borrow();
i.lookup.get(&step).copied().filter(|id| i.is_current(*id))
}) {
Some(id) => parent = id,
None => return Some(step),
}
}
Some(Path::under(parent, *last))
})();
let Some(p) = resolved else { return };
let recording = RECORDER.with(|r| r.borrow().is_some());
if recording || sinks_active() {
let change = Change {
components: parts.to_vec(),
label,
op,
prior: None,
value: None,
author: current_author(),
};
feed_sinks(&change);
if recording {
RECORDER.with(|r| {
if let Some(log) = r.borrow_mut().as_mut() {
log.push(change);
}
});
}
}
wake(p);
}
pub trait Source<T: 'static>: Copy + 'static {
const DYNAMIC: bool = false;
fn track_extra(self) {}
fn path(self) -> Path;
fn node(self) -> NodeId;
fn components(self, out: &mut Vec<u64>);
fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R;
fn update_value(self, f: impl FnOnce(&mut T)) -> bool;
fn bump_version(self);
fn with<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
self.track_extra();
track(self.path());
self.with_value_untracked(f)
}
}
pub type TxPaths = Vec<(Vec<u64>, &'static str)>;
pub struct Store<T: 'static> {
inner: &'static Inner<T>,
node: NodeId,
root_id: u64,
}
impl<T> Clone for Store<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Store<T> {}
struct Inner<T> {
data: RwLock<T>,
pending: Mutex<TxPaths>,
version: AtomicU64,
}
static NEXT_STORE: AtomicU64 = AtomicU64::new(1);
impl<T: 'static> Store<T> {
pub fn new(value: T) -> Store<T> {
let inner: &'static Inner<T> = Box::leak(Box::new(Inner {
data: RwLock::new(value),
pending: Mutex::new(Vec::new()),
version: AtomicU64::new(0),
}));
let root_id = NEXT_STORE.fetch_add(1, Ordering::Relaxed);
let node = intern(Path::root(root_id));
pin(node);
Store {
inner,
node,
root_id,
}
}
pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
f(&self.inner.data.read().expect("store poisoned"))
}
pub fn update(self, label: &'static str, f: impl FnOnce(&mut T)) {
{
let mut g = self.inner.data.write().expect("store poisoned");
f(&mut g);
}
self.inner.version.fetch_add(1, Ordering::Relaxed);
let root_id = self.root_id;
notify_change(
path_of(self.node),
|| vec![root_id],
label,
Op::Set,
None,
None,
);
}
#[must_use]
pub fn version(self) -> u64 {
self.inner.version.load(Ordering::Relaxed)
}
#[must_use]
pub fn store_id(self) -> u64 {
self.root_id
}
#[must_use]
pub fn pump(self) -> usize {
let drained: TxPaths = {
let mut q = self.inner.pending.lock().expect("queue poisoned");
std::mem::take(&mut *q)
};
let n = drained.len();
day_reactive::batch(|| {
for (parts, label) in drained {
announce(&parts, label);
}
});
n
}
}
impl<T: 'static> Source<T> for Store<T> {
fn path(self) -> Path {
path_of(self.node)
}
fn node(self) -> NodeId {
self.node
}
fn components(self, out: &mut Vec<u64>) {
out.push(self.root_id);
}
fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
f(Some(&self.inner.data.read().expect("store poisoned")))
}
fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
let mut g = self.inner.data.write().expect("store poisoned");
f(&mut g);
true
}
fn bump_version(self) {
self.inner.version.fetch_add(1, Ordering::Relaxed);
}
}
unsafe impl<T: Send + Sync> Send for Store<T> {}
unsafe impl<T: Send + Sync> Sync for Store<T> {}
impl<T: Send + Sync + 'static> Store<T> {
#[must_use]
pub fn transact(self) -> Tx<T> {
Tx {
store: self,
guard: Some(self.inner.data.write().expect("store poisoned")),
touched: Vec::new(),
}
}
}
pub struct Tx<T: Send + Sync + 'static> {
store: Store<T>,
guard: Option<std::sync::RwLockWriteGuard<'static, T>>,
touched: TxPaths,
}
impl<T: Send + Sync + 'static> Tx<T> {
#[expect(
clippy::missing_panics_doc,
reason = "the guard is taken in Drop alone, so the `expect` cannot fail on a live Tx"
)]
pub fn data(&mut self) -> &mut T {
self.guard.as_mut().expect("transaction already committed")
}
pub fn touched(&mut self, parts: Vec<u64>, label: &'static str) {
self.touched.push((parts, label));
}
pub fn paths(&mut self) -> &mut TxPaths {
&mut self.touched
}
}
impl<T: Send + Sync + 'static> Drop for Tx<T> {
fn drop(&mut self) {
let touched = std::mem::take(&mut self.touched);
let store = self.store;
drop(self.guard.take());
store.inner.version.fetch_add(1, Ordering::Relaxed);
store
.inner
.pending
.lock()
.expect("queue poisoned")
.extend(touched);
}
}
const WIDE_BASE: u64 = 1 << 63;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Key {
U64(u64),
Uuid(u128),
Str(Arc<str>),
Pair(u64, u64),
}
impl Key {
#[must_use]
pub fn handle(&self) -> u64 {
match self {
Key::U64(k) => *k,
Key::Uuid(u) => intern_wide(WideKey::Uuid(*u)),
Key::Str(s) => intern_wide(WideKey::Str(s.clone())),
Key::Pair(a, b) => intern_wide(WideKey::Pair(*a, *b)),
}
}
#[must_use]
pub fn of_handle(handle: u64) -> Option<Key> {
if handle < WIDE_BASE {
return Some(Key::U64(handle));
}
let idx = (handle - WIDE_BASE) as usize;
wide_keys()
.read()
.expect("key interner poisoned")
.reverse
.get(idx)
.map(|w| match w {
WideKey::Uuid(u) => Key::Uuid(*u),
WideKey::Str(s) => Key::Str(s.clone()),
WideKey::Pair(a, b) => Key::Pair(*a, *b),
})
}
#[must_use]
pub fn as_u64(&self) -> Option<u64> {
match self {
Key::U64(k) => Some(*k),
_ => None,
}
}
#[must_use]
pub fn as_uuid(&self) -> Option<uuid::Uuid> {
match self {
Key::Uuid(u) => Some(uuid::Uuid::from_u128(*u)),
_ => None,
}
}
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Key::Str(s) => Some(s),
_ => None,
}
}
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Key::U64(k) => write!(f, "{k}"),
Key::Uuid(u) => write!(f, "{}", uuid::Uuid::from_u128(*u)),
Key::Str(s) => f.write_str(s),
Key::Pair(a, b) => write!(f, "{a}:{b}"),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
enum WideKey {
Uuid(u128),
Str(Arc<str>),
Pair(u64, u64),
}
#[derive(Default)]
struct WideKeys {
lookup: HashMap<WideKey, u64>,
reverse: Vec<WideKey>,
}
static WIDE_KEYS: OnceLock<RwLock<WideKeys>> = OnceLock::new();
fn wide_keys() -> &'static RwLock<WideKeys> {
WIDE_KEYS.get_or_init(Default::default)
}
fn intern_wide(k: WideKey) -> u64 {
if let Some(h) = wide_keys()
.read()
.expect("key interner poisoned")
.lookup
.get(&k)
{
return *h;
}
let mut w = wide_keys().write().expect("key interner poisoned");
if let Some(h) = w.lookup.get(&k) {
return *h; }
let h = WIDE_BASE + w.reverse.len() as u64;
w.reverse.push(k.clone());
w.lookup.insert(k, h);
h
}
#[must_use]
pub fn interned_keys() -> usize {
wide_keys()
.read()
.expect("key interner poisoned")
.reverse
.len()
}
pub trait AsKey {
fn as_key(&self) -> Key;
}
fn int_key(k: u64) -> Key {
debug_assert!(
k < WIDE_BASE,
"u64 keys reserve the top bit for interned handles (got {k:#x})"
);
Key::U64(k)
}
macro_rules! int_key {
($($t:ty),*) => {$(
impl AsKey for $t {
fn as_key(&self) -> Key {
int_key(*self as u64)
}
}
)*};
}
macro_rules! lossless_int_key {
($($t:ty),*) => {$(
impl AsKey for $t {
fn as_key(&self) -> Key {
int_key(u64::from(*self))
}
}
)*};
}
lossless_int_key!(u8, u16, u32);
int_key!(u64, usize, i8, i16, i32, i64, isize);
impl AsKey for String {
fn as_key(&self) -> Key {
Key::Str(Arc::from(self.as_str()))
}
}
impl AsKey for &str {
fn as_key(&self) -> Key {
Key::Str(Arc::from(*self))
}
}
impl AsKey for Arc<str> {
fn as_key(&self) -> Key {
Key::Str(self.clone())
}
}
impl AsKey for uuid::Uuid {
fn as_key(&self) -> Key {
Key::Uuid(self.as_u128())
}
}
impl AsKey for Key {
fn as_key(&self) -> Key {
self.clone()
}
}
pub struct ModelId<M: ?Sized> {
handle: u64,
_m: PhantomData<fn() -> M>,
}
impl<M: ?Sized> Clone for ModelId<M> {
fn clone(&self) -> Self {
*self
}
}
impl<M: ?Sized> Copy for ModelId<M> {}
impl<M: ?Sized> PartialEq for ModelId<M> {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl<M: ?Sized> Eq for ModelId<M> {}
impl<M: ?Sized> std::hash::Hash for ModelId<M> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.handle.hash(state);
}
}
impl<M: ?Sized> PartialOrd for ModelId<M> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<M: ?Sized> Ord for ModelId<M> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.handle.cmp(&other.handle)
}
}
impl<M: ?Sized> fmt::Debug for ModelId<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match Key::of_handle(self.handle) {
Some(k) => write!(f, "ModelId({k})"),
None => write!(f, "ModelId(#{:x})", self.handle),
}
}
}
impl<M: ?Sized> ModelId<M> {
#[expect(
clippy::needless_pass_by_value,
reason = "public signature; callers pass key literals and owned keys by value"
)]
pub fn of(key: impl AsKey) -> Self {
Self::from_handle(key.as_key().handle())
}
#[must_use]
pub const fn from_handle(handle: u64) -> Self {
ModelId {
handle,
_m: PhantomData,
}
}
#[must_use]
pub fn handle(self) -> u64 {
self.handle
}
#[must_use]
pub fn key(self) -> Key {
Key::of_handle(self.handle).unwrap_or(Key::U64(self.handle))
}
}
impl<M: ?Sized> PartialEq<u64> for ModelId<M> {
fn eq(&self, other: &u64) -> bool {
self.handle == *other
}
}
impl<M: ?Sized> PartialEq<ModelId<M>> for u64 {
fn eq(&self, other: &ModelId<M>) -> bool {
*self == other.handle
}
}
impl<M: ?Sized> From<u64> for ModelId<M> {
fn from(handle: u64) -> Self {
ModelId::from_handle(handle)
}
}
impl<M: ?Sized> From<u32> for ModelId<M> {
fn from(k: u32) -> Self {
ModelId::of(k)
}
}
impl<M: ?Sized> From<i32> for ModelId<M> {
fn from(k: i32) -> Self {
ModelId::of(k)
}
}
impl<M: ?Sized> From<usize> for ModelId<M> {
fn from(k: usize) -> Self {
ModelId::of(k)
}
}
impl<M: ?Sized> From<uuid::Uuid> for ModelId<M> {
fn from(k: uuid::Uuid) -> Self {
ModelId::of(k)
}
}
impl<M: ?Sized> From<&str> for ModelId<M> {
fn from(k: &str) -> Self {
ModelId::of(k)
}
}
impl<M: ?Sized> From<String> for ModelId<M> {
fn from(k: String) -> Self {
ModelId::of(k)
}
}
impl<M: ?Sized> From<Key> for ModelId<M> {
fn from(k: Key) -> Self {
ModelId::from_handle(k.handle())
}
}
impl<M: ?Sized> From<&Key> for ModelId<M> {
fn from(k: &Key) -> Self {
ModelId::from_handle(k.handle())
}
}
pub trait Identified {
fn key(&self) -> Key;
fn handle(&self) -> u64 {
self.key().handle()
}
fn model_id(&self) -> ModelId<Self>
where
Self: Sized,
{
ModelId::from_handle(self.handle())
}
}
pub struct Keyed<T> {
items: Vec<T>,
index: HashMap<u64, usize>,
stale: bool,
}
impl<T: Identified> Default for Keyed<T> {
fn default() -> Self {
Keyed {
items: Vec::new(),
index: HashMap::new(),
stale: false,
}
}
}
impl<T: Identified> Keyed<T> {
#[must_use]
pub fn new(items: Vec<T>) -> Self {
let mut k = Keyed {
items,
index: HashMap::new(),
stale: false,
};
k.reindex();
k
}
pub fn reindex(&mut self) {
self.index.clear();
for (i, item) in self.items.iter().enumerate() {
self.index.insert(item.handle(), i);
}
self.stale = false;
}
pub fn reindex_if_stale(&mut self) {
if self.stale {
self.reindex();
}
}
#[must_use]
pub fn get(&self, key: u64) -> Option<&T> {
self.index.get(&key).and_then(|i| self.items.get(*i))
}
pub fn get_mut(&mut self, key: u64) -> Option<&mut T> {
match self.index.get(&key) {
Some(i) => self.items.get_mut(*i),
None => None,
}
}
#[must_use]
pub fn keys(&self) -> Vec<u64> {
self.items.iter().map(Identified::handle).collect()
}
#[must_use]
pub fn items(&self) -> &[T] {
&self.items
}
#[must_use]
pub fn len(&self) -> usize {
self.items.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[must_use]
pub fn next_key(&self) -> u64 {
let used = || {
self.items
.iter()
.map(Identified::handle)
.filter(|h| (1..WIDE_BASE).contains(h))
};
match used().max() {
None => 1,
Some(max) if max + 1 < WIDE_BASE => max + 1,
Some(_) => {
let mut keys: Vec<u64> = used().collect();
keys.sort_unstable();
let gap = keys.iter().zip(1u64..).find(|(k, want)| **k != *want);
gap.map_or(keys.len() as u64 + 1, |(_, want)| want)
}
}
}
pub fn push(&mut self, item: T) {
self.index.insert(item.handle(), self.items.len());
self.items.push(item);
}
pub fn remove(&mut self, key: u64) -> Option<T> {
let i = self.index.remove(&key)?;
let item = self.items.remove(i);
self.reindex();
Some(item)
}
pub fn move_item(&mut self, from: usize, to: usize) {
if from >= self.items.len() || to >= self.items.len() {
return;
}
let item = self.items.remove(from);
self.items.insert(to, item);
self.reindex();
}
pub fn clear(&mut self) {
self.items.clear();
self.index.clear();
self.stale = false;
}
pub fn items_mut(&mut self) -> &mut Vec<T> {
self.stale = true;
&mut self.items
}
}
pub struct Elem<T: 'static> {
store: Store<Keyed<T>>,
key: u64,
node: NodeId,
}
impl<T> Clone for Elem<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Elem<T> {}
impl<T: Identified + 'static> Store<Keyed<T>> {
pub fn elem(self, key: impl Into<ModelId<T>>) -> Elem<T> {
let key = key.into().handle();
Elem {
store: self,
key,
node: intern(Path::under(self.node, key)),
}
}
#[must_use]
pub fn keys(self) -> Vec<u64> {
track(Path::under(self.node, STRUCTURE));
self.with_untracked(|k| k.keys().clone())
}
pub fn ids(self) -> Vec<ModelId<T>> {
self.keys().into_iter().map(ModelId::from_handle).collect()
}
pub fn restructure(
self,
label: &'static str,
op: Op,
key: impl Into<ModelId<T>>,
f: impl FnOnce(&mut Keyed<T>),
) where
T: Clone,
{
let key = key.into().handle();
let capture = values_wanted();
let mut prior: Option<Rc<dyn Any>> = None;
let mut value: Option<Rc<dyn Any>> = None;
{
let mut g = self.inner.data.write().expect("store poisoned");
let index = |k: &Keyed<T>| k.items().iter().position(|t| t.handle() == key);
let before = if capture { index(&g) } else { None };
if capture && op == Op::Delete {
prior = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
}
f(&mut g);
g.reindex_if_stale();
if capture {
let after = index(&g);
let at = |i: Option<usize>| i.map(|i| Rc::new(i) as Rc<dyn Any>);
match op {
Op::Insert => {
value = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
prior = at(after);
}
Op::Delete => value = at(before),
Op::Move => (prior, value) = (at(before), at(after)),
Op::Set => {}
}
}
}
self.inner.version.fetch_add(1, Ordering::Relaxed);
let root_id = self.root_id;
notify_change(
Path::under(self.node, key),
|| vec![root_id, key],
label,
op,
prior,
value,
);
notify_change(
Path::under(self.node, STRUCTURE),
|| vec![root_id, STRUCTURE],
label,
op,
None,
None,
);
}
pub fn push(self, item: T)
where
T: Clone,
{
let key = item.handle();
self.restructure("push", Op::Insert, ModelId::from_handle(key), |k| {
k.push(item);
});
}
pub fn remove(self, key: impl Into<ModelId<T>>) -> bool
where
T: Clone,
{
let key = key.into().handle();
if self.with_untracked(|k| k.get(key).is_none()) {
return false;
}
self.restructure("remove", Op::Delete, ModelId::from_handle(key), |k| {
k.remove(key);
});
true
}
pub fn move_row(self, from: usize, to: usize) -> bool
where
T: Clone,
{
let key = self.with_untracked(|k| {
if from == to || to >= k.len() {
return None;
}
k.items().get(from).map(Identified::handle)
});
let Some(key) = key else { return false };
self.restructure("move", Op::Move, ModelId::from_handle(key), |k| {
k.move_item(from, to);
});
true
}
#[must_use]
pub fn next_key(self) -> u64 {
self.with_untracked(Keyed::next_key)
}
pub fn merge_row(self, key: impl Into<ModelId<T>>, value: T, changed: &[&'static str]) -> bool
where
T: Clone,
{
let key = key.into().handle();
{
let mut g = self.inner.data.write().expect("store poisoned");
match g.get_mut(key) {
Some(slot) => *slot = value,
None => return false,
}
}
self.inner.version.fetch_add(1, Ordering::Relaxed);
let elem = intern(Path::under(self.node, key));
let root_id = self.root_id;
for &label in changed {
notify_change(
Path::under(elem, field_id(label)),
|| vec![root_id, key, field_id(label)],
label,
Op::Set,
None,
None,
);
}
true
}
pub fn write_field<V: Clone + 'static>(
self,
key: impl Into<ModelId<T>>,
label: &'static str,
value: V,
) -> bool
where
T: ApplyField,
{
let key = key.into().handle();
let capture = values_wanted() && !previewing();
let mut prior: Option<Rc<dyn Any>> = None;
let ok = {
let mut g = self.inner.data.write().expect("store poisoned");
match g.get_mut(key) {
Some(t) => {
if capture {
prior = t.read_field(label);
}
t.apply_field(label, &value)
}
None => false,
}
};
if !ok {
return false;
}
self.inner.version.fetch_add(1, Ordering::Relaxed);
let elem = intern(Path::under(self.node, key));
let after: Option<Rc<dyn Any>> = if capture { Some(Rc::new(value)) } else { None };
let root_id = self.root_id;
notify_change(
Path::under(elem, field_id(label)),
|| vec![root_id, key, field_id(label)],
label,
Op::Set,
prior,
after,
);
true
}
pub fn populate(self, rows: Vec<T>) {
{
let mut g = self.inner.data.write().expect("store poisoned");
for row in rows {
let key = row.handle();
match g.get_mut(key) {
Some(slot) => *slot = row,
None => g.push(row),
}
}
}
self.inner.version.fetch_add(1, Ordering::Relaxed);
}
pub fn depopulate(self, key: impl Into<ModelId<T>>) -> bool {
let key = key.into().handle();
let removed = {
let mut g = self.inner.data.write().expect("store poisoned");
g.remove(key).is_some()
};
if removed {
self.inner.version.fetch_add(1, Ordering::Relaxed);
}
removed
}
pub fn depopulate_many(self, keys: &[u64]) -> usize {
if keys.is_empty() {
return 0;
}
let set: std::collections::HashSet<u64> = keys.iter().copied().collect();
let removed = {
let mut g = self.inner.data.write().expect("store poisoned");
let before = g.len();
g.items_mut().retain(|item| !set.contains(&item.handle()));
g.reindex_if_stale();
before - g.len()
};
if removed > 0 {
self.inner.version.fetch_add(1, Ordering::Relaxed);
}
removed
}
#[doc(hidden)]
pub fn dispose_contents(self) {
let old = {
let mut data = self
.inner
.data
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
std::mem::replace(&mut *data, Keyed::new(Vec::new()))
};
drop(old);
}
pub fn is_observed(self, key: impl Into<ModelId<T>>) -> bool {
let key = key.into().handle();
let elem = Path::under(self.node, key);
if TRIGGERS.with(|t| t.borrow().contains_key(&elem)) {
return true;
}
NODES.with(|n| {
let i = n.borrow();
match i.lookup.get(&elem) {
Some(id) => match i.slots.get(id.idx as usize) {
Some(s) if s.alive && s.generation == id.generation => {
s.triggers > 0 || s.children > 0
}
_ => false,
},
None => false,
}
})
}
}
impl<T: Identified + 'static> Elem<T> {
#[must_use]
pub fn key(self) -> u64 {
self.key
}
#[must_use]
pub fn model_id(self) -> ModelId<T> {
ModelId::from_handle(self.key)
}
#[must_use]
pub fn exists(self) -> bool {
track(self.path());
self.with_value_untracked(|v| v.is_some())
}
fn live_node(self) -> NodeId {
if is_current(self.node) {
self.node
} else {
intern(Path::under(self.store.node, self.key))
}
}
}
impl<T: Identified + 'static> Source<T> for Elem<T> {
fn path(self) -> Path {
Path::under(self.store.node, self.key)
}
fn node(self) -> NodeId {
self.live_node()
}
fn components(self, out: &mut Vec<u64>) {
self.store.components(out);
out.push(self.key);
}
fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
let g = self.store.inner.data.read().expect("store poisoned");
f(g.get(self.key))
}
fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
let mut g = self.store.inner.data.write().expect("store poisoned");
match g.get_mut(self.key) {
Some(t) => {
f(t);
true
}
None => false,
}
}
fn bump_version(self) {
self.store.inner.version.fetch_add(1, Ordering::Relaxed);
}
}
pub struct Field<S, T: 'static, V: 'static> {
src: S,
path: Path,
part: u64,
label: &'static str,
get: fn(&T) -> &V,
get_mut: fn(&mut T) -> &mut V,
}
impl<S: Copy, T, V> Clone for Field<S, T, V> {
fn clone(&self) -> Self {
*self
}
}
impl<S: Copy, T, V> Copy for Field<S, T, V> {}
pub fn project<S: Source<T>, T: 'static, V: 'static>(
src: S,
label: &'static str,
get: fn(&T) -> &V,
get_mut: fn(&mut T) -> &mut V,
) -> Field<S, T, V> {
let part = field_id(label);
Field {
src,
path: Path::under(src.node(), part),
part,
label,
get,
get_mut,
}
}
impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
fn live_path(self) -> Path {
if !S::DYNAMIC && is_current(self.path.parent) {
self.path
} else {
Path::under(self.src.node(), self.part)
}
}
pub fn with<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
self.src.track_extra();
track(self.live_path());
self.src.with_value_untracked(|t| f(t.map(self.get)))
}
pub fn with_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
self.src.with_value_untracked(|t| f(t.map(self.get)))
}
pub fn update(self, f: impl FnOnce(&mut V))
where
V: Clone,
{
let capture = values_wanted() && !previewing();
let mut prior: Option<Rc<dyn Any>> = None;
let mut after: Option<Rc<dyn Any>> = None;
let get_mut = self.get_mut;
let ok = self.src.update_value(|t| {
let slot = get_mut(t);
if capture {
prior = Some(Rc::new(slot.clone()));
}
f(slot);
if capture {
after = Some(Rc::new(slot.clone()));
}
});
if ok {
self.src.bump_version();
notify_change(
self.live_path(),
|| {
let mut parts = Vec::new();
Source::<V>::components(self, &mut parts);
parts
},
self.label,
Op::Set,
prior,
after,
);
}
}
pub fn touch(self, tx: &mut TxPaths) {
let mut parts = Vec::new();
Source::<V>::components(self, &mut parts);
tx.push((parts, self.label));
}
pub fn path(self) -> Path {
self.live_path()
}
pub fn label(self) -> &'static str {
self.label
}
}
impl<S: Source<T>, T: 'static, V: 'static> Source<V> for Field<S, T, V> {
const DYNAMIC: bool = S::DYNAMIC;
fn track_extra(self) {
self.src.track_extra();
}
fn path(self) -> Path {
self.live_path()
}
fn node(self) -> NodeId {
intern(self.live_path())
}
fn components(self, out: &mut Vec<u64>) {
self.src.components(out);
out.push(self.part);
}
fn with_value_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
self.with_untracked(f)
}
fn update_value(self, f: impl FnOnce(&mut V)) -> bool {
let get_mut = self.get_mut;
self.src.update_value(|t| f(get_mut(t)))
}
fn bump_version(self) {
self.src.bump_version();
}
}
impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Binding<V> for Field<S, T, V> {
fn read(&self) -> V {
self.with(|v| v.cloned().unwrap_or_default())
}
fn peek(&self) -> V {
self.with_untracked(|v| v.cloned().unwrap_or_default())
}
fn write(&self, v: V) {
self.update(move |slot| *slot = v);
}
fn write_preview(&self, v: V) {
Field::write_preview(*self, v);
}
fn write_commit(&self, v: V) {
Field::write_commit(*self, v);
}
fn end_preview(&self) {
Field::end_preview(*self);
}
}
pub struct Mapped<F, V: 'static, U: 'static> {
inner: F,
to: fn(&V) -> U,
from: fn(&U) -> V,
label: &'static str,
}
impl<F: Copy, V, U> Clone for Mapped<F, V, U> {
fn clone(&self) -> Self {
*self
}
}
impl<F: Copy, V, U> Copy for Mapped<F, V, U> {}
impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
pub fn map<U: 'static>(self, to: fn(&V) -> U, from: fn(&U) -> V) -> Mapped<Self, V, U> {
Mapped {
inner: self,
to,
from,
label: self.label,
}
}
}
impl<F: Source<V>, V: Clone + Default + 'static, U: Clone + 'static> Binding<U>
for Mapped<F, V, U>
{
fn read(&self) -> U {
self.inner.track_extra();
track(self.inner.path());
self.peek()
}
fn peek(&self) -> U {
self.inner.with_value_untracked(|v| match v {
Some(v) => (self.to)(v),
None => (self.to)(&V::default()),
})
}
fn write_preview(&self, u: U) {
let v = (self.from)(&u);
let inner = self.inner;
let mut parts = Vec::new();
inner.components(&mut parts);
PREVIEWS.with(|p| {
p.borrow_mut().entry(parts).or_insert_with(|| {
Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()))
});
});
PREVIEW_WRITE.with(|f| f.set(true));
let ok = inner.update_value(|slot| *slot = v);
if ok {
inner.bump_version();
notify_change(inner.path(), Vec::new, self.label, Op::Set, None, None);
}
PREVIEW_WRITE.with(|f| f.set(false));
}
fn end_preview(&self) {
let mut parts = Vec::new();
self.inner.components(&mut parts);
PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
}
fn write_commit(&self, u: U) {
let inner = self.inner;
let mut parts = Vec::new();
inner.components(&mut parts);
let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
match open {
None => self.write(u),
Some(prior) => {
let v = (self.from)(&u);
PREVIEW_WRITE.with(|f| f.set(true));
let ok = inner.update_value(|slot| *slot = v);
PREVIEW_WRITE.with(|f| f.set(false));
if ok {
inner.bump_version();
let after: Rc<dyn Any> =
Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()));
notify_change(
inner.path(),
|| parts,
self.label,
Op::Set,
Some(prior),
Some(after),
);
}
}
}
}
fn write(&self, u: U) {
let v = (self.from)(&u);
let inner = self.inner;
let capture = values_wanted();
let mut prior: Option<Rc<dyn Any>> = None;
let mut after: Option<Rc<dyn Any>> = None;
let ok = inner.update_value(|slot| {
if capture {
prior = Some(Rc::new(slot.clone()));
}
*slot = v;
if capture {
after = Some(Rc::new(slot.clone()));
}
});
if ok {
inner.bump_version();
notify_change(
inner.path(),
|| {
let mut parts = Vec::new();
inner.components(&mut parts);
parts
},
self.label,
Op::Set,
prior,
after,
);
}
}
}
impl<F: Source<V> + Copy, V: 'static> Mapped<F, V, usize> {
pub fn map_to_f64(self) -> Numeric<Self> {
Numeric { inner: self }
}
}
pub struct Numeric<M> {
inner: M,
}
#[expect(
clippy::expl_impl_clone_on_copy,
reason = "a derive would widen `Clone` to non-`Copy` bindings; this keeps the public bounds"
)]
impl<M: Copy> Clone for Numeric<M> {
fn clone(&self) -> Self {
*self
}
}
impl<M: Copy> Copy for Numeric<M> {}
impl<M: Binding<usize> + Copy + 'static> Binding<f64> for Numeric<M> {
fn read(&self) -> f64 {
self.inner.read() as f64
}
fn peek(&self) -> f64 {
self.inner.peek() as f64
}
fn write(&self, v: f64) {
self.inner.write(v.round().max(0.0) as usize);
}
}
impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Field<S, T, V> {
pub fn write_preview(self, v: V) {
let mut parts = Vec::new();
Source::<V>::components(self, &mut parts);
PREVIEWS.with(|p| {
p.borrow_mut().entry(parts).or_insert_with(|| {
Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()))
});
});
PREVIEW_WRITE.with(|f| f.set(true));
self.update(move |slot| *slot = v);
PREVIEW_WRITE.with(|f| f.set(false));
}
pub fn write_commit(self, v: V) {
let mut parts = Vec::new();
Source::<V>::components(self, &mut parts);
let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
let open = open.filter(|_| self.with_untracked(|s| s.is_some()));
match open {
None => self.update(move |slot| *slot = v),
Some(prior) => {
PREVIEW_WRITE.with(|f| f.set(true));
self.update(move |slot| *slot = v);
PREVIEW_WRITE.with(|f| f.set(false));
let after: Rc<dyn Any> =
Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()));
notify_change(
self.live_path(),
|| parts,
self.label,
Op::Set,
Some(prior),
Some(after),
);
}
}
}
pub fn end_preview(self) {
let mut parts = Vec::new();
Source::<V>::components(self, &mut parts);
PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
}
pub fn session(self) -> FieldSession<S, T, V> {
FieldSession { field: self }
}
}
pub struct FieldSession<S: 'static, T: 'static, V: 'static> {
field: Field<S, T, V>,
}
impl<S: Copy, T, V> Clone for FieldSession<S, T, V> {
fn clone(&self) -> Self {
*self
}
}
impl<S: Copy, T, V> Copy for FieldSession<S, T, V> {}
impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> FieldSession<S, T, V> {
pub fn preview(self, v: V) {
self.field.write_preview(v);
}
pub fn commit(self) {
let v = self
.field
.with_untracked(|s| s.cloned().unwrap_or_default());
self.field.write_commit(v);
}
pub fn cancel(self) {
let mut parts = Vec::new();
Source::<V>::components(self.field, &mut parts);
if let Some(prior) = PREVIEWS.with(|p| p.borrow_mut().remove(&parts))
&& let Ok(prior) = prior.downcast::<V>()
{
self.field.write_preview((*prior).clone());
let mut parts = Vec::new();
Source::<V>::components(self.field, &mut parts);
PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
}
}
}
pub trait ApplyField {
fn apply_field(&mut self, label: &str, value: &dyn Any) -> bool;
fn read_field(&self, label: &str) -> Option<Rc<dyn Any>> {
let _ = label;
None
}
}
type SetFieldFn = Rc<dyn Fn(u64, &'static str, &Rc<dyn Any>) -> bool>;
type InsertRowFn = Rc<dyn Fn(u64, &Rc<dyn Any>, Option<usize>) -> bool>;
struct StoreOps {
set_field: SetFieldFn,
insert_row: InsertRowFn,
remove_row: Rc<dyn Fn(u64) -> bool>,
move_row: Rc<dyn Fn(u64, usize) -> bool>,
}
#[derive(Clone)]
struct UndoUnit {
label: &'static str,
changes: Vec<Change>,
context: Option<Rc<dyn Any>>,
}
type ContextRestore = Rc<dyn Fn(&dyn Any)>;
struct ContextHook {
capture: Rc<dyn Fn() -> Rc<dyn Any>>,
restore: ContextRestore,
base: Rc<dyn Any>,
}
#[derive(Clone, Copy, PartialEq)]
enum Replay {
No,
Undoing,
Redoing,
}
struct UndoInner {
levels: usize,
undo: RefCell<std::collections::VecDeque<UndoUnit>>,
redo: RefCell<Vec<UndoUnit>>,
open: RefCell<Vec<Change>>,
group_label: Cell<Option<&'static str>>,
grouping: Cell<usize>,
replaying: Cell<Replay>,
ops: RefCell<HashMap<u64, StoreOps>>,
can_undo: day_reactive::Signal<bool>,
can_redo: day_reactive::Signal<bool>,
undo_label: day_reactive::Signal<String>,
redo_label: day_reactive::Signal<String>,
resolver: RefCell<Rc<dyn Fn(&'static str) -> String>>,
sink: Cell<Option<ChangeSinkId>>,
context: RefCell<Option<ContextHook>>,
}
#[derive(Clone)]
pub struct UndoStack {
inner: Rc<UndoInner>,
}
pub struct UndoCheckpoint {
undo: std::collections::VecDeque<UndoUnit>,
redo: Vec<UndoUnit>,
open: Vec<Change>,
}
#[must_use = "keep the group alive until the interaction finishes"]
pub struct UndoGroup {
stack: UndoStack,
}
impl Drop for UndoGroup {
fn drop(&mut self) {
let depth = self.stack.inner.grouping.get() - 1;
self.stack.inner.grouping.set(depth);
if depth == 0 {
self.stack.seal();
self.stack.inner.group_label.set(None);
}
}
}
impl UndoStack {
#[must_use]
pub fn new(levels: usize) -> UndoStack {
let (can_undo, can_redo, undo_label, redo_label) =
day_reactive::Scope::detached().enter(|| {
(
day_reactive::Signal::new(false),
day_reactive::Signal::new(false),
day_reactive::Signal::new(String::new()),
day_reactive::Signal::new(String::new()),
)
});
let stack = UndoStack {
inner: Rc::new(UndoInner {
levels: levels.max(1),
undo: RefCell::new(std::collections::VecDeque::new()),
redo: RefCell::new(Vec::new()),
open: RefCell::new(Vec::new()),
group_label: Cell::new(None),
grouping: Cell::new(0),
replaying: Cell::new(Replay::No),
ops: RefCell::new(HashMap::new()),
can_undo,
can_redo,
undo_label,
redo_label,
resolver: RefCell::new(Rc::new(|label: &'static str| {
let mut s: String = label.replace(['_', '-'], " ");
if let Some(first) = s.get_mut(0..1) {
first.make_ascii_uppercase();
}
s
})),
sink: Cell::new(None),
context: RefCell::new(None),
}),
};
want_values_standing(true);
let weak = Rc::downgrade(&stack.inner);
let sink = install_change_sink(move |change| {
if let Some(inner) = weak.upgrade() {
UndoStack { inner }.capture(change);
}
});
stack.inner.sink.set(Some(sink));
let weak = Rc::downgrade(&stack.inner);
day_reactive::on_turn_end(move || {
if let Some(inner) = weak.upgrade() {
let stack = UndoStack { inner };
if stack.inner.grouping.get() == 0 {
stack.seal();
}
}
});
stack
}
pub fn watch<T: ApplyField + Identified + Clone + 'static>(&self, store: Store<Keyed<T>>) {
let ops = StoreOps {
set_field: {
Rc::new(move |key: u64, label: &'static str, value: &Rc<dyn Any>| {
let elem = store.elem(key);
let mut applied = false;
let ok = elem.update_value(|row| {
applied = row.apply_field(label, value.as_ref());
});
if ok && applied {
elem.bump_version();
announce_op(&[store.store_id(), key, field_id(label)], label, Op::Set);
}
ok && applied
})
},
insert_row: {
Rc::new(move |key: u64, row: &Rc<dyn Any>, at: Option<usize>| {
let Some(row) = row.downcast_ref::<T>() else {
return false;
};
let row = row.clone();
store.restructure("undo", Op::Insert, key, move |k| match at {
Some(at) if at < k.len() => k.items_mut().insert(at, row),
_ => k.push(row),
});
true
})
},
remove_row: {
Rc::new(move |key: u64| {
store.restructure("undo", Op::Delete, key, move |k| {
k.remove(key);
});
true
})
},
move_row: {
Rc::new(move |key: u64, to: usize| {
let from =
store.with_untracked(|k| k.items().iter().position(|t| t.handle() == key));
from.is_some_and(|from| store.move_row(from, to))
})
},
};
self.inner.ops.borrow_mut().insert(store.store_id(), ops);
}
fn capture(&self, change: &Change) {
if self.inner.replaying.get() != Replay::No {
return;
}
if change.author.is_some() {
return;
}
let Some(&store) = change.components.first() else {
return;
};
if !self.inner.ops.borrow().contains_key(&store) {
return;
}
let Some(&key) = change.components.get(1) else {
self.clear();
return;
};
if key == STRUCTURE {
return;
}
if change.op == Op::Set && change.components.len() >= 3 && change.prior.is_none() {
return;
}
self.inner.open.borrow_mut().push(change.clone());
}
fn seal(&self) {
let changes = std::mem::take(&mut *self.inner.open.borrow_mut());
if changes.is_empty() {
return;
}
let label = self
.inner
.group_label
.take()
.unwrap_or_else(|| changes.first().map_or("", |c| c.label));
let context = self.inner.context.borrow().as_ref().map(|h| (h.capture)());
let mut undo = self.inner.undo.borrow_mut();
undo.push_back(UndoUnit {
label,
changes,
context,
});
while undo.len() > self.inner.levels {
undo.pop_front();
}
drop(undo);
self.inner.redo.borrow_mut().clear();
self.refresh();
}
pub fn grouped(&self, label: &'static str, f: impl FnOnce()) {
let _group = self.begin_group(label);
f();
}
pub fn begin_group(&self, label: &'static str) -> UndoGroup {
if self.inner.grouping.get() == 0 {
self.seal();
self.inner.group_label.set(Some(label));
}
self.inner.grouping.set(self.inner.grouping.get() + 1);
UndoGroup {
stack: self.clone(),
}
}
#[must_use]
pub fn checkpoint(&self) -> UndoCheckpoint {
UndoCheckpoint {
undo: self.inner.undo.borrow().clone(),
redo: self.inner.redo.borrow().clone(),
open: self.inner.open.borrow().clone(),
}
}
pub fn restore_checkpoint(&self, checkpoint: UndoCheckpoint) {
*self.inner.undo.borrow_mut() = checkpoint.undo;
*self.inner.redo.borrow_mut() = checkpoint.redo;
*self.inner.open.borrow_mut() = checkpoint.open;
self.refresh();
}
#[must_use]
pub fn can_undo(&self) -> day_reactive::Signal<bool> {
self.inner.can_undo
}
#[must_use]
pub fn can_redo(&self) -> day_reactive::Signal<bool> {
self.inner.can_redo
}
#[must_use]
pub fn undo_label(&self) -> day_reactive::Signal<String> {
self.inner.undo_label
}
#[must_use]
pub fn redo_label(&self) -> day_reactive::Signal<String> {
self.inner.redo_label
}
pub fn set_label_resolver(&self, f: impl Fn(&'static str) -> String + 'static) {
*self.inner.resolver.borrow_mut() = Rc::new(f);
self.refresh();
}
pub fn set_transient_context(
&self,
capture: impl Fn() -> Rc<dyn Any> + 'static,
restore: impl Fn(&dyn Any) + 'static,
) {
let base = capture();
*self.inner.context.borrow_mut() = Some(ContextHook {
capture: Rc::new(capture),
restore: Rc::new(restore),
base,
});
}
fn restore_context(&self) {
let (target, restore) = {
let hook = self.inner.context.borrow();
let Some(h) = hook.as_ref() else { return };
let target = match self.inner.undo.borrow().back() {
Some(unit) => unit.context.clone(),
None => Some(h.base.clone()),
};
(target, h.restore.clone())
};
if let Some(ctx) = target {
restore(&*ctx);
}
}
pub fn undo(&self) -> bool {
if self.inner.grouping.get() > 0 {
return false;
}
self.seal();
let Some(unit) = self.inner.undo.borrow_mut().pop_back() else {
return false;
};
self.inner.replaying.set(Replay::Undoing);
with_author("undo", || {
day_reactive::batch(|| {
for ch in unit.changes.iter().rev() {
self.apply(ch, true);
}
});
});
self.inner.replaying.set(Replay::No);
self.inner.redo.borrow_mut().push(unit);
self.restore_context();
self.refresh();
true
}
pub fn redo(&self) -> bool {
if self.inner.grouping.get() > 0 {
return false;
}
let Some(unit) = self.inner.redo.borrow_mut().pop() else {
return false;
};
self.inner.replaying.set(Replay::Redoing);
with_author("redo", || {
day_reactive::batch(|| {
for ch in &unit.changes {
self.apply(ch, false);
}
});
});
self.inner.replaying.set(Replay::No);
self.inner.undo.borrow_mut().push_back(unit);
self.restore_context();
self.refresh();
true
}
pub fn clear(&self) {
self.inner.undo.borrow_mut().clear();
self.inner.redo.borrow_mut().clear();
self.inner.open.borrow_mut().clear();
self.refresh();
}
fn apply(&self, ch: &Change, invert: bool) {
let (Some(&store), Some(&key)) = (ch.components.first(), ch.components.get(1)) else {
return;
};
let ops = self.inner.ops.borrow();
let Some(ops) = ops.get(&store) else {
return;
};
let effective = if invert {
match ch.op {
Op::Set => Op::Set,
Op::Insert => Op::Delete,
Op::Delete => Op::Insert,
Op::Move => Op::Move,
}
} else {
ch.op
};
let index = |v: &Option<Rc<dyn Any>>| {
v.as_deref()
.and_then(|v| v.downcast_ref::<usize>().copied())
};
match effective {
Op::Set => {
let v = if invert { &ch.prior } else { &ch.value };
if let Some(v) = v {
(ops.set_field)(key, ch.label, v);
}
}
Op::Insert => {
let (row, at) = if invert {
(&ch.prior, index(&ch.value))
} else {
(&ch.value, index(&ch.prior))
};
if let Some(row) = row {
(ops.insert_row)(key, row, at);
}
}
Op::Delete => {
(ops.remove_row)(key);
}
Op::Move => {
let to = if invert { &ch.prior } else { &ch.value };
if let Some(to) = index(to) {
(ops.move_row)(key, to);
}
}
}
}
fn refresh(&self) {
let resolver = self.inner.resolver.borrow().clone();
let undo = self.inner.undo.borrow();
self.inner.can_undo.set_if_changed(!undo.is_empty());
self.inner
.undo_label
.set_if_changed(undo.back().map_or_default(|u| resolver(u.label)));
drop(undo);
let redo = self.inner.redo.borrow();
self.inner.can_redo.set_if_changed(!redo.is_empty());
self.inner
.redo_label
.set_if_changed(redo.last().map_or_default(|u| resolver(u.label)));
}
}
impl Drop for UndoInner {
fn drop(&mut self) {
if let Some(sink) = self.sink.take() {
remove_change_sink(sink);
}
let _ = WANT_VALUES_STANDING.try_with(|w| w.set(w.get().saturating_sub(1)));
}
}