tmcode 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
termcode/modals.py ADDED
@@ -0,0 +1,431 @@
1
+ """Reusable modal dialogs for TermCode."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from rich.text import Text
8
+ from textual import events
9
+ from textual.app import ComposeResult
10
+ from textual.binding import Binding
11
+ from textual.containers import Horizontal, Vertical
12
+ from textual.screen import ModalScreen
13
+ from textual.widgets import Button, Input, Label, OptionList
14
+ from textual.widgets.option_list import Option
15
+
16
+ from termcode import theme
17
+ from termcode.commands import CommandSpec, filter_commands
18
+
19
+
20
+ def command_label(spec: CommandSpec, desc_width: int = 33) -> Text:
21
+ """One-line palette row: command, muted description, shortcut at the end."""
22
+ desc = spec.description
23
+ if len(desc) > desc_width:
24
+ desc = desc[: desc_width - 1] + "…"
25
+ row = Text(no_wrap=True, overflow="ellipsis")
26
+ row.append(f"{spec.command:<18}", theme.TEXT)
27
+ row.append(f"{desc:<{desc_width}}", theme.MUTED)
28
+ row.append(f" {spec.shortcut:>8}", theme.FAINT)
29
+ return row
30
+
31
+
32
+ class CommandPaletteModal(ModalScreen[str | None]):
33
+ """Searchable `/` action menu showing every command and its keyboard shortcut."""
34
+
35
+ BINDINGS = [
36
+ Binding("escape", "cancel", "Close", show=False),
37
+ ]
38
+
39
+ def __init__(self, initial_query: str = "/") -> None:
40
+ super().__init__()
41
+ self._initial_query = initial_query
42
+ self._filtered: list[CommandSpec] = list(filter_commands(initial_query))
43
+
44
+ def compose(self) -> ComposeResult:
45
+ with Vertical(id="palette-dialog", classes="modal-box"):
46
+ yield Label("Commands", classes="modal-title")
47
+ yield Input(
48
+ value=self._initial_query,
49
+ placeholder="/run, /save, /new-file...",
50
+ id="palette-input",
51
+ )
52
+ yield OptionList(id="palette-list")
53
+
54
+ def on_mount(self) -> None:
55
+ self._refresh_options(self._initial_query)
56
+ inp = self.query_one("#palette-input", Input)
57
+ inp.focus()
58
+ inp.cursor_position = len(inp.value)
59
+
60
+ def _refresh_options(self, query: str) -> None:
61
+ self._filtered = filter_commands(query)
62
+ option_list = self.query_one("#palette-list", OptionList)
63
+ option_list.clear_options()
64
+ for spec in self._filtered:
65
+ option_list.add_option(Option(command_label(spec), id=spec.action))
66
+ if self._filtered:
67
+ option_list.highlighted = 0
68
+
69
+ def on_input_changed(self, event: Input.Changed) -> None:
70
+ if event.input.id == "palette-input":
71
+ self._refresh_options(event.value)
72
+
73
+ def on_input_submitted(self, event: Input.Submitted) -> None:
74
+ if event.input.id == "palette-input":
75
+ self._select_highlighted()
76
+
77
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
78
+ if event.option_id is not None:
79
+ self.dismiss(str(event.option_id))
80
+
81
+ def on_key(self, event: events.Key) -> None:
82
+ option_list = self.query_one("#palette-list", OptionList)
83
+ if event.key == "down":
84
+ option_list.action_cursor_down()
85
+ event.prevent_default()
86
+ event.stop()
87
+ elif event.key == "up":
88
+ option_list.action_cursor_up()
89
+ event.prevent_default()
90
+ event.stop()
91
+
92
+ def _select_highlighted(self) -> None:
93
+ option_list = self.query_one("#palette-list", OptionList)
94
+ idx = option_list.highlighted
95
+ if idx is not None and 0 <= idx < len(self._filtered):
96
+ self.dismiss(self._filtered[idx].action)
97
+ elif self._filtered:
98
+ self.dismiss(self._filtered[0].action)
99
+ else:
100
+ self.dismiss(None)
101
+
102
+ def action_cancel(self) -> None:
103
+ self.dismiss(None)
104
+
105
+
106
+ class TextInputModal(ModalScreen[str | None]):
107
+ """Single-line text input dialog for filenames, folders, renames, and directory paths."""
108
+
109
+ BINDINGS = [
110
+ Binding("escape", "cancel", "Cancel", show=False),
111
+ ]
112
+
113
+ def __init__(
114
+ self,
115
+ title: str,
116
+ prompt: str,
117
+ initial: str = "",
118
+ placeholder: str = "",
119
+ confirm_label: str = "OK",
120
+ ) -> None:
121
+ super().__init__()
122
+ self._title = title
123
+ self._prompt = prompt
124
+ self._initial = initial
125
+ self._placeholder = placeholder
126
+ self._confirm_label = confirm_label
127
+
128
+ def compose(self) -> ComposeResult:
129
+ with Vertical(id="text-dialog", classes="modal-box"):
130
+ yield Label(self._title, classes="modal-title")
131
+ yield Label(self._prompt, classes="modal-subtitle")
132
+ yield Input(value=self._initial, placeholder=self._placeholder, id="modal-input")
133
+ with Horizontal(classes="modal-buttons"):
134
+ yield Button(self._confirm_label, variant="primary", id="ok-btn")
135
+ yield Button("Cancel", id="cancel-btn")
136
+
137
+ def on_mount(self) -> None:
138
+ inp = self.query_one("#modal-input", Input)
139
+ inp.focus()
140
+ inp.cursor_position = len(inp.value)
141
+
142
+ def on_input_submitted(self, event: Input.Submitted) -> None:
143
+ self.dismiss(event.value)
144
+
145
+ def on_button_pressed(self, event: Button.Pressed) -> None:
146
+ if event.button.id == "ok-btn":
147
+ self.dismiss(self.query_one("#modal-input", Input).value)
148
+ else:
149
+ self.dismiss(None)
150
+
151
+ def action_cancel(self) -> None:
152
+ self.dismiss(None)
153
+
154
+
155
+ class FilePickerModal(ModalScreen[Path | None]):
156
+ """Quick-open fuzzy file picker for selecting any file in the current workspace."""
157
+
158
+ BINDINGS = [
159
+ Binding("escape", "cancel", "Close", show=False),
160
+ ]
161
+
162
+ def __init__(self, root: Path, files: list[Path]) -> None:
163
+ super().__init__()
164
+ self._root = root
165
+ self._all_files = files
166
+ self._filtered: list[Path] = list(files)
167
+
168
+ def compose(self) -> ComposeResult:
169
+ with Vertical(id="picker-dialog", classes="modal-box"):
170
+ yield Label(f"Open a file in {self._root.name}", classes="modal-title")
171
+ yield Input(placeholder="Type part of a file name or path", id="picker-input")
172
+ yield OptionList(id="picker-list")
173
+
174
+ def on_mount(self) -> None:
175
+ self._refresh_options("")
176
+ self.query_one("#picker-input", Input).focus()
177
+
178
+ def _rel_label(self, path: Path) -> str:
179
+ try:
180
+ return path.relative_to(self._root).as_posix()
181
+ except ValueError:
182
+ return str(path)
183
+
184
+ def _refresh_options(self, query: str) -> None:
185
+ needle = query.strip().lower()
186
+ if not needle:
187
+ self._filtered = list(self._all_files)
188
+ else:
189
+ self._filtered = [
190
+ p for p in self._all_files if needle in self._rel_label(p).lower()
191
+ ]
192
+ option_list = self.query_one("#picker-list", OptionList)
193
+ option_list.clear_options()
194
+ for idx, path in enumerate(self._filtered):
195
+ option_list.add_option(Option(self._rel_label(path), id=str(idx)))
196
+ if self._filtered:
197
+ option_list.highlighted = 0
198
+
199
+ def on_input_changed(self, event: Input.Changed) -> None:
200
+ if event.input.id == "picker-input":
201
+ self._refresh_options(event.value)
202
+
203
+ def on_input_submitted(self, event: Input.Submitted) -> None:
204
+ if event.input.id == "picker-input":
205
+ self._select_highlighted()
206
+
207
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
208
+ if event.option_id is not None:
209
+ idx = int(event.option_id)
210
+ if 0 <= idx < len(self._filtered):
211
+ self.dismiss(self._filtered[idx])
212
+
213
+ def on_key(self, event: events.Key) -> None:
214
+ option_list = self.query_one("#picker-list", OptionList)
215
+ if event.key == "down":
216
+ option_list.action_cursor_down()
217
+ event.prevent_default()
218
+ event.stop()
219
+ elif event.key == "up":
220
+ option_list.action_cursor_up()
221
+ event.prevent_default()
222
+ event.stop()
223
+
224
+ def _select_highlighted(self) -> None:
225
+ option_list = self.query_one("#picker-list", OptionList)
226
+ idx = option_list.highlighted
227
+ if idx is not None and 0 <= idx < len(self._filtered):
228
+ self.dismiss(self._filtered[idx])
229
+ elif self._filtered:
230
+ self.dismiss(self._filtered[0])
231
+ else:
232
+ self.dismiss(None)
233
+
234
+ def action_cancel(self) -> None:
235
+ self.dismiss(None)
236
+
237
+
238
+ class ConfirmModal(ModalScreen[bool]):
239
+ """Confirmation dialog for destructive actions such as deleting files or folders."""
240
+
241
+ BINDINGS = [
242
+ Binding("escape", "cancel", "Cancel", show=False),
243
+ ]
244
+
245
+ def __init__(self, title: str, message: str, confirm_label: str = "Delete") -> None:
246
+ super().__init__()
247
+ self._title = title
248
+ self._message = message
249
+ self._confirm_label = confirm_label
250
+
251
+ def compose(self) -> ComposeResult:
252
+ with Vertical(id="confirm-dialog", classes="modal-box"):
253
+ yield Label(self._title, classes="modal-title")
254
+ yield Label(self._message, classes="modal-subtitle")
255
+ with Horizontal(classes="modal-buttons"):
256
+ yield Button(self._confirm_label, variant="error", id="confirm-btn")
257
+ yield Button("Cancel", id="cancel-btn")
258
+
259
+ def on_mount(self) -> None:
260
+ self.query_one("#cancel-btn", Button).focus()
261
+
262
+ def on_button_pressed(self, event: Button.Pressed) -> None:
263
+ self.dismiss(event.button.id == "confirm-btn")
264
+
265
+ def action_cancel(self) -> None:
266
+ self.dismiss(False)
267
+
268
+
269
+ class UnsavedChangesModal(ModalScreen[str]):
270
+ """Three-way confirmation when leaving a buffer with unsaved changes."""
271
+
272
+ BINDINGS = [
273
+ Binding("escape", "cancel", "Cancel", show=False),
274
+ ]
275
+
276
+ def __init__(self, filename: str) -> None:
277
+ super().__init__()
278
+ self._filename = filename
279
+
280
+ def compose(self) -> ComposeResult:
281
+ with Vertical(id="unsaved-dialog", classes="modal-box"):
282
+ yield Label("Unsaved changes", classes="modal-title")
283
+ yield Label(
284
+ f"Save changes to '{self._filename}' before continuing?",
285
+ classes="modal-subtitle",
286
+ )
287
+ with Horizontal(classes="modal-buttons"):
288
+ yield Button("Save", variant="primary", id="save-btn")
289
+ yield Button("Discard", variant="error", id="discard-btn")
290
+ yield Button("Cancel", id="cancel-btn")
291
+
292
+ def on_mount(self) -> None:
293
+ self.query_one("#save-btn", Button).focus()
294
+
295
+ def on_button_pressed(self, event: Button.Pressed) -> None:
296
+ if event.button.id == "save-btn":
297
+ self.dismiss("save")
298
+ elif event.button.id == "discard-btn":
299
+ self.dismiss("discard")
300
+ else:
301
+ self.dismiss("cancel")
302
+
303
+ def action_cancel(self) -> None:
304
+ self.dismiss("cancel")
305
+
306
+
307
+ class FolderPickerModal(ModalScreen[Path | None]):
308
+ """Interactive VS Code-style folder browser and path selector."""
309
+
310
+ BINDINGS = [
311
+ Binding("escape", "cancel", "Cancel", show=False),
312
+ ]
313
+
314
+ def __init__(self, start_dir: Path | None = None) -> None:
315
+ super().__init__()
316
+ initial = start_dir if (start_dir and start_dir.is_dir()) else Path.home()
317
+ self._current: Path = initial.resolve()
318
+ self._entries: list[Path] = []
319
+
320
+ def compose(self) -> ComposeResult:
321
+ home = Path.home()
322
+ quick_places: list[tuple[str, str, Path]] = [("quick-home", "~ Home", home)]
323
+ for label_name in ("Documents", "Desktop", "Projects"):
324
+ candidate = home / label_name
325
+ if candidate.is_dir():
326
+ quick_places.append((f"quick-{label_name.lower()}", label_name, candidate))
327
+ self._quick_map: dict[str, Path] = {btn_id: p for btn_id, _, p in quick_places}
328
+
329
+ with Vertical(id="folder-dialog", classes="modal-box"):
330
+ yield Label("Open folder", classes="modal-title", markup=False)
331
+ yield Input(
332
+ value=str(self._current),
333
+ placeholder="Type a path, or pick a folder below",
334
+ id="folder-path-input",
335
+ )
336
+ with Horizontal(classes="quick-bar"):
337
+ yield Button("↑ Up", id="quick-up", classes="quick-btn")
338
+ for btn_id, label, _ in quick_places:
339
+ yield Button(label, id=btn_id, classes="quick-btn")
340
+ yield OptionList(id="folder-list")
341
+ with Horizontal(classes="modal-buttons"):
342
+ yield Button("Open this folder", variant="primary", id="open-folder-btn")
343
+ yield Button("Cancel", id="cancel-btn")
344
+
345
+ def on_mount(self) -> None:
346
+ self._load_directory(self._current)
347
+ self.query_one("#folder-list", OptionList).focus()
348
+
349
+ def _load_directory(self, directory: Path) -> None:
350
+ self._current = directory.resolve()
351
+ path_input = self.query_one("#folder-path-input", Input)
352
+ path_input.value = str(self._current)
353
+
354
+ option_list = self.query_one("#folder-list", OptionList)
355
+ option_list.clear_options()
356
+ self._entries = []
357
+
358
+ if self._current.parent != self._current:
359
+ self._entries.append(self._current.parent)
360
+ option_list.add_option(Option(Text("↑ .. parent folder", style=theme.MUTED), id="0"))
361
+
362
+ try:
363
+ subdirs = sorted(
364
+ (
365
+ p
366
+ for p in self._current.iterdir()
367
+ if p.is_dir() and not p.name.startswith(".")
368
+ ),
369
+ key=lambda p: p.name.lower(),
370
+ )
371
+ except OSError:
372
+ subdirs = []
373
+
374
+ for subdir in subdirs:
375
+ idx = len(self._entries)
376
+ self._entries.append(subdir)
377
+ option_list.add_option(Option(f"{subdir.name}/", id=str(idx)))
378
+
379
+ if self._entries:
380
+ option_list.highlighted = 0
381
+
382
+ def _resolve_input_path(self) -> Path | None:
383
+ raw = self.query_one("#folder-path-input", Input).value.strip()
384
+ if not raw:
385
+ return self._current
386
+ candidate = Path(raw).expanduser()
387
+ if not candidate.is_absolute():
388
+ candidate = self._current / candidate
389
+ try:
390
+ resolved = candidate.resolve()
391
+ except OSError:
392
+ return None
393
+ return resolved if resolved.is_dir() else None
394
+
395
+ def on_input_submitted(self, event: Input.Submitted) -> None:
396
+ if event.input.id != "folder-path-input":
397
+ return
398
+ resolved = self._resolve_input_path()
399
+ if resolved is None:
400
+ self.app.notify(f"Folder not found: {event.value}", severity="error")
401
+ return
402
+ if resolved == self._current:
403
+ self.dismiss(resolved)
404
+ else:
405
+ self._load_directory(resolved)
406
+
407
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
408
+ if event.option_id is None:
409
+ return
410
+ idx = int(event.option_id)
411
+ if 0 <= idx < len(self._entries):
412
+ self._load_directory(self._entries[idx])
413
+
414
+ def on_button_pressed(self, event: Button.Pressed) -> None:
415
+ btn_id = event.button.id or ""
416
+ if btn_id == "open-folder-btn":
417
+ resolved = self._resolve_input_path()
418
+ if resolved is None:
419
+ self.app.notify("Enter a valid existing folder path.", severity="error")
420
+ return
421
+ self.dismiss(resolved)
422
+ elif btn_id == "cancel-btn":
423
+ self.dismiss(None)
424
+ elif btn_id == "quick-up":
425
+ if self._current.parent != self._current:
426
+ self._load_directory(self._current.parent)
427
+ elif btn_id in self._quick_map:
428
+ self._load_directory(self._quick_map[btn_id])
429
+
430
+ def action_cancel(self) -> None:
431
+ self.dismiss(None)