Command Palette tweaks and docs (#3289)

* renames to command palette and docs

* docs

* simplifyt

* note

* docstring

* Update src/textual/command.py

Co-authored-by: Rodrigo Girão Serrão <5621605+rodrigogiraoserrao@users.noreply.github.com>

* Update docs/examples/guide/command_palette/command01.py

Co-authored-by: Dave Pearson <davep@davep.org>

* populate text

* screen commands

* Update docs/guide/command_palette.md

Co-authored-by: Dave Pearson <davep@davep.org>

* Update docs/guide/command_palette.md

Co-authored-by: Dave Pearson <davep@davep.org>

---------

Co-authored-by: Rodrigo Girão Serrão <5621605+rodrigogiraoserrao@users.noreply.github.com>
Co-authored-by: Dave Pearson <davep@davep.org>
This commit is contained in:
Will McGugan
2023-09-13 15:03:25 +01:00
committed by GitHub
parent 0a14bf0549
commit 5d6a95dec5
22 changed files with 637 additions and 563 deletions

View File

@@ -0,0 +1,65 @@
from pathlib import Path
from rich.syntax import Syntax
from textual.app import App, ComposeResult
from textual.command import Hit, Hits, Source
from textual.containers import VerticalScroll
from textual.widgets import Static
class PythonFileSource(Source):
"""A command source to open a Python file in the current working directory."""
def read_files(self) -> list[Path]:
"""Get a list of Python files in the current working directory."""
return list(Path("./").glob("*.py"))
async def post_init(self) -> None: # (1)!
"""Called once when the command palette is opened, prior to searching."""
worker = self.app.run_worker(self.read_files, thread=True)
self.python_paths = await worker.wait()
async def search(self, query: str) -> Hits: # (2)!
"""Search for Python files."""
matcher = self.matcher(query) # (3)!
app = self.app
assert isinstance(app, ViewerApp)
for path in self.python_paths:
command = f"open {str(path)}"
score = matcher.match(command) # (4)!
if score > 0:
yield Hit(
score,
matcher.highlight(command), # (5)!
lambda: app.open_file(path),
help="Open this file in the viewer",
)
class ViewerApp(App):
"""Demonstrate a command source."""
COMMAND_SOURCES = App.COMMAND_SOURCES | {PythonFileSource} # (6)!
def compose(self) -> ComposeResult:
with VerticalScroll():
yield Static(id="code", expand=True)
def open_file(self, path: Path) -> None:
"""Open and display a file with syntax highlighting."""
syntax = Syntax.from_path(
str(path),
line_numbers=True,
word_wrap=False,
indent_guides=True,
theme="github-dark",
)
self.query_one("#code", Static).update(syntax)
if __name__ == "__main__":
app = ViewerApp()
app.run()