Coverage for fastblocks / htmx.py: 95%
203 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""FastBlocks Native HTMX Support.
3This module consolidates and enhances HTMX functionality for FastBlocks,
4originally based on the asgi-htmx library.
6Original asgi-htmx library:
7- Author: Marcelo Trylesinski
8- Repository: https://github.com/marcelotrylesisnki/asgi-htmx
9- License: MIT
11The FastBlocks implementation extends the original with:
12- ACB (Asynchronous Component Base) integration
13- FastBlocks-specific debugging and logging
14- Enhanced template integration
15- Response helpers optimized for FastBlocks
16- Event-driven HTMX updates via ACB Events system
17"""
19import asyncio
20import json
21import typing as t
22from contextlib import suppress
23from typing import Any
24from urllib.parse import unquote
26# Oneiric imports
27from oneiric.core.logging import get_logger
30# Create debug function for Oneiric
31def debug(msg: str) -> None:
32 logger = get_logger("fastblocks.htmx")
33 logger.debug(msg)
36from starlette.responses import HTMLResponse
38if t.TYPE_CHECKING:
39 from starlette.types import Scope
40else:
41 Scope = dict
43try:
44 from starlette.requests import Request as StarletteRequest
46 _starlette_available = True
47except ImportError:
48 _starlette_available = False
49 StarletteRequest: t.Any = t.Any # type: ignore[misc,no-redef] # Fallback when Starlette unavailable
51STARLETTE_AVAILABLE = _starlette_available
54class HtmxDetails:
55 def __init__(self, scope: "Scope") -> None:
56 self._scope = scope
57 debug(
58 f"HtmxDetails: Processing HTMX headers for {scope.get('path', 'unknown')}"
59 )
61 def _get_header(self, name: bytes) -> str | None:
62 value = _get_header(self._scope, name)
63 if value and debug:
64 debug(f"HtmxDetails: {name.decode()}: {value}")
65 return value
67 def __bool__(self) -> bool:
68 is_htmx = self._get_header(b"HX-Request") == "true"
69 debug(f"HtmxDetails: Is HTMX request: {is_htmx}")
70 return is_htmx
72 @property
73 def boosted(self) -> bool:
74 return self._get_header(b"HX-Boosted") == "true"
76 @property
77 def current_url(self) -> str | None:
78 return self._get_header(b"HX-Current-URL")
80 @property
81 def history_restore_request(self) -> bool:
82 return self._get_header(b"HX-History-Restore-Request") == "true"
84 @property
85 def prompt(self) -> str | None:
86 return self._get_header(b"HX-Prompt")
88 @property
89 def target(self) -> str | None:
90 return self._get_header(b"HX-Target")
92 @property
93 def trigger(self) -> str | None:
94 return self._get_header(b"HX-Trigger")
96 @property
97 def trigger_name(self) -> str | None:
98 return self._get_header(b"HX-Trigger-Name")
100 @property
101 def triggering_event(self) -> t.Any:
102 value = self._get_header(b"Triggering-Event")
103 if value is None:
104 return None
105 try:
106 event_data = json.loads(value)
107 debug(f"HtmxDetails: Parsed triggering event: {event_data}")
108 return event_data
109 except json.JSONDecodeError as e:
110 debug(f"HtmxDetails: Failed to parse triggering event JSON: {e}")
111 return None
113 def get_all_headers(self) -> dict[str, str | None]:
114 headers = {
115 "HX-Request": self._get_header(b"HX-Request"),
116 "HX-Boosted": self._get_header(b"HX-Boosted"),
117 "HX-Current-URL": self.current_url,
118 "HX-History-Restore-Request": self._get_header(
119 b"HX-History-Restore-Request"
120 ),
121 "HX-Prompt": self.prompt,
122 "HX-Target": self.target,
123 "HX-Trigger": self.trigger,
124 "HX-Trigger-Name": self.trigger_name,
125 "Triggering-Event": self._get_header(b"Triggering-Event"),
126 }
128 return {k: v for k, v in headers.items() if v is not None}
131def _get_header(scope: "Scope", key: bytes) -> str | None:
132 key_lower = key.lower()
133 value: str | None = None
134 should_unquote = False
136 # Extract header value and autoencoding flag
137 try:
138 for k, v in scope["headers"]:
139 if k.lower() == key_lower:
140 value = v.decode("latin-1")
141 if k.lower() == b"%s-uri-autoencoded" % key_lower and v == b"true":
142 should_unquote = True
143 except (KeyError, UnicodeDecodeError) as e:
144 debug(f"HtmxDetails: Error processing header {key}: {e}")
145 return None
147 # Return None if no value found
148 if value is None:
149 return None
151 # Handle URI autoencoding if needed
152 try:
153 return unquote(value) if should_unquote else value
154 except Exception as e:
155 debug(f"HtmxDetails: Error unquoting header value: {e}")
156 return value
159HtmxScope = dict[str, t.Any]
161if STARLETTE_AVAILABLE and StarletteRequest is not t.Any:
163 class HtmxRequest(StarletteRequest): # type: ignore[misc]
164 scope: HtmxScope
166 @property
167 def htmx(self) -> HtmxDetails:
168 return t.cast(HtmxDetails, self.scope["htmx"])
170 def is_htmx(self) -> bool:
171 return bool(self.htmx)
173 def is_boosted(self) -> bool:
174 return self.htmx.boosted
176 def get_htmx_headers(self) -> dict[str, str | None]:
177 return self.htmx.get_all_headers()
178else:
180 class HtmxRequest: # type: ignore[misc,no-redef]
181 """Placeholder HtmxRequest when Starlette is not available."""
183 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
184 raise ImportError(
185 "Starlette is required for HtmxRequest. Install with: uv add starlette"
186 )
189class HtmxResponse(HTMLResponse):
190 def __init__(
191 self,
192 content: str = "",
193 status_code: int = 200,
194 headers: t.Mapping[str, str] | None = None,
195 media_type: str | None = None,
196 background: t.Any = None,
197 trigger: str | None = None,
198 trigger_after_settle: str | None = None,
199 trigger_after_swap: str | None = None,
200 retarget: str | None = None,
201 reselect: str | None = None,
202 reswap: str | None = None,
203 push_url: str | bool | None = None,
204 replace_url: str | bool | None = None,
205 refresh: bool = False,
206 redirect: str | None = None,
207 location: dict[str, t.Any] | str | None = None,
208 ) -> None:
209 init_headers = dict(headers or {})
211 # Set HTMX-specific headers
212 self._set_htmx_headers(
213 init_headers,
214 trigger=trigger,
215 trigger_after_settle=trigger_after_settle,
216 trigger_after_swap=trigger_after_swap,
217 retarget=retarget,
218 reselect=reselect,
219 reswap=reswap,
220 push_url=push_url,
221 replace_url=replace_url,
222 refresh=refresh,
223 redirect=redirect,
224 location=location,
225 )
227 super().__init__(
228 content=content,
229 status_code=status_code,
230 headers=init_headers,
231 media_type=media_type,
232 background=background,
233 )
235 def _set_htmx_headers(
236 self,
237 headers: dict[str, str],
238 *,
239 trigger: str | None = None,
240 trigger_after_settle: str | None = None,
241 trigger_after_swap: str | None = None,
242 retarget: str | None = None,
243 reselect: str | None = None,
244 reswap: str | None = None,
245 push_url: str | bool | None = None,
246 replace_url: str | bool | None = None,
247 refresh: bool = False,
248 redirect: str | None = None,
249 location: dict[str, t.Any] | str | None = None,
250 ) -> None:
251 """Set HTMX-specific headers in the response."""
252 if trigger:
253 headers["HX-Trigger"] = trigger
254 if trigger_after_settle:
255 headers["HX-Trigger-After-Settle"] = trigger_after_settle
256 if trigger_after_swap:
257 headers["HX-Trigger-After-Swap"] = trigger_after_swap
258 if retarget:
259 headers["HX-Retarget"] = retarget
260 if reselect:
261 headers["HX-Reselect"] = reselect
262 if reswap:
263 headers["HX-Reswap"] = reswap
264 if push_url is not None:
265 headers["HX-Push-Url"] = str(push_url).lower()
266 if replace_url is not None:
267 headers["HX-Replace-Url"] = str(replace_url).lower()
268 if refresh:
269 headers["HX-Refresh"] = "true"
270 if redirect:
271 headers["HX-Redirect"] = redirect
272 if location:
273 if isinstance(location, dict):
274 headers["HX-Location"] = json.dumps(location)
275 else:
276 headers["HX-Location"] = str(location)
279def htmx_trigger(
280 trigger_events: str | dict[str, t.Any],
281 content: str = "",
282 status_code: int = 200,
283 **kwargs: t.Any,
284) -> HtmxResponse:
285 trigger_data: dict[str, Any]
286 if isinstance(trigger_events, dict):
287 trigger_value = json.dumps(trigger_events)
288 trigger_name = next(iter(trigger_events.keys()), "custom_trigger")
289 trigger_data = trigger_events
290 else:
291 trigger_value = trigger_events
292 trigger_name = trigger_events
293 trigger_data = {}
295 # Schedule event publishing in background
296 def _run_publish_event() -> None:
297 async def _publish_event(
298 trigger_name: str, trigger_data: dict[str, t.Any]
299 ) -> None:
300 from .adapters.templates._events_wrapper import publish_htmx_trigger
302 await publish_htmx_trigger(
303 trigger_name=trigger_name,
304 trigger_data=trigger_data,
305 )
307 # Create and schedule the task to run the async function
308 try:
309 asyncio.create_task(_publish_event(trigger_name, trigger_data))
310 except RuntimeError:
311 # If not in an event loop, run in a new one
312 import threading
314 if threading.current_thread() is threading.main_thread():
315 # In main thread, run in new event loop
316 loop = asyncio.new_event_loop()
317 asyncio.set_event_loop(loop)
318 loop.run_until_complete(_publish_event(trigger_name, trigger_data))
319 else:
320 # In a different thread, we can't easily start an event loop
321 # Just run the function synchronously (though this won't be truly async)
322 pass
324 with suppress(Exception):
325 _run_publish_event()
327 return HtmxResponse(
328 content=content,
329 status_code=status_code,
330 trigger=trigger_value,
331 **kwargs,
332 )
335def htmx_redirect(url: str, **kwargs: t.Any) -> HtmxResponse:
336 # Schedule event publishing in background
337 def _run_publish_event() -> None:
338 async def _publish_event(url: str) -> None:
339 from ._events_integration import get_event_publisher
341 publisher = get_event_publisher()
342 if publisher:
343 await publisher.publish_htmx_update(
344 update_type="redirect",
345 target=url,
346 )
348 # Create and schedule the task to run the async function
349 try:
350 asyncio.create_task(_publish_event(url))
351 except RuntimeError:
352 # If not in an event loop, run in a new one
353 import threading
355 if threading.current_thread() is threading.main_thread():
356 # In main thread, run in new event loop
357 loop = asyncio.new_event_loop()
358 asyncio.set_event_loop(loop)
359 loop.run_until_complete(_publish_event(url))
360 else:
361 # In a different thread, we can't easily start an event loop
362 # Just run the function synchronously (though this won't be truly async)
363 pass
365 with suppress(Exception):
366 _run_publish_event()
368 return HtmxResponse(redirect=url, **kwargs)
371def htmx_refresh(**kwargs: t.Any) -> HtmxResponse:
372 # Get target from kwargs if provided
373 target = kwargs.get("target", "#body")
375 # Schedule event publishing in background
376 def _run_publish_event() -> None:
377 async def _publish_event(target: str) -> None:
378 from .adapters.templates._events_wrapper import publish_htmx_refresh
380 await publish_htmx_refresh(target=target)
382 # Create and schedule the task to run the async function
383 try:
384 asyncio.create_task(_publish_event(target))
385 except RuntimeError:
386 # If not in an event loop, run in a new one
387 import threading
389 if threading.current_thread() is threading.main_thread():
390 # In main thread, run in new event loop
391 loop = asyncio.new_event_loop()
392 asyncio.set_event_loop(loop)
393 loop.run_until_complete(_publish_event(target))
394 else:
395 # In a different thread, we can't easily start an event loop
396 # Just run the function synchronously (though this won't be truly async)
397 pass
399 with suppress(Exception):
400 _run_publish_event()
402 return HtmxResponse(refresh=True, **kwargs)
405def htmx_push_url(url: str, content: str = "", **kwargs: t.Any) -> HtmxResponse:
406 return HtmxResponse(content=content, push_url=url, **kwargs)
409def htmx_retarget(target: str, content: str = "", **kwargs: t.Any) -> HtmxResponse:
410 return HtmxResponse(content=content, retarget=target, **kwargs)
413def is_htmx(scope_or_request: dict[str, t.Any] | t.Any) -> bool:
414 if hasattr(scope_or_request, "headers"):
415 headers = getattr(scope_or_request, "headers", {})
416 return headers.get("HX-Request") == "true"
417 else:
418 if isinstance(scope_or_request, dict):
419 details = HtmxDetails(scope_or_request)
420 return bool(getattr(details, "is_htmx", False))
421 return False
424__all__ = [
425 "HtmxDetails",
426 "HtmxRequest",
427 "HtmxResponse",
428 "htmx_trigger",
429 "htmx_redirect",
430 "htmx_refresh",
431 "htmx_push_url",
432 "htmx_retarget",
433 "is_htmx",
434]