htmy 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.
Potentially problematic release.
This version of htmy might be problematic. Click here for more details.
- htmy/__init__.py +35 -0
- htmy/core.py +502 -0
- htmy/html.py +1247 -0
- htmy/py.typed +0 -0
- htmy/renderer.py +103 -0
- htmy/typing.py +89 -0
- htmy/utils.py +44 -0
- htmy-0.1.0.dist-info/LICENSE +21 -0
- htmy-0.1.0.dist-info/METADATA +315 -0
- htmy-0.1.0.dist-info/RECORD +11 -0
- htmy-0.1.0.dist-info/WHEEL +4 -0
htmy/py.typed
ADDED
|
File without changes
|
htmy/renderer.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections import ChainMap
|
|
5
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
6
|
+
|
|
7
|
+
from .core import ErrorBoundary, xml_format_string
|
|
8
|
+
from .typing import Component, ComponentType, Context, ContextProvider, HTMYComponentType
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class HTMY:
|
|
12
|
+
"""HTMY component renderer."""
|
|
13
|
+
|
|
14
|
+
__slots__ = ("_default_context", "_string_formatter")
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
default_context: Context | None = None,
|
|
19
|
+
*,
|
|
20
|
+
string_formatter: Callable[[str], str] = xml_format_string,
|
|
21
|
+
) -> None:
|
|
22
|
+
"""
|
|
23
|
+
Initialization.
|
|
24
|
+
|
|
25
|
+
Arguments:
|
|
26
|
+
default_context: The default context to use for rendering if `render()` doesn't
|
|
27
|
+
receive a context.
|
|
28
|
+
string_formatter: Callable that should be used to format plain strings. By default
|
|
29
|
+
an XML-safe string formatter will be used.
|
|
30
|
+
"""
|
|
31
|
+
self._default_context: Context = {} if default_context is None else default_context
|
|
32
|
+
self._string_formatter = string_formatter
|
|
33
|
+
|
|
34
|
+
async def render(self, component: Component, context: Context | None = None) -> str:
|
|
35
|
+
"""
|
|
36
|
+
Renders the given component.
|
|
37
|
+
|
|
38
|
+
Arguments:
|
|
39
|
+
component: The component to render.
|
|
40
|
+
context: An optional rendering context. If `None`, the renderer's default context will be used.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
The rendered string.
|
|
44
|
+
"""
|
|
45
|
+
return await self._render(component, self._default_context if context is None else context)
|
|
46
|
+
|
|
47
|
+
async def _render(self, component: Component, context: Context) -> str:
|
|
48
|
+
"""
|
|
49
|
+
Renders a single component "level".
|
|
50
|
+
|
|
51
|
+
Arguments:
|
|
52
|
+
component: The component to render.
|
|
53
|
+
context: The current rendering context.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
The rendered string.
|
|
57
|
+
"""
|
|
58
|
+
if isinstance(component, str):
|
|
59
|
+
return self._string_formatter(component)
|
|
60
|
+
elif isinstance(component, Iterable):
|
|
61
|
+
rendered_children = await asyncio.gather(
|
|
62
|
+
*(self._render_one(comp, context) for comp in component)
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
return "".join(rendered_children)
|
|
66
|
+
else:
|
|
67
|
+
return await self._render_one(component, context)
|
|
68
|
+
|
|
69
|
+
async def _render_one(self, component: ComponentType, context: Context) -> str:
|
|
70
|
+
"""
|
|
71
|
+
Renders a single component.
|
|
72
|
+
|
|
73
|
+
Arguments:
|
|
74
|
+
component: The component to render.
|
|
75
|
+
context: The current rendering context.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
The rendered string.
|
|
79
|
+
"""
|
|
80
|
+
child_context = context
|
|
81
|
+
if isinstance(component, ContextProvider):
|
|
82
|
+
extra_context = component.htmy_context()
|
|
83
|
+
if isinstance(extra_context, Awaitable):
|
|
84
|
+
extra_context = await extra_context
|
|
85
|
+
|
|
86
|
+
child_context = ChainMap(extra_context, context)
|
|
87
|
+
|
|
88
|
+
if isinstance(component, HTMYComponentType):
|
|
89
|
+
try:
|
|
90
|
+
children = component.htmy(child_context)
|
|
91
|
+
if isinstance(children, Awaitable):
|
|
92
|
+
children = await children
|
|
93
|
+
|
|
94
|
+
return await self._render(children, child_context)
|
|
95
|
+
except Exception as e:
|
|
96
|
+
if isinstance(component, ErrorBoundary):
|
|
97
|
+
return await self._render_one(component.fallback_component(e), context)
|
|
98
|
+
|
|
99
|
+
raise e
|
|
100
|
+
elif isinstance(component, str):
|
|
101
|
+
return self._string_formatter(component)
|
|
102
|
+
else:
|
|
103
|
+
raise TypeError("Unknown component type.")
|
htmy/typing.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from collections.abc import Callable, Coroutine, Mapping
|
|
2
|
+
from typing import Any, Protocol, TypeAlias, TypeGuard, TypeVar, runtime_checkable
|
|
3
|
+
|
|
4
|
+
T = TypeVar("T")
|
|
5
|
+
U = TypeVar("U")
|
|
6
|
+
|
|
7
|
+
# -- Properties
|
|
8
|
+
|
|
9
|
+
PropertyValue: TypeAlias = Any | None
|
|
10
|
+
"""Component/XML tag property value."""
|
|
11
|
+
|
|
12
|
+
Properties: TypeAlias = Mapping[str, PropertyValue]
|
|
13
|
+
"""Component/XML tag property mapping."""
|
|
14
|
+
|
|
15
|
+
# -- Context
|
|
16
|
+
|
|
17
|
+
ContextKey: TypeAlias = Any
|
|
18
|
+
"""Context key."""
|
|
19
|
+
|
|
20
|
+
ContextValue: TypeAlias = Any
|
|
21
|
+
"""Context value."""
|
|
22
|
+
|
|
23
|
+
Context: TypeAlias = Mapping[ContextKey, ContextValue]
|
|
24
|
+
"""Context mapping."""
|
|
25
|
+
|
|
26
|
+
# -- Components
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@runtime_checkable
|
|
30
|
+
class SyncComponent(Protocol):
|
|
31
|
+
"""Protocol definition for sync `htmy` components."""
|
|
32
|
+
|
|
33
|
+
def htmy(self, context: Context, /) -> "Component": ...
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@runtime_checkable
|
|
37
|
+
class AsyncComponent(Protocol):
|
|
38
|
+
"""Protocol definition for async `htmy` components."""
|
|
39
|
+
|
|
40
|
+
async def htmy(self, context: Context, /) -> "Component": ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
HTMYComponentType: TypeAlias = SyncComponent | AsyncComponent
|
|
44
|
+
"""Sync or async `htmy` component type."""
|
|
45
|
+
|
|
46
|
+
ComponentType: TypeAlias = HTMYComponentType | str
|
|
47
|
+
"""Type definition for a single component."""
|
|
48
|
+
|
|
49
|
+
# Omit strings from this type to simplify checks.
|
|
50
|
+
ComponentSequence: TypeAlias = list[ComponentType] | tuple[ComponentType, ...]
|
|
51
|
+
"""Component sequence type."""
|
|
52
|
+
|
|
53
|
+
Component: TypeAlias = ComponentType | ComponentSequence
|
|
54
|
+
"""Component type: a single component or a sequence of components."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_component_sequence(obj: Any) -> TypeGuard[ComponentSequence]:
|
|
58
|
+
"""Returns whether the given object is a component sequence."""
|
|
59
|
+
return isinstance(obj, (list, tuple))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
SyncFunctionComponent: TypeAlias = Callable[[T, Context], Component]
|
|
63
|
+
"""Protocol definition for sync function components."""
|
|
64
|
+
|
|
65
|
+
AsyncFunctionComponent: TypeAlias = Callable[[T, Context], Coroutine[Any, Any, Component]]
|
|
66
|
+
"""Protocol definition for async function components."""
|
|
67
|
+
|
|
68
|
+
FunctionComponent: TypeAlias = SyncFunctionComponent[T] | AsyncFunctionComponent[T]
|
|
69
|
+
"""Function component type."""
|
|
70
|
+
|
|
71
|
+
# -- Context providers
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@runtime_checkable
|
|
75
|
+
class SyncContextProvider(Protocol):
|
|
76
|
+
"""Protocol definition for sync context providers."""
|
|
77
|
+
|
|
78
|
+
def htmy_context(self) -> Context: ...
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@runtime_checkable
|
|
82
|
+
class AsyncContextProvider(Protocol):
|
|
83
|
+
"""Protocol definition for async context providers."""
|
|
84
|
+
|
|
85
|
+
async def htmy_context(self) -> Context: ...
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
ContextProvider: TypeAlias = SyncContextProvider | AsyncContextProvider
|
|
89
|
+
"""Context provider type."""
|
htmy/utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Generator
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .typing import ComponentSequence, ComponentType
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def join_components(
|
|
11
|
+
components: ComponentSequence,
|
|
12
|
+
separator: ComponentType,
|
|
13
|
+
pad: bool = False,
|
|
14
|
+
) -> Generator[ComponentType, None, None]:
|
|
15
|
+
"""
|
|
16
|
+
Joins the given components using the given separator.
|
|
17
|
+
|
|
18
|
+
Arguments:
|
|
19
|
+
components: The components to join.
|
|
20
|
+
separator: The separator to use.
|
|
21
|
+
pad: Whether to add a separator before the first and after the last components.
|
|
22
|
+
"""
|
|
23
|
+
if len(components) == 0:
|
|
24
|
+
return
|
|
25
|
+
|
|
26
|
+
if pad:
|
|
27
|
+
yield separator
|
|
28
|
+
|
|
29
|
+
components_iterator = iter(components)
|
|
30
|
+
yield next(components_iterator)
|
|
31
|
+
|
|
32
|
+
for component in components_iterator:
|
|
33
|
+
yield separator
|
|
34
|
+
yield component
|
|
35
|
+
|
|
36
|
+
if pad:
|
|
37
|
+
yield separator
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def join(*items: str | None, separator: str = " ") -> str:
|
|
41
|
+
"""
|
|
42
|
+
Joins the given strings with the given separator, skipping `None` values.
|
|
43
|
+
"""
|
|
44
|
+
return separator.join(i for i in items if i)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Peter Volf
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: htmy
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async, zero-dependency, pure-Python rendering engine.
|
|
5
|
+
License: MIT
|
|
6
|
+
Author: Peter Volf
|
|
7
|
+
Author-email: do.volfp@gmail.com
|
|
8
|
+
Requires-Python: >=3.11,<4.0
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+

|
|
16
|
+

|
|
17
|
+

|
|
18
|
+

|
|
19
|
+
|
|
20
|
+
**Source code**: [https://github.com/volfpeter/htmy](https://github.com/volfpeter/htmy)
|
|
21
|
+
|
|
22
|
+
**Documentation and examples**: [https://volfpeter.github.io/htmy](https://volfpeter.github.io/htmy/)
|
|
23
|
+
|
|
24
|
+
# `htmy`
|
|
25
|
+
|
|
26
|
+
**Async**, **zero-dependency**, **pure-Python** rendering engine.
|
|
27
|
+
|
|
28
|
+
## Key features
|
|
29
|
+
|
|
30
|
+
- **Async**-first, to let you make the best use of [modern async tools](https://github.com/timofurrer/awesome-asyncio).
|
|
31
|
+
- **Powerful**, React-like **context support**, so you can avoid prop-drilling.
|
|
32
|
+
- Sync and async **function components** with **decorator syntax**.
|
|
33
|
+
- All baseline **HTML** tags built-in.
|
|
34
|
+
- Built-in, easy to use `ErrorBoundary` component for graceful error handling.
|
|
35
|
+
- Everything is **easily customizable**, from the rendering engine to components, formatting and context management.
|
|
36
|
+
- Automatic and customizable **property-name conversion** from snake case to kebab case.
|
|
37
|
+
- **Fully-typed**.
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
The package is available on PyPI and can be installed with:
|
|
42
|
+
|
|
43
|
+
```console
|
|
44
|
+
$ pip install htmy
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Concepts
|
|
48
|
+
|
|
49
|
+
The entire library -- from the rendering engine itself to the built-in components -- is built around a few simple protocols and a handful of simple utility classes. This means that you can easily customize, extend, or replace basically everything in the library. Yes, even the rendering engine. The remaining parts will keep working as expected.
|
|
50
|
+
|
|
51
|
+
Also, the library doesn't rely on advanced Python features such as metaclasses or descriptors. There are also no complex base classes and the like. Even a junior engineer could understand, develop, and debug an application that's built with `htmy`.
|
|
52
|
+
|
|
53
|
+
### Components
|
|
54
|
+
|
|
55
|
+
Every class with a sync or async `htmy(context: Context) -> Component` method is an `htmy` component (technically an `HTMYComponentType`). Strings are also components, as well as lists or tuples of `HTMYComponentType` or string objects.
|
|
56
|
+
|
|
57
|
+
Using this method name enables the conversion of any of your business objects (from `TypedDicts`s or `pydantic` models to ORM classes) into components without the fear of name collision with other tools.
|
|
58
|
+
|
|
59
|
+
Async support makes it possible to load data or execute async business logic right in your components. This can reduce the amount of boilerplate you need to write in some cases, and also gives you the freedom to split the rendering and non-rendering logic in any way you see fit.
|
|
60
|
+
|
|
61
|
+
Example:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from dataclasses import dataclass
|
|
65
|
+
|
|
66
|
+
from htmy import Component, Context, html
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
69
|
+
class User:
|
|
70
|
+
username: str
|
|
71
|
+
name: str
|
|
72
|
+
email: str
|
|
73
|
+
|
|
74
|
+
async def is_admin(self) -> bool:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
class UserRow(User):
|
|
78
|
+
async def htmy(self, context: Context) -> Component:
|
|
79
|
+
role = "admin" if await self.is_admin() else "restricted"
|
|
80
|
+
return html.tr(
|
|
81
|
+
html.td(self.username),
|
|
82
|
+
html.td(self.name),
|
|
83
|
+
html.td(html.a(self.email, href=f"mailto:{self.email}")),
|
|
84
|
+
html.td(role)
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
88
|
+
class UserRows:
|
|
89
|
+
users: list[User]
|
|
90
|
+
def htmy(self, context: Context) -> Component:
|
|
91
|
+
# Note that a list is returned here. A list or tuple of `HTMYComponentType | str` objects is also a component.
|
|
92
|
+
return [UserRow(username=u.username, name=u.name, email=u.email) for u in self.users]
|
|
93
|
+
|
|
94
|
+
user_table = html.table(
|
|
95
|
+
UserRows(
|
|
96
|
+
users=[
|
|
97
|
+
User(username="Foo", name="Foo", email="foo@example.com"),
|
|
98
|
+
User(username="Bar", name="Bar", email="bar@example.com"),
|
|
99
|
+
]
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`htmy` also provides a `@component` decorator that can be used on sync or async `my_component(props: MyProps, context: Context) -> Component` functions to convert them into components (preserving the `props` typing).
|
|
105
|
+
|
|
106
|
+
Here is the same example as above, but with function components:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from dataclasses import dataclass
|
|
110
|
+
|
|
111
|
+
from htmy import Component, Context, component, html
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
114
|
+
class User:
|
|
115
|
+
username: str
|
|
116
|
+
name: str
|
|
117
|
+
email: str
|
|
118
|
+
|
|
119
|
+
async def is_admin(self) -> bool:
|
|
120
|
+
return False
|
|
121
|
+
|
|
122
|
+
@component
|
|
123
|
+
async def user_row(user: User, context: Context) -> Component:
|
|
124
|
+
# The first argument of function components is their "props", the data they need.
|
|
125
|
+
# The second argument is the rendering context.
|
|
126
|
+
role = "admin" if await user.is_admin() else "restricted"
|
|
127
|
+
return html.tr(
|
|
128
|
+
html.td(user.username),
|
|
129
|
+
html.td(user.name),
|
|
130
|
+
html.td(html.a(user.email, href=f"mailto:{user.email}")),
|
|
131
|
+
html.td(role)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
@component
|
|
135
|
+
def user_rows(users: list[User], context: Context) -> Component:
|
|
136
|
+
# Nothing to await in this component, so it's sync.
|
|
137
|
+
# Note that we only pass the "props" to the user_row() component (well, function component wrapper).
|
|
138
|
+
# The context will be passed to the wrapper during rendering.
|
|
139
|
+
return [user_row(user) for user in users]
|
|
140
|
+
|
|
141
|
+
user_table = html.table(
|
|
142
|
+
user_rows(
|
|
143
|
+
[
|
|
144
|
+
User(username="Foo", name="Foo", email="foo@example.com"),
|
|
145
|
+
User(username="Bar", name="Bar", email="bar@example.com"),
|
|
146
|
+
]
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Built-in components
|
|
152
|
+
|
|
153
|
+
`htmy` has a rich set of built-in base and utility components for both HTML and other use-cases:
|
|
154
|
+
|
|
155
|
+
- `html` module: a complete set of [baseline HTML tags](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility).
|
|
156
|
+
- `BaseTag`, `TagWithProps`, `StandaloneTag`, `Tag`: base classes for custom XML tags.
|
|
157
|
+
- `ErrorBoundary`, `Fragment`, `SafeStr`, `WithContext`: utilities for error handling, component wrappers, context providers, and formatting.
|
|
158
|
+
|
|
159
|
+
### Rendering
|
|
160
|
+
|
|
161
|
+
`htmy.HTMY` is the built-in, default renderer of the library.
|
|
162
|
+
|
|
163
|
+
If you're using the library in an async web framework like [FastAPI](https://fastapi.tiangolo.com/), then you're already in an async environment, so you can render components as simply as this: `await HTMY().render(my_root_component)`.
|
|
164
|
+
|
|
165
|
+
If you're trying to run the renderer in a sync environment, like a local script or CLI, then you first need to wrap the renderer in an async task and execute that task with `asyncio.run()`:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
import asyncio
|
|
169
|
+
|
|
170
|
+
from htmy import HTMY, html
|
|
171
|
+
|
|
172
|
+
async def render_page() -> None:
|
|
173
|
+
page = (
|
|
174
|
+
html.DOCTYPE.html,
|
|
175
|
+
html.html(
|
|
176
|
+
html.body(
|
|
177
|
+
html.h1("Hello World!"),
|
|
178
|
+
html.p("This page was rendered by ", html.code("htmy")),
|
|
179
|
+
),
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
result = await HTMY().render(page)
|
|
184
|
+
print(result)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
if __name__ == "__main__":
|
|
188
|
+
asyncio.run(render_page())
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### Context
|
|
192
|
+
|
|
193
|
+
As you could see from the code examples above, every component has a `context: Context` argument, which we haven't used so far. Context is a way to share data with the entire subtree of a component without "prop drilling".
|
|
194
|
+
|
|
195
|
+
The context (technically a `Mapping`) is entirely managed by the renderer. Context provider components (any class with a sync or async `htmy_context() -> Context` method) add new data to the context to make it available to components in their subtree, and components can simply take what they need from the context.
|
|
196
|
+
|
|
197
|
+
There is no restriction on what can be in the context, it can be used for anything the application needs, for example making the current user, UI preferences, themes, or formatters available to components. In fact, built-in components get their `Formatter` from the context if it contains one, to make it possible to customize tag property name and value formatting.
|
|
198
|
+
|
|
199
|
+
Here's an example context provider and consumer implementation:
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
import asyncio
|
|
203
|
+
|
|
204
|
+
from htmy import HTMY, Component, ComponentType, Context, component, html
|
|
205
|
+
|
|
206
|
+
class UserContext:
|
|
207
|
+
def __init__(self, *children: ComponentType, username: str, theme: str) -> None:
|
|
208
|
+
self._children = children
|
|
209
|
+
self.username = username
|
|
210
|
+
self.theme = theme
|
|
211
|
+
|
|
212
|
+
def htmy_context(self) -> Context:
|
|
213
|
+
# Context provider implementation.
|
|
214
|
+
return {UserContext: self}
|
|
215
|
+
|
|
216
|
+
def htmy(self, context: Context) -> Component:
|
|
217
|
+
# Context providers must also be components, as they just
|
|
218
|
+
# wrap some children components in their context.
|
|
219
|
+
return self._children
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def from_context(cls, context: Context) -> "UserContext":
|
|
223
|
+
user_context = context[cls]
|
|
224
|
+
if isinstance(user_context, UserContext):
|
|
225
|
+
return user_context
|
|
226
|
+
|
|
227
|
+
raise TypeError("Invalid user context.")
|
|
228
|
+
|
|
229
|
+
@component
|
|
230
|
+
def welcome_page(text: str, context: Context) -> Component:
|
|
231
|
+
# Get user information from the context.
|
|
232
|
+
user = UserContext.from_context(context)
|
|
233
|
+
return (
|
|
234
|
+
html.DOCTYPE.html,
|
|
235
|
+
html.html(
|
|
236
|
+
html.body(
|
|
237
|
+
html.h1(text, html.strong(user.username)),
|
|
238
|
+
data_theme=user.theme,
|
|
239
|
+
),
|
|
240
|
+
),
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
async def render_welcome_page() -> None:
|
|
244
|
+
page = UserContext(
|
|
245
|
+
welcome_page("Welcome back "),
|
|
246
|
+
username="John",
|
|
247
|
+
theme="dark",
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
result = await HTMY().render(page)
|
|
251
|
+
print(result)
|
|
252
|
+
|
|
253
|
+
if __name__ == "__main__":
|
|
254
|
+
asyncio.run(render_welcome_page())
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
You can of course rely on the built-in context related utilities like the `ContextAware` or `WithContext` classes for convenient and typed context use with less boilerplate code.
|
|
258
|
+
|
|
259
|
+
### Formatter
|
|
260
|
+
|
|
261
|
+
As mentioned before, the built-in `Formatter` class is responsible for tag attribute name and value formatting. You can completely override or extend the built-in formatting behavior simply by extending this class or adding new rules to an instance of it, and then adding the custom instance to the context, either directly in `HTMY` or `HTMY.render()`, or in a context provider component.
|
|
262
|
+
|
|
263
|
+
These are default tag attribute formatting rules:
|
|
264
|
+
|
|
265
|
+
- Underscores are converted to dashes in attribute names (`_` -> `-`) unless the attribute name starts or ends with an underscore, in which case leading and trailing underscores are removed and the rest of attribute name is preserved. For example `data_theme="dark"` is converted to `data-theme="dark"`, but `_data_theme="dark"` will end up as `data_theme="dark"` in the rendered text. More importantly `class_="text-danger"`, `_class="text-danger"`, `_class__="text-danger"` are all converted to `class="text-danger"`, and `_for="my-input"` or `for_="my_input"` will become `for="my-input"`.
|
|
266
|
+
- `bool` attribute values are converted to strings (`"true"` and `"false"`).
|
|
267
|
+
- `XBool.true` attributes values are converted to an empty string, and `XBool.false` values are skipped (only the attribute name is rendered).
|
|
268
|
+
- `date` and `datetime` attribute values are converted to ISO strings.
|
|
269
|
+
|
|
270
|
+
### Error boundary
|
|
271
|
+
|
|
272
|
+
The `ErrorBoundary` component is useful if you want your application to fail gracefully (e.g. display an error message) instead of raising an HTTP error.
|
|
273
|
+
|
|
274
|
+
The error boundary wraps a component component subtree. When the renderer encounters an `ErrorBoundary` component, it will try to render its wrapped content. If rendering fails with an exception at any point in the `ErrorBoundary`'s subtree, the renderer will automatically fall back to the component you assigned to the `ErrorBoundary`'s `fallback` property.
|
|
275
|
+
|
|
276
|
+
Optionally, you can define which errors an error boundary can handle, giving you fine control over error handling.
|
|
277
|
+
|
|
278
|
+
### Sync or async?
|
|
279
|
+
|
|
280
|
+
In general, a component should be async if it must await some async call inside.
|
|
281
|
+
|
|
282
|
+
If a component executes a potentially "long-running" synchronous call, it is strongly recommended to delegate that call to a worker thread an await it (thus making the component async). This can be done for example with `anyio`'s `to_thread` [utility](https://anyio.readthedocs.io/en/stable/threads.html), `starlette`'s (or `fastapi`'s) `run_in_threadpool()`, and so on. The goal here is to avoid blocking the asyncio event loop, as that can lead to performance issues.
|
|
283
|
+
|
|
284
|
+
In all other cases, it's best to use sync components.
|
|
285
|
+
|
|
286
|
+
## Why
|
|
287
|
+
|
|
288
|
+
At one end of the spectrum, there are the complete application frameworks that combine the server (Python) and client (JavaScript) applications with the entire state management and synchronization into a single Python (an in some cases an additional JavaScript) package. Some of the most popular examples are: [Reflex](https://github.com/reflex-dev/reflex), [NiceGUI](https://github.com/zauberzeug/nicegui/), [ReactPy](https://github.com/reactive-python/reactpy), and [FastUI](https://github.com/pydantic/FastUI).
|
|
289
|
+
|
|
290
|
+
The main benefit of these frameworks is rapid application prototyping and a very convenient developer experience (at least as long as you stay within the built-in feature set of the framework). In exchange for that, they are very opinionated (from components to frontend tooling and state management), the underlying engineering is very complex, deployment and scaling can be hard or costly, and they can be hard to migrate away from. Even with these caveats, they can be a very good choice for internal tools and application prototyping.
|
|
291
|
+
|
|
292
|
+
The other end of spectrum -- plain rendering engines -- is dominated by the [Jinja](https://jinja.palletsprojects.com) templating engine, which is a safe choice as it has been and will be around for a long time. The main drawbacks with Jinja are the lack of good IDE support, the complete lack of static code analysis support, and the (subjectively) ugly syntax.
|
|
293
|
+
|
|
294
|
+
Then there are tools that aim for the middleground, usually by providing most of the benefits and drawbacks of complete application frameworks while leaving state management, client-server communication, and dynamic UI updates for the user to solve, often with some level of [HTMX](https://htmx.org/) support. This group includes libraries like [FastHTML](https://github.com/answerdotai/fasthtml) and [Ludic](https://github.com/getludic/ludic).
|
|
295
|
+
|
|
296
|
+
The primary aim of `htmy` is to be an **async**, pure-Python rendering engine, which is as **simple**, **maintainable**, and **customizable** as possible, while still providing all the building blocks for (conveniently) creating complex and maintainable applications.
|
|
297
|
+
|
|
298
|
+
## Dependencies
|
|
299
|
+
|
|
300
|
+
The library has **no dependencies**.
|
|
301
|
+
|
|
302
|
+
## Development
|
|
303
|
+
|
|
304
|
+
Use `ruff` for linting and formatting, `mypy` for static code analysis, and `pytest` for testing.
|
|
305
|
+
|
|
306
|
+
The documentation is built with `mkdocs-material` and `mkdocstrings`.
|
|
307
|
+
|
|
308
|
+
## Contributing
|
|
309
|
+
|
|
310
|
+
All contributions are welcome, including more documentation, examples, code, and tests. Even questions.
|
|
311
|
+
|
|
312
|
+
## License - MIT
|
|
313
|
+
|
|
314
|
+
The package is open-sourced under the conditions of the [MIT license](https://choosealicense.com/licenses/mit/).
|
|
315
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
htmy/__init__.py,sha256=EiVFNXpgdN5jeb0l2zH2u2Fl33i_dsvoXu6q7GLFLJw,1718
|
|
2
|
+
htmy/core.py,sha256=zguaJ9zC2nEt_AURnTMJKFlpBvnpRlDpp86PlgGOW_8,15586
|
|
3
|
+
htmy/html.py,sha256=ShXj5-kPA26ZikIhvom1R4auv3TGvTbDnZolLT-TYs4,20936
|
|
4
|
+
htmy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
htmy/renderer.py,sha256=nGHbAmPqoC0VRku3HtakaiQr5_HkhwLuCAxgjy-aZoI,3539
|
|
6
|
+
htmy/typing.py,sha256=neCEmfzlvPjlfOE2Dj5jHujz8c_70O-hzwTae2s7aAo,2448
|
|
7
|
+
htmy/utils.py,sha256=7_CyA39l2m6jzDqparPKkKgRB2wiGuBZXbiPgiZOXKA,1093
|
|
8
|
+
htmy-0.1.0.dist-info/LICENSE,sha256=rFtoGU_3c_rlacXgOZapTHfMErN-JFPT5Bq_col4bqI,1067
|
|
9
|
+
htmy-0.1.0.dist-info/METADATA,sha256=IVMzWa9d21GdO48UYOgcz3fvZCee0z3Es1f3JwT8DYU,15299
|
|
10
|
+
htmy-0.1.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
|
11
|
+
htmy-0.1.0.dist-info/RECORD,,
|