chano-htmx 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chano_htmx/__init__.py +43 -0
- chano_htmx/errors.py +12 -0
- chano_htmx/layout.py +48 -0
- chano_htmx/py.typed +0 -0
- chano_htmx/request.py +76 -0
- chano_htmx/responses.py +318 -0
- chano_htmx-0.1.0.dist-info/METADATA +34 -0
- chano_htmx-0.1.0.dist-info/RECORD +10 -0
- chano_htmx-0.1.0.dist-info/WHEEL +4 -0
- chano_htmx-0.1.0.dist-info/licenses/LICENSE +201 -0
chano_htmx/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""First-class HTMX 4 support for Chano."""
|
|
2
|
+
|
|
3
|
+
from chano_htmx.errors import html_error_recover
|
|
4
|
+
from chano_htmx.layout import layout
|
|
5
|
+
from chano_htmx.request import Htmx, get_htmx
|
|
6
|
+
from chano_htmx.responses import (
|
|
7
|
+
OOB,
|
|
8
|
+
Fragment,
|
|
9
|
+
HxHeaders,
|
|
10
|
+
HxResponseHeaders,
|
|
11
|
+
Partial,
|
|
12
|
+
hx_push_url,
|
|
13
|
+
hx_redirect,
|
|
14
|
+
hx_refresh,
|
|
15
|
+
hx_reswap,
|
|
16
|
+
hx_retarget,
|
|
17
|
+
hx_trigger,
|
|
18
|
+
sse_fragment,
|
|
19
|
+
sync_sse_fragment,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"OOB",
|
|
26
|
+
"Fragment",
|
|
27
|
+
"Htmx",
|
|
28
|
+
"HxHeaders",
|
|
29
|
+
"HxResponseHeaders",
|
|
30
|
+
"Partial",
|
|
31
|
+
"__version__",
|
|
32
|
+
"get_htmx",
|
|
33
|
+
"html_error_recover",
|
|
34
|
+
"hx_push_url",
|
|
35
|
+
"hx_redirect",
|
|
36
|
+
"hx_refresh",
|
|
37
|
+
"hx_reswap",
|
|
38
|
+
"hx_retarget",
|
|
39
|
+
"hx_trigger",
|
|
40
|
+
"layout",
|
|
41
|
+
"sse_fragment",
|
|
42
|
+
"sync_sse_fragment",
|
|
43
|
+
]
|
chano_htmx/errors.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""HTML error recovery for Chano HTMX boundaries."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from chano import Failure, Recover, View, recover_view
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def html_error_recover(
|
|
9
|
+
view: View[Failure[Any]], *, validation_status: int = 422
|
|
10
|
+
) -> Recover:
|
|
11
|
+
"""Render failures for HTML requests; leave other representations unchanged."""
|
|
12
|
+
return recover_view("text/html", view, validation_status=validation_status)
|
chano_htmx/layout.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""HTMX 4 layout rules for Chano core layouts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from chano.layouts import Layout, LayoutFn, LayoutMatch, OnSlotFn
|
|
6
|
+
from chano.requests import Request
|
|
7
|
+
from chano_htmx.request import get_htmx
|
|
8
|
+
|
|
9
|
+
_LAYOUT_VARY_HEADERS = (
|
|
10
|
+
"HX-Request",
|
|
11
|
+
"HX-Request-Type",
|
|
12
|
+
"HX-Boosted",
|
|
13
|
+
"HX-History-Restore-Request",
|
|
14
|
+
"HX-Target",
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def layout(
|
|
19
|
+
fn: LayoutFn,
|
|
20
|
+
*,
|
|
21
|
+
slot: str | None = None,
|
|
22
|
+
on_slot: OnSlotFn | None = None,
|
|
23
|
+
) -> Layout:
|
|
24
|
+
"""Build a core ``Layout`` for ``text/html`` driven by HTMX 4 request headers.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
- ``LayoutMatch.FULL`` for non-HTMX requests, ``HX-Request-Type: full``,
|
|
28
|
+
boosted requests, or history-restore requests.
|
|
29
|
+
- ``LayoutMatch.SLOT`` for partial requests whose ``HX-Target`` matches
|
|
30
|
+
``slot`` (supporting ``#id`` against ``tag#id`` or an exact match).
|
|
31
|
+
- ``LayoutMatch.PARTIAL`` for any other partial request.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def _match(request: Request) -> LayoutMatch:
|
|
35
|
+
hx = get_htmx(request)
|
|
36
|
+
if not hx.is_partial:
|
|
37
|
+
return LayoutMatch.FULL
|
|
38
|
+
if slot is not None and hx.targets(slot):
|
|
39
|
+
return LayoutMatch.SLOT
|
|
40
|
+
return LayoutMatch.PARTIAL
|
|
41
|
+
|
|
42
|
+
return Layout(
|
|
43
|
+
fn,
|
|
44
|
+
media_type="text/html",
|
|
45
|
+
match=_match,
|
|
46
|
+
on_slot=on_slot,
|
|
47
|
+
vary=_LAYOUT_VARY_HEADERS,
|
|
48
|
+
)
|
chano_htmx/py.typed
ADDED
|
File without changes
|
chano_htmx/request.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
import msgspec
|
|
6
|
+
|
|
7
|
+
from chano.requests import Request
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _targets_match(hx_target: str, target: str) -> bool:
|
|
11
|
+
"""Return ``True`` when ``hx_target`` matches ``target`` (with ``tag#id``)."""
|
|
12
|
+
if hx_target == target:
|
|
13
|
+
return True
|
|
14
|
+
if target.startswith("#") and "#" in hx_target:
|
|
15
|
+
return hx_target.split("#", 1)[1] == target[1:]
|
|
16
|
+
return False
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Htmx(msgspec.Struct, frozen=True):
|
|
20
|
+
"""Typed HTMX 4 request headers and base-path-aware URL helper."""
|
|
21
|
+
|
|
22
|
+
request: bool = False
|
|
23
|
+
request_type: Literal["partial", "full"] | None = None
|
|
24
|
+
boosted: bool = False
|
|
25
|
+
history_restore: bool = False
|
|
26
|
+
target: str | None = None
|
|
27
|
+
source: str | None = None
|
|
28
|
+
current_url: str | None = None
|
|
29
|
+
base_path: str = ""
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def is_partial(self) -> bool:
|
|
33
|
+
"""Return ``True`` when the request targets a partial swap rather than full."""
|
|
34
|
+
if not self.request:
|
|
35
|
+
return False
|
|
36
|
+
return not (self.request_type == "full" or self.boosted or self.history_restore)
|
|
37
|
+
|
|
38
|
+
def targets(self, selector: str) -> bool:
|
|
39
|
+
"""Return ``True`` when ``HX-Target`` matches ``selector``.
|
|
40
|
+
|
|
41
|
+
Matches exact values (such as ``div#list`` or ``body``) and normalizes
|
|
42
|
+
HTMX 4 ``tag#id`` headers against ``#id`` selectors.
|
|
43
|
+
"""
|
|
44
|
+
if self.target is None:
|
|
45
|
+
return False
|
|
46
|
+
return _targets_match(self.target, selector)
|
|
47
|
+
|
|
48
|
+
def url(self, path: str) -> str:
|
|
49
|
+
"""Prefix ``path`` with ``base_path`` when mounted under a sub-path."""
|
|
50
|
+
clean = "/" + path.lstrip("/")
|
|
51
|
+
if not self.base_path:
|
|
52
|
+
return clean
|
|
53
|
+
return f"{self.base_path.rstrip('/')}{clean}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_htmx(request: Request) -> Htmx:
|
|
57
|
+
"""Extract HTMX 4 headers from the incoming request for ``Depends(get_htmx)``."""
|
|
58
|
+
h = request.headers
|
|
59
|
+
raw_type = h.get("hx-request-type")
|
|
60
|
+
request_type: Literal["partial", "full"] | None = (
|
|
61
|
+
raw_type if raw_type in ("partial", "full") else None
|
|
62
|
+
)
|
|
63
|
+
raw_base = getattr(request, "base_path", None)
|
|
64
|
+
if not isinstance(raw_base, str):
|
|
65
|
+
scope_root = request.scope.get("root_path", "")
|
|
66
|
+
raw_base = scope_root if isinstance(scope_root, str) else ""
|
|
67
|
+
return Htmx(
|
|
68
|
+
request=h.get("hx-request") == "true",
|
|
69
|
+
request_type=request_type,
|
|
70
|
+
boosted=h.get("hx-boosted") == "true",
|
|
71
|
+
history_restore=h.get("hx-history-restore-request") == "true",
|
|
72
|
+
target=h.get("hx-target"),
|
|
73
|
+
source=h.get("hx-source"),
|
|
74
|
+
current_url=h.get("hx-current-url"),
|
|
75
|
+
base_path=raw_base.rstrip("/"),
|
|
76
|
+
)
|
chano_htmx/responses.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Fragments, OOB helpers, HTMX response headers, and SSE fragments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
from html.parser import HTMLParser
|
|
8
|
+
from typing import Any, Self, TypedDict, cast
|
|
9
|
+
|
|
10
|
+
import msgspec
|
|
11
|
+
|
|
12
|
+
from chano import SupportsHtml
|
|
13
|
+
from chano.responses import ServerSentEvent
|
|
14
|
+
|
|
15
|
+
_OPENING_TAG_RE = re.compile(
|
|
16
|
+
r"""^<([A-Za-z][A-Za-z0-9:-]*)((?:\s+[^\s<>'"=/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`/]+))?)*\s*)(/?)>"""
|
|
17
|
+
)
|
|
18
|
+
_VOID_ELEMENTS = frozenset(
|
|
19
|
+
{
|
|
20
|
+
"area",
|
|
21
|
+
"base",
|
|
22
|
+
"br",
|
|
23
|
+
"col",
|
|
24
|
+
"embed",
|
|
25
|
+
"hr",
|
|
26
|
+
"img",
|
|
27
|
+
"input",
|
|
28
|
+
"link",
|
|
29
|
+
"meta",
|
|
30
|
+
"source",
|
|
31
|
+
"track",
|
|
32
|
+
"wbr",
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _RootElementCounter(HTMLParser):
|
|
38
|
+
def __init__(self) -> None:
|
|
39
|
+
super().__init__(convert_charrefs=False)
|
|
40
|
+
self.depth = 0
|
|
41
|
+
self.root_count = 0
|
|
42
|
+
|
|
43
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
44
|
+
if self.depth == 0:
|
|
45
|
+
self.root_count += 1
|
|
46
|
+
if tag.lower() not in _VOID_ELEMENTS:
|
|
47
|
+
self.depth += 1
|
|
48
|
+
|
|
49
|
+
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
50
|
+
if self.depth == 0:
|
|
51
|
+
self.root_count += 1
|
|
52
|
+
|
|
53
|
+
def handle_endtag(self, tag: str) -> None:
|
|
54
|
+
if self.depth > 0:
|
|
55
|
+
self.depth -= 1
|
|
56
|
+
|
|
57
|
+
def handle_data(self, data: str) -> None:
|
|
58
|
+
if self.depth == 0 and data.strip():
|
|
59
|
+
self.root_count += 1
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_single_root_element(markup: str) -> bool:
|
|
63
|
+
parser = _RootElementCounter()
|
|
64
|
+
parser.feed(markup)
|
|
65
|
+
parser.close()
|
|
66
|
+
return parser.root_count == 1 and parser.depth == 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
HxResponseHeaders = TypedDict(
|
|
70
|
+
"HxResponseHeaders",
|
|
71
|
+
{
|
|
72
|
+
"HX-Location": str,
|
|
73
|
+
"HX-Push-Url": str,
|
|
74
|
+
"HX-Redirect": str,
|
|
75
|
+
"HX-Refresh": str,
|
|
76
|
+
"HX-Replace-Url": str,
|
|
77
|
+
"HX-Reswap": str,
|
|
78
|
+
"HX-Retarget": str,
|
|
79
|
+
"HX-Reselect": str,
|
|
80
|
+
"HX-Trigger": str,
|
|
81
|
+
},
|
|
82
|
+
total=False,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _encode_json(value: Any) -> str:
|
|
87
|
+
return msgspec.json.encode(value).decode("utf-8")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _render_html(value: Any) -> str:
|
|
91
|
+
if value is None:
|
|
92
|
+
return ""
|
|
93
|
+
html_method = getattr(value, "__html__", None)
|
|
94
|
+
if callable(html_method):
|
|
95
|
+
return str(html_method())
|
|
96
|
+
if isinstance(value, str):
|
|
97
|
+
return html.escape(value, quote=True)
|
|
98
|
+
return html.escape(str(value), quote=True)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _format_markup(data: str | SupportsHtml) -> str:
|
|
102
|
+
if isinstance(data, str):
|
|
103
|
+
return data
|
|
104
|
+
html_method = getattr(data, "__html__", None)
|
|
105
|
+
if callable(html_method):
|
|
106
|
+
return str(html_method())
|
|
107
|
+
raise TypeError(f"expected str or SupportsHtml, got {type(data).__name__}")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _format_bool_or_url(value: str | bool) -> str:
|
|
111
|
+
if isinstance(value, bool):
|
|
112
|
+
return "true" if value else "false"
|
|
113
|
+
return value
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class HxHeaders(dict[str, str]):
|
|
117
|
+
"""Fluent builder for HTMX response headers.
|
|
118
|
+
|
|
119
|
+
Inherits from ``dict[str, str]`` so instances can be passed directly as
|
|
120
|
+
``headers=...`` or finalized via ``.build()`` as ``HxResponseHeaders``.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def _set_trigger(self, header: str, event: str, detail: Any = None) -> Self:
|
|
124
|
+
existing = self.get(header)
|
|
125
|
+
if existing is None:
|
|
126
|
+
self[header] = event if detail is None else _encode_json({event: detail})
|
|
127
|
+
return self
|
|
128
|
+
|
|
129
|
+
if detail is None and not existing.lstrip().startswith("{"):
|
|
130
|
+
self[header] = f"{existing}, {event}"
|
|
131
|
+
return self
|
|
132
|
+
|
|
133
|
+
if existing.lstrip().startswith("{"):
|
|
134
|
+
merged = msgspec.json.decode(existing, type=dict[str, Any])
|
|
135
|
+
else:
|
|
136
|
+
merged = {
|
|
137
|
+
name.strip(): None for name in existing.split(",") if name.strip()
|
|
138
|
+
}
|
|
139
|
+
merged[event] = detail
|
|
140
|
+
self[header] = _encode_json(merged)
|
|
141
|
+
return self
|
|
142
|
+
|
|
143
|
+
def trigger(self, event: str, detail: Any = None) -> Self:
|
|
144
|
+
return self._set_trigger("HX-Trigger", event, detail)
|
|
145
|
+
|
|
146
|
+
def retarget(self, target: str) -> Self:
|
|
147
|
+
self["HX-Retarget"] = target
|
|
148
|
+
return self
|
|
149
|
+
|
|
150
|
+
def reswap(self, swap: str) -> Self:
|
|
151
|
+
self["HX-Reswap"] = swap
|
|
152
|
+
return self
|
|
153
|
+
|
|
154
|
+
def reselect(self, selector: str) -> Self:
|
|
155
|
+
self["HX-Reselect"] = selector
|
|
156
|
+
return self
|
|
157
|
+
|
|
158
|
+
def redirect(self, url: str) -> Self:
|
|
159
|
+
self["HX-Redirect"] = url
|
|
160
|
+
return self
|
|
161
|
+
|
|
162
|
+
def refresh(self, value: bool = True) -> Self:
|
|
163
|
+
self["HX-Refresh"] = "true" if value else "false"
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
def push_url(self, url: str | bool) -> Self:
|
|
167
|
+
self["HX-Push-Url"] = _format_bool_or_url(url)
|
|
168
|
+
return self
|
|
169
|
+
|
|
170
|
+
def replace_url(self, url: str | bool) -> Self:
|
|
171
|
+
self["HX-Replace-Url"] = _format_bool_or_url(url)
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
def location(self, url: str | dict[str, Any]) -> Self:
|
|
175
|
+
self["HX-Location"] = url if isinstance(url, str) else _encode_json(url)
|
|
176
|
+
return self
|
|
177
|
+
|
|
178
|
+
def build(self) -> HxResponseHeaders:
|
|
179
|
+
return cast(HxResponseHeaders, dict(self))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def hx_trigger(event: str, detail: Any = None) -> HxResponseHeaders:
|
|
183
|
+
return HxHeaders().trigger(event, detail).build()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def hx_redirect(url: str) -> HxResponseHeaders:
|
|
187
|
+
return HxHeaders().redirect(url).build()
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def hx_refresh() -> HxResponseHeaders:
|
|
191
|
+
return HxHeaders().refresh().build()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def hx_retarget(target: str) -> HxResponseHeaders:
|
|
195
|
+
return HxHeaders().retarget(target).build()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def hx_reswap(swap: str) -> HxResponseHeaders:
|
|
199
|
+
return HxHeaders().reswap(swap).build()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def hx_push_url(url: str | bool) -> HxResponseHeaders:
|
|
203
|
+
return HxHeaders().push_url(url).build()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class Fragment:
|
|
207
|
+
"""Concatenate multiple HTML parts (strings, ``__html__`` objects, ``OOB``)."""
|
|
208
|
+
|
|
209
|
+
def __init__(self, *parts: Any) -> None:
|
|
210
|
+
self.parts = parts
|
|
211
|
+
|
|
212
|
+
def __html__(self) -> str:
|
|
213
|
+
return "".join(_render_html(part) for part in self.parts)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _wrap_oob(rendered: str, swap: str, target: str | None) -> str:
|
|
217
|
+
oob_value = f"{swap}:{target}" if target else swap
|
|
218
|
+
attr = f'hx-swap-oob="{html.escape(oob_value, quote=True)}"'
|
|
219
|
+
stripped = rendered.strip()
|
|
220
|
+
match = _OPENING_TAG_RE.match(stripped)
|
|
221
|
+
if (
|
|
222
|
+
match
|
|
223
|
+
and "hx-swap-oob" not in match.group(2)
|
|
224
|
+
and _is_single_root_element(stripped)
|
|
225
|
+
):
|
|
226
|
+
tag, attrs, self_close = match.group(1), match.group(2), match.group(3)
|
|
227
|
+
suffix = "/>" if self_close else ">"
|
|
228
|
+
rest = stripped[match.end() :]
|
|
229
|
+
return f"<{tag}{attrs} {attr}{suffix}{rest}"
|
|
230
|
+
return f"<div {attr}>{rendered}</div>"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class Partial:
|
|
234
|
+
"""Wrap HTML content in an HTMX 4 ``<hx-partial>`` element."""
|
|
235
|
+
|
|
236
|
+
def __init__(
|
|
237
|
+
self,
|
|
238
|
+
content: Any,
|
|
239
|
+
*,
|
|
240
|
+
target: str | None = None,
|
|
241
|
+
id: str | None = None,
|
|
242
|
+
swap: str | None = None,
|
|
243
|
+
) -> None:
|
|
244
|
+
self.content = content
|
|
245
|
+
self.target = target
|
|
246
|
+
self.id = id
|
|
247
|
+
self.swap = swap
|
|
248
|
+
|
|
249
|
+
def __html__(self) -> str:
|
|
250
|
+
return _wrap_partial(
|
|
251
|
+
_render_html(self.content),
|
|
252
|
+
target=self.target,
|
|
253
|
+
id=self.id,
|
|
254
|
+
swap=self.swap,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _wrap_partial(
|
|
259
|
+
rendered: str,
|
|
260
|
+
*,
|
|
261
|
+
target: str | None = None,
|
|
262
|
+
id: str | None = None,
|
|
263
|
+
swap: str | None = None,
|
|
264
|
+
) -> str:
|
|
265
|
+
attrs: list[str] = []
|
|
266
|
+
if id is not None:
|
|
267
|
+
attrs.append(f'id="{html.escape(id, quote=True)}"')
|
|
268
|
+
if target is not None:
|
|
269
|
+
attrs.append(f'hx-target="{html.escape(target, quote=True)}"')
|
|
270
|
+
if swap is not None:
|
|
271
|
+
attrs.append(f'hx-swap="{html.escape(swap, quote=True)}"')
|
|
272
|
+
attr_str = (" " + " ".join(attrs)) if attrs else ""
|
|
273
|
+
return f"<hx-partial{attr_str}>{rendered}</hx-partial>"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class OOB:
|
|
277
|
+
"""Wrap or annotate HTML content with ``hx-swap-oob`` for out-of-band swaps."""
|
|
278
|
+
|
|
279
|
+
def __init__(
|
|
280
|
+
self,
|
|
281
|
+
content: Any,
|
|
282
|
+
*,
|
|
283
|
+
swap: str = "outerHTML",
|
|
284
|
+
target: str | None = None,
|
|
285
|
+
) -> None:
|
|
286
|
+
self.content = content
|
|
287
|
+
self.swap = swap
|
|
288
|
+
self.target = target
|
|
289
|
+
|
|
290
|
+
def __html__(self) -> str:
|
|
291
|
+
return _wrap_oob(_render_html(self.content), self.swap, self.target)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
async def sse_fragment(
|
|
295
|
+
data: str | SupportsHtml,
|
|
296
|
+
*,
|
|
297
|
+
event: str | None = None,
|
|
298
|
+
id: str | None = None,
|
|
299
|
+
retry: int | None = None,
|
|
300
|
+
) -> ServerSentEvent:
|
|
301
|
+
"""Format already-rendered HTML markup as a ``ServerSentEvent``.
|
|
302
|
+
|
|
303
|
+
Defaults to an unnamed event (``event=None``), which HTMX 4's ``hx-sse``
|
|
304
|
+
swaps directly into the target element. Pass ``event`` to dispatch a named
|
|
305
|
+
DOM event instead.
|
|
306
|
+
"""
|
|
307
|
+
return ServerSentEvent(data=_format_markup(data), event=event, id=id, retry=retry)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def sync_sse_fragment(
|
|
311
|
+
data: str | SupportsHtml,
|
|
312
|
+
*,
|
|
313
|
+
event: str | None = None,
|
|
314
|
+
id: str | None = None,
|
|
315
|
+
retry: int | None = None,
|
|
316
|
+
) -> ServerSentEvent:
|
|
317
|
+
"""Format already-rendered HTML markup as a ``ServerSentEvent`` synchronously."""
|
|
318
|
+
return ServerSentEvent(data=_format_markup(data), event=event, id=id, retry=retry)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: chano-htmx
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: First-class HTMX support for Chano
|
|
5
|
+
Project-URL: Homepage, https://chanochano.com
|
|
6
|
+
Project-URL: Repository, https://github.com/scotttrinh/chano
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
15
|
+
Requires-Python: >=3.13
|
|
16
|
+
Requires-Dist: chano<2,>=1.0.0a3
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# chano-htmx
|
|
20
|
+
|
|
21
|
+
`chano-htmx` integrates HTMX 4 with [Chano](https://chanochano.com). It requires Python 3.13+ and `chano>=1.0.0a3,<2`; the minimum Chano version is a prerelease.
|
|
22
|
+
|
|
23
|
+
Use `get_htmx` to read typed request headers. For example, define an `HxRequest` alias in your application and use it to annotate a handler parameter:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from chano import Depends
|
|
27
|
+
from chano_htmx import Htmx as HxRequest, get_htmx
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def GET(hx: HxRequest = Depends(get_htmx)):
|
|
31
|
+
return {"partial": hx.is_partial}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Check `hx.is_partial` on that parameter to choose between a fragment and a full page. Use `Partial` to render an `<hx-partial>` element, or `OOB` to update a target outside the primary swap. `await sse_fragment(markup)` wraps rendered HTML in a server-sent event. `html_error_recover(view)` renders failures for HTML requests while leaving JSON error handling to Chano.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
chano_htmx/__init__.py,sha256=P8mvFdD4N8Op0T2WbN6ARtBUpSbig47lcJNuqMT34aA,791
|
|
2
|
+
chano_htmx/errors.py,sha256=-7D395G-hryLDzoZ4WmoWB31u5cROjD44_zcpRMp0xA,399
|
|
3
|
+
chano_htmx/layout.py,sha256=-s1XrQj5EGbP8BGq1CY02VHA-r5scB2xFwMNThNxv2k,1350
|
|
4
|
+
chano_htmx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
chano_htmx/request.py,sha256=wBUcLKGKeq4C8bcT5Y0oBiKIJrSNDbRSOO71i-yNr4I,2642
|
|
6
|
+
chano_htmx/responses.py,sha256=Vv-4UvgZi_IHmb2IGOPfIzvz7A9KKguM1BDxHHhkoSo,8964
|
|
7
|
+
chano_htmx-0.1.0.dist-info/METADATA,sha256=JrOivtHSnsEpXDcatIbMNvZTsxRrds0VxD8zwwriPK8,1535
|
|
8
|
+
chano_htmx-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
chano_htmx-0.1.0.dist-info/licenses/LICENSE,sha256=OIIZS33ahENiuo7OpyJqNqBWRQhg6k0x8798qaZzD7w,11341
|
|
10
|
+
chano_htmx-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Scott Trinh
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|