repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
textual | tests/snapshot_tests/snapshot_apps/modified_tabs.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Button, TabbedContent
class FiddleWithTabsApp(App[None]):
CSS = """
TabPane:disabled {
background: red;
}
"""
def compose(self) -> ComposeResult:
with TabbedContent():
yield Button()
yie... | 28 | 679 |
textual | tests/snapshot_tests/snapshot_apps/footer_classic_styling.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Footer
class ClassicFooterStylingApp(App):
"""
This app attempts to replicate the styling of the classic footer in
Textual before v0.63.0, in particular the distinct background color
for the binding keys and spacing between the key... | 46 | 1,067 |
textual | tests/snapshot_tests/snapshot_apps/width_100.py | .py | from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import Label
class Width100PCentApp(App[None]):
CSS = """
Vertical {
border: solid red;
width: auto;
Label {
border: solid green;
}
#first {
... | 37 | 735 |
textual | tests/snapshot_tests/snapshot_apps/text_area_alternate_screen.py | .py | from textual.app import App
from textual.screen import Screen
from textual.widgets import TextArea
TEXT = """\
foo
bar
baz
"""
class AltScreen(Screen[None]):
def compose(self):
yield TextArea(TEXT)
class TABug(App[None]):
def on_mount(self):
self.push_screen(AltScreen())
if __name__ == "_... | 25 | 362 |
textual | tests/snapshot_tests/snapshot_apps/ansi_mapping.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label
class AnsiMappingApp(App[None]):
def compose(self) -> ComposeResult:
ansi_colors = [
"ansi_red",
"ansi_green",
"ansi_yellow",
"ansi_blue",
"ansi_magenta",
"a... | 27 | 704 |
textual | tests/snapshot_tests/snapshot_apps/dock_scroll.py | .py | from textual.app import App
from textual.widgets import Header, Label, Footer
class TestApp(App):
BINDINGS = [("ctrl+q", "app.quit", "Quit")]
CSS = """
Label {
border: solid red;
}
Footer {
height: 4;
}
"""
def compose(self):
text = (
"this is ... | 29 | 531 |
textual | tests/snapshot_tests/snapshot_apps/capture_print.py | .py | from textual.app import App, ComposeResult
from textual import events
from textual.widgets import RichLog
class PrintLogger(RichLog):
"""A RichLog which captures printed text."""
def on_print(self, event: events.Print) -> None:
self.write(event.text)
class CaptureApp(App):
def compose(self) -> ... | 28 | 702 |
textual | tests/snapshot_tests/snapshot_apps/grid_auto.py | .py | from textual.app import App, ComposeResult
from textual.containers import Grid
from textual.widgets import Placeholder
class KeylineApp(App):
CSS = """
Grid {
grid-size: 3 3;
grid-gutter: 1;
grid-columns: 2;
grid-rows: 1;
keyline: thin;
width: auto;
heig... | 35 | 799 |
textual | tests/snapshot_tests/snapshot_apps/programmatic_scrollbar_gutter_change.py | .py | from textual.app import App
from textual.containers import Grid
from textual.widgets import Label
class ProgrammaticScrollbarGutterChange(App[None]):
CSS = """
Grid { grid-size: 2 2; scrollbar-size: 5 5; }
Label { width: 100%; height: 100%; background: red; }
"""
def compose(self):
yield ... | 28 | 659 |
textual | tests/snapshot_tests/snapshot_apps/fr_with_min.py | .py | from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical, VerticalScroll
from textual.widgets import Header, Footer, Static
class ScreenSplitApp(App[None]):
CSS = """
Horizontal {
width: 1fr;
}
Vertical {
width: 1fr;
background: bl... | 51 | 1,129 |
textual | tests/snapshot_tests/snapshot_apps/text_area.py | .py | """Tests the rendering of the TextArea for all supported languages."""
from textual.app import App, ComposeResult
from textual.widgets import TextArea
class TextAreaSnapshot(App):
def compose(self) -> ComposeResult:
text_area = TextArea.code_editor()
text_area.cursor_blink = False
yield te... | 16 | 396 |
textual | tests/snapshot_tests/snapshot_apps/data_table_column_cursor.py | .py | import csv
import io
from textual.app import App, ComposeResult
from textual.widgets import DataTable
CSV = """lane,swimmer,country,time
4,Joseph Schooling,Singapore,50.39
2,Michael Phelps,United States,51.14
5,Chad le Clos,South Africa,51.14
6,László Cseh,Hungary,51.14
3,Li Zhuhao,China,51.26
8,Mehdy Metella,France,... | 37 | 883 |
textual | tests/snapshot_tests/snapshot_apps/auto_grid.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label, Input
from textual.containers import Container
class GridApp(App):
CSS = """
Screen {
align: center middle;
}
Container {
layout: grid;
grid-size: 2;
grid-columns: auto 1fr;
grid-rows:... | 53 | 1,093 |
textual | tests/snapshot_tests/snapshot_apps/auto_tab_active.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Button, Footer, TabbedContent, TabPane
class ExampleApp(App):
BINDINGS = [("space", "focus_button_2_2", "Focus button 2.2")]
def compose(self) -> ComposeResult:
with TabbedContent(id="tabbed-root"):
with TabPane("[ansi... | 37 | 1,361 |
textual | tests/snapshot_tests/snapshot_apps/fr_units.py | .py | from textual.app import App, ComposeResult
from textual.containers import Horizontal, VerticalScroll
from textual.widgets import Static
class StaticText(Static):
pass
class FRApp(App):
CSS = """
StaticText {
height: 1fr;
background: $boost;
border: heavy white;
}
#foo {
... | 55 | 964 |
textual | tests/snapshot_tests/snapshot_apps/tabbed_content_style_leak_test.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Button, Label, TabbedContent, Tabs, TabPane
class TabbedContentStyleLeakTestApp(App[None]):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("Leak Test"):
yield Label("This label should... | 15 | 537 |
textual | tests/snapshot_tests/snapshot_apps/remove_auto.py | .py | from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import Header, Footer, Label
class VerticalRemoveApp(App[None]):
CSS = """
Vertical {
border: round green;
height: auto;
}
Label {
border: round yellow;
background: ... | 39 | 862 |
textual | tests/snapshot_tests/snapshot_apps/log_write.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Log
from textual.containers import Horizontal
class LogApp(App):
def compose(self) -> ComposeResult:
yield Log()
def on_ready(self) -> None:
log = self.query_one(Log)
log.write("Hello,")
log.write(" World")... | 23 | 489 |
textual | tests/snapshot_tests/snapshot_apps/directory_tree_reload.py | .py | from pathlib import Path
from textual.app import App, ComposeResult
from textual.widgets import DirectoryTree
class DirectoryTreeReloadApp(App[None]):
BINDINGS = [
("r", "reload"),
("e", "expand"),
("d", "delete"),
]
async def setup(self, path_root: Path) -> None:
self.pa... | 59 | 1,603 |
textual | tests/snapshot_tests/snapshot_apps/multi_keys.py | .py | from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widgets import Footer
class MApp(App):
BINDINGS = [Binding("o,ctrl+o", "options", "Options")]
def compose(self) -> ComposeResult:
yield Footer()
if __name__ == "__main__":
MApp().run()
| 12 | 299 |
textual | tests/snapshot_tests/snapshot_apps/notification_with_inline_link.py | .py | from textual.app import App
class NotifyWithInlineLinkApp(App):
def on_mount(self) -> None:
self.notify("Click [@click=bell]here[/] for the bell sound.")
if __name__ == "__main__":
app = NotifyWithInlineLinkApp()
app.run()
| 12 | 247 |
textual | tests/snapshot_tests/snapshot_apps/tab_rename.py | .py | from textual.app import App, ComposeResult
from textual.widgets import TabbedContent, TabPane
class TabRenameApp(App[None]):
def compose(self) -> ComposeResult:
with TabbedContent():
yield TabPane("!", id="test")
for n in range(5):
yield TabPane(str(n) * (n+1))
... | 17 | 506 |
textual | tests/snapshot_tests/snapshot_apps/line_api_scrollbars.py | .py | from rich.text import Text
from textual.app import App, ComposeResult
from textual.containers import VerticalScroll
from textual.widget import Widget
from textual.widgets import RichLog
class MyWidget(Widget):
def render(self):
return Text(
"\n".join(f"{n} 0123456789" for n in range(20)),
... | 55 | 1,108 |
textual | tests/snapshot_tests/snapshot_apps/nested_fr.py | .py | from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import Static
class AutoApp(App):
"""The innermost container should push its parents outwards, to fill the screen."""
CSS = """
#outer {
background: blue;
height: auto;
border: ... | 40 | 857 |
textual | tests/snapshot_tests/snapshot_apps/select_rebuild.py | .py | """Test https://github.com/Textualize/textual/issues/2557"""
from textual.app import App, ComposeResult
from textual.widgets import Select, Button
class SelectRebuildApp(App[None]):
def compose(self) -> ComposeResult:
yield Select[int]((("1", 1), ("2", 2)))
yield Button("Rebuild")
def on_bu... | 22 | 594 |
textual | tests/snapshot_tests/snapshot_apps/offsets.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label, Static
class Box(Static):
DEFAULT_CSS = """
Box {
border: solid white;
background: darkblue;
width: 16;
height: auto;
}
"""
def compose(self) -> ComposeResult:
yield Label... | 40 | 645 |
textual | tests/snapshot_tests/snapshot_apps/placeholder_disabled.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Placeholder
class DisabledPlaceholderApp(App[None]):
CSS = """
Placeholder {
height: 1fr;
}
"""
def compose(self) -> ComposeResult:
yield Placeholder()
yield Placeholder(disabled=True)
if __name__ == "... | 19 | 367 |
textual | tests/snapshot_tests/snapshot_apps/multiple_css/multiple_css.py | .py | """Testing multiple CSS files, including app-level CSS
-- element #one
The `background` rule on #one tests a 3-way specificity clash between
classvar CSS and two separate CSS files. The background ends up red
because classvar CSS wins.
The `color` rule tests a clash between loading two external CSS files.
The color en... | 35 | 1,036 |
textual | examples/breakpoints.py | .py | from textual.app import App, ComposeResult
from textual.containers import Grid
from textual.widgets import Footer, Markdown, Placeholder
HELP = """\
## Breakpoints
A demonstration of how to make an app respond to the dimensions of the terminal.
Try resizing the terminal, then have a look at the source to see how it ... | 54 | 1,277 |
textual | examples/calculator.py | .py | """
An implementation of a classic calculator, with a layout inspired by macOS calculator.
Works like a real calculator. Click the buttons or press the equivalent keys.
"""
from decimal import Decimal
from textual import events, on
from textual.app import App, ComposeResult
from textual.containers import Container
f... | 172 | 5,930 |
textual | examples/five_by_five.py | .py | """Simple version of 5x5, developed for/with Textual."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, cast
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal
from textual.css.query import DOMQuery
f... | 324 | 10,056 |
textual | examples/clock.py | .py | """
An App to show the current time.
"""
from datetime import datetime
from textual.app import App, ComposeResult
from textual.widgets import Digits
class ClockApp(App):
CSS = """
Screen { align: center middle; }
Digits { width: auto; }
"""
def compose(self) -> ComposeResult:
yield Digi... | 32 | 628 |
textual | examples/sidebar.py | .py | """
A simple animated sidebar.
See comments for details.
"""
from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Footer, Label
TEXT = """I must not fear.
Fear is the mind-killer.
Fear i... | 96 | 2,234 |
textual | examples/code_browser.py | .py | """
Code browser example.
Run with:
python code_browser.py PATH
"""
from __future__ import annotations
import sys
from pathlib import Path
from rich.traceback import Traceback
from textual.app import App, ComposeResult
from textual.containers import Container, VerticalScroll
from textual.highlight import high... | 89 | 2,561 |
textual | examples/markdown.py | .py | from __future__ import annotations
from pathlib import Path
from sys import argv
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.reactive import var
from textual.widgets import Footer, MarkdownViewer
class MarkdownApp(App):
"""A simple Markdown viewer application."""
... | 79 | 2,476 |
textual | examples/dictionary.py | .py | from __future__ import annotations
try:
import httpx
except ImportError:
raise ImportError("Please install httpx with 'pip install httpx' ")
from textual import getters, work
from textual.app import App, ComposeResult
from textual.containers import VerticalScroll
from textual.widgets import Input, Markdown
... | 76 | 2,464 |
textual | examples/json_tree.py | .py | import json
from pathlib import Path
from rich.text import Text
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Tree
from textual.widgets.tree import TreeNode
class TreeApp(App):
BINDINGS = [
("a", "add", "Add node"),
("c", "clear", "Clear"),
("t",... | 94 | 2,808 |
textual | examples/theme_sandbox.py | .py | from __future__ import annotations
from functools import partial
from typing import Any
from textual._on import on
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Container, Grid, Horizontal, VerticalScroll
from textual.widgets import (
Button,
Col... | 495 | 13,619 |
textual | examples/pride.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Static
class PrideApp(App):
"""Displays a pride flag."""
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
def compose(self) -> ComposeResult:
for color in self.COLORS:
stripe = Static()
... | 20 | 469 |
textual | examples/mother.py | .py | """
A simple example of chatting to an LLM with Textual.
Lots of room for improvement here.
See https://textual.textualize.io/blog/2024/09/15/anatomy-of-a-textual-user-interface/
"""
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "llm",
# "textual",
# ]
# ///
from textual import on, work
fro... | 108 | 2,916 |
textual | examples/merlin.py | .py | from __future__ import annotations
import random
from datetime import timedelta
from time import monotonic
from textual import events
from textual.app import App, ComposeResult
from textual.containers import Grid
from textual.reactive import var
from textual.renderables.gradient import LinearGradient
from textual.wid... | 178 | 4,694 |
textual | examples/splash.py | .py | from time import time
from textual.app import App, ComposeResult, RenderableType
from textual.containers import Container
from textual.renderables.gradient import LinearGradient
from textual.widgets import Static
COLORS = [
"#881177",
"#aa3355",
"#cc6666",
"#ee9944",
"#eedd00",
"#99dd55",
... | 59 | 1,223 |
textual | examples/color_command.py | .py | from dataclasses import dataclass
from functools import partial
from textual import on
from textual._color_constants import COLOR_NAME_TO_RGB
from textual.app import App, ComposeResult
from textual.command import Hit, Hits, Provider
from textual.message import Message
from textual.widgets import Header, Static
@data... | 68 | 1,695 |
textual | src/textual/types.py | .py | """
Export some objects that are used by Textual and that help document other features.
"""
from textual._animator import Animatable, EasingFunction
from textual._context import NoActiveAppError
from textual._path import CSSPathError, CSSPathType
from textual._types import (
AnimationLevel,
CallbackType,
I... | 53 | 1,381 |
textual | src/textual/_extrema.py | .py | from __future__ import annotations
from fractions import Fraction
from typing import NamedTuple
from textual.geometry import Size
class Extrema(NamedTuple):
"""Specifies minimum and maximum dimensions."""
min_width: Fraction | None = None
max_width: Fraction | None = None
min_height: Fraction | Non... | 65 | 1,662 |
textual | src/textual/layout.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar, Iterable, NamedTuple
from textual._spatial_map import SpatialMap
from textual.canvas import Canvas, Rectangle
from textual.geometry import Offset, Region, Size, Spacing
... | 315 | 9,963 |
textual | src/textual/_event_broker.py | .py | from __future__ import annotations
from typing import Any, NamedTuple
class NoHandler(Exception):
"""Raised when handler isn't found in the meta."""
class HandlerArguments(NamedTuple):
"""Information for event handler."""
modifiers: set[str]
action: Any
def extract_handler_actions(event_name: st... | 38 | 999 |
textual | src/textual/_callback.py | .py | from __future__ import annotations
import asyncio
from functools import partial
from inspect import isawaitable, signature
from typing import TYPE_CHECKING, Any, Callable
from textual import active_app
if TYPE_CHECKING:
from textual.app import App
# Maximum seconds before warning about a slow callback
INVOKE_TI... | 97 | 2,753 |
textual | src/textual/canvas.py | .py | """
A Canvas class used to render keylines.
!!! note
This API is experimental, and may change in the near future.
"""
from __future__ import annotations
import sys
from array import array
from collections import defaultdict
from dataclasses import dataclass
from operator import itemgetter
from typing import Nam... | 285 | 8,420 |
textual | src/textual/logging.py | .py | """
A Textual Logging handler.
If there is an active Textual app, then log messages will go via the app (and logged via textual console).
If there is *no* active app, then log messages will go to stderr or stdout, depending on configuration.
"""
import sys
from logging import Handler, LogRecord
from textual._contex... | 41 | 1,187 |
textual | src/textual/_import_app.py | .py | from __future__ import annotations
import os
import runpy
import shlex
import sys
from pathlib import Path
from typing import TYPE_CHECKING, cast
if TYPE_CHECKING:
from textual.app import App
class AppFail(Exception):
pass
def shebang_python(candidate: Path) -> bool:
"""Does the given file look like i... | 127 | 3,609 |
textual | src/textual/_work_decorator.py | .py | """
A decorator used to create [workers](/guide/workers).
"""
from __future__ import annotations
from functools import partial, wraps
from inspect import iscoroutinefunction
from typing import TYPE_CHECKING, Callable, Coroutine, TypeVar, Union, cast, overload
from typing_extensions import ParamSpec, TypeAlias
if TY... | 159 | 5,109 |
textual | src/textual/notifications.py | .py | """Provides classes for holding and managing notifications."""
from __future__ import annotations
from dataclasses import dataclass, field
from time import time
from typing import Iterator
from uuid import uuid4
from rich.repr import Result
from typing_extensions import Literal, Self, TypeAlias
from textual.message... | 121 | 3,714 |
textual | src/textual/_border.py | .py | from __future__ import annotations
from functools import lru_cache
from typing import TYPE_CHECKING, Iterable, Tuple, cast
from rich.segment import Segment
from textual.color import Color
from textual.css.types import AlignHorizontal, EdgeStyle, EdgeType
from textual.style import Style
if TYPE_CHECKING:
from ty... | 480 | 13,018 |
textual | src/textual/_wrap.py | .py | from __future__ import annotations
import re
from typing import Iterable
from rich.cells import get_character_cell_size
from textual._cells import cell_len
from textual._loop import loop_last
from textual.expand_tabs import get_tab_widths
re_chunk = re.compile(r"\S+\s*|\s+")
def chunks(text: str) -> Iterable[tupl... | 148 | 5,986 |
textual | src/textual/_path.py | .py | from __future__ import annotations
import inspect
from pathlib import Path, PurePath
from typing import List, Union
from typing_extensions import TypeAlias
CSSPathType: TypeAlias = Union[
str,
PurePath,
List[Union[str, PurePath]],
]
"""Valid ways of specifying paths to CSS files."""
class CSSPathError(... | 73 | 2,062 |
textual | src/textual/render.py | .py | from __future__ import annotations
from rich.cells import cell_len
from rich.console import Console, RenderableType
from rich.protocol import rich_cast
def measure(
console: Console,
renderable: RenderableType,
default: int,
*,
container_width: int | None = None,
) -> int:
"""Measure a rich r... | 42 | 1,135 |
textual | src/textual/errors.py | .py | """
General exception classes.
"""
from __future__ import annotations
class TextualError(Exception):
"""Base class for Textual errors."""
class NoWidget(TextualError):
"""Specified widget was not found."""
class RenderError(TextualError):
"""An object could not be rendered."""
class DuplicateKeyHa... | 27 | 534 |
textual | src/textual/selection.py | .py | from __future__ import annotations
from operator import attrgetter
from typing import TYPE_CHECKING, Iterable, Iterator, NamedTuple
from textual.geometry import Offset, Shape
if TYPE_CHECKING:
from textual.widget import Widget
class Selection(NamedTuple):
"""A selected range of lines."""
start: Offset... | 462 | 16,772 |
textual | src/textual/driver.py | .py | from __future__ import annotations
import asyncio
import threading
from abc import ABC, abstractmethod
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any, BinaryIO, Iterator, Literal, TextIO
from textual import events, log, messages
from textual.events import MouseUp
... | 302 | 10,325 |
textual | src/textual/app.py | .py | """
Here you will find the [App][textual.app.App] class, which is the base class for Textual apps.
See [app basics](/guide/app) for how to build Textual apps.
"""
from __future__ import annotations
import asyncio
import importlib
import inspect
import io
import mimetypes
import os
import signal
import sys
import th... | 5,041 | 184,776 |
textual | src/textual/_dispatch_key.py | .py | from __future__ import annotations
from typing import Callable
from textual import events
from textual._callback import invoke
from textual.dom import DOMNode
from textual.errors import DuplicateKeyHandlers
from textual.message_pump import MessagePump
async def dispatch_key(node: DOMNode, event: events.Key) -> bool... | 69 | 2,462 |
textual | src/textual/file_monitor.py | .py | from __future__ import annotations
import os
from pathlib import Path
from typing import Callable, Iterable, Sequence
import rich.repr
from textual._callback import invoke
@rich.repr.auto
class FileMonitor:
"""Monitors files for changes and invokes a callback when it does."""
_paths: set[Path]
def __... | 65 | 1,945 |
textual | src/textual/suggester.py | .py | """
Contains the `Suggester` class, used by the [Input](/widgets/input) widget.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Iterable
from textual.cache import LRUCache
from textual.dom import DOMNode
from textual.message import Mes... | 145 | 4,723 |
textual | src/textual/_compat.py | .py | from __future__ import annotations
import sys
from typing import Any, Generic, TypeVar, overload
if sys.version_info >= (3, 12):
from functools import cached_property
else:
# based on the code from Python 3.14:
# https://github.com/python/cpython/blob/
# 5507eff19c757a908a2ff29dfe423e35595fda00/Lib/fu... | 74 | 2,849 |
textual | src/textual/fuzzy.py | .py | """
Fuzzy matcher.
This class is used by the [command palette](/guide/command_palette) to match search terms.
"""
from __future__ import annotations
from functools import lru_cache
from operator import itemgetter
from re import finditer
from typing import Iterable, Sequence
import rich.repr
from textual.cache imp... | 225 | 6,973 |
textual | src/textual/compose.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from textual.app import App, ComposeResult
from textual.widget import Widget
__all__ = ["compose"]
def compose(
node: App | Widget, compose_result: ComposeResult | None = None
) -> list[Widget]:
"""Compose child w... | 100 | 3,129 |
textual | src/textual/_widget_navigation.py | .py | """
Utilities to move index-based selections backward/forward.
These utilities concern themselves with selections where not all options are available,
otherwise it would be enough to increment/decrement the index and use the operator `%`
to implement wrapping.
"""
from __future__ import annotations
from itertools im... | 183 | 5,702 |
textual | src/textual/system_commands.py | .py | """
This module contains `SystemCommands`, a command palette command provider for Textual system commands.
This is a simple command provider that makes the most obvious application
actions available via the [command palette][textual.command.CommandPalette].
!!! note
The App base class installs this automaticall... | 65 | 2,041 |
textual | src/textual/eta.py | .py | from __future__ import annotations
import bisect
from math import ceil
from time import monotonic
import rich.repr
@rich.repr.auto(angular=True)
class ETA:
"""Calculate speed and estimate time to arrival."""
def __init__(
self, estimation_period: float = 60, extrapolate_period: float = 30
) -> ... | 130 | 4,645 |
textual | src/textual/_binary_encode.py | .py | """
An encoding / decoding format suitable for serializing data structures to binary.
This is based on https://en.wikipedia.org/wiki/Bencode with some extensions.
The following data types may be encoded:
- None
- int
- bool
- bytes
- str
- list
- tuple
- dict
"""
from __future__ import annotations
from typing imp... | 326 | 7,653 |
textual | src/textual/await_complete.py | .py | from __future__ import annotations
from asyncio import Future, gather
from typing import TYPE_CHECKING, Any, Awaitable, Generator
import rich.repr
from typing_extensions import Self
from textual._debug import get_caller_file_and_line
from textual.message_pump import MessagePump
if TYPE_CHECKING:
from textual.ty... | 86 | 2,598 |
textual | src/textual/screen.py | .py | """
This module contains the `Screen` class and related objects.
The `Screen` class is a special widget which represents the content in the terminal. See [Screens](/guide/screens/) for details.
"""
from __future__ import annotations
import asyncio
from functools import partial
from operator import attrgetter
from ... | 2,195 | 79,934 |
textual | src/textual/signal.py | .py | """
Signals are a simple pub-sub mechanism.
DOMNodes can subscribe to a signal, which will invoke a callback when the signal is published.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Generic, TypeVar, Union
from weakref import WeakKeyDictionary, ref
import ric... | 138 | 4,296 |
textual | src/textual/_arrange.py | .py | from __future__ import annotations
from collections import defaultdict
from fractions import Fraction
from operator import attrgetter
from typing import TYPE_CHECKING, Iterable, Mapping, Sequence
from textual._partition import partition
from textual.geometry import NULL_OFFSET, NULL_SPACING, Region, Size, Spacing
fro... | 254 | 9,045 |
textual | src/textual/rlock.py | .py | from __future__ import annotations
from asyncio import Lock, Task, current_task
class RLock:
"""A re-entrant asyncio lock."""
def __init__(self) -> None:
self._owner: Task | None = None
self._count = 0
self._lock = Lock()
async def acquire(self) -> None:
"""Wait until th... | 62 | 1,657 |
textual | src/textual/_easing.py | .py | """
Define a series of easing functions for more natural-looking animations.
Taken from https://easings.net/ and translated from JavaScript.
"""
from math import cos, pi, sin, sqrt
def _in_out_expo(x: float) -> float:
"""https://easings.net/#easeInOutExpo"""
if 0 < x < 0.5:
return pow(2, 20 * x - 10)... | 132 | 4,101 |
textual | src/textual/_files.py | .py | from __future__ import annotations
from datetime import datetime
def generate_datetime_filename(
prefix: str, suffix: str, datetime_format: str | None = None
) -> str:
"""Generate a filename which includes the current date and time.
Useful for ensuring a degree of uniqueness when saving files.
Args... | 29 | 1,002 |
textual | src/textual/_ansi_sequences.py | .py | from __future__ import annotations
from typing import Mapping, Tuple
from typing_extensions import Final
from textual.keys import Keys
class IgnoredSequence:
"""Class used to mark that a sequence should be ignored."""
IGNORE_SEQUENCE: Final[IgnoredSequence] = IgnoredSequence()
"""Constant to indicate that a ... | 455 | 18,565 |
textual | src/textual/_line_split.py | .py | from __future__ import annotations
import re
# Pre-compile the regular expression and store it in a global constant
LINE_AND_ENDING_PATTERN = re.compile(r"(.*?)(\r\n|\r|\n|$)", re.S)
def line_split(input_string: str) -> list[tuple[str, str]]:
r"""
Splits an arbitrary string into a list of tuples, where each... | 24 | 846 |
textual | src/textual/containers.py | .py | """
Container widgets for quick styling.
With the exception of `Center` and `Middle` containers will fill all of the space in the parent widget.
"""
from __future__ import annotations
from typing import ClassVar
from textual.binding import Binding, BindingType
from textual.layout import Layout
from textual.layouts... | 312 | 8,693 |
textual | src/textual/_node_list.py | .py | from __future__ import annotations
import sys
import weakref
from operator import attrgetter
from typing import TYPE_CHECKING, Any, Callable, Iterator, Sequence, overload
import rich.repr
if TYPE_CHECKING:
from _typeshed import SupportsRichComparison
from textual.dom import DOMNode
from textual.widget i... | 237 | 7,599 |
textual | src/textual/color.py | .py | """
This module contains a powerful [Color][textual.color.Color] class which Textual uses to manipulate colors.
## Named colors
The following named colors are used by the [parse][textual.color.Color.parse] method.
```{.rich columns="80" title="colors"}
from textual._color_constants import COLOR_NAME_TO_RGB
from tex... | 857 | 28,040 |
textual | src/textual/clock.py | .py | from __future__ import annotations
from time import monotonic
from typing import Callable
import rich.repr
@rich.repr.auto(angular=True)
class Clock:
"""An object to get relative time.
The `time` attribute of clock will return the time in seconds since the
Clock was created or reset.
"""
def ... | 75 | 2,022 |
textual | src/textual/_on.py | .py | from __future__ import annotations
from typing import Callable, TypeVar
from textual.css.model import SelectorSet
from textual.css.parse import parse_selectors
from textual.css.tokenizer import TokenError
from textual.message import Message
DecoratedType = TypeVar("DecoratedType")
class OnDecoratorError(Exception)... | 94 | 3,336 |
textual | src/textual/_sleep.py | .py | from __future__ import annotations
from asyncio import Future, get_running_loop
from threading import Event, Thread
from time import perf_counter, sleep
class Sleeper(Thread):
def __init__(
self,
) -> None:
self._exit = False
self._sleep_time = 0.0
self._event = Event()
... | 61 | 1,620 |
textual | src/textual/expand_tabs.py | .py | from __future__ import annotations
import re
from rich.cells import cell_len
from rich.text import Text
_TABS_SPLITTER_RE = re.compile(r"(.*?\t|.+?$)")
def get_tab_widths(line: str, tab_size: int = 4) -> list[tuple[str, int]]:
"""Splits a string line into tuples (str, int).
Each tuple represents a section... | 109 | 3,538 |
textual | src/textual/__main__.py | .py | from rich import print
from rich.panel import Panel
from textual.demo.demo_app import DemoApp
if __name__ == "__main__":
app = DemoApp()
app.run()
print(
Panel.fit(
"[b magenta]Hope you liked the demo![/]\n\n"
"Please consider sponsoring me if you get value from my work.\n\... | 20 | 563 |
textual | src/textual/_opacity.py | .py | from typing import Iterable, cast
from rich.segment import Segment
from rich.style import Style
from textual.color import Color
def _apply_opacity(
segments: Iterable[Segment],
base_background: Color,
opacity: float,
) -> Iterable[Segment]:
"""Takes an iterable of foreground Segments and blends them... | 43 | 1,527 |
textual | src/textual/__init__.py | .py | """
The root Textual module.
Exposes some commonly used symbols.
"""
from __future__ import annotations
import inspect
import weakref
from typing import TYPE_CHECKING, Callable
import rich.repr
from textual import constants
from textual._context import active_app
from textual._log import LogGroup, LogVerbosity
fr... | 208 | 5,694 |
textual | src/textual/filter.py | .py | """Filter classes.
!!! note
Filters are used internally, and not recommended for use by Textual app developers.
Filters are used internally to process terminal output after it has been rendered.
Currently this is used internally to convert the application to monochrome, when the NO_COLOR env var is set.
In the ... | 289 | 7,880 |
textual | src/textual/keys.py | .py | from __future__ import annotations
import unicodedata
from enum import Enum
from functools import lru_cache
# Adapted from prompt toolkit https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/keys.py
class Keys(str, Enum): # type: ignore[no-redef]
"""
List of keys for use in key... | 369 | 10,258 |
textual | src/textual/_resolve.py | .py | from __future__ import annotations
from fractions import Fraction
from itertools import accumulate
from typing import TYPE_CHECKING, Iterable, Sequence, cast
from typing_extensions import Literal
from textual.box_model import BoxModel
from textual.css.scalar import Scalar
from textual.css.styles import RenderStyles
... | 348 | 11,050 |
textual | src/textual/_color_constants.py | .py | from __future__ import annotations
ANSI_COLORS = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
"bright_black",
"bright_red",
"bright_green",
"bright_yellow",
"bright_blue",
"bright_magenta",
"bright_cyan",
"bright_white",
]
"""T... | 193 | 6,099 |
textual | src/textual/constants.py | .py | """
This module contains constants, which may be set in environment variables.
"""
from __future__ import annotations
import os
from typing import get_args
from typing_extensions import Final, TypeGuard
from textual._types import AnimationLevel
get_environ = os.environ.get
def _get_environ_bool(name: str) -> boo... | 176 | 5,666 |
textual | src/textual/_slug.py | .py | """Provides a utility function and class for creating Markdown-friendly slugs.
The approach to creating slugs is designed to be as close to
GitHub-flavoured Markdown as possible. However, because there doesn't appear
to be any actual documentation for this 'standard', the code here involves
some guesswork and also som... | 141 | 4,392 |
textual | src/textual/geometry.py | .py | """
Functions and classes to manage terminal geometry (anything involving coordinates or dimensions).
"""
from __future__ import annotations
import os
from functools import lru_cache
from operator import attrgetter, itemgetter
from typing import (
TYPE_CHECKING,
Any,
Collection,
Iterable,
Literal... | 1,501 | 45,783 |
textual | src/textual/_compositor.py | .py | """
The compositor handles combining widgets into a single screen (i.e. compositing).
It also stores the results of that process, so that Textual knows the widgets on
the screen and their locations. The compositor uses this information to answer
queries regarding the widget under an offset, or the style under an offs... | 1,273 | 44,251 |
textual | src/textual/_loop.py | .py | from __future__ import annotations
from typing import Iterable, Literal, Sequence, TypeVar
T = TypeVar("T")
def loop_first(values: Iterable[T]) -> Iterable[tuple[bool, T]]:
"""Iterate and generate a tuple with a flag for first value."""
iter_values = iter(values)
try:
value = next(iter_values)
... | 87 | 2,602 |
textual | src/textual/_layout_resolve.py | .py | from __future__ import annotations
from fractions import Fraction
from typing import Sequence, cast
from typing_extensions import Protocol
class EdgeProtocol(Protocol):
"""Any object that defines an edge (such as Layout)."""
# Size of edge in cells, or None for no fixed size
size: int | None
# Port... | 86 | 3,274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.