-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathexperimental.py
179 lines (141 loc) · 4.94 KB
/
experimental.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""Experimental features for anywidget."""
from __future__ import annotations
import dataclasses
import typing
import psygnal
from ._descriptor import MimeBundleDescriptor
if typing.TYPE_CHECKING: # pragma: no cover
import pathlib
from ._protocols import WidgetBase
__all__ = ["MimeBundleDescriptor", "dataclass", "widget"]
T = typing.TypeVar("T")
def widget(
*,
esm: str | pathlib.Path,
css: None | str | pathlib.Path = None,
**kwargs: typing.Any, # noqa: ANN401
) -> typing.Callable[[T], T]:
"""Decorator to register a widget class as a mimebundle.
Parameters
----------
esm : str | pathlib.Path
The path or contents of an ES Module for the widget.
css : None | str | pathlib.Path, optional
The path or contents of a CSS file for the widget.
**kwargs
Additional keyword arguments to pass to the
Returns
-------
Callable
A decorator that registers the widget class as a mimebundle.
"""
kwargs["_esm"] = esm
if css is not None:
kwargs["_css"] = css
def _decorator(cls: T) -> T:
setattr(cls, "_repr_mimebundle_", MimeBundleDescriptor(**kwargs)) # noqa: B010
return cls
return _decorator
# To preserve the signature of the decorated class.
# see: https://github.com/pyapp-kit/magicgui/blob/5e068f31eaeeb130f43c38727b25423cc3ea4de3/src/magicgui/schema/_guiclass.py#L145-L162
def __dataclass_transform__( # noqa: N807
*,
eq_default: bool = True, # noqa: ARG001
order_default: bool = False, # noqa: ARG001
kw_only_default: bool = False, # noqa: ARG001
field_specifiers: tuple[type | typing.Callable[..., object], ...] = (()), # noqa: ARG001
) -> typing.Callable[[T], T]:
return lambda a: a
@__dataclass_transform__(field_specifiers=(dataclasses.Field, dataclasses.field))
def dataclass(
cls: T | None = None,
*,
esm: str | pathlib.Path,
css: None | str | pathlib.Path = None,
**dataclass_kwargs: object,
) -> typing.Callable[[T], T]:
"""Turns class into a dataclass, makes it evented, and registers it as a widget.
Parameters
----------
cls : T | None
The class to decorate.
esm : str | pathlib.Path
The path or contents of an ES Module for the widget.
css : None | str | pathlib.Path, optional
The path or contents of a CSS file for the widget.
dataclass_kwargs : object
Additional keyword arguments to pass to the dataclass decorator.
Returns
-------
type
The evented dataclass.
Examples
--------
>>> @dataclass(esm="index.js")
... class Counter:
... value: int = 0
...
>>> counter = Counter()
>>> counter.value = 1
>>> counter
"""
def _decorator(cls: T) -> T:
cls = dataclasses.dataclass(cls, **dataclass_kwargs) # type: ignore[call-overload]
cls = psygnal.evented(cls) # type: ignore[call-overload]
return widget(esm=esm, css=css)(cls)
return _decorator(cls) if cls is not None else _decorator # type: ignore[return-value]
_ANYWIDGET_COMMAND = "_anywidget_command"
_ANYWIDGET_COMMANDS = "_anywidget_commands"
_AnyWidgetCommand = typing.Callable[
[object, object, list[bytes] | list[memoryview]],
tuple[object, list[bytes] | list[memoryview]],
]
def command(cmd: T) -> T:
"""Mark a function as a command for anywidget.
Parameters
----------
cmd : Callable
The function to mark as a command.
Returns
-------
Callable
The decorated function annotated as a command.
"""
setattr(cmd, _ANYWIDGET_COMMAND, True)
return cmd
def _collect_anywidget_commands(widget_cls: type) -> None:
cmds: dict[str, _AnyWidgetCommand] = {}
for base in widget_cls.__mro__:
if not hasattr(base, "__dict__"):
continue
for name, attr in base.__dict__.items():
if callable(attr) and getattr(attr, _ANYWIDGET_COMMAND, False):
cmds[name] = attr # noqa: PERF403
setattr(widget_cls, _ANYWIDGET_COMMANDS, cmds)
def _register_anywidget_commands(widget: WidgetBase) -> None:
"""Register a custom message reducer for a widget if it implements the protocol."""
# Only add the callback if the widget has any commands.
cmds = typing.cast(
"dict[str, _AnyWidgetCommand]",
getattr(type(widget), _ANYWIDGET_COMMANDS, {}),
)
if not cmds:
return
def handle_anywidget_command(
self: WidgetBase,
msg: typing.Any,
buffers: list[bytes] | list[memoryview],
) -> None:
if not isinstance(msg, dict) or msg.get("kind") != "anywidget-command":
return
cmd = cmds[msg["name"]]
response, buffers = cmd(widget, msg["msg"], buffers or [])
widget.send(
{
"id": msg["id"],
"kind": "anywidget-command-response",
"response": response,
},
buffers,
)
widget.on_msg(handle_anywidget_command)