-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_paste_button.py
178 lines (141 loc) · 5.54 KB
/
_paste_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
import logging
from io import StringIO
from typing import TYPE_CHECKING
import panel as pn
import param
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
import pandas as pd
def do_nothing(self, data: str) -> str:
"""Return the data."""
return data
def read_csv(self, data: str) -> "pd.DataFrame":
"""Return the data as a DataFrame."""
import pandas as pd
if not data:
return pd.DataFrame()
decimal = self.decimal_separator or "."
return pd.read_csv(StringIO(data), sep="\t", decimal=decimal)
class PasteButtonBase(pn.custom.JSComponent):
"""A custom Panel widget to paste a value from the clipboard onto an optional target."""
data = param.String(default="", doc="""The string value transferred from the clip board.""")
button = pn.custom.Child(constant=True, doc="""A custom Button or ButtonIcon to use.""")
target = param.Parameter(
doc="""If a widget its value is set to value when it changes. If a Pane its object will be
set to the value. If a callable the callable will be executed on the value.""",
allow_refs=False,
)
_transform_func = do_nothing
_DEFAULT_BUTTON = pn.widgets.ButtonIcon(description="Paste from clipboard.", icon="clipboard", active_icon="check", toggle_duration=1500)
_rename = {"value": None, "target": None}
_esm = """
export function render({ model, el }) {
const button = model.get_child("button")
el.appendChild(button)
button.addEventListener('click', (event) => {
navigator.clipboard.readText()
.then(pastedData => {
if (model.data==pastedData){
model.data=pastedData + " ";
} else {
model.data = pastedData;
}
})
});
}
"""
def __init__(self, **params):
if "button" not in params:
params["button"] = self._get_new_button()
self._transform_func = params.pop("_transform_func", self._transform_func) # type: ignore[method-assign]
super().__init__(**params)
@classmethod
def _get_new_button(cls):
return cls._DEFAULT_BUTTON.clone()
@param.depends("data", watch=True)
def _handle_data(self):
self.value = self._transform_func(self.data)
if self.target:
self._set_target_value(self.target, self.value)
@staticmethod
def _set_target_value(target, value):
if callable(target):
target(value)
elif hasattr(target, "object"):
target.object = value
elif hasattr(target, "value"):
target.value = value
else:
msg = f"Target of type '{type(target)}' is not supported."
logger.error(msg)
class PasteButton(PasteButtonBase):
"""
A Custom Panel widget to paste a string value from the clipboard.
Examples
--------
>>> import panel as pn
>>> from panel_copy_paste import PasteButton
>>> pn.extension("codeeditor")
>>> editor = pn.widgets.CodeEditor()
>>> button = PasteButton(target=editor)
>>> pn.Column(button, editor).servable()
"""
value = param.String(default="", doc="""The value from the clip board as a string.""")
button = pn.custom.Child(constant=True, doc="""An optional custom Button or ButtonIcon to use.""")
target = param.Parameter(
doc="""If a widget its value is set to value when it changes. If a Pane its object will be
set to the value. If a callable the callable will be executed on the value.""",
allow_refs=False,
)
_transform_func = do_nothing
class PasteToDataFrameButton(PasteButtonBase):
"""
A Custom Panel widget to paste a tab separated string from the clipboard into a Pandas DataFrame.
Examples
--------
>>> import panel as pn
>>> from panel_copy_paste import PasteToDataFrameButton
>>> pn.extension("tabulator")
>>> table = pn.widgets.Tabulator()
>>> button = PasteToDataFrameButton(target=table)
>>> pn.Column(button, table).servable()
"""
_esm = """
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithDecimalSeparator)
.find(part => part.type === 'decimal')
.value;
}
export function render({ model, el }) {
const button = model.get_child("button")
el.appendChild(button)
if (model._decimal_separator === null) {
model.decimal_separator = getDecimalSeparator();
}
button.addEventListener('click', (event) => {
navigator.clipboard.readText()
.then(pastedData => {
if (model.data==pastedData){
model.data=pastedData + " ";
} else {
model.data = pastedData;
}
})
});
}
"""
value = param.DataFrame(doc="""The value from the clip board as a Pandas DataFrame.""")
button = pn.custom.Child(constant=True, doc="""A custom Button or ButtonIcon to use.""")
target = param.Parameter(
doc="""If a widget its value is set to value when it changes. If a Pane its object will be
set to the value. If a callable the callable will be executed on the value.""",
allow_refs=False,
)
decimal_separator = param.Selector(
default=None,
objects=[None, ".", ","],
doc="""The decimal symbol used when transforming a DataFrame. If not provided set to the decimal symbol of the client.""",
)
_transform_func = read_csv