File size: 1,979 Bytes
2c3c408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from pathlib import Path
from typing import Iterable

from rich.console import RenderableType
from rich.table import Table
from rich.text import Text

from textual.app import App
from textual.geometry import Size
from textual.reactive import Reactive
from textual.widget import Widget
from textual.widgets._input import Input


def get_files() -> list[Path]:
    files = list(Path.cwd().iterdir())
    return files


class FileTable(Widget):
    filter = Reactive("", layout=True)

    def __init__(self, *args, files: Iterable[Path] | None = None, **kwargs):
        super().__init__(*args, **kwargs)
        self.files = files if files is not None else []

    @property
    def filtered_files(self) -> list[Path]:
        return [
            file
            for file in self.files
            if self.filter == "" or (self.filter and self.filter in file.name)
        ]

    def get_content_height(self, container: Size, viewport: Size, width: int) -> int:
        return len(self.filtered_files)

    def render(self) -> RenderableType:
        grid = Table.grid()
        grid.add_column()
        for file in self.filtered_files:
            file_text = Text(f" {file.name}")
            if self.filter:
                file_text.highlight_regex(self.filter, "black on yellow")
            grid.add_row(file_text)
        return grid


class FileSearchApp(App):
    dark = True

    def on_mount(self) -> None:
        self.file_table = FileTable(id="file_table", files=list(Path.cwd().iterdir()))
        self.search_bar = Input(placeholder="Search for files...")
        # self.search_bar.focus()
        self.mount(search_bar=self.search_bar)
        self.mount(file_table_wrapper=Widget(self.file_table))

    def on_input_changed(self, event: Input.Changed) -> None:
        self.file_table.filter = event.value


app = FileSearchApp(css_path="file_search.scss", watch_css=True)

if __name__ == "__main__":
    result = app.run()