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
15 changes: 10 additions & 5 deletions docs/site-pages/litestar-guide.html
Original file line number Diff line number Diff line change
Expand Up @@ -621,13 +621,16 @@ <h3 id="http-app">Wiring into Litestar</h3>
<pre><code><span class="kw">from</span> litestar <span class="kw">import</span> <span class="cls">Litestar</span>
<span class="kw">from</span> litestar.contrib.jinja <span class="kw">import</span> <span class="cls">JinjaTemplateEngine</span>
<span class="kw">from</span> litestar.template <span class="kw">import</span> <span class="cls">TemplateConfig</span>
<span class="kw">from</span> jinjax <span class="kw">import</span> <span class="cls">Catalog</span>
<span class="kw">from</span> component_framework.adapters.litestar <span class="kw">import</span> <span class="fn">component_endpoint</span>
<span class="kw">from</span> component_framework.adapters.jinjax_renderer <span class="kw">import</span> <span class="cls">Jinja2Renderer</span>
<span class="kw">from</span> component_framework.adapters.jinjax_renderer <span class="kw">import</span> <span class="cls">JinjaxRenderer</span>
<span class="kw">from</span> component_framework.core.component <span class="kw">import</span> <span class="cls">Component</span>

<span class="kw">import</span> components <span class="cm"># registers CounterComponent via @registry.register</span>

<span class="cls">Component</span>.renderer = <span class="cls">Jinja2Renderer</span>(<span class="str">"templates"</span>)
catalog = <span class="cls">Catalog</span>()
catalog.<span class="fn">add_folder</span>(<span class="str">"templates"</span>)
<span class="cls">Component</span>.renderer = <span class="cls">JinjaxRenderer</span>(catalog)

app = <span class="cls">Litestar</span>(
route_handlers=[<span class="fn">component_endpoint</span>],
Expand Down Expand Up @@ -881,11 +884,14 @@ <h2 id="full-example" data-n="06">Full Example App</h2>
<span class="fn">component_stream_endpoint</span>,
<span class="fn">component_websocket_endpoint</span>,
)
<span class="kw">from</span> component_framework.adapters.jinjax_renderer <span class="kw">import</span> <span class="cls">Jinja2Renderer</span>
<span class="kw">from</span> jinjax <span class="kw">import</span> <span class="cls">Catalog</span>
<span class="kw">from</span> component_framework.adapters.jinjax_renderer <span class="kw">import</span> <span class="cls">JinjaxRenderer</span>
<span class="kw">from</span> component_framework.core.component <span class="kw">import</span> <span class="cls">Component</span>

<span class="cm"># Point the renderer at the templates directory</span>
<span class="cls">Component</span>.renderer = <span class="cls">Jinja2Renderer</span>(<span class="cls">Path</span>(<span class="str">"examples/litestar_templates"</span>))
catalog = <span class="cls">Catalog</span>()
catalog.<span class="fn">add_folder</span>(<span class="cls">Path</span>(<span class="str">"examples/litestar_templates"</span>))
<span class="cls">Component</span>.renderer = <span class="cls">JinjaxRenderer</span>(catalog)

<span class="kw">import</span> examples.litestar_components <span class="cm"># noqa: F401 — side-effect: registers all components</span>

Expand Down Expand Up @@ -943,7 +949,6 @@ <h2 id="testing" data-n="07">Testing</h2>
<span class="kw">from</span> litestar.testing <span class="kw">import</span> <span class="cls">TestClient</span>
<span class="kw">from</span> litestar.testing <span class="kw">import</span> <span class="fn">create_test_client</span>
<span class="kw">from</span> component_framework.adapters.litestar <span class="kw">import</span> <span class="fn">component_endpoint</span>
<span class="kw">from</span> component_framework.adapters.jinjax_renderer <span class="kw">import</span> <span class="cls">Jinja2Renderer</span>
<span class="kw">from</span> component_framework.core.component <span class="kw">import</span> <span class="cls">Component</span>

