use canvist_model::BlockId;
use canvist_model::BlockTypeId;
use canvist_model::Schema;
use rustc_hash::FxHashMap;
use yrs::Array;
use yrs::ArrayRef;
use yrs::ID;
use yrs::MapRef;
use yrs::Out;
use yrs::ReadTxn;
use crate::registry::branch_id;
use crate::tree;
use crate::tree::Shape;
pub(crate) trait Claim {
fn claim(&mut self, id: BlockId, map: &ID) -> bool;
}
#[derive(Debug, Default)]
pub(crate) struct Owners(FxHashMap<BlockId, ID>);
impl Owners {
pub(crate) fn scan<T: ReadTxn>(
&mut self,
map: &MapRef,
parent: Option<BlockTypeId>,
txn: &T,
schema: &Schema,
) {
let Some((id, kind, shape)) = tree::header(map, parent, txn, schema) else {
return;
};
if let Some(item) = branch_id(map) {
self.0
.entry(id)
.and_modify(|best| *best = (*best).min(item))
.or_insert(item);
}
if let Shape::Children(children) = shape {
self.scan_array(&children, Some(kind), txn, schema);
}
}
pub(crate) fn scan_array<T: ReadTxn>(
&mut self,
array: &ArrayRef,
parent: Option<BlockTypeId>,
txn: &T,
schema: &Schema,
) {
for item in array.iter(txn) {
if let Out::YMap(map) = item {
self.scan(&map, parent, txn, schema);
}
}
}
pub(crate) fn get(&self, id: BlockId) -> Option<&ID> {
self.0.get(&id)
}
}
impl Claim for Owners {
fn claim(&mut self, id: BlockId, map: &ID) -> bool {
self.get(id) == Some(map)
}
}