-
Notifications
You must be signed in to change notification settings - Fork 786
/
code_browser.py
76 lines (60 loc) · 2.1 KB
/
code_browser.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
"""
Code browser example.
Run with:
python code_browser.py PATH
"""
import sys
from rich.syntax import Syntax
from rich.traceback import Traceback
from textual.app import App, ComposeResult
from textual.containers import Container, VerticalScroll
from textual.reactive import var
from textual.widgets import DirectoryTree, Footer, Header, Static
class CodeBrowser(App):
"""Textual code browser app."""
CSS_PATH = "code_browser.tcss"
BINDINGS = [
("f", "toggle_files", "Toggle Files"),
("q", "quit", "Quit"),
]
show_tree = var(True)
def watch_show_tree(self, show_tree: bool) -> None:
"""Called when show_tree is modified."""
self.set_class(show_tree, "-show-tree")
def compose(self) -> ComposeResult:
"""Compose our UI."""
path = "./" if len(sys.argv) < 2 else sys.argv[1]
yield Header()
with Container():
yield DirectoryTree(path, id="tree-view")
with VerticalScroll(id="code-view"):
yield Static(id="code", expand=True)
yield Footer()
def on_mount(self) -> None:
self.query_one(DirectoryTree).focus()
def on_directory_tree_file_selected(
self, event: DirectoryTree.FileSelected
) -> None:
"""Called when the user click a file in the directory tree."""
event.stop()
code_view = self.query_one("#code", Static)
try:
syntax = Syntax.from_path(
str(event.path),
line_numbers=True,
word_wrap=False,
indent_guides=True,
theme="github-dark",
)
except Exception:
code_view.update(Traceback(theme="github-dark", width=None))
self.sub_title = "ERROR"
else:
code_view.update(syntax)
self.query_one("#code-view").scroll_home(animate=False)
self.sub_title = str(event.path)
def action_toggle_files(self) -> None:
"""Called in response to key binding."""
self.show_tree = not self.show_tree
if __name__ == "__main__":
CodeBrowser().run()