|
| 1 | +import csv |
| 2 | +import io |
| 3 | + |
| 4 | +from rich.table import Table |
| 5 | +from rich.syntax import Syntax |
| 6 | + |
| 7 | +from textual.app import App, ComposeResult |
| 8 | +from textual import events |
| 9 | +from textual.widgets import TextLog |
| 10 | + |
| 11 | + |
| 12 | +CSV = """lane,swimmer,country,time |
| 13 | +4,Joseph Schooling,Singapore,50.39 |
| 14 | +2,Michael Phelps,United States,51.14 |
| 15 | +5,Chad le Clos,South Africa,51.14 |
| 16 | +6,László Cseh,Hungary,51.14 |
| 17 | +3,Li Zhuhao,China,51.26 |
| 18 | +8,Mehdy Metella,France,51.58 |
| 19 | +7,Tom Shields,United States,51.73 |
| 20 | +1,Aleksandr Sadovnikov,Russia,51.84""" |
| 21 | + |
| 22 | + |
| 23 | +CODE = '''\ |
| 24 | +def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: |
| 25 | + """Iterate and generate a tuple with a flag for first and last value.""" |
| 26 | + iter_values = iter(values) |
| 27 | + try: |
| 28 | + previous_value = next(iter_values) |
| 29 | + except StopIteration: |
| 30 | + return |
| 31 | + first = True |
| 32 | + for value in iter_values: |
| 33 | + yield first, False, previous_value |
| 34 | + first = False |
| 35 | + previous_value = value |
| 36 | + yield first, True, previous_value\ |
| 37 | +''' |
| 38 | + |
| 39 | + |
| 40 | +class TextLogApp(App): |
| 41 | + def compose(self) -> ComposeResult: |
| 42 | + yield TextLog(highlight=True, markup=True) |
| 43 | + |
| 44 | + def on_ready(self) -> None: |
| 45 | + """Called when the DOM is ready.""" |
| 46 | + text_log = self.query_one(TextLog) |
| 47 | + |
| 48 | + text_log.write(Syntax(CODE, "python", indent_guides=True)) |
| 49 | + |
| 50 | + rows = iter(csv.reader(io.StringIO(CSV))) |
| 51 | + table = Table(*next(rows)) |
| 52 | + for row in rows: |
| 53 | + table.add_row(*row) |
| 54 | + |
| 55 | + text_log.write(table) |
| 56 | + text_log.write("[bold magenta]Write text or any Rich renderable!") |
| 57 | + |
| 58 | + def on_key(self, event: events.Key) -> None: |
| 59 | + """Write Key events to log.""" |
| 60 | + text_log = self.query_one(TextLog) |
| 61 | + text_log.write(event) |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + app = TextLogApp() |
| 66 | + app.run() |
0 commit comments