Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 96 additions & 13 deletions src/component_framework/core/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,92 @@ def render(self) -> str:

# ---------- Dispatch ----------

def _prepare(self, state: dict | None) -> None:
"""Run the mount-or-hydrate step shared by ``resolve()`` and ``dispatch()``."""
if state:
self.hydrate(state)
else:
self.mount()

def resolve(
self,
event: str | None = None,
payload: dict | None = None,
state: dict | None = None,
) -> dict:
"""
Lightweight, state-only entry point: mount/hydrate + handle_event,
**without** rendering.

Use this when you need the resolved state to do further server-side
work (e.g. a DB re-query driven by the new filter/page/sort value)
before deciding what to render — the normal shape being "resolve
state -> do expensive server-side work -> build the real render".
``dispatch()`` pays for a full template render whether or not the
caller wants the HTML; ``resolve()`` stops right after
:meth:`handle_event`.

Note: because this returns *before* :meth:`render` runs, any state
mutations a subclass makes in :meth:`before_render` are **not**
reflected in the returned dict — that hook only ever runs as part of
rendering. Call :meth:`render` yourself afterward if you need it.

For components with ``async def on_*`` handlers, use
:meth:`async_resolve` instead.

Args:
event: Event name to handle
payload: Event data
state: Serialized state to restore

Returns:
The resolved state dict (i.e. :meth:`dehydrate`'s output).
"""
try:
self._prepare(state)

if event:
self.handle_event(event, payload or {})

return self.dehydrate()

except Exception:
logger.exception(f"Error in {self.__class__.__name__}.resolve()")
raise

async def async_resolve(
self,
event: str | None = None,
payload: dict | None = None,
state: dict | None = None,
) -> dict:
"""
Async counterpart to :meth:`resolve`.

Works with both sync and async event handlers, exactly like
:meth:`async_dispatch` does relative to :meth:`dispatch`. See
:meth:`resolve` for the rationale and the ``before_render`` caveat.

Args:
event: Event name to handle
payload: Event data
state: Serialized state to restore

Returns:
The resolved state dict (i.e. :meth:`dehydrate`'s output).
"""
try:
self._prepare(state)

if event:
await self.async_handle_event(event, payload or {})

return self.dehydrate()

except Exception:
logger.exception(f"Error in {self.__class__.__name__}.async_resolve()")
raise

