Skip to content

Instantly share code, notes, and snippets.

@paulrobello
Last active August 15, 2024 18:12
Show Gist options
  • Save paulrobello/0a2f807ddd195c42f87cec9ff5825ac8 to your computer and use it in GitHub Desktop.
Save paulrobello/0a2f807ddd195c42f87cec9ff5825ac8 to your computer and use it in GitHub Desktop.
textual tab change detect
"""MRE for Textual"""
from __future__ import annotations
import http
import requests
from textual import on, work
from textual.app import App, ComposeResult
from textual.message import Message
from textual.screen import Screen
from textual.widgets import (
Header,
Footer,
TabbedContent,
TabPane,
Placeholder,
MarkdownViewer,
)
class DataLoaded(Message):
"""Data loaded message"""
class LazyTab(TabPane):
"""Lazy tab"""
url: str
data: str = ""
def __init__(self, url: str, **kwargs) -> None:
"""Initialise the tab"""
super().__init__(**kwargs)
self.url = url
self.loading = True
def compose(self) -> ComposeResult:
self.loading = not self.data
yield MarkdownViewer(self.data)
@work
async def get_data(self):
"""Fetch data from URL"""
response = requests.get(self.url, timeout=10)
self.data = response.text
self.post_message(DataLoaded())
async def on_data_loaded(self, msg: DataLoaded) -> None:
msg.stop()
await self.recompose()
def on_show(self):
"""Load Data"""
self.get_data()
class MainScreen(Screen[None]):
"""Main screen"""
DEFAULT_CSS = """
Placeholder {
width: 1fr;
height: 1fr;
}
"""
def __init__(self) -> None:
"""Initialise the screen."""
super().__init__()
def compose(self) -> ComposeResult:
"""Compose the screen"""
yield Header()
yield Footer()
with TabbedContent(id="tabbed_content"):
with LazyTab(
title="Tab 1",
id="tab1",
url="https://raw.githubusercontent.com/paulrobello/parllama/main/README.md",
):
yield Placeholder("Tab 1")
with LazyTab(
title="Tab 2",
id="tab2",
url="https://raw.githubusercontent.com/paulrobello/parllama/main/README.md",
):
yield Placeholder("Tab 2")
with LazyTab(
title="Tab 3",
id="tab3",
url="https://raw.githubusercontent.com/paulrobello/parllama/main/README.md",
):
yield Placeholder("Tab 3")
@on(TabbedContent.TabActivated)
def on_tab_activated(self, msg: TabbedContent.TabActivated) -> None:
"""Tab activated event"""
msg.stop()
self.notify(f"tab activated: {msg.tab.label.plain}")
class MyApp(App[None]):
"""App to test Textual stuff"""
def __init__(self) -> None:
"""Initialise the app."""
super().__init__()
self.main_screen = MainScreen()
async def on_mount(self) -> None:
"""Mount the screen."""
await self.push_screen(self.main_screen)
if __name__ == "__main__":
MyApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment