-
Notifications
You must be signed in to change notification settings - Fork 29
Add @with_children decorator
#113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import functools | ||
| import typing as t | ||
|
|
||
| from markupsafe import Markup as _Markup | ||
|
|
||
| if t.TYPE_CHECKING: | ||
| from collections.abc import Callable, Iterator, Mapping | ||
|
|
||
| import htpy | ||
|
|
||
|
|
||
| C = t.TypeVar("C", bound="htpy.Node") | ||
| P = t.ParamSpec("P") | ||
| R = t.TypeVar("R", bound="htpy.Renderable") | ||
|
|
||
|
|
||
| class _WithChildrenUnbound(t.Generic[C, P, R]): | ||
| """Decorator to make a component support children nodes. | ||
|
|
||
| This decorator is used to create a component that can accept children nodes, | ||
| just like native htpy components. | ||
|
|
||
| It lets you convert this: | ||
|
|
||
| ```python | ||
| def my_component(*, title: str, children: h.Node) -> h.Element: | ||
| ... | ||
|
|
||
| my_component(title="My title", children=h.div["My content"]) | ||
| ``` | ||
|
|
||
| To this: | ||
|
|
||
| ```python | ||
| @h.with_children | ||
| def my_component(children: h.Node, *, title: str) -> h.Element: | ||
| ... | ||
|
|
||
| my_component(title="My title")[h.div["My content"]] | ||
| ``` | ||
| """ | ||
|
|
||
| wrapped: Callable[t.Concatenate[C | None, P], R] | ||
|
|
||
| def __init__(self, func: Callable[t.Concatenate[C | None, P], R]) -> None: | ||
| # This instance is created at import time when decorating the component. | ||
| # It means that this object is global, and shared between all renderings | ||
| # of the same component. | ||
| self.wrapped = func | ||
| functools.update_wrapper(self, func) | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"with_children({self.wrapped.__name__}, <unbound>)" | ||
|
|
||
| def __call__(self, *args: P.args, **kwargs: P.kwargs) -> _WithChildrenBound[C, P, R]: | ||
| # This is the first call to the component, where we get the | ||
| # component's args and kwargs: | ||
| # | ||
| # my_component(title="My title") | ||
| # | ||
| # It is important that we return a new instance bound to the args | ||
| # and kwargs instead of mutating, so that state doesn't leak between | ||
| # multiple renderings of the same component. | ||
| # | ||
| return _WithChildrenBound(self.wrapped, args, kwargs) | ||
|
|
||
| def __getitem__(self, children: C | None) -> R: | ||
| # This is the unbound component being used with children: | ||
| # | ||
| # my_component["My content"] | ||
| # | ||
| return self.wrapped(children) # type: ignore[call-arg] | ||
|
|
||
| def __str__(self) -> _Markup: | ||
| # This is the unbound component being rendered to a string: | ||
| # | ||
| # str(my_component) | ||
| # | ||
| return _Markup(self.wrapped(None)) # type: ignore[call-arg] | ||
|
|
||
| __html__ = __str__ | ||
|
|
||
| def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: | ||
| return str(self).encode(encoding, errors) | ||
|
|
||
| def iter_chunks( | ||
| self, | ||
| context: Mapping[htpy.Context[t.Any], t.Any] | None = None, | ||
| ) -> Iterator[str]: | ||
| return self.wrapped(None).iter_chunks(context) # type: ignore[call-arg] | ||
|
|
||
|
|
||
| class _WithChildrenBound(t.Generic[C, P, R]): | ||
| _func: Callable[t.Concatenate[C | None, P], R] | ||
| _args: tuple[t.Any, ...] | ||
| _kwargs: Mapping[str, t.Any] | ||
|
|
||
| def __init__( | ||
| self, | ||
| func: Callable[t.Concatenate[C | None, P], R], | ||
| args: tuple[t.Any, ...], | ||
| kwargs: Mapping[str, t.Any], | ||
| ) -> None: | ||
| # This is called at runtime when the component is being passed args and | ||
| # kwargs. This instance is only used for the current rendering of the | ||
| # component. | ||
| self._func = func | ||
| self._args = args | ||
| self._kwargs = kwargs | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"with_children({self._func.__name__}, {self._args}, {self._kwargs})" | ||
|
|
||
| def __getitem__(self, children: C | None) -> R: | ||
| # This is a bound component being used with children: | ||
| # | ||
| # my_component(title="My title")["My content"] | ||
| # | ||
| return self._func(children, *self._args, **self._kwargs) | ||
|
|
||
| def __str__(self) -> _Markup: | ||
| # This is a bound component being rendered to a string: | ||
| # | ||
| # str(my_component(title="My title")) | ||
| # | ||
| return _Markup(self._func(None, *self._args, **self._kwargs)) | ||
|
|
||
| __html__ = __str__ | ||
|
|
||
| def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: | ||
| return str(self).encode(encoding, errors) | ||
|
|
||
| def iter_chunks( | ||
| self, | ||
| context: Mapping[htpy.Context[t.Any], t.Any] | None = None, | ||
| ) -> Iterator[str]: | ||
| return self._func(None, *self._args, **self._kwargs).iter_chunks(context) | ||
|
|
||
|
|
||
| with_children = _WithChildrenUnbound |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import pytest | ||
|
|
||
| import htpy as h | ||
|
|
||
|
|
||
| @h.with_children | ||
| def example_with_children( | ||
| content: h.Node, | ||
| *, | ||
| title: str = "default!", | ||
| ) -> h.Element: | ||
| return h.div[ | ||
| h.h1[title], | ||
| h.p[content], | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("component", "expected"), | ||
| [ | ||
| ( | ||
| example_with_children, | ||
| "with_children(example_with_children, <unbound>)", | ||
| ), | ||
| ( | ||
| example_with_children(title="title!"), | ||
| "with_children(example_with_children, (), {'title': 'title!'})", | ||
| ), | ||
| ], | ||
| ) | ||
| def test_with_children_repr(component: h.Renderable, expected: str) -> None: | ||
| assert repr(component) == expected |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.