htmy 0.4.2__tar.gz → 0.5.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.

Potentially problematic release.


This version of htmy might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: htmy
3
- Version: 0.4.2
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
@@ -17,6 +17,7 @@
17
17
  - **Powerful**, React-like **context support**, so you can avoid prop-drilling.
18
18
  - Sync and async **function components** with **decorator syntax**.
19
19
  - All baseline **HTML** tags built-in.
20
+ - Support for **native HTML/XML** documents with dynamic formatting and **slot rendering**.
20
21
  - **Markdown** support with tools for customization.
21
22
  - Async, JSON based **internationalization**.
22
23
  - Built-in, easy to use `ErrorBoundary` component for graceful error handling.
@@ -142,11 +143,11 @@ user_table = html.table(
142
143
  `htmy` has a rich set of built-in utilities and components for both HTML and other use-cases:
143
144
 
144
145
  - `html` module: a complete set of [baseline HTML tags](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility).
146
+ - `Snippet` and `Slots`: utilities for creating dynamic, customizable document snippets in their native file format (HTML, XML, Markdown, etc.), with slot rendering support.
145
147
  - `md`: `MarkdownParser` utility and `MD` component for loading, parsing, converting, and rendering markdown content.
146
148
  - `i18n`: utilities for async, JSON based internationalization.
147
149
  - `BaseTag`, `TagWithProps`, `Tag`, `WildcardTag`: base classes for custom XML tags.
148
150
  - `ErrorBoundary`, `Fragment`, `SafeStr`, `WithContext`: utilities for error handling, component wrappers, context providers, and formatting.
149
- - `Snippet`: utility class for loading and customizing document snippets from the file system.
150
151
  - `etree.ETreeConverter`: utility that converts XML to a component tree with support for custom HTMY components.
151
152
 
152
153
  ### Rendering
@@ -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 .typing import is_component_sequence as is_component_sequence
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
@@ -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 Awaitable, Callable, Container
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,10 +19,8 @@ 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
26
  from typing_extensions import Never, Self
@@ -97,11 +93,7 @@ class ErrorBoundary(Fragment):
97
93
  if not (self._errors is None or any(e in self._errors for e in type(error).mro())):
98
94
  raise error
99
95
 
100
- return (
101
- Fragment(*self._fallback)
102
- if is_component_sequence(self._fallback)
103
- else cast(ComponentType, self._fallback)
104
- )
96
+ return as_component_type(self._fallback)
105
97
 
106
98
 
107
99
  class WithContext(Fragment):
@@ -127,59 +119,6 @@ class WithContext(Fragment):
127
119
  return self._context
128
120
 
129
121
 
130
- class Snippet:
131
- """
132
- Base component that can load its content from a file.
133
- """
134
-
135
- __slots__ = ("_path_or_text", "_text_processor")
136
-
137
- def __init__(
138
- self,
139
- path_or_text: Text | str | Path,
140
- *,
141
- text_processor: TextProcessor | None = None,
142
- ) -> None:
143
- """
144
- Initialization.
145
-
146
- Arguments:
147
- path_or_text: The path from where the content should be loaded or a `Text`
148
- instance if this value should be rendered directly.
149
- text_processor: An optional text processors that can be used to process the text
150
- content before rendering. It can be used for example for token replacement or
151
- string formatting.
152
- """
153
- self._path_or_text = path_or_text
154
- self._text_processor = text_processor
155
-
156
- async def htmy(self, context: Context) -> Component:
157
- """Renders the component."""
158
- text = await self._get_text_content()
159
- if self._text_processor is not None:
160
- processed = self._text_processor(text, context)
161
- text = (await processed) if isinstance(processed, Awaitable) else processed
162
-
163
- return self._render_text(text, context)
164
-
165
- async def _get_text_content(self) -> str:
166
- """Returns the plain text content that should be rendered."""
167
- path_or_text = self._path_or_text
168
-
169
- if isinstance(path_or_text, Text):
170
- return path_or_text
171
- else:
172
- async with await open_file(path_or_text, "r") as f:
173
- return await f.read()
174
-
175
- def _render_text(self, text: str, context: Context) -> Component:
176
- """
177
- Render function that takes the text that must be rendered and the current rendering context,
178
- and returns the corresponding component.
179
- """
180
- return SafeStr(text)
181
-
182
-
183
122
  # -- Context utilities
184
123
 
185
124
 
@@ -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, Snippet, Text
8
- from htmy.typing import TextProcessor
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
- """Component for reading, customizing, and rendering markdown documents."""
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
 
@@ -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, is_component_sequence
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:
@@ -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)
@@ -1,5 +1,5 @@
1
1
  from collections.abc import Callable, Coroutine, Mapping, MutableMapping
2
- from typing import Any, Protocol, TypeAlias, TypeGuard, TypeVar, runtime_checkable
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
+ ...
@@ -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
1
  [tool.poetry]
2
2
  name = "htmy"
3
- version = "0.4.2"
3
+ version = "0.5.0"
4
4
  description = "Async, pure-Python rendering engine."
5
5
  authors = ["Peter Volf <do.volfp@gmail.com>"]
6
6
  license = "MIT"
@@ -15,7 +15,7 @@ markdown = "^3.7"
15
15
  [tool.poetry.group.dev.dependencies]
16
16
  mkdocs-material = "^9.5.39"
17
17
  mkdocstrings = {extras = ["python"], version = "^0.26.1"}
18
- mypy = "^1.11.2"
18
+ mypy = "^1.14.1"
19
19
  poethepoet = "^0.29.0"
20
20
  pytest = "^8.3.3"
21
21
  pytest-asyncio = "^0.24.0"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes