chano-htmx 0.1.0__tar.gz

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.
@@ -0,0 +1,18 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .vercel/
6
+ dist/
7
+ node_modules/
8
+ .next/
9
+ next-env.d.ts
10
+ *.tsbuildinfo
11
+ .env.local
12
+ examples/tutorial/backend/assistant.db*
13
+ .lat-build
14
+ .claude
15
+ .mcp.json
16
+ .codex
17
+ .coverage
18
+ .workspaces/
@@ -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.
@@ -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,16 @@
1
+ # chano-htmx
2
+
3
+ `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.
4
+
5
+ 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:
6
+
7
+ ```python
8
+ from chano import Depends
9
+ from chano_htmx import Htmx as HxRequest, get_htmx
10
+
11
+
12
+ def GET(hx: HxRequest = Depends(get_htmx)):
13
+ return {"partial": hx.is_partial}
14
+ ```
15
+
16
+ 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,31 @@
1
+ [project]
2
+ name = "chano-htmx"
3
+ version = "0.1.0"
4
+ description = "First-class HTMX support for Chano"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "License :: OSI Approved :: Apache Software License",
13
+ "Programming Language :: Python :: 3.13",
14
+ "Programming Language :: Python :: 3.14",
15
+ "Programming Language :: Python :: 3.15",
16
+ ]
17
+ dependencies = ["chano>=1.0.0a3,<2"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://chanochano.com"
21
+ Repository = "https://github.com/scotttrinh/chano"
22
+
23
+ [tool.uv.sources]
24
+ chano = { workspace = true }
25
+
26
+ [build-system]
27
+ requires = ["hatchling"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/chano_htmx"]
@@ -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
+ ]
@@ -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)
@@ -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
+ )
File without changes
@@ -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
+ )
@@ -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,213 @@
1
+ import asyncio
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import htpy
7
+ import httpx
8
+ import pytest
9
+
10
+ from chano import (
11
+ Boundary,
12
+ Chano,
13
+ Depends,
14
+ Failure,
15
+ Rendered,
16
+ create_app,
17
+ represent_html,
18
+ represent_json,
19
+ )
20
+ from chano.requests import Request
21
+ from chano.status import OK, NotFound, Unauthorized
22
+ from chano_htmx import HxHeaders, html_error_recover, layout
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class PageMeta:
27
+ title: str
28
+
29
+
30
+ def test_html_error_recover_renders_html_and_reraises_for_json():
31
+ def brand() -> str:
32
+ return "Pulse"
33
+
34
+ async def error_view(
35
+ failure: Failure[Any], request: Request, name: str = Depends(brand)
36
+ ) -> Rendered[PageMeta]:
37
+ return Rendered(
38
+ htpy.p[f"{name}:{request.path}:{failure.status_code}"],
39
+ meta=PageMeta(title=f"Error {failure.status_code}"),
40
+ headers=HxHeaders().retarget("#errors"),
41
+ )
42
+
43
+ recover = html_error_recover(error_view, validation_status=400)
44
+
45
+ boundary = Boundary(
46
+ recover=(recover,),
47
+ layouts=(
48
+ layout(
49
+ lambda body, meta: f"<html><title>{meta.title}</title>{body}</html>",
50
+ slot="#main",
51
+ on_slot=lambda meta: f"<title>{meta.title}</title>",
52
+ ),
53
+ ),
54
+ )
55
+
56
+ @represent_html(lambda d: Rendered(f"<p>{d['n']}</p>", meta=PageMeta(title="OK")))
57
+ @represent_json
58
+ async def item(n: int) -> OK[dict[str, int]] | NotFound | Unauthorized:
59
+ if n == 0:
60
+ return NotFound("missing", headers={"X-Reason": "gone"})
61
+ if n < 0:
62
+ return Unauthorized("nope", headers={"WWW-Authenticate": "Bearer"})
63
+ return OK({"n": n})
64
+
65
+ app = Chano()
66
+ app.add_route("/items", item, ["GET"], boundaries=[boundary])
67
+
68
+ async def run() -> None:
69
+ transport = httpx.ASGITransport(app=app)
70
+ async with httpx.AsyncClient(
71
+ transport=transport, base_url="http://test"
72
+ ) as client:
73
+ # HTML representation -> error_view + layout, preserving headers
74
+ res_html = await client.get("/items?n=0", headers={"Accept": "text/html"})
75
+ assert res_html.status_code == 404
76
+ assert res_html.headers["content-type"].startswith("text/html")
77
+ assert res_html.headers["x-reason"] == "gone"
78
+ assert res_html.headers["hx-retarget"] == "#errors"
79
+ assert (
80
+ res_html.text
81
+ == "<html><title>Error 404</title><p>Pulse:/items:404</p></html>"
82
+ )
83
+
84
+ slot = await client.get(
85
+ "/items?n=0", headers={"HX-Request": "true", "HX-Target": "#main"}
86
+ )
87
+ assert (slot.status_code, slot.text) == (
88
+ 404,
89
+ "<p>Pulse:/items:404</p><title>Error 404</title>",
90
+ )
91
+
92
+ # Preserves WWW-Authenticate header on 401
93
+ res_401 = await client.get("/items?n=-1", headers={"Accept": "text/html"})
94
+ assert res_401.status_code == 401
95
+ assert res_401.headers["www-authenticate"] == "Bearer"
96
+
97
+ # RequestValidationError uses validation_status
98
+ res_val = await client.get(
99
+ "/items?n=not-an-int", headers={"Accept": "text/html"}
100
+ )
101
+ assert res_val.status_code == 400
102
+ assert res_val.headers["content-type"].startswith("text/html")
103
+ assert "<p>Pulse:/items:422</p>" in res_val.text
104
+
105
+ # JSON representation -> re-raises so JSON default applies
106
+ res_json = await client.get(
107
+ "/items?n=0", headers={"Accept": "application/json"}
108
+ )
109
+ assert res_json.status_code == 404
110
+ assert res_json.headers["content-type"].startswith("application/json")
111
+ assert res_json.headers["x-reason"] == "gone"
112
+ assert res_json.json() == {"detail": "missing"}
113
+
114
+ # JSON validation error -> default 422 JSON
115
+ res_json_val = await client.get(
116
+ "/items?n=not-an-int", headers={"Accept": "application/json"}
117
+ )
118
+ assert res_json_val.status_code == 422
119
+ assert res_json_val.headers["content-type"].startswith("application/json")
120
+
121
+ asyncio.run(run())
122
+
123
+
124
+ def test_html_error_view_shares_dependency_with_handler_but_not_across_requests():
125
+ from itertools import count
126
+
127
+ visits = count(1)
128
+
129
+ def ticket() -> int:
130
+ return next(visits)
131
+
132
+ def error_view(failure: Failure[Any], number: int = Depends(ticket)) -> str:
133
+ return f"{failure.content.detail}; view {number}"
134
+
135
+ @represent_html(lambda value: str(value))
136
+ def item(number: int = Depends(ticket)) -> NotFound:
137
+ return NotFound(f"handler {number}")
138
+
139
+ app = Chano()
140
+ boundary = Boundary(recover=[html_error_recover(error_view)])
141
+ app.add_route("/items", item, ["GET"], boundaries=[boundary])
142
+
143
+ async def run() -> None:
144
+ async with httpx.AsyncClient(
145
+ transport=httpx.ASGITransport(app), base_url="http://test"
146
+ ) as client:
147
+ for n in (1, 2):
148
+ response = await client.get("/items", headers={"Accept": "text/html"})
149
+ assert response.status_code == 404
150
+ assert response.text == f"handler {n}; view {n}"
151
+
152
+ asyncio.run(run())
153
+
154
+
155
+ def test_html_error_recover_participates_in_load_time_layout_metadata_check(
156
+ tmp_path: Path,
157
+ ):
158
+ app_dir = tmp_path / "app"
159
+ app_dir.mkdir()
160
+ (app_dir / "boundary.py").write_text(
161
+ "from dataclasses import dataclass\n"
162
+ "from chano import Boundary, Failure\n"
163
+ "from chano_htmx import html_error_recover, layout\n"
164
+ "@dataclass(frozen=True)\n"
165
+ "class PageMeta:\n"
166
+ " title: str\n"
167
+ "def shell(body: str, meta: PageMeta) -> str:\n"
168
+ " return f'<title>{meta.title}</title>{body}'\n"
169
+ "def bad_error_view(failure: Failure) -> str:\n"
170
+ " return '<p>err</p>'\n"
171
+ "boundary = Boundary(\n"
172
+ " layouts=(layout(shell),),\n"
173
+ " recover=(html_error_recover(bad_error_view),),\n"
174
+ ")\n"
175
+ )
176
+ (app_dir / "route.py").write_text(
177
+ "from chano import Rendered, represent_html\n"
178
+ "from app.boundary import PageMeta\n"
179
+ "def ok_view(data: dict) -> Rendered[PageMeta]:\n"
180
+ " return Rendered('<p>ok</p>', meta=PageMeta(title='Home'))\n"
181
+ "@represent_html(ok_view)\n"
182
+ "async def GET() -> dict:\n"
183
+ " return {'ok': True}\n"
184
+ )
185
+
186
+ with pytest.raises(TypeError, match="bad_error_view"):
187
+ create_app(app_dir)
188
+
189
+
190
+ def test_html_error_recover_rejects_raw_response_return():
191
+ from chano.responses import HTMLResponse
192
+
193
+ def bad_view(failure: Failure[Any]) -> Any:
194
+ return HTMLResponse("<p>bypassed</p>", status_code=200)
195
+
196
+ boundary = Boundary(recover=(html_error_recover(bad_view),))
197
+
198
+ @represent_html(lambda d: "<p>ok</p>")
199
+ async def endpoint() -> OK[dict[str, bool]] | NotFound:
200
+ return NotFound("missing", headers={"X-Reason": "gone"})
201
+
202
+ app = Chano()
203
+ app.add_route("/fail", endpoint, ["GET"], boundaries=[boundary])
204
+
205
+ async def run() -> None:
206
+ transport = httpx.ASGITransport(app=app)
207
+ async with httpx.AsyncClient(
208
+ transport=transport, base_url="http://test"
209
+ ) as client:
210
+ res = await client.get("/fail", headers={"Accept": "text/html"})
211
+ assert res.status_code == 500
212
+
213
+ asyncio.run(run())
@@ -0,0 +1,58 @@
1
+ import asyncio
2
+ import json
3
+
4
+ import httpx
5
+ import pytest
6
+
7
+ from chano import Chano, Depends, Response
8
+ from chano_htmx import Htmx, HxHeaders, get_htmx
9
+
10
+
11
+ @pytest.mark.parametrize(
12
+ ("base", "mount", "path"),
13
+ [("", "", "/todos"), ("/web", "", "/web/todos"), ("/web", "/web", "/todos")],
14
+ )
15
+ def test_mounted_form_submission_returns_browser_actions(base, mount, path):
16
+ app = Chano(base_path=base)
17
+
18
+ def save(hx: Htmx = Depends(get_htmx)) -> Response:
19
+ headers = (
20
+ HxHeaders()
21
+ .push_url(hx.url("todos/1"))
22
+ .trigger("saved")
23
+ .trigger("origin", {"source": hx.source, "url": hx.current_url})
24
+ )
25
+ if hx.is_partial and hx.targets("#list") and not hx.targets("div#list"):
26
+ headers.retarget("#list").reswap("beforeend")
27
+ return Response(
28
+ "<li>saved</li>", status_code=201, headers=headers, media_type="text/html"
29
+ )
30
+
31
+ app.add_route(base + "/todos", save, ["POST"])
32
+
33
+ async def submit():
34
+ async with httpx.AsyncClient(
35
+ transport=httpx.ASGITransport(app=app, root_path=mount),
36
+ base_url="http://test",
37
+ ) as client:
38
+ res = await client.post(
39
+ path,
40
+ headers={
41
+ "HX-Request": "true",
42
+ "HX-Target": "ul#list",
43
+ "HX-Source": "button#save",
44
+ "HX-Current-URL": "http://test/new",
45
+ },
46
+ )
47
+ assert res.status_code == 201 and res.text == "<li>saved</li>"
48
+ assert res.headers["hx-push-url"] == base + "/todos/1"
49
+ assert res.headers["hx-retarget"] == "#list"
50
+ assert res.headers["hx-reswap"] == "beforeend"
51
+ assert json.loads(res.headers["hx-trigger"]) == {
52
+ "saved": None,
53
+ "origin": {"source": "button#save", "url": "http://test/new"},
54
+ }
55
+ plain = await client.post(path)
56
+ assert "hx-retarget" not in plain.headers
57
+
58
+ asyncio.run(submit())
@@ -0,0 +1,107 @@
1
+ import asyncio
2
+
3
+ import httpx
4
+ import msgspec
5
+ from markupsafe import Markup
6
+
7
+ from chano import Chano, SSEResponse
8
+ from chano_htmx import (
9
+ OOB,
10
+ Fragment,
11
+ HxHeaders,
12
+ Partial,
13
+ hx_push_url,
14
+ hx_redirect,
15
+ hx_refresh,
16
+ hx_trigger,
17
+ sse_fragment,
18
+ sync_sse_fragment,
19
+ )
20
+
21
+
22
+ def test_rendered_event_stream_carries_html_fragments_and_escaped_text():
23
+ app = Chano()
24
+
25
+ async def events() -> SSEResponse:
26
+ return SSEResponse(
27
+ [
28
+ await sse_fragment(
29
+ Fragment(
30
+ Markup("<li>saved</li>"),
31
+ "<em>A & B</em>",
32
+ Partial("A & B", target="#count"),
33
+ )
34
+ ),
35
+ sync_sse_fragment("<p>done</p>", event="done", id="2", retry=3000),
36
+ ]
37
+ )
38
+
39
+ app.add_route("/stream", events, ["GET"])
40
+
41
+ async def read():
42
+ async with httpx.AsyncClient(
43
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
44
+ ) as client:
45
+ res = await client.get("/stream", headers={"accept": "text/event-stream"})
46
+ assert res.headers["content-type"].startswith("text/event-stream")
47
+ first, last = res.text.strip().split("\n\n")
48
+ assert (
49
+ first == "data: <li>saved</li>&lt;em&gt;A &amp; B&lt;/em&gt;"
50
+ '<hx-partial hx-target="#count">A &amp; B</hx-partial>'
51
+ )
52
+ assert set(last.splitlines()) == {
53
+ "event: done",
54
+ "id: 2",
55
+ "retry: 3000",
56
+ "data: <p>done</p>",
57
+ }
58
+
59
+ asyncio.run(read())
60
+
61
+
62
+ def test_navigation_headers_encode_location_and_boolean_controls():
63
+ headers = (
64
+ HxHeaders()
65
+ .location({"path": "/new", "target": "#main"})
66
+ .replace_url("/new")
67
+ .reselect("#body")
68
+ .build()
69
+ )
70
+ assert msgspec.json.decode(headers["HX-Location"]) == {
71
+ "path": "/new",
72
+ "target": "#main",
73
+ }
74
+ assert headers["HX-Replace-Url"] == "/new"
75
+ assert headers["HX-Reselect"] == "#body"
76
+ assert hx_push_url(False) == {"HX-Push-Url": "false"}
77
+ assert hx_refresh() == {"HX-Refresh": "true"}
78
+ assert hx_trigger("saved") == {"HX-Trigger": "saved"}
79
+ assert hx_redirect("/next") == {"HX-Redirect": "/next"}
80
+
81
+
82
+ def test_oob_variants():
83
+ wrapped = OOB("<plain>", swap="innerHTML", target="#msg").__html__()
84
+ assert wrapped == '<div hx-swap-oob="innerHTML:#msg">&lt;plain&gt;</div>'
85
+
86
+ self_closing = OOB(Markup('<input value="x"/>'), swap="true").__html__()
87
+ assert self_closing == '<input value="x" hx-swap-oob="true"/>'
88
+
89
+ bool_attr = OOB(Markup("<input disabled/>")).__html__()
90
+ assert bool_attr == '<input disabled hx-swap-oob="outerHTML"/>'
91
+
92
+ unquoted_attr = OOB(Markup("<input type=text/>")).__html__()
93
+ assert unquoted_attr == '<input type=text hx-swap-oob="outerHTML"/>'
94
+
95
+ multi_root = OOB(Fragment(Markup("<li>1</li>"), Markup("<li>2</li>"))).__html__()
96
+ assert multi_root == '<div hx-swap-oob="outerHTML"><li>1</li><li>2</li></div>'
97
+
98
+ nested_multi = OOB(
99
+ Markup("<div><div>a</div></div><div>b</div>"), target="#box"
100
+ ).__html__()
101
+ assert (
102
+ nested_multi
103
+ == '<div hx-swap-oob="outerHTML:#box"><div><div>a</div></div><div>b</div></div>'
104
+ )
105
+
106
+ malformed = OOB(Markup("<div " + "a " * 200)).__html__()
107
+ assert malformed.startswith('<div hx-swap-oob="outerHTML">')