changed events

This commit is contained in:
John Lancaster
2026-02-22 18:19:48 -06:00
parent 62204abdd0
commit 07bdbe0b46
4 changed files with 12 additions and 11 deletions

View File

@@ -16,6 +16,7 @@ class HookFunction(Protocol):
class HookedContainer(ABC, Sized, Iterable[T], Container[T]):
_path: MutableSequence[int]
_root: MutableMapping[T] | MutableSequence[T] | None = None
hook: HookFunction
def __repr__(self):
@@ -36,12 +37,12 @@ class HookedContainer(ABC, Sized, Iterable[T], Container[T]):
def __setitem__(self, s, value):
self._data[s] = value
if self.hook:
self.hook(e.SetItemEvent(index=s, item=value, path=self._path))
self.hook(e.SetItemEvent(self.new_path(s), value))
def __delitem__(self, s):
item = self._data.pop(s)
if self.hook:
self.hook(e.RemoveItemEvent(index=s, item=item, path=self._path))
self.hook(e.RemoveItemEvent(self.new_path(s), item))
@abstractmethod
def insert(self, index, value): ...

View File

@@ -7,9 +7,8 @@ T = TypeVar("T")
@dataclass(frozen=True)
class ChangeEvent(Generic[T]):
index: int
path: MutableSequence[int]
item: T
path: MutableSequence[int] | None = None
@dataclass(frozen=True)

View File

@@ -35,13 +35,14 @@ class HookedMapping(HookedContainer[T], MutableMapping[T, MutableNesting[T]]):
def insert(self, key: T, value: MutableNesting[T]) -> None:
self._data[key] = value
if self.hook:
self.hook(e.AddItemEvent(index=key, item=value, path=self.new_path(key)))
self.hook(e.AddItemEvent(value, path=self.new_path(key)))
# HookedContainer methods
def __getitem__(self, key: T) -> MutableNesting[T]:
if key not in self._data:
self.insert(key, {})
return HookedMapping(self._data[key], hook=self.hook, path=self.new_path(key))
value = self._data[key]
match value:
case HookedMapping(_data=seq):
@@ -54,13 +55,13 @@ class HookedMapping(HookedContainer[T], MutableMapping[T, MutableNesting[T]]):
def __setitem__(self, key: T, value: MutableNesting[T]) -> None:
if key not in self._data:
self.insert(key, value)
return
else:
self._data[key] = value
if self.hook:
self.hook(e.SetItemEvent(index=key, item=value, path=self.new_path(key)))
self.hook(e.SetItemEvent(value, path=self.new_path(key)))
def __delitem__(self, key: T) -> None:
item = self._data[key]
del self._data[key]
if self.hook:
self.hook(e.RemoveItemEvent(index=key, item=item, path=self.new_path(key)))
self.hook(e.RemoveItemEvent(item, path=self.new_path(key)))

View File

@@ -42,4 +42,4 @@ class HookedList(HookedContainer[T], MutableSequence[T]):
def insert(self, index, value):
self._data.insert(index, value)
if self.hook:
self.hook(e.AddItemEvent(index=index, item=value, path=self._path))
self.hook(e.AddItemEvent(self.new_path(index), value))