|
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 _wrap_function( |
| 43 | + function: Callable[..., ComponentType | VdomDict] |
| 44 | +) -> Callable[..., Component]: |
24 | 45 | sig = inspect.signature(function) |
25 | 46 | key_is_kwarg = "key" in sig.parameters and sig.parameters["key"].kind in ( |
26 | 47 | inspect.Parameter.KEYWORD_ONLY, |
@@ -77,3 +98,110 @@ def __repr__(self) -> str: |
77 | 98 | return f"{self._func.__name__}({id(self)}, {items})" |
78 | 99 | else: |
79 | 100 | return f"{self._func.__name__}({id(self)})" |
| 101 | + |
| 102 | + |
| 103 | +_Wrapped = TypeVar("_Wrapped", bound=Any) |
| 104 | + |
| 105 | + |
| 106 | +def _wrap_class(cls: type[_Wrapped]) -> type[_Wrapped]: |
| 107 | + """Modifies the given class such that it can operate as a stateful component |
| 108 | +
|
| 109 | + Adds the following attributes to the class: |
| 110 | +
|
| 111 | + - ``key`` |
| 112 | + - ``state`` |
| 113 | + - ``_set_state`` |
| 114 | +
|
| 115 | + And wraps the following methods with extra logic that is opaque to the user: |
| 116 | +
|
| 117 | + - ``__init__`` |
| 118 | + - ``render`` |
| 119 | + """ |
| 120 | + |
| 121 | + if hasattr(cls, "__slots__"): |
| 122 | + raise ValueError("Component classes cannot have __slots__") |
| 123 | + |
| 124 | + original_render = cls.render |
| 125 | + original_init = getattr(cls, "__init__", object.__init__) |
| 126 | + |
| 127 | + def __init__( # noqa: N807 |
| 128 | + self: Any, |
| 129 | + *args: Any, |
| 130 | + key: Optional[Any] = None, |
| 131 | + **kwargs: Any, |
| 132 | + ) -> None: |
| 133 | + self.key = key |
| 134 | + # initialize with a no-op set state callback |
| 135 | + self._set_state = lambda _: None |
| 136 | + cls.__init__.inherited_method(self) |
| 137 | + if not hasattr(self, "state"): |
| 138 | + raise AttributeError(f"{self} did not initialize a 'state' attribute") |
| 139 | + |
| 140 | + def render(self: Any) -> Any: |
| 141 | + self.state, self._set_state = use_state(self.state) # noqa: ROH101 |
| 142 | + use_effect(getattr(self, "effect", None), args=[]) # noqa: ROH101 |
| 143 | + return cls.render.inherited_method(self) |
| 144 | + |
| 145 | + cls.__init__ = _OwnerInheritorDescriptor(__init__, original_init) |
| 146 | + cls.render = _OwnerInheritorDescriptor(render, original_render) |
| 147 | + |
| 148 | + # need to manually set up descriptor |
| 149 | + cls.__init__.__set_name__(cls, "__init__") |
| 150 | + cls.render.__set_name__(cls, "render") |
| 151 | + |
| 152 | + cls.state = _StateDescriptor() |
| 153 | + |
| 154 | + return cls |
| 155 | + |
| 156 | + |
| 157 | +class _OwnerInheritorDescriptor: |
| 158 | + """Show one value for the owner of this descriptor and another for the owner's subclass |
| 159 | +
|
| 160 | + Example: |
| 161 | + .. code-block:: |
| 162 | +
|
| 163 | + class Owner: |
| 164 | + method = _OwnerInheritorDescriptor( |
| 165 | + own_method=lambda self: 1, |
| 166 | + inherited_method=lambda self: 2, |
| 167 | + ) |
| 168 | +
|
| 169 | + class Inheritor(Owner): |
| 170 | + def method(self): |
| 171 | + return super().method() |
| 172 | +
|
| 173 | + assert Owner().method() == 1 |
| 174 | + assert Inheritor().method() == 2 |
| 175 | + """ |
| 176 | + |
| 177 | + owner: type[Any] |
| 178 | + |
| 179 | + def __init__( |
| 180 | + self, |
| 181 | + own_method: Any, |
| 182 | + inherited_method: Any, |
| 183 | + ) -> None: |
| 184 | + self.own_method = own_method |
| 185 | + self.inherited_method = inherited_method |
| 186 | + |
| 187 | + def __set_name__(self, cls: type[Any], name: str) -> None: |
| 188 | + self.owner = cls |
| 189 | + |
| 190 | + def __get__(self, obj: Any | None, cls: type[Any]) -> Any: |
| 191 | + if obj is None: |
| 192 | + return self |
| 193 | + elif cls is self.owner: |
| 194 | + return self.own_method.__get__(obj, cls) |
| 195 | + else: |
| 196 | + return self.inherited_method.__get__(obj, cls) |
| 197 | + |
| 198 | + |
| 199 | +class _StateDescriptor: |
| 200 | + """Simple descriptor that call ``obj._set_state`` of the value changes""" |
| 201 | + |
| 202 | + def __get__(self, obj: Any, cls: Any) -> Any: |
| 203 | + return self if obj is None else obj._state |
| 204 | + |
| 205 | + def __set__(self, obj: Any, new: Any) -> None: |
| 206 | + obj._set_state(new) |
| 207 | + obj._state = new |
0 commit comments