htmy 0.4.1__py3-none-any.whl → 0.5.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 +5 -2
- htmy/core.py +11 -65
- htmy/md/core.py +18 -4
- htmy/renderer/default.py +2 -1
- htmy/snippet.py +259 -0
- htmy/typing.py +19 -7
- htmy/utils.py +21 -2
- {htmy-0.4.1.dist-info → htmy-0.5.0.dist-info}/METADATA +4 -3
- htmy-0.5.0.dist-info/RECORD +20 -0
- {htmy-0.4.1.dist-info → htmy-0.5.0.dist-info}/WHEEL +1 -1
- htmy-0.4.1.dist-info/RECORD +0 -19
- {htmy-0.4.1.dist-info → htmy-0.5.0.dist-info}/LICENSE +0 -0
htmy/__init__.py
CHANGED
|
@@ -5,7 +5,6 @@ from .core import Formatter as Formatter
|
|
|
5
5
|
from .core import Fragment as Fragment
|
|
6
6
|
from .core import SafeStr as SafeStr
|
|
7
7
|
from .core import SkipProperty as SkipProperty
|
|
8
|
-
from .core import Snippet as Snippet
|
|
9
8
|
from .core import Tag as Tag
|
|
10
9
|
from .core import TagConfig as TagConfig
|
|
11
10
|
from .core import TagWithProps as TagWithProps
|
|
@@ -16,6 +15,8 @@ from .core import XBool as XBool
|
|
|
16
15
|
from .core import component as component
|
|
17
16
|
from .core import xml_format_string as xml_format_string
|
|
18
17
|
from .renderer import Renderer as Renderer
|
|
18
|
+
from .snippet import Slots as Slots
|
|
19
|
+
from .snippet import Snippet as Snippet
|
|
19
20
|
from .typing import AsyncComponent as AsyncComponent
|
|
20
21
|
from .typing import AsyncContextProvider as AsyncContextProvider
|
|
21
22
|
from .typing import AsyncFunctionComponent as AsyncFunctionComponent
|
|
@@ -34,7 +35,9 @@ from .typing import PropertyValue as PropertyValue
|
|
|
34
35
|
from .typing import SyncComponent as SyncComponent
|
|
35
36
|
from .typing import SyncContextProvider as SyncContextProvider
|
|
36
37
|
from .typing import SyncFunctionComponent as SyncFunctionComponent
|
|
37
|
-
from .
|
|
38
|
+
from .utils import as_component_sequence as as_component_sequence
|
|
39
|
+
from .utils import as_component_type as as_component_type
|
|
40
|
+
from .utils import is_component_sequence as is_component_sequence
|
|
38
41
|
from .utils import join_components as join_components
|
|
39
42
|
|
|
40
43
|
HTMY = Renderer
|
htmy/core.py
CHANGED
|
@@ -3,13 +3,11 @@ from __future__ import annotations
|
|
|
3
3
|
import abc
|
|
4
4
|
import asyncio
|
|
5
5
|
import enum
|
|
6
|
-
from collections.abc import
|
|
7
|
-
from pathlib import Path
|
|
6
|
+
from collections.abc import Callable, Container
|
|
8
7
|
from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypedDict, cast, overload
|
|
9
8
|
from xml.sax.saxutils import escape as xml_escape
|
|
10
9
|
from xml.sax.saxutils import quoteattr as xml_quoteattr
|
|
11
10
|
|
|
12
|
-
from .io import open_file
|
|
13
11
|
from .typing import (
|
|
14
12
|
AsyncFunctionComponent,
|
|
15
13
|
Component,
|
|
@@ -21,14 +19,13 @@ from .typing import (
|
|
|
21
19
|
PropertyValue,
|
|
22
20
|
SyncFunctionComponent,
|
|
23
21
|
T,
|
|
24
|
-
TextProcessor,
|
|
25
|
-
is_component_sequence,
|
|
26
22
|
)
|
|
27
|
-
from .utils import join_components
|
|
23
|
+
from .utils import as_component_type, join_components
|
|
28
24
|
|
|
29
25
|
if TYPE_CHECKING:
|
|
30
|
-
from typing_extensions import Self
|
|
26
|
+
from typing_extensions import Never, Self
|
|
31
27
|
else:
|
|
28
|
+
Never = Any
|
|
32
29
|
Self = Any
|
|
33
30
|
|
|
34
31
|
# -- Utility components
|
|
@@ -96,11 +93,7 @@ class ErrorBoundary(Fragment):
|
|
|
96
93
|
if not (self._errors is None or any(e in self._errors for e in type(error).mro())):
|
|
97
94
|
raise error
|
|
98
95
|
|
|
99
|
-
return (
|
|
100
|
-
Fragment(*self._fallback)
|
|
101
|
-
if is_component_sequence(self._fallback)
|
|
102
|
-
else cast(ComponentType, self._fallback)
|
|
103
|
-
)
|
|
96
|
+
return as_component_type(self._fallback)
|
|
104
97
|
|
|
105
98
|
|
|
106
99
|
class WithContext(Fragment):
|
|
@@ -126,59 +119,6 @@ class WithContext(Fragment):
|
|
|
126
119
|
return self._context
|
|
127
120
|
|
|
128
121
|
|
|
129
|
-
class Snippet:
|
|
130
|
-
"""
|
|
131
|
-
Base component that can load its content from a file.
|
|
132
|
-
"""
|
|
133
|
-
|
|
134
|
-
__slots__ = ("_path_or_text", "_text_processor")
|
|
135
|
-
|
|
136
|
-
def __init__(
|
|
137
|
-
self,
|
|
138
|
-
path_or_text: Text | str | Path,
|
|
139
|
-
*,
|
|
140
|
-
text_processor: TextProcessor | None = None,
|
|
141
|
-
) -> None:
|
|
142
|
-
"""
|
|
143
|
-
Initialization.
|
|
144
|
-
|
|
145
|
-
Arguments:
|
|
146
|
-
path_or_text: The path from where the content should be loaded or a `Text`
|
|
147
|
-
instance if this value should be rendered directly.
|
|
148
|
-
text_processor: An optional text processors that can be used to process the text
|
|
149
|
-
content before rendering. It can be used for example for token replacement or
|
|
150
|
-
string formatting.
|
|
151
|
-
"""
|
|
152
|
-
self._path_or_text = path_or_text
|
|
153
|
-
self._text_processor = text_processor
|
|
154
|
-
|
|
155
|
-
async def htmy(self, context: Context) -> Component:
|
|
156
|
-
"""Renders the component."""
|
|
157
|
-
text = await self._get_text_content()
|
|
158
|
-
if self._text_processor is not None:
|
|
159
|
-
processed = self._text_processor(text, context)
|
|
160
|
-
text = (await processed) if isinstance(processed, Awaitable) else processed
|
|
161
|
-
|
|
162
|
-
return self._render_text(text, context)
|
|
163
|
-
|
|
164
|
-
async def _get_text_content(self) -> str:
|
|
165
|
-
"""Returns the plain text content that should be rendered."""
|
|
166
|
-
path_or_text = self._path_or_text
|
|
167
|
-
|
|
168
|
-
if isinstance(path_or_text, Text):
|
|
169
|
-
return path_or_text
|
|
170
|
-
else:
|
|
171
|
-
async with await open_file(path_or_text, "r") as f:
|
|
172
|
-
return await f.read()
|
|
173
|
-
|
|
174
|
-
def _render_text(self, text: str, context: Context) -> Component:
|
|
175
|
-
"""
|
|
176
|
-
Render function that takes the text that must be rendered and the current rendering context,
|
|
177
|
-
and returns the corresponding component.
|
|
178
|
-
"""
|
|
179
|
-
return SafeStr(text)
|
|
180
|
-
|
|
181
|
-
|
|
182
122
|
# -- Context utilities
|
|
183
123
|
|
|
184
124
|
|
|
@@ -348,6 +288,11 @@ class SkipProperty(Exception):
|
|
|
348
288
|
|
|
349
289
|
...
|
|
350
290
|
|
|
291
|
+
@classmethod
|
|
292
|
+
def format_property(cls, _: Any) -> Never:
|
|
293
|
+
"""Property formatter that raises a `SkipProperty` error regardless of the received value."""
|
|
294
|
+
raise cls("skip-property")
|
|
295
|
+
|
|
351
296
|
|
|
352
297
|
class Text(str):
|
|
353
298
|
"""Marker class for differentiating text content from other strings."""
|
|
@@ -484,6 +429,7 @@ class Formatter(ContextAware):
|
|
|
484
429
|
date: lambda d: cast(date, d).isoformat(),
|
|
485
430
|
datetime: lambda d: cast(datetime, d).isoformat(),
|
|
486
431
|
XBool: lambda v: cast(XBool, v).format(),
|
|
432
|
+
type(None): SkipProperty.format_property,
|
|
487
433
|
}
|
|
488
434
|
|
|
489
435
|
|
htmy/md/core.py
CHANGED
|
@@ -4,8 +4,9 @@ from typing import TYPE_CHECKING, ClassVar
|
|
|
4
4
|
|
|
5
5
|
from markdown import Markdown
|
|
6
6
|
|
|
7
|
-
from htmy.core import ContextAware, SafeStr,
|
|
8
|
-
from htmy.
|
|
7
|
+
from htmy.core import ContextAware, SafeStr, Text
|
|
8
|
+
from htmy.snippet import Snippet
|
|
9
|
+
from htmy.typing import TextProcessor, TextResolver
|
|
9
10
|
|
|
10
11
|
if TYPE_CHECKING:
|
|
11
12
|
from collections.abc import Callable
|
|
@@ -78,7 +79,17 @@ class MarkdownParser(ContextAware):
|
|
|
78
79
|
|
|
79
80
|
|
|
80
81
|
class MD(Snippet):
|
|
81
|
-
"""
|
|
82
|
+
"""
|
|
83
|
+
Component for reading, customizing, and rendering markdown documents.
|
|
84
|
+
|
|
85
|
+
It supports all the processing utilities of `Snippet`, including `text_resolver` and
|
|
86
|
+
`text_processor` for formatting, token replacement, and slot conversion to components.
|
|
87
|
+
|
|
88
|
+
One note regaring slot convesion (`text_resolver`): it is executed before markdown parsing,
|
|
89
|
+
and all string segments of the resulting component sequence are parsed individually by the
|
|
90
|
+
markdown parser. As a consequence, you should only use slots in places where the preceding
|
|
91
|
+
and following texts individually result in valid markdown.
|
|
92
|
+
"""
|
|
82
93
|
|
|
83
94
|
__slots__ = (
|
|
84
95
|
"_converter",
|
|
@@ -88,6 +99,7 @@ class MD(Snippet):
|
|
|
88
99
|
def __init__(
|
|
89
100
|
self,
|
|
90
101
|
path_or_text: Text | str | Path,
|
|
102
|
+
text_resolver: TextResolver | None = None,
|
|
91
103
|
*,
|
|
92
104
|
converter: Callable[[str], Component] | None = None,
|
|
93
105
|
renderer: MarkdownRenderFunction | None = None,
|
|
@@ -98,6 +110,8 @@ class MD(Snippet):
|
|
|
98
110
|
|
|
99
111
|
Arguments:
|
|
100
112
|
path_or_text: The path where the markdown file is located or a markdown `Text`.
|
|
113
|
+
text_resolver: An optional `TextResolver` (e.g. `Slots`) that converts the processed
|
|
114
|
+
text into a component.
|
|
101
115
|
converter: Function that converts an HTML string (the parsed and processed markdown text)
|
|
102
116
|
into a component.
|
|
103
117
|
renderer: Function that gets the parsed and converted content and the metadata (if it exists)
|
|
@@ -106,7 +120,7 @@ class MD(Snippet):
|
|
|
106
120
|
content before rendering. It can be used for example for token replacement or
|
|
107
121
|
string formatting.
|
|
108
122
|
"""
|
|
109
|
-
super().__init__(path_or_text, text_processor=text_processor)
|
|
123
|
+
super().__init__(path_or_text, text_resolver, text_processor=text_processor)
|
|
110
124
|
self._converter: Callable[[str], Component] = SafeStr if converter is None else converter
|
|
111
125
|
self._renderer = renderer
|
|
112
126
|
|
htmy/renderer/default.py
CHANGED
|
@@ -6,7 +6,8 @@ from collections.abc import Awaitable, Callable, Iterator
|
|
|
6
6
|
from typing import TypeAlias
|
|
7
7
|
|
|
8
8
|
from htmy.core import ErrorBoundary, xml_format_string
|
|
9
|
-
from htmy.typing import Component, ComponentType, Context, ContextProvider
|
|
9
|
+
from htmy.typing import Component, ComponentType, Context, ContextProvider
|
|
10
|
+
from htmy.utils import is_component_sequence
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
class _Node:
|
htmy/snippet.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Awaitable, Iterator, Mapping
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from .core import SafeStr, Text
|
|
6
|
+
from .io import open_file
|
|
7
|
+
from .typing import (
|
|
8
|
+
Component,
|
|
9
|
+
ComponentType,
|
|
10
|
+
Context,
|
|
11
|
+
TextProcessor,
|
|
12
|
+
TextResolver,
|
|
13
|
+
)
|
|
14
|
+
from .utils import as_component_sequence, as_component_type, is_component_sequence
|
|
15
|
+
|
|
16
|
+
# -- Components and utilities
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Slots:
|
|
20
|
+
"""
|
|
21
|
+
Utility that resolves slots in a string input to components.
|
|
22
|
+
|
|
23
|
+
More technically, it splits a string into slot and non-slot parts, replaces the
|
|
24
|
+
slot parts with the corresponding components (which may be component sequences)
|
|
25
|
+
from the given slot mapping, and returns the resulting component sequence.
|
|
26
|
+
|
|
27
|
+
The default slot placeholder is a standard XML/HTML comment of the following form:
|
|
28
|
+
`<!-- slot[slot-key] -->`. Any number of whitespaces (including 0) are allowed in
|
|
29
|
+
the placeholder, but the slot key must not contain any whitespaces. For details, see
|
|
30
|
+
`Slots.slot_re`.
|
|
31
|
+
|
|
32
|
+
Besides the pre-defined regular expressions in `Slots.slot_re`, any other regular
|
|
33
|
+
expression can be used to identify slots as long as it meets the requirements described
|
|
34
|
+
in `Slots.slots_re`.
|
|
35
|
+
|
|
36
|
+
Implements: `htmy.typing.TextResolver`
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
__slots__ = ("_slot_mapping", "_slot_re", "_not_found")
|
|
40
|
+
|
|
41
|
+
class slot_re:
|
|
42
|
+
"""
|
|
43
|
+
Slot regular expressions.
|
|
44
|
+
|
|
45
|
+
Requirements:
|
|
46
|
+
|
|
47
|
+
- The regular expression must have exactly one capturing group that captures the slot key.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
square_bracket = re.compile(r"<!-- *slot *\[ *([^[ ]+) *\] *-->")
|
|
51
|
+
"""
|
|
52
|
+
Slot regular expression that matches slots defined as follows: `<!-- slot[slot-key] -->`.
|
|
53
|
+
|
|
54
|
+
The slot key must not contain any whitespaces and there must not be any additional text
|
|
55
|
+
in the XML/HTML comment. Any number of whitespaces (including 0) are allowed around the
|
|
56
|
+
parts of the slot placeholder.
|
|
57
|
+
"""
|
|
58
|
+
parentheses = re.compile(r"<!-- *slot *\( *([^( ]+) *\) *-->")
|
|
59
|
+
"""
|
|
60
|
+
Slot regular expression that matches slots defined as follows: `<!-- slot(slot-key) -->`.
|
|
61
|
+
|
|
62
|
+
The slot key must not contain any whitespaces and there must not be any additional text
|
|
63
|
+
in the XML/HTML comment. Any number of whitespaces (including 0) are allowed around the
|
|
64
|
+
parts of the slot placeholder.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
# There are no defaults for angle bracket and curly braces, because
|
|
68
|
+
# they may conflict with HTML and format strings.
|
|
69
|
+
|
|
70
|
+
default = square_bracket
|
|
71
|
+
"""
|
|
72
|
+
The default slot regular expression. Same as `Slots.slot_re.square_bracket`.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
slot_mapping: Mapping[str, Component],
|
|
78
|
+
*,
|
|
79
|
+
slot_re: re.Pattern[str] = slot_re.default,
|
|
80
|
+
not_found: Component | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
"""
|
|
83
|
+
Initialization.
|
|
84
|
+
|
|
85
|
+
Slot regular expressions are used to find slot keys in strings, which are then replaced
|
|
86
|
+
with the corresponding component from the slot mapping. `slot_re` must have exactly one
|
|
87
|
+
capturing group that captures the slot key. `Slots.slot_re` contains some predefined slot
|
|
88
|
+
regular expressions, but any other regular expression can be used as long as it matches
|
|
89
|
+
the capturing group requirement above.
|
|
90
|
+
|
|
91
|
+
Arguments:
|
|
92
|
+
slot_mapping: Slot mapping the maps slot keys to the corresponding component.
|
|
93
|
+
slot_re: The slot regular expression that is used to find slot keys in strings.
|
|
94
|
+
not_found: The component that is used to replace slot keys that are not found in
|
|
95
|
+
`slot_mapping`. If `None` and the slot key is not found in `slot_mapping`,
|
|
96
|
+
then a `KeyError` will be raised by `resolve()`.
|
|
97
|
+
"""
|
|
98
|
+
self._slot_mapping = slot_mapping
|
|
99
|
+
self._slot_re = slot_re
|
|
100
|
+
self._not_found = not_found
|
|
101
|
+
|
|
102
|
+
def resolve_text(self, text: str) -> Component:
|
|
103
|
+
"""
|
|
104
|
+
Resolves the given string into components using the instance's slot regular expression
|
|
105
|
+
and slot mapping.
|
|
106
|
+
|
|
107
|
+
Arguments:
|
|
108
|
+
text: The text to resolve.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
The component sequence the text resolves to.
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
KeyError: If a slot key is not found in the slot mapping and `not_found` is `None`.
|
|
115
|
+
"""
|
|
116
|
+
return tuple(self._resolve_text(text))
|
|
117
|
+
|
|
118
|
+
def _resolve_text(self, text: str) -> Iterator[ComponentType]:
|
|
119
|
+
"""
|
|
120
|
+
Generator that yields the slot and non-slot parts of the given string in order.
|
|
121
|
+
|
|
122
|
+
Arguments:
|
|
123
|
+
text: The text to resolve.
|
|
124
|
+
|
|
125
|
+
Yields:
|
|
126
|
+
The slot and non-slot parts of the given string.
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
KeyError: If a slot key is not found in the slot mapping and `not_found` is `None`.
|
|
130
|
+
"""
|
|
131
|
+
is_slot = False
|
|
132
|
+
# The implementation requires that the slot regular expression has exactly one capturing group.
|
|
133
|
+
for part in self._slot_re.split(text):
|
|
134
|
+
if is_slot:
|
|
135
|
+
resolved = self._slot_mapping.get(part, self._not_found)
|
|
136
|
+
if resolved is None:
|
|
137
|
+
raise KeyError(f"Component not found for slot: {part}")
|
|
138
|
+
|
|
139
|
+
if is_component_sequence(resolved):
|
|
140
|
+
yield from resolved
|
|
141
|
+
else:
|
|
142
|
+
# mypy complains that resolved may be a sequence, but that's not the case.
|
|
143
|
+
yield resolved # type: ignore[misc]
|
|
144
|
+
else:
|
|
145
|
+
yield part
|
|
146
|
+
|
|
147
|
+
is_slot = not is_slot
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Snippet:
|
|
151
|
+
"""
|
|
152
|
+
Component that renders text, which may be asynchronously loaded from a file.
|
|
153
|
+
|
|
154
|
+
The entire snippet processing pipeline consists of the following steps:
|
|
155
|
+
|
|
156
|
+
1. The text content is loaded from a file or passed directly as a `Text` instance.
|
|
157
|
+
2. The text content is processed by a `TextProcessor` if provided.
|
|
158
|
+
3. The processed text is converted into a component (may be component sequence)
|
|
159
|
+
by a `TextResolver`, for example `Slots`.
|
|
160
|
+
4. Every `str` children (produced by the steps above) is converted into a `SafeStr` for
|
|
161
|
+
rendering.
|
|
162
|
+
|
|
163
|
+
The pipeline above is a bit abstract, so here are some usage notes:
|
|
164
|
+
|
|
165
|
+
- The text content of a snippet can be a Python format string template, in which case the
|
|
166
|
+
`TextProcessor` can be a simple method that calls `str.format()` with the correct arguments.
|
|
167
|
+
- Alternatively, a text processor can also be used to get only a substring -- commonly referred
|
|
168
|
+
to as fragment in frameworks like Jinja -- of the original text.
|
|
169
|
+
- The text processor is applied before the text resolver, which makes it possible to insert
|
|
170
|
+
placeholders into the text (for example slots, like in this case:
|
|
171
|
+
`..."{toolbar}...".format(toolbar="<!-- slot[toolbar] -->")`) that are then replaced with any
|
|
172
|
+
`htmy.Component` by the `TextResolver` (for example `Slots`).
|
|
173
|
+
- `TextResolver` can return plain `str` values, it is not necessary for it to convert strings
|
|
174
|
+
to `SafeStr` to prevent unwanted escaping.
|
|
175
|
+
|
|
176
|
+
Example:
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
from datetime import date
|
|
180
|
+
from htmy import Snippet, Slots
|
|
181
|
+
|
|
182
|
+
def text_processor(text: str, context: Context) -> str:
|
|
183
|
+
return text.format(today=date.today())
|
|
184
|
+
|
|
185
|
+
snippet = Snippet(
|
|
186
|
+
"my-page.html",
|
|
187
|
+
text_processor=text_processor,
|
|
188
|
+
text_resolver=Slots(
|
|
189
|
+
{
|
|
190
|
+
"date-picker": MyDatePicker(class_="text-primary"),
|
|
191
|
+
"Toolbar": MyPageToolbar(active_page="home"),
|
|
192
|
+
...
|
|
193
|
+
}
|
|
194
|
+
),
|
|
195
|
+
)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
In the above example, if `my-page.html` contains a `{today}` placeholder, it will be replaced
|
|
199
|
+
with the current date. If it contains a `<!-- slot[toolbar] -->}` slot, then the `MyPageToolbar`
|
|
200
|
+
`htmy` component instance will be rendered in its place, and the `<!-- slot[date-picker] -->` slot
|
|
201
|
+
will be replaced with the `MyDatePicker` component instance.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
__slots__ = ("_path_or_text", "_text_processor", "_text_resolver")
|
|
205
|
+
|
|
206
|
+
def __init__(
|
|
207
|
+
self,
|
|
208
|
+
path_or_text: Text | str | Path,
|
|
209
|
+
text_resolver: TextResolver | None = None,
|
|
210
|
+
*,
|
|
211
|
+
text_processor: TextProcessor | None = None,
|
|
212
|
+
) -> None:
|
|
213
|
+
"""
|
|
214
|
+
Initialization.
|
|
215
|
+
|
|
216
|
+
Arguments:
|
|
217
|
+
path_or_text: The path from where the content should be loaded or a `Text`
|
|
218
|
+
instance if this value should be rendered directly.
|
|
219
|
+
text_resolver: An optional `TextResolver` (e.g. `Slots`) that converts the processed
|
|
220
|
+
text into a component. If not provided, the text will be rendered as a `SafeStr`.
|
|
221
|
+
text_processor: An optional `TextProcessor` that can be used to process the text
|
|
222
|
+
content before rendering. It can be used for example for token replacement or
|
|
223
|
+
string formatting.
|
|
224
|
+
"""
|
|
225
|
+
self._path_or_text = path_or_text
|
|
226
|
+
self._text_processor = text_processor
|
|
227
|
+
self._text_resolver = text_resolver
|
|
228
|
+
|
|
229
|
+
async def htmy(self, context: Context) -> Component:
|
|
230
|
+
"""Renders the component."""
|
|
231
|
+
text = await self._get_text_content()
|
|
232
|
+
if self._text_processor is not None:
|
|
233
|
+
processed = self._text_processor(text, context)
|
|
234
|
+
text = (await processed) if isinstance(processed, Awaitable) else processed
|
|
235
|
+
|
|
236
|
+
if self._text_resolver is None:
|
|
237
|
+
return self._render_text(text, context)
|
|
238
|
+
|
|
239
|
+
comps = as_component_sequence(self._text_resolver.resolve_text(text))
|
|
240
|
+
return tuple(
|
|
241
|
+
as_component_type(self._render_text(c, context)) if isinstance(c, str) else c for c in comps
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
async def _get_text_content(self) -> str:
|
|
245
|
+
"""Returns the plain text content that should be rendered."""
|
|
246
|
+
path_or_text = self._path_or_text
|
|
247
|
+
|
|
248
|
+
if isinstance(path_or_text, Text):
|
|
249
|
+
return path_or_text
|
|
250
|
+
else:
|
|
251
|
+
async with await open_file(path_or_text, "r") as f:
|
|
252
|
+
return await f.read()
|
|
253
|
+
|
|
254
|
+
def _render_text(self, text: str, context: Context) -> Component:
|
|
255
|
+
"""
|
|
256
|
+
Render function that takes the text that must be rendered and the current rendering context,
|
|
257
|
+
and returns the corresponding component.
|
|
258
|
+
"""
|
|
259
|
+
return SafeStr(text)
|
htmy/typing.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
from collections.abc import Callable, Coroutine, Mapping, MutableMapping
|
|
2
|
-
from typing import Any, Protocol, TypeAlias,
|
|
2
|
+
from typing import Any, Protocol, TypeAlias, TypeVar, runtime_checkable
|
|
3
3
|
|
|
4
4
|
T = TypeVar("T")
|
|
5
5
|
U = TypeVar("U")
|
|
@@ -66,11 +66,6 @@ Component: TypeAlias = ComponentType | ComponentSequence
|
|
|
66
66
|
"""Component type: a single component or a sequence of components."""
|
|
67
67
|
|
|
68
68
|
|
|
69
|
-
def is_component_sequence(obj: Any) -> TypeGuard[ComponentSequence]:
|
|
70
|
-
"""Returns whether the given object is a component sequence."""
|
|
71
|
-
return isinstance(obj, (list, tuple))
|
|
72
|
-
|
|
73
|
-
|
|
74
69
|
SyncFunctionComponent: TypeAlias = Callable[[T, Context], Component]
|
|
75
70
|
"""Protocol definition for sync function components."""
|
|
76
71
|
|
|
@@ -104,8 +99,25 @@ class AsyncContextProvider(Protocol):
|
|
|
104
99
|
ContextProvider: TypeAlias = SyncContextProvider | AsyncContextProvider
|
|
105
100
|
"""Context provider type."""
|
|
106
101
|
|
|
107
|
-
|
|
108
102
|
# -- Text processors
|
|
109
103
|
|
|
110
104
|
TextProcessor: TypeAlias = Callable[[str, Context], str | Coroutine[Any, Any, str]]
|
|
111
105
|
"""Callable type that expects a string and a context, and returns a processed string."""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class TextResolver(Protocol):
|
|
109
|
+
"""
|
|
110
|
+
Protocol definition for resolvers that convert a string to a component.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def resolve_text(self, text: str) -> Component:
|
|
114
|
+
"""
|
|
115
|
+
Returns the resolved component for the given text.
|
|
116
|
+
|
|
117
|
+
Arguments:
|
|
118
|
+
text: The text to resolve.
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
KeyError: If the text cannot be resolved to a component.
|
|
122
|
+
"""
|
|
123
|
+
...
|
htmy/utils.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
from collections.abc import Generator
|
|
4
|
-
from typing import TYPE_CHECKING
|
|
4
|
+
from typing import TYPE_CHECKING, TypeGuard
|
|
5
5
|
|
|
6
6
|
if TYPE_CHECKING:
|
|
7
|
-
from .typing import ComponentSequence, ComponentType
|
|
7
|
+
from .typing import Component, ComponentSequence, ComponentType
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def join_components(
|
|
@@ -42,3 +42,22 @@ def join(*items: str | None, separator: str = " ") -> str:
|
|
|
42
42
|
Joins the given strings with the given separator, skipping `None` values.
|
|
43
43
|
"""
|
|
44
44
|
return separator.join(i for i in items if i)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_component_sequence(comp: Component) -> TypeGuard[ComponentSequence]:
|
|
48
|
+
"""Returns whether the given component is a component sequence."""
|
|
49
|
+
return isinstance(comp, (list, tuple))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def as_component_sequence(comp: Component) -> ComponentSequence:
|
|
53
|
+
"""Returns the given component as a component sequence."""
|
|
54
|
+
# mypy doesn't understand the `is_component_sequence` type guard.
|
|
55
|
+
return comp if is_component_sequence(comp) else (comp,) # type: ignore[return-value]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def as_component_type(comp: Component) -> ComponentType:
|
|
59
|
+
"""Returns the given component as a `ComponentType` (not sequence)."""
|
|
60
|
+
from .core import Fragment
|
|
61
|
+
|
|
62
|
+
# mypy doesn't understand the `is_component_sequence` type guard.
|
|
63
|
+
return comp if not is_component_sequence(comp) else Fragment(*comp) # type: ignore[return-value]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
2
|
Name: htmy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Async, pure-Python rendering engine.
|
|
5
5
|
License: MIT
|
|
6
6
|
Author: Peter Volf
|
|
@@ -36,6 +36,7 @@ Description-Content-Type: text/markdown
|
|
|
36
36
|
- **Powerful**, React-like **context support**, so you can avoid prop-drilling.
|
|
37
37
|
- Sync and async **function components** with **decorator syntax**.
|
|
38
38
|
- All baseline **HTML** tags built-in.
|
|
39
|
+
- Support for **native HTML/XML** documents with dynamic formatting and **slot rendering**.
|
|
39
40
|
- **Markdown** support with tools for customization.
|
|
40
41
|
- Async, JSON based **internationalization**.
|
|
41
42
|
- Built-in, easy to use `ErrorBoundary` component for graceful error handling.
|
|
@@ -161,11 +162,11 @@ user_table = html.table(
|
|
|
161
162
|
`htmy` has a rich set of built-in utilities and components for both HTML and other use-cases:
|
|
162
163
|
|
|
163
164
|
- `html` module: a complete set of [baseline HTML tags](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility).
|
|
165
|
+
- `Snippet` and `Slots`: utilities for creating dynamic, customizable document snippets in their native file format (HTML, XML, Markdown, etc.), with slot rendering support.
|
|
164
166
|
- `md`: `MarkdownParser` utility and `MD` component for loading, parsing, converting, and rendering markdown content.
|
|
165
167
|
- `i18n`: utilities for async, JSON based internationalization.
|
|
166
168
|
- `BaseTag`, `TagWithProps`, `Tag`, `WildcardTag`: base classes for custom XML tags.
|
|
167
169
|
- `ErrorBoundary`, `Fragment`, `SafeStr`, `WithContext`: utilities for error handling, component wrappers, context providers, and formatting.
|
|
168
|
-
- `Snippet`: utility class for loading and customizing document snippets from the file system.
|
|
169
170
|
- `etree.ETreeConverter`: utility that converts XML to a component tree with support for custom HTMY components.
|
|
170
171
|
|
|
171
172
|
### Rendering
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
htmy/__init__.py,sha256=dg1PFP21pFiWdM7eCpZiBCRHcNO4NJMT92FFqBi54Ig,2061
|
|
2
|
+
htmy/core.py,sha256=5cqcxXRJGEsLrxyvoadfhcJEex2Vys-sJ6CpLbbmHQ4,17551
|
|
3
|
+
htmy/etree.py,sha256=yKxom__AdsJY-Q1kbU0sdTMr0ZF5dMSVBKxayntNFyQ,3062
|
|
4
|
+
htmy/html.py,sha256=7UohfPRtl-3IoSbOiDxazsSHQpCZ0tyRdNayQISPM8A,21086
|
|
5
|
+
htmy/i18n.py,sha256=brNazQjObBFfbnViZCpcnxa0qgxQbJfX7xJAH-MqTW8,5124
|
|
6
|
+
htmy/io.py,sha256=iebJOZp7L0kZ9SWdqMatKtW5VGRIkEd-eD0_vTAldH8,41
|
|
7
|
+
htmy/md/__init__.py,sha256=lxBJnYplkDuxYuiese6My9KYp1DeGdzo70iUdYTvMnE,334
|
|
8
|
+
htmy/md/core.py,sha256=Xu-8xGAOGqSYLGPOib0Wn-blmyQBHl3MrAOza_w__Y8,4456
|
|
9
|
+
htmy/md/typing.py,sha256=LF-AEvo7FCW2KumyR5l55rsXizV2E4AHVLKFf6lApgM,762
|
|
10
|
+
htmy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
htmy/renderer/__init__.py,sha256=xnP_aaoK-pTok-69wi8O_xlsgjoKTzWd2lIIeHGcuaY,226
|
|
12
|
+
htmy/renderer/baseline.py,sha256=hHb7CoQhFFdD7Sdw0ltR1-XLGwE9pqmfL5yKFeF2rCg,4288
|
|
13
|
+
htmy/renderer/default.py,sha256=lVMGuRybpFZ0u7pMB3IGOsFxw_rY8KqFQzWcNlmKCVI,10789
|
|
14
|
+
htmy/snippet.py,sha256=dkHEOuULGsgawIMnSz99hghvNu8pLVGAQMQSlrn9ibY,10260
|
|
15
|
+
htmy/typing.py,sha256=UE6tSMi-NyDazH4GKARx8dMxRFc6sSDIpLA5TSn0T7I,3346
|
|
16
|
+
htmy/utils.py,sha256=Kp0j9G8CBeRiyFGmz-CoDiLtXHfpvHzlTVsWeDhIebM,1935
|
|
17
|
+
htmy-0.5.0.dist-info/LICENSE,sha256=rFtoGU_3c_rlacXgOZapTHfMErN-JFPT5Bq_col4bqI,1067
|
|
18
|
+
htmy-0.5.0.dist-info/METADATA,sha256=yA1X4Tp13Z5GcgyvDNwhTH8AoN93NX0KETLHYsIr1Gw,16550
|
|
19
|
+
htmy-0.5.0.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
|
|
20
|
+
htmy-0.5.0.dist-info/RECORD,,
|
htmy-0.4.1.dist-info/RECORD
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
htmy/__init__.py,sha256=yMPXQHkXQCjyx7UUVcfsMQ_5YjvNT62Kb9TI1xEcw2A,1899
|
|
2
|
-
htmy/core.py,sha256=5V019PwIes9Eyzu0eWwsvBZNZ6x7DhQy9y99myCw9A0,19322
|
|
3
|
-
htmy/etree.py,sha256=yKxom__AdsJY-Q1kbU0sdTMr0ZF5dMSVBKxayntNFyQ,3062
|
|
4
|
-
htmy/html.py,sha256=7UohfPRtl-3IoSbOiDxazsSHQpCZ0tyRdNayQISPM8A,21086
|
|
5
|
-
htmy/i18n.py,sha256=brNazQjObBFfbnViZCpcnxa0qgxQbJfX7xJAH-MqTW8,5124
|
|
6
|
-
htmy/io.py,sha256=iebJOZp7L0kZ9SWdqMatKtW5VGRIkEd-eD0_vTAldH8,41
|
|
7
|
-
htmy/md/__init__.py,sha256=lxBJnYplkDuxYuiese6My9KYp1DeGdzo70iUdYTvMnE,334
|
|
8
|
-
htmy/md/core.py,sha256=EK-QoB2BIra3o1nvTK0lGP3mQQPtRXuE6zBKF_IWR_o,3675
|
|
9
|
-
htmy/md/typing.py,sha256=LF-AEvo7FCW2KumyR5l55rsXizV2E4AHVLKFf6lApgM,762
|
|
10
|
-
htmy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
-
htmy/renderer/__init__.py,sha256=xnP_aaoK-pTok-69wi8O_xlsgjoKTzWd2lIIeHGcuaY,226
|
|
12
|
-
htmy/renderer/baseline.py,sha256=hHb7CoQhFFdD7Sdw0ltR1-XLGwE9pqmfL5yKFeF2rCg,4288
|
|
13
|
-
htmy/renderer/default.py,sha256=rdx-yFYz-cz197xfe9co8Lru2cdZxAjOO4dqY250Y1Q,10767
|
|
14
|
-
htmy/typing.py,sha256=f4QZ8vQL7JfN402yDb8Hq_DYvQS_GUgdXK8-xTBM8y8,3122
|
|
15
|
-
htmy/utils.py,sha256=7_CyA39l2m6jzDqparPKkKgRB2wiGuBZXbiPgiZOXKA,1093
|
|
16
|
-
htmy-0.4.1.dist-info/LICENSE,sha256=rFtoGU_3c_rlacXgOZapTHfMErN-JFPT5Bq_col4bqI,1067
|
|
17
|
-
htmy-0.4.1.dist-info/METADATA,sha256=-xo4VOq4dtGVSfQrLYXPgM701HztcohcK4CXga2IFRo,16379
|
|
18
|
-
htmy-0.4.1.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
|
|
19
|
-
htmy-0.4.1.dist-info/RECORD,,
|
|
File without changes
|