|
8 | 8 | import inspect |
9 | 9 | import warnings |
10 | 10 | from functools import wraps |
11 | | -from typing import Any, Callable, Dict, Optional, Tuple, Union |
| 11 | +from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union, overload |
12 | 12 |
|
| 13 | +from .hooks import use_effect, use_state |
13 | 14 | from .proto import ComponentType, VdomDict |
14 | 15 |
|
15 | 16 |
|
16 | | -def component( |
17 | | - function: Callable[..., Union[ComponentType, VdomDict]] |
18 | | -) -> Callable[..., "Component"]: |
| 17 | +_Class = TypeVar("_Class", bound=Type[ComponentType]) |
| 18 | + |
| 19 | + |
| 20 | +@overload |
| 21 | +def component(function_or_class: _Class) -> _Class: |
| 22 | + ... |
| 23 | + |
| 24 | + |
| 25 | +@overload |
| 26 | +def component(function_or_class: Callable[..., Any]) -> Callable[..., ComponentType]: |
| 27 | + ... |
| 28 | + |
| 29 | + |
| 30 | +def component(function_or_class: Any) -> Callable[..., ComponentType]: |
19 | 31 | """A decorator for defining an :class:`Component`. |
20 | 32 |
|
21 | 33 | Parameters: |
22 | 34 | function: The function that will render a :class:`VdomDict`. |
23 | 35 | """ |
| 36 | + if not inspect.isclass(function_or_class): |
| 37 | + return _wrap_function(function_or_class) |
| 38 | + else: |
| 39 | + return _wrap_class(function_or_class) |
| 40 | + |
| 41 | + |
| 42 | +def update(cmpt: Any, state: Any) -> None: |
| 43 | + """A function for re-rendering a class-based component with updated state""" |
| 44 | + try: |
| 45 | + set_state = cmpt._set_state |
| 46 | + except AttributeError: |
| 47 | + if isinstance(cmpt, ComponentType): |
| 48 | + raise RuntimeError("Cannot update a component that has not rendered yet") |
| 49 | + else: |
| 50 | + raise TypeError(f"{cmpt} is not a component class") |
| 51 | + else: |
| 52 | + set_state(state) |
| 53 | + |
| 54 | + |
| 55 | +def _wrap_function( |
| 56 | + function: Callable[..., ComponentType | VdomDict] |
| 57 | +) -> Callable[..., Component]: |
24 | 58 | sig = inspect.signature(function) |
25 | 59 | key_is_kwarg = "key" in sig.parameters and sig.parameters["key"].kind in ( |
26 | 60 | inspect.Parameter.KEYWORD_ONLY, |
@@ -77,3 +111,91 @@ def __repr__(self) -> str: |
77 | 111 | return f"{self._func.__name__}({id(self)}, {items})" |
78 | 112 | else: |
79 | 113 | return f"{self._func.__name__}({id(self)})" |
| 114 | + |
| 115 | + |
| 116 | +_Wrapped = TypeVar("_Wrapped", bound=Any) |
| 117 | + |
| 118 | + |
| 119 | +def _wrap_class(cls: type[_Wrapped]) -> type[_Wrapped]: |
| 120 | + """Modifies the given class such that it can operate as a stateful component |
| 121 | +
|
| 122 | + Adds the following attributes to the class: |
| 123 | +
|
| 124 | + - ``key`` |
| 125 | + - ``state`` |
| 126 | + - ``_set_state`` |
| 127 | +
|
| 128 | + And wraps the following methods with extra logic that is opaque to the user: |
| 129 | +
|
| 130 | + - ``__init__`` |
| 131 | + - ``render`` |
| 132 | + """ |
| 133 | + |
| 134 | + if hasattr(cls, "__slots__"): |
| 135 | + raise ValueError("Component classes cannot have __slots__") |
| 136 | + |
| 137 | + old_init = getattr(cls, "__init__", object.__init__) |
| 138 | + old_render = cls.render |
| 139 | + |
| 140 | + @wraps(old_init) |
| 141 | + def new_init(self: Any, *args: Any, key: Any | None = None, **kwargs: Any) -> None: |
| 142 | + self.key = key |
| 143 | + self.state = None |
| 144 | + old_init(self, *args, **kwargs) |
| 145 | + |
| 146 | + @wraps(old_render) |
| 147 | + def new_render(self: Any) -> Any: |
| 148 | + self.state, self._set_state = use_state(self.state) # noqa: ROH101 |
| 149 | + use_effect(getattr(self, "effect", None), args=[]) # noqa: ROH101 |
| 150 | + return old_render(self) |
| 151 | + |
| 152 | + # wrap the original methods |
| 153 | + cls.__init__ = _OwnerInheritorDescriptor(new_init, old_init) |
| 154 | + cls.render = _OwnerInheritorDescriptor(new_render, old_render) |
| 155 | + # manually set up descriptor |
| 156 | + cls.__init__.__set_name__(cls, "__init__") |
| 157 | + cls.render.__set_name__(cls, "render") |
| 158 | + |
| 159 | + return cls |
| 160 | + |
| 161 | + |
| 162 | +class _OwnerInheritorDescriptor: |
| 163 | + """Show one value for the owner of this descriptor and another for the owner's subclass |
| 164 | +
|
| 165 | + Example: |
| 166 | + .. code-block:: |
| 167 | +
|
| 168 | + class Owner: |
| 169 | + method = _OwnerInheritorDescriptor( |
| 170 | + own_method=lambda self: 1, |
| 171 | + inherited_method=lambda self: 2, |
| 172 | + ) |
| 173 | +
|
| 174 | + class Inheritor(Owner): |
| 175 | + def method(self): |
| 176 | + return super().method() |
| 177 | +
|
| 178 | + assert Owner().method() == 1 |
| 179 | + assert Inheritor().method() == 2 |
| 180 | + """ |
| 181 | + |
| 182 | + owner: type[Any] |
| 183 | + |
| 184 | + def __init__( |
| 185 | + self, |
| 186 | + own_method: Any, |
| 187 | + inherited_method: Any, |
| 188 | + ) -> None: |
| 189 | + self.own_method = own_method |
| 190 | + self.inherited_method = inherited_method |
| 191 | + |
| 192 | + def __set_name__(self, cls: type[Any], name: str) -> None: |
| 193 | + self.owner = cls |
| 194 | + |
| 195 | + def __get__(self, obj: Any | None, cls: type[Any]) -> Any: |
| 196 | + if obj is None: |
| 197 | + return self |
| 198 | + elif cls is self.owner: |
| 199 | + return self.own_method.__get__(obj, cls) |
| 200 | + else: |
| 201 | + return self.inherited_method.__get__(obj, cls) |
0 commit comments