def dispatch(
self,
event: str | None = None,
Expand All @@ -310,6 +396,10 @@ def dispatch(
"""
Synchronous entry point for component execution.

Internally this is :meth:`resolve`'s lifecycle (mount/hydrate +
handle_event) followed by :meth:`render`. Use :meth:`resolve` instead
when you only need the resolved state and want to skip the render.

For components with ``async def on_*`` handlers, use
:meth:`async_dispatch` instead.

Expand All @@ -322,13 +412,8 @@ def dispatch(
Dict with 'html' and 'state' keys
"""
try:
# Lifecycle: mount or hydrate
if state:
self.hydrate(state)
else:
self.mount()
self._prepare(state)

# Handle event if provided
if event:
self.handle_event(event, payload or {})

Expand Down Expand Up @@ -357,7 +442,10 @@ async def async_dispatch(

Works with both sync and async event handlers. Use this from async
adapters (FastAPI, Litestar, WebSocket) to support ``async def on_*``
handlers.
handlers. Internally this is :meth:`async_resolve`'s lifecycle
(mount/hydrate + async_handle_event) followed by :meth:`render`. Use
:meth:`async_resolve` instead when you only need the resolved state
and want to skip the render.

Args:
event: Event name to handle
Expand All @@ -368,13 +456,8 @@ async def async_dispatch(
Dict with 'html' and 'state' keys
"""
try:
# Lifecycle: mount or hydrate
if state:
self.hydrate(state)
else:
self.mount()
self._prepare(state)

# Handle event if provided
if event:
await self.async_handle_event(event, payload or {})

Expand Down
134 changes: 134 additions & 0 deletions tests/test_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,71 @@ def test_dispatch_event_error_propagates(self):
with pytest.raises(ComponentError):
comp.dispatch(event="nonexistent", state={"value": 0})

def test_dispatch_still_calls_render(self, monkeypatch):
"""Regression: refactoring dispatch() around resolve() must not drop render()."""
comp = SampleComponent(initial=3)
calls = []
original_render = comp.render

def spy_render():
calls.append(True)
return original_render()

monkeypatch.setattr(comp, "render", spy_render)
result = comp.dispatch()
assert calls == [True]
assert "html" in result
# before_render() mutation must still be reflected — proves dehydrate()
# still runs *after* render(), not before.
assert result["state"]["doubled"] == 6


# ---------- Resolve (state-only, no render) ----------


class TestComponentResolve:
"""Component.resolve() — lightweight state-only path (issue #40)."""

def setup_method(self):
Component.renderer = MockRenderer()

def test_resolve_mount_path_returns_state_dict(self):
comp = SampleComponent(initial=7)
result = comp.resolve()
assert result == {"value": 7}

def test_resolve_hydrate_path(self):
comp = SampleComponent()
result = comp.resolve(state={"value": 20})
assert result == {"value": 20}

def test_resolve_with_event(self):
comp = SampleComponent()
result = comp.resolve(event="update", payload={"value": 50}, state={"value": 0})
assert result == {"value": 50}

def test_resolve_does_not_call_render(self, monkeypatch):
comp = SampleComponent(initial=5)
calls = []
monkeypatch.setattr(comp, "render", lambda: calls.append(True))
result = comp.resolve()
assert calls == []
# "doubled" is only ever set in before_render(), which only runs
# inside render() — its absence proves render() never ran.
assert "doubled" not in result
assert "html" not in result

def test_resolve_event_error_propagates(self):
comp = SampleComponent()
with pytest.raises(ComponentError):
comp.resolve(event="nonexistent", state={"value": 0})

def test_resolve_returns_plain_state_dict_shape(self):
comp = SampleComponent(initial=1)
result = comp.resolve()
assert isinstance(result, dict)
assert set(result.keys()) == {"value"}


# ---------- StateSerializer ----------

Expand Down Expand Up @@ -405,3 +470,72 @@ async def test_async_dispatch_event_error_propagates(self):
comp = AsyncSampleComponent()
with pytest.raises(ComponentError):
await comp.async_dispatch(event="nonexistent", state={"value": 0})

@pytest.mark.asyncio
async def test_async_dispatch_still_calls_render(self, monkeypatch):
"""Regression: refactoring async_dispatch() around resolve() must not drop render()."""
comp = AsyncSampleComponent(initial=3)
calls = []
original_render = comp.render

def spy_render():
calls.append(True)
return original_render()

monkeypatch.setattr(comp, "render", spy_render)
result = await comp.async_dispatch()
assert calls == [True]
assert "html" in result
assert result["state"]["doubled"] == 6


# ---------- Async Resolve (state-only, no render) ----------


class TestAsyncResolve:
"""Component.async_resolve() — async counterpart to resolve() (issue #40)."""

def setup_method(self):
Component.renderer = MockRenderer()

@pytest.mark.asyncio
async def test_async_resolve_mount_path_returns_state_dict(self):
comp = AsyncSampleComponent(initial=7)
result = await comp.async_resolve()
assert result == {"value": 7}

@pytest.mark.asyncio
async def test_async_resolve_hydrate_path(self):
comp = AsyncSampleComponent()
result = await comp.async_resolve(state={"value": 20})
assert result == {"value": 20}

@pytest.mark.asyncio
async def test_async_resolve_with_async_event(self):
comp = AsyncSampleComponent()
result = await comp.async_resolve(event="update", payload={"value": 50}, state={"value": 0})
assert result == {"value": 50}

@pytest.mark.asyncio
async def test_async_resolve_with_sync_event(self):
comp = AsyncSampleComponent()
result = await comp.async_resolve(
event="sync_event", payload={"value": 77}, state={"value": 0}
)
assert result == {"value": 77}

@pytest.mark.asyncio
async def test_async_resolve_does_not_call_render(self, monkeypatch):
comp = AsyncSampleComponent(initial=5)
calls = []
monkeypatch.setattr(comp, "render", lambda: calls.append(True))
result = await comp.async_resolve()
assert calls == []
assert "doubled" not in result
assert "html" not in result

@pytest.mark.asyncio
async def test_async_resolve_event_error_propagates(self):
comp = AsyncSampleComponent()
with pytest.raises(ComponentError):
await comp.async_resolve(event="nonexistent", state={"value": 0})
Loading