forked from posit-dev/py-shiny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.py
386 lines (297 loc) · 9.32 KB
/
types.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# Needed for NotRequired with Python 3.7 - 3.9
# See https://www.python.org/dev/peps/pep-0655/#usage-in-python-3-11
from __future__ import annotations
__all__ = (
"MISSING",
"MISSING_TYPE",
"Jsonifiable",
"FileInfo",
"ImgData",
"SafeException",
"SilentException",
"SilentCancelOutputException",
)
from typing import (
TYPE_CHECKING,
Any,
BinaryIO,
Dict,
List,
Literal,
NamedTuple,
Optional,
Protocol,
Tuple,
TypeVar,
Union,
)
from htmltools import TagChild
from ._docstring import add_example
from ._typing_extensions import NotRequired, TypedDict
if TYPE_CHECKING:
from matplotlib.figure import Figure
# Sentinel value - indicates a missing value in a function call.
class MISSING_TYPE:
pass
MISSING: MISSING_TYPE = MISSING_TYPE()
T = TypeVar("T")
ListOrTuple = Union[List[T], Tuple[T, ...]]
# Information about a single file, with a structure like:
# {'name': 'mtcars.csv', 'size': 1303, 'type': 'text/csv', 'datapath: '/...../mtcars.csv'}
# The incoming data doesn't include 'datapath'; that field is added by the
# FileUploadOperation class.
@add_example(ex_dir="./api-examples/input_file")
class FileInfo(TypedDict):
"""
Class for information about a file upload.
See Also
--------
* :func:`~shiny.ui.input_file`
"""
name: str
"""The name of the file being uploaded."""
size: int
"""The size of the file in bytes."""
type: str
"""The MIME type of the file."""
datapath: str
"""The path to the file on the server."""
@add_example(ex_dir="./api-examples/output_image")
class ImgData(TypedDict):
"""
Return type for :class:`~shiny.render.image`.
See Also
--------
* :class:`~shiny.render.image`
"""
src: str
"""The ``src`` attribute of the ``<img>`` tag."""
width: NotRequired[str | float]
"""The ``width`` attribute of the ``<img>`` tag."""
height: NotRequired[str | float]
"""The ``height`` attribute of the ``<img>`` tag."""
alt: NotRequired[str]
"""The ``alt`` attribute of the ``<img>`` tag."""
style: NotRequired[str]
"""The ``style`` attribute of the ``<img>`` tag."""
coordmap: NotRequired[Any]
"""TODO """
@add_example()
class SafeException(Exception):
"""
Throw a safe exception.
When ``shiny.App.SANITIZE_ERRORS`` is ``True`` (which is the case
in some production environments like Posit Connect), exceptions are sanitized
to prevent leaking of sensitive information. This class provides a way to
generate an error that is OK to be displayed to the user.
"""
pass
@add_example()
class SilentException(Exception):
"""
Throw a silent exception.
Normally, when an exception occurs inside a reactive context, it's either:
- Displayed to the user (as a big red error message)
- This happens when the exception is raised from an output context (e.g., :class:`shiny.render.ui`)
- Crashes the application
- This happens when the exception is raised from an :func:`shiny.reactive.effect`
This exception is used to silently throw inside a reactive context, meaning that
execution is paused, and no output is shown to users (or the python console).
See Also
--------
* :class:`~shiny.types.SilentCancelOutputException`
"""
pass
@add_example()
class SilentCancelOutputException(Exception):
"""
Throw a silent exception and don't clear output
Similar to :class:`~shiny.types.SilentException`, but if thrown in an output context,
existing output isn't cleared.
See Also
--------
* :class:`~shiny.types.SilentException`
"""
pass
class SilentOperationInProgressException(SilentException):
# Throw a silent exception to indicate that an operation is in progress
# Similar to :class:`~SilentException`, but if thrown in an output context, existing
# output isn't cleared and stays in recalculating mode until the next time it is
# invalidated.
pass
class NotifyException(Exception):
"""
This exception can be raised in a (non-output) reactive effect
to display a message to the user.
Parameters
----------
message
The message to display to the user.
sanitize
If ``True``, the message is sanitized to prevent leaking sensitive information.
close
If ``True``, the session is closed after the message is displayed.
"""
sanitize: bool
close: bool
def __init__(self, message: str, sanitize: bool = True, close: bool = False):
super().__init__(message)
self.sanitize = sanitize
self.close = close
class ActionButtonValue(int):
pass
class NavSetArg(Protocol):
"""
A value suitable for passing to a navigation container (e.g.,
:func:`~shiny.ui.navset_tab`).
"""
def resolve(
self, selected: Optional[str], context: dict[str, Any]
) -> tuple[TagChild, TagChild]:
"""
Resolve information provided by the navigation container.
Parameters
----------
selected
The value of the navigation item to be shown on page load.
context
Additional context supplied by the navigation container.
"""
...
def get_value(self) -> Optional[str]:
"""
Get the value of this navigation item (if any).
This value is only used to determine what navigation item should be shown
by default when none is specified (i.e., the first navigation item that
returns a value is used to determine the container's ``selected`` value).
"""
...
# =============================================================================
# Types for plots and images
# =============================================================================
# Use this protocol to avoid needing to maintain working stubs for plotnint. If
# good stubs ever become available for plotnine, use those instead.
class PlotnineFigure(Protocol):
scales: list[Any]
coordinates: Any
facet: Any
layout: Any
mapping: dict[str, str]
theme: PlotnineTheme
def save(
self,
filename: BinaryIO,
format: str,
units: str,
dpi: float,
width: float,
height: float,
verbose: bool,
bbox_inches: object = None,
): ...
def draw(self, show: bool) -> Figure: ...
class PlotnineTheme(NamedTuple):
themeables: PlotnineThemeables
class PlotnineThemeables(TypedDict):
figure_size: PlotnineThemeable | None
class PlotnineThemeable(NamedTuple):
properties: dict[str, Any]
class CoordmapDims(TypedDict):
width: float
height: float
class CoordmapPanelLog(TypedDict):
x: float | None
y: float | None
class CoordmapPanelDomain(TypedDict):
left: float
right: float
bottom: float
top: float
class CoordmapPanelRange(TypedDict):
left: float
right: float
bottom: float
top: float
class CoordmapPanelMapping(TypedDict):
x: str | None
y: str | None
panelvar1: NotRequired[str]
panelvar2: NotRequired[str]
class CoordmapPanelvarValues(TypedDict):
panelvar1: NotRequired[float]
panelvar2: NotRequired[float]
class CoordmapPanel(TypedDict):
panel: int
row: NotRequired[int]
col: NotRequired[int]
panel_vars: NotRequired[CoordmapPanelvarValues]
log: CoordmapPanelLog
domain: CoordmapPanelDomain
mapping: CoordmapPanelMapping
range: CoordmapPanelRange
class Coordmap(TypedDict):
panels: list[CoordmapPanel]
dims: CoordmapDims
class CoordXY(TypedDict):
x: float
y: float
# Data structure sent from client to server when a plot is clicked, double-clicked, or
# hovered.
class CoordInfo(TypedDict):
x: float
y: float
coords_css: CoordXY
coords_img: CoordXY
img_css_ratio: CoordXY
panelvar1: NotRequired[str]
panelvar2: NotRequired[str]
mapping: CoordmapPanelMapping
domain: CoordmapPanelDomain
range: CoordmapPanelRange
log: CoordmapPanelLog
# .nonce: float
class BrushInfo(TypedDict):
xmin: float
xmax: float
ymin: float
ymax: float
coords_css: CoordXY
coords_img: CoordXY
img_css_ratio: CoordXY
panelvar1: NotRequired[str]
panelvar2: NotRequired[str]
mapping: CoordmapPanelMapping
domain: CoordmapPanelDomain
range: CoordmapPanelRange
log: CoordmapPanelLog
direction: Literal["x", "y", "xy"]
# .nonce: float
# https://github.com/python/cpython/blob/df1eec3dae3b1eddff819fd70f58b03b3fbd0eda/Lib/json/encoder.py#L77-L95
# +-------------------+---------------+
# | Python | JSON |
# +===================+===============+
# | dict | object |
# +-------------------+---------------+
# | list, tuple | array |
# +-------------------+---------------+
# | str | string |
# +-------------------+---------------+
# | int, float | number |
# +-------------------+---------------+
# | True | true |
# +-------------------+---------------+
# | False | false |
# +-------------------+---------------+
# | None | null |
# +-------------------+---------------+
Jsonifiable = Union[
str,
int,
float,
bool,
None,
List["Jsonifiable"],
Tuple["Jsonifiable"],
"JsonifiableDict",
]
JsonifiableDict = Dict[str, Jsonifiable]