<span class="kw">from</span> tests.fixtures <span class="kw">import</span> <span class="cls">MockRenderer</span>
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ django = [
litestar = [
"litestar>=2.0",
"jinja2>=3.1",
"jinjax>=0.41",
]
flask = [
"flask>=3.0",
Expand Down
31 changes: 29 additions & 2 deletions src/component_framework/adapters/litestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,26 @@ def _extract_params(data: dict) -> tuple[dict, str | None, dict, dict | None]:
return params, event, payload, state


def _wants_html_response(request: Request) -> bool:
"""Return True when the request carries htmx's ``HX-Request`` header.

This is the standard htmx convention for identifying requests made by
htmx itself, so plain ``hx-post``/``hx-swap`` usage can be served an
HTML fragment instead of the JSON envelope aimed at ``component-client.js``.
"""
return request.headers.get("HX-Request") is not None


def _format_html_sse_frame(html: str) -> str:
"""Format an HTML fragment as an SSE ``data:`` frame for htmx's SSE extension.

Per the SSE spec, multi-line data must be sent as one ``data:`` line per
line of content; htmx's ``sse-swap`` then concatenates them back together.
"""
lines = html.split("\n")
return "".join(f"data: {line}\n" for line in lines) + "\n"


@post("/components/{name:str}")
async def component_endpoint(name: str, request: Request) -> Response:
"""
Expand Down Expand Up @@ -101,6 +121,9 @@ async def component_endpoint(name: str, request: Request) -> Response:

result["state"] = StateSerializer.serialize(result["state"])

if _wants_html_response(request):
return Response(content=result["html"], media_type="text/html", status_code=200)

return Response(content=result, media_type="application/json", status_code=200)

except HTTPException:
Expand Down Expand Up @@ -134,13 +157,17 @@ async def stream_component_endpoint(name: str, request: Request) -> Stream:
params, event, payload, state = _extract_params(data)

component = component_cls(**params)
want_html = _wants_html_response(request)

async def event_generator():
async for frame in component.async_stream_dispatch(
event=event, payload=payload, state=state
):
frame["state"] = StateSerializer.serialize(frame["state"])
yield format_sse_frame(frame)
if want_html:
yield _format_html_sse_frame(frame["html"])
else:
frame["state"] = StateSerializer.serialize(frame["state"])
yield format_sse_frame(frame)

return Stream(event_generator(), media_type="text/event-stream", status_code=200)

Expand Down
43 changes: 43 additions & 0 deletions tests/test_litestar_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,49 @@ def test_form_encoded_event(self, client):
assert deserialized["count"] == 7


# ---------- htmx content negotiation (HX-Request header) ----------


class TestHtmxContentNegotiation:
def test_hx_request_returns_html_fragment(self, client):
"""A request carrying HX-Request should get the raw HTML fragment."""
response = client.post(
"/components/test_counter",
json={"params": {"initial": 5}},
headers={"HX-Request": "true"},
)
assert response.status_code == 200
assert response.headers["content-type"].startswith("text/html")
assert response.text.startswith("<div>")

def test_hx_request_event_returns_html_fragment(self, client):
"""HX-Request should also work for event dispatch, not just mount."""
r1 = client.post("/components/test_counter", json={})
state = r1.json()["state"]

r2 = client.post(
"/components/test_counter",
json={"event": "increment", "payload": {"amount": 3}, "state": state},
headers={"HX-Request": "true"},
)
assert r2.status_code == 200
assert r2.headers["content-type"].startswith("text/html")
assert r2.text.startswith("<div>")

def test_no_hx_request_header_keeps_json_envelope(self, client):
"""Without HX-Request, the existing JSON envelope must be unchanged."""
response = client.post(
"/components/test_counter",
json={"params": {"initial": 5}},
)
assert response.status_code == 200
assert response.headers["content-type"].startswith("application/json")
data = response.json()
assert "html" in data
assert "state" in data
assert "component_id" in data


# ---------- route registration ----------


Expand Down
32 changes: 32 additions & 0 deletions tests/test_litestar_sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,35 @@ def test_stream_non_streaming_component(self, client):
json={"event": "count_up"},
)
assert response.status_code == 400


class TestHtmxStreamContentNegotiation:
def test_hx_request_stream_emits_html_not_json(self, client):
"""With HX-Request, each SSE frame should carry raw HTML, not a JSON envelope."""
response = client.post(
"/components/stream_counter/stream",
json={"event": "count_up", "payload": {"steps": 2}},
headers={"HX-Request": "true"},
)
assert response.status_code == 200
assert "text/event-stream" in response.headers["content-type"]

lines = [ln for ln in response.text.strip("\n").split("\n") if ln.startswith("data: ")]
assert len(lines) >= 1
payloads = [ln.removeprefix("data: ") for ln in lines]
assert any(p.startswith("<div>") for p in payloads)
# None of the frames should be the JSON envelope from the default path.
for p in payloads:
with pytest.raises((json.JSONDecodeError, AssertionError)):
parsed = json.loads(p)
assert "stream_done" in parsed

def test_no_hx_request_stream_keeps_json_envelope(self, client):
"""Without HX-Request, frames must remain the existing JSON envelope."""
response = client.post(
"/components/stream_counter/stream",
json={"event": "count_up", "payload": {"steps": 2}},
)
lines = [ln for ln in response.text.strip("\n").split("\n") if ln.startswith("data: ")]
frames = [json.loads(ln.removeprefix("data: ")) for ln in lines]
assert all("stream_done" in frame for frame in frames)
Loading