Skip to content

Commit 7a16bc6

Browse files
committed
add util methods to LayoutUpdate
1 parent 72e6f93 commit 7a16bc6

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

idom/core/dispatcher.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
from anyio import create_task_group
66
from anyio.abc import TaskGroup
7-
from jsonpatch import make_patch, apply_patch
87

98
from .layout import (
109
LayoutEvent,
@@ -122,14 +121,14 @@ async def run(
122121
async def _render_loop(self) -> None:
123122
while True:
124123
update = await super()._outgoing(self.layout, None)
125-
self._model_state = _apply_layout_update(self._model_state, update)
124+
self._model_state = update.apply_to(self._model_state)
126125
# append updates to all other contexts
127126
for queue in self._update_queues.values():
128127
await queue.put(update)
129128

130129
async def _outgoing_loop(self, send: SendCoroutine, context: Any) -> None:
131130
self._update_queues[context] = asyncio.Queue()
132-
await send(LayoutUpdate("", make_patch({}, self._model_state).patch))
131+
await send(LayoutUpdate.create_from({}, self._model_state))
133132
await super()._outgoing_loop(send, context)
134133

135134
async def _outgoing(self, layout: Layout, context: str) -> LayoutUpdate:
@@ -142,9 +141,3 @@ async def _join_event(self) -> AsyncIterator[asyncio.Event]:
142141
yield event
143142
finally:
144143
event.set()
145-
146-
147-
def _apply_layout_update(doc: Dict[str, Any], update: LayoutUpdate) -> Any:
148-
return apply_patch(
149-
doc, [{**c, "path": update.path + c["path"]} for c in update.changes]
150-
)

idom/core/layout.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
)
1616

1717
from loguru import logger
18-
from jsonpatch import make_patch
18+
from jsonpatch import make_patch, apply_patch
1919

2020
from .element import AbstractElement
2121
from .events import EventHandler, EventTarget
@@ -29,6 +29,16 @@ class LayoutUpdate(NamedTuple):
2929
path: str
3030
changes: List[Dict[str, Any]]
3131

32+
def apply_to(self, model: Any) -> Any:
33+
"""Return the model resulting from the changes in this update"""
34+
return apply_patch(
35+
model, [{**c, "path": self.path + c["path"]} for c in self.changes]
36+
)
37+
38+
@classmethod
39+
def create_from(cls, source: Any, target: Any) -> "LayoutUpdate":
40+
return cls("", make_patch(source, target).patch)
41+
3242

3343
class LayoutEvent(NamedTuple):
3444
target: str

0 commit comments

Comments
 (0)