Skip to content

Commit

Permalink
add util methods to LayoutUpdate
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorshea committed Sep 15, 2020
1 parent 72e6f93 commit 7a16bc6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
11 changes: 2 additions & 9 deletions idom/core/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from anyio import create_task_group
from anyio.abc import TaskGroup
from jsonpatch import make_patch, apply_patch

from .layout import (
LayoutEvent,
Expand Down Expand Up @@ -122,14 +121,14 @@ async def run(
async def _render_loop(self) -> None:
while True:
update = await super()._outgoing(self.layout, None)
self._model_state = _apply_layout_update(self._model_state, update)
self._model_state = update.apply_to(self._model_state)
# append updates to all other contexts
for queue in self._update_queues.values():
await queue.put(update)

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

async def _outgoing(self, layout: Layout, context: str) -> LayoutUpdate:
Expand All @@ -142,9 +141,3 @@ async def _join_event(self) -> AsyncIterator[asyncio.Event]:
yield event
finally:
event.set()


def _apply_layout_update(doc: Dict[str, Any], update: LayoutUpdate) -> Any:
return apply_patch(
doc, [{**c, "path": update.path + c["path"]} for c in update.changes]
)
12 changes: 11 additions & 1 deletion idom/core/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
)

from loguru import logger
from jsonpatch import make_patch
from jsonpatch import make_patch, apply_patch

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

def apply_to(self, model: Any) -> Any:
"""Return the model resulting from the changes in this update"""
return apply_patch(
model, [{**c, "path": self.path + c["path"]} for c in self.changes]
)

@classmethod
def create_from(cls, source: Any, target: Any) -> "LayoutUpdate":
return cls("", make_patch(source, target).patch)


class LayoutEvent(NamedTuple):
target: str
Expand Down

0 comments on commit 7a16bc6

Please sign in to comment.