-
-
Notifications
You must be signed in to change notification settings - Fork 477
/
button.py
376 lines (285 loc) · 12.6 KB
/
button.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
"""
Defines the Button and button-like widgets which allow triggering
events or merely toggling between on-off states.
"""
from __future__ import annotations
from typing import (
TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, List, Mapping,
Optional, Type,
)
import param
from bokeh.events import ButtonClick, MenuItemClick
from bokeh.models import Dropdown as _BkDropdown, Toggle as _BkToggle
from bokeh.models.ui import SVGIcon, TablerIcon
from ..io.resources import CDN_DIST
from ..links import Callback
from ..models.widgets import Button as _BkButton
from ._mixin import TooltipMixin
from .base import Widget
if TYPE_CHECKING:
from bokeh.document import Document
from bokeh.model import Model
from pyviz_comms import Comm
from ..links import JSLinkTarget, Link
BUTTON_TYPES: List[str] = ['default', 'primary', 'success', 'warning', 'danger', 'light']
BUTTON_STYLES: List[str] = ['solid', 'outline']
class _ButtonBase(Widget):
button_type = param.ObjectSelector(default='default', objects=BUTTON_TYPES, doc="""
A button theme; should be one of 'default' (white), 'primary'
(blue), 'success' (green), 'info' (yellow), 'light' (light),
or 'danger' (red).""")
button_style = param.ObjectSelector(default='solid', objects=BUTTON_STYLES, doc="""
A button style to switch between 'solid', 'outline'.""")
_rename: ClassVar[Mapping[str, str | None]] = {'name': 'label', 'button_style': None}
_source_transforms: ClassVar[Mapping[str, str | None]] = {'button_style': None}
_stylesheets: ClassVar[List[str]] = [f'{CDN_DIST}css/button.css']
__abstract = True
def _process_param_change(self, params):
if 'button_style' in params or 'css_classes' in params:
params['css_classes'] = [
params.pop('button_style', self.button_style)
] + params.get('css_classes', self.css_classes)
return super()._process_param_change(params)
class IconMixin(Widget):
icon = param.String(default=None, doc="""
An icon to render to the left of the button label. Either an SVG or an
icon name which is loaded from https://tabler-icons.io.""")
icon_size = param.String(default='1em', doc="""
Size of the icon as a string, e.g. 12px or 1em.""")
_rename: ClassVar[Mapping[str, str | None]] = {
'icon_size': None, '_icon': 'icon', 'icon': None
}
__abstract = True
def __init__(self, **params) -> None:
self._rename = dict(self._rename, **IconMixin._rename)
super().__init__(**params)
def _process_param_change(self, params):
icon_size = params.pop('icon_size', self.icon_size)
if params.get('icon') is not None:
icon = params['icon']
if icon.lstrip().startswith('<svg'):
icon_model = SVGIcon(svg=icon, size=icon_size)
else:
icon_model = TablerIcon(icon_name=icon, size=icon_size)
params['_icon'] = icon_model
return super()._process_param_change(params)
class _ClickButton(Widget):
__abstract = True
_event: ClassVar[str] = 'button_click'
def _get_model(
self, doc: Document, root: Optional[Model] = None,
parent: Optional[Model] = None, comm: Optional[Comm] = None
) -> Model:
model = super()._get_model(doc, root, parent, comm)
self._register_events(self._event, model=model, doc=doc, comm=comm)
return model
def js_on_click(self, args: Dict[str, Any] = {}, code: str = "") -> Callback:
"""
Allows defining a JS callback to be triggered when the button
is clicked.
Arguments
----------
args: dict
A mapping of objects to make available to the JS callback
code: str
The Javascript code to execute when the button is clicked.
Returns
-------
callback: Callback
The Callback which can be used to disable the callback.
"""
from ..links import Callback
return Callback(self, code={'event:'+self._event: code}, args=args)
def jscallback(self, args: Dict[str, Any] = {}, **callbacks: str) -> Callback:
"""
Allows defining a Javascript (JS) callback to be triggered when a property
changes on the source object. The keyword arguments define the
properties that trigger a callback and the JS code that gets
executed.
Arguments
----------
args: dict
A mapping of objects to make available to the JS callback
**callbacks: dict
A mapping between properties on the source model and the code
to execute when that property changes
Returns
-------
callback: Callback
The Callback which can be used to disable the callback.
"""
for k, v in list(callbacks.items()):
if k == 'clicks':
k = 'event:'+self._event
val = self._rename.get(v, v)
if val is not None:
callbacks[k] = val
return Callback(self, code=callbacks, args=args)
class Button(_ButtonBase, _ClickButton, IconMixin, TooltipMixin):
"""
The `Button` widget allows triggering events when the button is
clicked.
The Button provides a `value` parameter, which will toggle from
`False` to `True` while the click event is being processed
It also provides an additional `clicks` parameter, that can be
watched to subscribe to click events.
Reference: https://panel.holoviz.org/reference/widgets/Button.html#widgets-gallery-button
:Example:
>>> pn.widgets.Button(name='Click me', icon='caret-right', button_type='primary')
"""
clicks = param.Integer(default=0, doc="""
Number of clicks (can be listened to)""")
value = param.Event(doc="""
Toggles from False to True while the event is being processed.""")
_rename: ClassVar[Mapping[str, str | None]] = {
**TooltipMixin._rename, 'clicks': None, 'name': 'label', 'value': None,
}
_source_transforms: ClassVar[Mapping[str, str | None]] = {
'button_style': None, 'description': None
}
_target_transforms: ClassVar[Mapping[str, str | None]] = {
'event:button_click': None, 'value': None,
}
_widget_type: ClassVar[Type[Model]] = _BkButton
def __init__(self, **params):
click_handler = params.pop('on_click', None)
super().__init__(**params)
if click_handler:
self.on_click(click_handler)
@property
def _linkable_params(self) -> List[str]:
return super()._linkable_params + ['value']
def jslink(
self, target: JSLinkTarget, code: Optional[Dict[str, str]] = None,
args: Optional[Dict[str, Any]] = None, bidirectional: bool = False,
**links: str
) -> Link:
"""
Links properties on the this Button to those on the
`target` object in Javascript (JS) code.
Supports two modes, either specify a
mapping between the source and target model properties as
keywords or provide a dictionary of JS code snippets which
maps from the source parameter to a JS code snippet which is
executed when the property changes.
Arguments
----------
target: panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned
The target to link the value(s) to.
code: dict
Custom code which will be executed when the widget value
changes.
args: dict
A mapping of objects to make available to the JS callback
bidirectional: boolean
Whether to link source and target bi-directionally. Default is `False`.
**links: dict[str,str]
A mapping between properties on the source model and the
target model property to link it to.
Returns
-------
Link
The Link can be used unlink the widget and the target model.
"""
links = {'event:'+self._event if p == 'value' else p: v for p, v in links.items()}
return super().jslink(target, code, args, bidirectional, **links)
def _process_event(self, event: ButtonClick) -> None:
self.param.trigger('value')
self.clicks += 1
def on_click(
self, callback: Callable[[param.parameterized.Event], None | Awaitable[None]]
) -> param.parameterized.Watcher:
"""
Register a callback to be executed when the `Button` is clicked.
The callback is given an `Event` argument declaring the number of clicks
Example
-------
>>> button = pn.widgets.Button(name='Click me')
>>> def handle_click(event):
... print("I was clicked!")
>>> button.on_click(handle_click)
Arguments
---------
callback:
The function to run on click events. Must accept a positional `Event` argument. Can
be a sync or async function
Returns
-------
watcher: param.Parameterized.Watcher
A `Watcher` that executes the callback when the button is clicked.
"""
return self.param.watch(callback, 'clicks', onlychanged=False)
class Toggle(_ButtonBase, IconMixin):
"""The `Toggle` widget allows toggling a single condition between `True`/`False` states.
This widget is interchangeable with the `Checkbox` widget.
Reference: https://panel.holoviz.org/reference/widgets/Toggle.html
:Example:
>>> Toggle(name='Toggle', button_type='success')
"""
value = param.Boolean(default=False, doc="""
Whether the button is currently toggled.""")
_rename: ClassVar[Mapping[str, str | None]] = {
'value': 'active', 'name': 'label',
}
_supports_embed: ClassVar[bool] = True
_widget_type: ClassVar[Type[Model]] = _BkToggle
def _get_embed_state(self, root, values=None, max_opts=3):
return (self, self._models[root.ref['id']][0], [False, True],
lambda x: x.active, 'active', 'cb_obj.active')
class MenuButton(_ButtonBase, _ClickButton, IconMixin):
"""
The `MenuButton` widget allows specifying a list of menu items to
select from triggering events when the button is clicked.
Unlike other widgets, it does not have a `value`
parameter. Instead it has a `clicked` parameter that can be
watched to trigger events and which reports the last clicked menu
item.
Reference: https://panel.holoviz.org/reference/widgets/MenuButton.html
:Example:
>>> menu_items = [('Option A', 'a'), ('Option B', 'b'), None, ('Option C', 'c')]
>>> MenuButton(name='Dropdown', items=menu_items, button_type='primary')
"""
clicked = param.String(default=None, doc="""
Last menu item that was clicked.""")
items = param.List(default=[], doc="""
Menu items in the dropdown. Allows strings, tuples of the form
(title, value) or Nones to separate groups of items.""")
split = param.Boolean(default=False, doc="""
Whether to add separate dropdown area to button.""")
_event: ClassVar[str] = 'menu_item_click'
_rename: ClassVar[Mapping[str, str | None]] = {'name': 'label', 'items': 'menu', 'clicked': None}
_widget_type: ClassVar[Type[Model]] = _BkDropdown
def __init__(self, **params):
click_handler = params.pop('on_click', None)
super().__init__(**params)
if click_handler:
self.on_click(click_handler)
def _get_model(
self, doc: Document, root: Optional[Model] = None,
parent: Optional[Model] = None, comm: Optional[Comm] = None
) -> Model:
model = super()._get_model(doc, root, parent, comm)
self._register_events('button_click', model=model, doc=doc, comm=comm)
return model
def _process_event(self, event: ButtonClick):
if isinstance(event, MenuItemClick):
item = event.item
elif isinstance(event, ButtonClick):
item = self.name
self.clicked = item
def on_click(
self, callback: Callable[[param.parameterized.Event], None]
) -> param.parameterized.Watcher:
"""
Register a callback to be executed when the button is clicked.
The callback is given an `Event` argument declaring the number of clicks
Arguments
---------
callback: (Callable[[param.parameterized.Event], None])
The function to run on click events. Must accept a positional `Event` argument
Returns
-------
watcher: param.Parameterized.Watcher
A `Watcher` that executes the callback when the MenuButton is clicked.
"""
return self.param.watch(callback, 'clicked', onlychanged=False)