-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path_select.py
337 lines (280 loc) · 10.3 KB
/
_select.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
from __future__ import annotations
from textual.widget import Widget, events
from textual.containers import Vertical
from textual.widgets import Label, ListView, ListItem, Input
from textual.reactive import reactive
from textual.message import Message
from rich.highlighter import Highlighter
# from textual import log
class SelectListSearchInput(Input):
"""Input for searching through the list."""
DEFAULT_CSS = """
SelectListSearchInput {
border: none;
background: transparent;
border-bottom: tall $background;
}
SelectListSearchInput:focus {
border: none;
border-bottom: tall $accent;
}
"""
def __init__(
self,
select_list: SelectList,
value: str | None = None,
placeholder: str = "",
name: str | None = None,
id: str | None = None,
classes: str | None = None,
) -> None:
super().__init__(
value=value, placeholder=placeholder, name=name, id=id, classes=classes
)
self.select_list = select_list
def watch_value(self, value):
self.select_list.list_view.clear()
self.select_list.items_filtered = []
for item in self.select_list.items:
if value.lower() in item["text"].lower():
self.select_list.list_view.append(ListItem(Label(item["text"])))
self.select_list.items_filtered.append(item)
def action_scroll_down(self) -> None:
self.select_list.list_view.action_cursor_down()
def action_scroll_up(self) -> None:
self.select_list.list_view.action_cursor_up()
def on_blur(self) -> None:
self.select_list.display = False
self.value = ""
class SelectListView(ListView):
"""The ListView inside the SelectList which closes the list on blur."""
def __init__(
self,
*children: ListItem,
select_list: SelectList,
initial_index: int | None = 0,
name: str | None = None,
id: str | None = None,
classes: str | None = None,
) -> None:
super().__init__(
*children, initial_index=initial_index, name=name, id=id, classes=classes
)
self.select_list = select_list
def on_blur(self) -> None:
self.select_list.display = False
def on_list_item__child_clicked(self, event: ListItem._ChildClicked) -> None:
super().on_list_item__child_clicked(event)
self.select_list.select_highlighted_item()
self.select_list.display = False
class SelectList(Widget):
"""The dropdown list which is opened at the input."""
DEFAULT_CSS = """
SelectList {
layer: dialog;
background: $boost;
border: tall $accent;
display: none;
}
SelectList.--search ListView {
padding-top: 1;
}
SelectList ListItem {
background: transparent;
padding: 0 2;
}
SelectList ListItem:hover {
background: $boost;
}
SelectList ListView:focus > ListItem.--highlight {
}
SelectList SelectListSearchInput {
border: none;
border-bottom: wide $panel;
}
"""
def __init__(
self,
select: Select,
items: list,
*children: Widget,
search: bool | None = False,
name: str | None = None,
id: str | None = None,
classes: str | None = None,
) -> None:
if search:
# when a search is there, add a class for pad-top the list
classes = f"{str(classes)} --search"
super().__init__(name=name, id=id, classes=classes)
self.select = select
self.items = items
self.items_filtered = items
self.search = search
def compose(self):
widgets = []
list_items = []
for item in self.items:
list_items.append(ListItem(Label(item["text"])))
self.list_view = SelectListView(*list_items, select_list=self)
if self.search:
widgets.append(SelectListSearchInput(select_list=self))
widgets.append(self.list_view)
yield Vertical(*widgets)
def on_key(self, event: events.Key) -> None:
# NOTE: the message ListView.Selected has drawbacks, we can't use:
# * emitted when opened drop-down list
# * not emitted, when enter pressed on the initially highlighted ListItem
# * emitted on single click (can be ok, but would close immediately)
if event.key == "enter":
self.select_highlighted_item()
self.display = False
self.select.focus()
if event.key == "tab" or event.key == "shift+tab":
# suppress tab (blur) when drop-down is open.
# looks like Gtk is handling it the same.
event.prevent_default()
def select_highlighted_item(self) -> None:
if self.list_view.index is not None:
# index can be None, if a search results in no entries
# => do not change select value in this case
self.select.text = self.items_filtered[self.list_view.index]["text"]
self.select.value = self.items_filtered[self.list_view.index]["value"]
class Select(Widget, can_focus=True):
"""A select widget with a drop-down."""
# TODO: validate given items (list of dicts not like value, text)
# OPTIMIZE: when empty, show dimmed text (e.g. "no entries")
# OPTIMIZE: get rid of self.app.query_one(self.list_mount)
# OPTIMIZE: option: individual height
# OPTIMIZE: mini-bug: resize not nice when opened (edge case...)
# OPTIMIZE: auto-select by key-press without search? (hard)
DEFAULT_CSS = """
Select {
background: $boost;
color: $text;
padding: 0 2;
border: tall $background;
height: 1;
min-height: 1;
}
Select:focus {
border: tall $accent;
}
"""
value = reactive("", layout=True, init=False)
def __init__(
self,
items: list,
list_mount: str,
search: bool | None = False,
value: str | None = None,
placeholder: str = "",
highlighter: Highlighter | None = None,
name: str | None = None,
id: str | None = None,
classes: str | None = None,
) -> None:
self.select_classes = classes
super().__init__(name=name, id=id, classes=classes)
if value is not None:
self.value = value
self.placeholder = placeholder
self.items = items
self.list_mount = list_mount
self.highlighter = highlighter
self.search = search
# SelectList widget
self.select_list = None
# The selected text
self.text = ""
# there is a value, find the text to display
if self.value:
for item in self.items:
if str(item["value"]) == str(self.value):
self.text = item["text"]
break
def render(self) -> str:
chevron = "\u25bc"
width = self.content_size.width
text_space = width - 2
if text_space < 0:
text_space = 0
if not self.text:
text = self.placeholder
else:
text = self.text
if len(text) > text_space:
text = text[0:text_space]
text = f"{text:{text_space}} {chevron}"
return text
def on_mount(self):
# NOTE: mount-point for list is mandatory for the time beeing
#
# possibility to automatically find mount point of the drop-down list:
# * find an ancestor, which's height is greater than the lists height
# * if it fails (screen size too small, container too small), take
# screen container
#
# pseudo code:
# for ancestor in self.ancestors:
# if issubclass(ancestor.__class__, Widget):
# it's a normal widget
# else if issubclass(..., App):
# use this child...
if self.select_list is None:
self.select_list = SelectList(
select=self,
items=self.items,
search=self.search,
classes=self.select_classes,
)
self.app.query_one(self.list_mount).mount(self.select_list)
def on_key(self, event: events.Key) -> None:
if event.key == "enter":
self._show_select_list()
def on_click(self, event: events.MouseEvent) -> None:
self._show_select_list()
def _show_select_list(self) -> None:
mnt_widget = self.app.query_one(self.list_mount)
self.select_list.display = True
self.select_list.styles.width = self.outer_size.width
# OPTIMIZE: this could be done more configurable
default_height = 5
if self.search:
default_height = 8
if self.select_list.styles.height is None:
self.select_list.styles.height = default_height
if self.select_list.styles.min_height is None:
self.select_list.styles.min_height = default_height
if len(self.items) < 5:
height = max(1, len(self.items))
self.select_list.styles.height = height
self.select_list.styles.min_height = height
# calculate the offset by using the mount-point's offset:
# setting the offset directly from self.region (Select widget)
# has the header *not* included, therefore we need to subtract
# the mount-point's offset.
#
# further explanation (or assumption):
# it looks like the mount point has a relative offset, e.g. below
# the header. setting the offset of the list directly seams to be
# absolute.
self.select_list.offset = self.region.offset - mnt_widget.content_region.offset
if self.search:
self.select_list.query_one("SelectListSearchInput").focus()
else:
self.select_list.query("ListView").first().focus()
def on_blur(self) -> None:
pass
async def watch_value(self, value: str) -> None:
if value is None:
self.text = ""
self.select_list.list_view.index = 0
self.refresh(layout=True)
await self.post_message(self.Changed(self, value))
class Changed(Message, bubble=True):
"""Value was changed."""
def __init__(self, sender: Select, value: str) -> None:
super().__init__(sender)
self.value = value
self.select = sender