3
Makefile
@@ -12,3 +12,6 @@ docs-serve:
|
|||||||
mkdocs serve
|
mkdocs serve
|
||||||
docs-build:
|
docs-build:
|
||||||
mkdocs build
|
mkdocs build
|
||||||
|
docs-deploy:
|
||||||
|
mkdocs gh-deploy
|
||||||
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
# Actions
|
|
||||||
3
docs/events/index.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Events
|
||||||
|
|
||||||
|
A reference to Textual [events](../guide/events.md).
|
||||||
30
docs/examples/app/event01.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
from textual.app import App
|
||||||
|
from textual import events
|
||||||
|
|
||||||
|
|
||||||
|
class EventApp(App):
|
||||||
|
|
||||||
|
COLORS = [
|
||||||
|
"white",
|
||||||
|
"maroon",
|
||||||
|
"red",
|
||||||
|
"purple",
|
||||||
|
"fuchsia",
|
||||||
|
"olive",
|
||||||
|
"yellow",
|
||||||
|
"navy",
|
||||||
|
"teal",
|
||||||
|
"aqua",
|
||||||
|
]
|
||||||
|
|
||||||
|
def on_mount(self) -> None:
|
||||||
|
self.styles.background = "darkblue"
|
||||||
|
|
||||||
|
def on_key(self, event: events.Key) -> None:
|
||||||
|
if event.key.isdecimal():
|
||||||
|
self.styles.background = self.COLORS[int(event.key)]
|
||||||
|
|
||||||
|
|
||||||
|
app = EventApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run()
|
||||||
18
docs/examples/app/question01.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
from textual.app import App, ComposeResult
|
||||||
|
from textual.widgets import Static, Button
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionApp(App[str]):
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
yield Static("Do you love Textual?")
|
||||||
|
yield Button("Yes", id="yes", variant="primary")
|
||||||
|
yield Button("No", id="no", variant="error")
|
||||||
|
|
||||||
|
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||||
|
self.exit(event.button.id)
|
||||||
|
|
||||||
|
|
||||||
|
app = QuestionApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
reply = app.run()
|
||||||
|
print(reply)
|
||||||
17
docs/examples/app/question02.css
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
Screen {
|
||||||
|
layout: grid;
|
||||||
|
grid-size: 2;
|
||||||
|
grid-gutter: 2;
|
||||||
|
padding: 2;
|
||||||
|
}
|
||||||
|
#question {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
column-span: 2;
|
||||||
|
content-align: center bottom;
|
||||||
|
text-style: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
Button {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
18
docs/examples/app/question02.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
from textual.app import App, ComposeResult
|
||||||
|
from textual.widgets import Static, Button
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionApp(App[str]):
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
yield Static("Do you love Textual?", id="question")
|
||||||
|
yield Button("Yes", id="yes", variant="primary")
|
||||||
|
yield Button("No", id="no", variant="error")
|
||||||
|
|
||||||
|
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||||
|
self.exit(event.button.id)
|
||||||
|
|
||||||
|
|
||||||
|
app = QuestionApp(css_path="question02.css")
|
||||||
|
if __name__ == "__main__":
|
||||||
|
reply = app.run()
|
||||||
|
print(reply)
|
||||||
38
docs/examples/app/question03.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from textual.app import App, ComposeResult
|
||||||
|
from textual.widgets import Static, Button
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionApp(App[str]):
|
||||||
|
CSS = """
|
||||||
|
Screen {
|
||||||
|
layout: table;
|
||||||
|
table-size: 2;
|
||||||
|
table-gutter: 2;
|
||||||
|
padding: 2;
|
||||||
|
}
|
||||||
|
#question {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
column-span: 2;
|
||||||
|
content-align: center bottom;
|
||||||
|
text-style: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
Button {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
yield Static("Do you love Textual?", id="question")
|
||||||
|
yield Button("Yes", id="yes", variant="primary")
|
||||||
|
yield Button("No", id="no", variant="error")
|
||||||
|
|
||||||
|
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||||
|
self.exit(event.button.id)
|
||||||
|
|
||||||
|
|
||||||
|
app = QuestionApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
reply = app.run()
|
||||||
|
print(reply)
|
||||||
14
docs/examples/app/return.py
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
from textual.app import App, ComposeResult
|
||||||
|
from textual.widgets import Button
|
||||||
|
|
||||||
|
|
||||||
|
class ButtonsApp(App):
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
yield Button("Paul")
|
||||||
|
yield Button("Duncan")
|
||||||
|
yield Button("Chani")
|
||||||
|
|
||||||
|
|
||||||
|
app = ButtonsApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run()
|
||||||
5
docs/examples/app/simple01.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from textual.app import App
|
||||||
|
|
||||||
|
|
||||||
|
class MyApp(App):
|
||||||
|
pass
|
||||||
10
docs/examples/app/simple02.py
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
from textual.app import App
|
||||||
|
|
||||||
|
|
||||||
|
class MyApp(App):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
app = MyApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run()
|
||||||
15
docs/examples/app/widgets01.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
from textual.app import App, ComposeResult
|
||||||
|
from textual.widgets import Welcome
|
||||||
|
|
||||||
|
|
||||||
|
class WelcomeApp(App):
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
yield Welcome()
|
||||||
|
|
||||||
|
def on_button_pressed(self) -> None:
|
||||||
|
self.exit()
|
||||||
|
|
||||||
|
|
||||||
|
app = WelcomeApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run()
|
||||||
15
docs/examples/app/widgets02.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
from textual.app import App
|
||||||
|
from textual.widgets import Welcome
|
||||||
|
|
||||||
|
|
||||||
|
class WelcomeApp(App):
|
||||||
|
def on_key(self) -> None:
|
||||||
|
self.mount(Welcome())
|
||||||
|
|
||||||
|
def on_button_pressed(self) -> None:
|
||||||
|
self.exit()
|
||||||
|
|
||||||
|
|
||||||
|
app = WelcomeApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run()
|
||||||
@@ -10,7 +10,7 @@ CSS stands for _Cascading Stylesheets_. A stylesheet is a list of styles and rul
|
|||||||
|
|
||||||
Depending on what you want to build with Textual, you may not need to learn Textual CSS at all. Widgets are packaged with CSS styles so apps with exclusively pre-built widgets may not need any additional CSS.
|
Depending on what you want to build with Textual, you may not need to learn Textual CSS at all. Widgets are packaged with CSS styles so apps with exclusively pre-built widgets may not need any additional CSS.
|
||||||
|
|
||||||
Textual CSS defines a set of rules which apply visual _styles_ to your application and widgets. These style can customize a large variety of visual settings, such as color, border, size, alignment; and more dynamic features such as animation and hover effects. As powerful as it is, CSS in Textual is quite straightforward.
|
Textual CSS defines a set of rules which apply visual _styles_ to your application and widgets. These style can customize settings for properties such as color, border, size, alignment; and more dynamic features such as animation and hover effects. As powerful as it is, CSS in Textual is quite straightforward.
|
||||||
|
|
||||||
CSS is typically stored in an external file with the extension `.css` alongside your Python code.
|
CSS is typically stored in an external file with the extension `.css` alongside your Python code.
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ This is an example of a CSS _rule set_. There may be many such sections in any g
|
|||||||
|
|
||||||
Let's break this CSS code down a bit.
|
Let's break this CSS code down a bit.
|
||||||
|
|
||||||
```css hl_lines="1"
|
```sass hl_lines="1"
|
||||||
Header {
|
Header {
|
||||||
dock: top;
|
dock: top;
|
||||||
height: 3;
|
height: 3;
|
||||||
@@ -42,7 +42,7 @@ Header {
|
|||||||
|
|
||||||
The first line is a _selector_ which tells Textual which Widget(s) to modify. In the above example, the styles will be applied to a widget defined by the Python class `Header`.
|
The first line is a _selector_ which tells Textual which Widget(s) to modify. In the above example, the styles will be applied to a widget defined by the Python class `Header`.
|
||||||
|
|
||||||
```css hl_lines="2 3 4 5 6"
|
```sass hl_lines="2 3 4 5 6"
|
||||||
Header {
|
Header {
|
||||||
dock: top;
|
dock: top;
|
||||||
height: 3;
|
height: 3;
|
||||||
@@ -58,7 +58,7 @@ The first rule in the above example reads `"dock: top;"`. The rule name is `dock
|
|||||||
|
|
||||||
## The DOM
|
## The DOM
|
||||||
|
|
||||||
The DOM, or _Document Object Model_, is a term borrowed from the web world. Textual doesn't use documents but the term has stuck. In Textual CSS, the DOM is a an arrangement of widgets you can visualize as a tree-like structure.
|
The DOM, or _Document Object Model_, is a term borrowed from the web world. Textual doesn't use documents but the term has stuck. In Textual CSS, the DOM is an arrangement of widgets you can visualize as a tree-like structure.
|
||||||
|
|
||||||
Some widgets contain other widgets: for instance, a list control widget will likely also have item widgets, or a dialog widget may contain button widgets. These _child_ widgets form the branches of the tree.
|
Some widgets contain other widgets: for instance, a list control widget will likely also have item widgets, or a dialog widget may contain button widgets. These _child_ widgets form the branches of the tree.
|
||||||
|
|
||||||
@@ -391,3 +391,7 @@ Button:hover {
|
|||||||
background: blue !important;
|
background: blue !important;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## CSS Variables
|
||||||
|
|
||||||
|
TODO: Variables
|
||||||
|
|||||||
3
docs/guide/actions.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Actions
|
||||||
|
|
||||||
|
TODO: Actions docs
|
||||||
3
docs/guide/animator.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Animator
|
||||||
|
|
||||||
|
TODO: Animator docs
|
||||||
179
docs/guide/app.md
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
# App Basics
|
||||||
|
|
||||||
|
In this chapter we will cover how to use Textual's App class to create an application. Just enough to get you up to speed. We will go in to more detail in the following chapters.
|
||||||
|
|
||||||
|
## The App class
|
||||||
|
|
||||||
|
The first step in building a Textual app is to import the [App][textual.app.App] class and create a subclass. Let's look at the simplest app class:
|
||||||
|
|
||||||
|
```python
|
||||||
|
--8<-- "docs/examples/app/simple01.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
### The run method
|
||||||
|
|
||||||
|
To run an app we create an instance and call [run()][textual.app.App.run].
|
||||||
|
|
||||||
|
```python hl_lines="8-10" title="simple02.py"
|
||||||
|
--8<-- "docs/examples/app/simple02.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
Apps don't get much simpler than this—don't expect it to do much.
|
||||||
|
|
||||||
|
!!! tip
|
||||||
|
|
||||||
|
The `__name__ == "__main__":` condition is true only if you run the file with `python` command. This allows us to import `app` without running the app immediately. It also allows the [devtools run](devtools.md#run) command to run the app in development mode. See the [Python docs](https://docs.python.org/3/library/__main__.html#idiomatic-usage) for more information.
|
||||||
|
|
||||||
|
If we run this app with `python simple02.py` you will see a blank terminal, something like the following:
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/app/simple02.py"}
|
||||||
|
```
|
||||||
|
|
||||||
|
When you call [App.run()][textual.app.App.run] Textual puts the terminal in to a special state called *application mode*. When in application mode the terminal will no longer echo what you type. Textual will take over responding to user input (keyboard and mouse) and will update the visible portion of the terminal (i.e. the *screen*).
|
||||||
|
|
||||||
|
If you hit ++ctrl+c++ Textual will exit application mode and return you to the command prompt. Any content you had in the terminal prior to application mode will be restored.
|
||||||
|
|
||||||
|
## Events
|
||||||
|
|
||||||
|
Textual has an event system you can use to respond to key presses, mouse actions, and internal state changes. Event handlers are methods which are prefixed with `on_` followed by the name of the event.
|
||||||
|
|
||||||
|
One such event is the *mount* event which is sent to an application after it enters application mode. You can respond to this event by defining a method called `on_mount`.
|
||||||
|
|
||||||
|
!!! info
|
||||||
|
|
||||||
|
You may have noticed we use the term "send" and "sent" in relation to event handler methods in preference to "calling". This is because Textual uses a message passing system where events are passed (or *sent*) between components. We will cover the details in [events][./events.md].
|
||||||
|
|
||||||
|
Another such event is the *key* event which is sent when the user presses a key. The following example contains handlers for both those events:
|
||||||
|
|
||||||
|
```python title="event01.py"
|
||||||
|
--8<-- "docs/examples/app/event01.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
The `on_mount` handler sets the `self.styles.background` attribute to `"darkblue"` which (as you can probably guess) turns the background blue. Since the mount event is sent immediately after entering application mode, you will see a blue screen when you run the code:
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/app/event01.py" hl_lines="23-25"}
|
||||||
|
```
|
||||||
|
|
||||||
|
The key event handler (`on_key`) specifies an `event` parameter which will receive a [events.Key][textual.events.Key] instance. Every event has an associated event object which will be passed to the handler method if it is present in the method's parameter list.
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
|
||||||
|
It is unusual (but not unprecedented) for a method's parameters to affect how it is called. Textual accomplishes this by inspecting the method prior to calling it.
|
||||||
|
|
||||||
|
For some events, such as the key event, the event object contains additional information. In the case of [events.Key][textual.events.Key] it will contain the key that was pressed.
|
||||||
|
|
||||||
|
The `on_key` method above uses the `key` attribute on the Key event to change the background color if any of the keys ++0++ to ++9++ are pressed.
|
||||||
|
|
||||||
|
### Async events
|
||||||
|
|
||||||
|
Textual is powered by Python's [asyncio](https://docs.python.org/3/library/asyncio.html) framework which uses the `async` and `await` keywords to coordinate events.
|
||||||
|
|
||||||
|
Textual knows to *await* your event handlers if they are generators (i.e. prefixed with the `async` keyword).
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
|
||||||
|
Don't worry if you aren't familiar with the async programming in Python. You can build many apps without using them.
|
||||||
|
|
||||||
|
## Widgets
|
||||||
|
|
||||||
|
Widgets are self-contained components responsible for generating the output for a portion of the screen and can respond to events in much the same way as the App. Most apps that do anything interesting will contain at least one (and probably many) widgets which together form a User Interface.
|
||||||
|
|
||||||
|
Widgets can be as simple as a piece of text, a button, or a fully-fledge component like a text editor or file browser (which may contain widgets of their own).
|
||||||
|
|
||||||
|
### Composing
|
||||||
|
|
||||||
|
To add widgets to your app implement a [`compose()`][textual.app.App.compose] method which should return a iterable of Widget instances. A list would work, but it is convenient to yield widgets, making the method a *generator*.
|
||||||
|
|
||||||
|
The following example imports a builtin Welcome widget and yields it from compose.
|
||||||
|
|
||||||
|
```python title="widgets01.py"
|
||||||
|
--8<-- "docs/examples/app/widgets01.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
When you run this code, Textual will *mount* the Welcome widget which contains a Markdown content area and a button:
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/app/widgets01.py"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Notice the `on_button_pressed` method which handles the [Button.Pressed][textual.widgets.Button] event sent by a button contained in the Welcome widget. The handler calls [App.exit()][textual.app.App] to exit the app.
|
||||||
|
|
||||||
|
### Mounting
|
||||||
|
|
||||||
|
While composing is the preferred way of adding widgets when your app starts it is sometimes necessary to add new widget(s) in response to events. You can do this by calling [mount()][textual.widget.Widget.mount] which will add a new widget to the UI.
|
||||||
|
|
||||||
|
Here's an app which adds the welcome widget in response to any key press:
|
||||||
|
|
||||||
|
```python title="widgets02.py"
|
||||||
|
--8<-- "docs/examples/app/widgets02.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
When you first run this you will get a blank screen. Press any key to add the welcome widget. You can even press a key multiple times to add several widgets.
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/app/widgets02.py" press="a,a,a,down,down,down,down,down,down,_,_,_,_,_,_"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Exiting
|
||||||
|
|
||||||
|
An app will run until you call [App.exit()][textual.app.App.exit] which will exit application mode and the [run][textual.app.App.run] method will return. If this is the last line in your code you will return to the command prompt.
|
||||||
|
|
||||||
|
The exit method will also accept an optional positional value to be returned by `run()`. The following example uses this to return the `id` (identifier) of a clicked button.
|
||||||
|
|
||||||
|
```python title="question01.py"
|
||||||
|
--8<-- "docs/examples/app/question01.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
Running this app will give you the following:
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/app/question01.py"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Clicking either of those buttons will exit the app, and the `run()` method will return either `"yes"` or `"no"` depending on button clicked.
|
||||||
|
|
||||||
|
#### Return type
|
||||||
|
|
||||||
|
You may have noticed that we subclassed `App[str]` rather than the usual `App`.
|
||||||
|
|
||||||
|
```python title="question01.py" hl_lines="5"
|
||||||
|
--8<-- "docs/examples/app/question01.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
The addition of `[str]` tells Mypy that `run()` is expected to return a string. It may also return `None` if [App.exit()][textual.app.App.exit] is called without a return value, so the return type of `run` will be `str | None`.
|
||||||
|
|
||||||
|
You can change the type to match the values you intend to pass to App.exit()][textual.app.App.exit].
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
|
||||||
|
Type annotations are entirely optional (but recommended) with Textual.
|
||||||
|
|
||||||
|
## CSS
|
||||||
|
|
||||||
|
Textual apps can reference [CSS](CSS.md) files which define how your app and widgets will look, while keeping your Python code free of display related code (which tends to be messy).
|
||||||
|
|
||||||
|
The following chapter on [Textual CSS](CSS.md) will describe how to use CSS in detail. For now lets look at how your app references external CSS files.
|
||||||
|
|
||||||
|
The following example sets the `css_path` attribute on the app:
|
||||||
|
|
||||||
|
```python title="question02.py" hl_lines="15"
|
||||||
|
--8<-- "docs/examples/app/question02.py"
|
||||||
|
```
|
||||||
|
|
||||||
|
If the path is relative (as it is above) then it is taken as relative to where the app is defined. Hence this example references `"question01.css"` in the same directory as the Python code. Here is that CSS file:
|
||||||
|
|
||||||
|
```sass title="question02.css"
|
||||||
|
--8<-- "docs/examples/app/question02.css"
|
||||||
|
```
|
||||||
|
|
||||||
|
When `"question02.py"` runs it will load `"question02.css"` and update the app and widgets accordingly. Even though the code is almost identical to the previous sample, the app now looks quite different:
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/app/question02.py"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Classvar CSS
|
||||||
|
|
||||||
|
While external CSS files are recommended for most applications, and enable some cool features like *live editing* (see below), you can also specify the CSS directly within the Python code. To do this you can set the `CSS` class variable on the app which contains the CSS content.
|
||||||
|
|
||||||
|
Here's the question app with classvar CSS:
|
||||||
|
|
||||||
|
```python title="question03.py" hl_lines="6-24"
|
||||||
|
--8<-- "docs/examples/app/question03.py"
|
||||||
|
```
|
||||||
@@ -1,5 +1,13 @@
|
|||||||
# Devtools
|
# Devtools
|
||||||
|
|
||||||
|
!!! note inline end
|
||||||
|
|
||||||
|
If you don't have the `textual` command on your path, you may have forgotten so install with the `dev` switch.
|
||||||
|
|
||||||
|
See [getting started](../getting_started.md#installation) for details.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Textual comes with a command line application of the same name. The `textual` command is a super useful tool that will help you to build apps.
|
Textual comes with a command line application of the same name. The `textual` command is a super useful tool that will help you to build apps.
|
||||||
|
|
||||||
Take a moment to look through the available sub-commands. There will be even more helpful tools here in the future.
|
Take a moment to look through the available sub-commands. There will be even more helpful tools here in the future.
|
||||||
@@ -8,6 +16,7 @@ Take a moment to look through the available sub-commands. There will be even mor
|
|||||||
textual --help
|
textual --help
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
You can run Textual apps with the `run` subcommand. If you supply a path to a Python file it will load and run the application.
|
You can run Textual apps with the `run` subcommand. If you supply a path to a Python file it will load and run the application.
|
||||||
@@ -18,7 +27,7 @@ textual run my_app.py
|
|||||||
|
|
||||||
The `run` sub-command assumes you have an App instance called `app` in the global scope of your Python file. If the application is called something different, you can specify it with a colon following the filename:
|
The `run` sub-command assumes you have an App instance called `app` in the global scope of your Python file. If the application is called something different, you can specify it with a colon following the filename:
|
||||||
|
|
||||||
```
|
```bash
|
||||||
textual run my_app.py:alternative_app
|
textual run my_app.py:alternative_app
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -26,26 +35,92 @@ textual run my_app.py:alternative_app
|
|||||||
|
|
||||||
If the Python file contains a call to app.run() then you can launch the file as you normally would any other Python program. Running your app via `textual run` will give you access to a few Textual features such as live editing of CSS files.
|
If the Python file contains a call to app.run() then you can launch the file as you normally would any other Python program. Running your app via `textual run` will give you access to a few Textual features such as live editing of CSS files.
|
||||||
|
|
||||||
## Console
|
|
||||||
|
|
||||||
When running any terminal application, you can no longer use `print` when debugging (or log to the console). This is because anything you write to standard output would overwrite application content, making it unreadable. Fortunately Textual supplies a debug console of its own which has some super helpful features.
|
## Live editing
|
||||||
|
|
||||||
To use the console, open up 2 terminal emulators. In the first one, run the following:
|
If you combine the `run` command with the `--dev` switch your app will run in *development mode*.
|
||||||
|
|
||||||
```bash
|
|
||||||
textual console
|
|
||||||
```
|
|
||||||
|
|
||||||
This should look something like the following:
|
|
||||||
|
|
||||||
```{.textual title="textual console" path="docs/examples/getting_started/console.py", press="_,_"}
|
|
||||||
```
|
|
||||||
|
|
||||||
In the other console, run your application using `textual run` and the `--dev` switch:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
textual run --dev my_app.py
|
textual run --dev my_app.py
|
||||||
```
|
```
|
||||||
|
|
||||||
Anything you `print` from your application will be displayed in the console window. You can also call the [`log()`][textual.message_pump.MessagePump.log] method on App and Widget objects for advanced formatting. Try it with `self.log(self.tree)`.
|
One of the the features of *dev* mode is live editing of CSS files: any changes to your CSS will be reflected in the terminal a few milliseconds later.
|
||||||
|
|
||||||
|
This is a great feature for iterating on your app's look and feel. Open the CSS in your editor and have your app running in a terminal. Edits to your CSS will appear almost immediately after you save.
|
||||||
|
|
||||||
|
## Console
|
||||||
|
|
||||||
|
When building a typical terminal application you are generally unable to use `print` when debugging (or log to the console). This is because anything you write to standard output will overwrite application content. Textual has a solution to this in the form of a debug console which restores `print` and adds a few additional features to help you debug.
|
||||||
|
|
||||||
|
To use the console, open up **two** terminal emulators. Run the following in one of the terminals:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
textual console
|
||||||
|
```
|
||||||
|
|
||||||
|
You should see the Textual devtools welcome message:
|
||||||
|
|
||||||
|
```{.textual title="textual console" path="docs/examples/getting_started/console.py", press="_,_"}
|
||||||
|
```
|
||||||
|
|
||||||
|
In the other console, run your application with `textual run` and the `--dev` switch:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
textual run --dev my_app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Anything you `print` from your application will be displayed in the console window. Textual will also write log messages to this window which may be helpful when debugging your application.
|
||||||
|
|
||||||
|
|
||||||
|
### Verbosity
|
||||||
|
|
||||||
|
Textual writes log messages to inform you about certain events, such as when the user presses a key or clicks on the terminal. To avoid swamping you with too much information, some events are marked as "verbose" and will be excluded from the logs. If you want to see these log messages, you can add the `-v` switch.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
textual console -v
|
||||||
|
```
|
||||||
|
|
||||||
|
## Textual log
|
||||||
|
|
||||||
|
In addition to simple strings, Textual console supports [Rich](https://rich.readthedocs.io/en/latest/) formatting. To write rich logs, import `log` as follows:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from textual import log
|
||||||
|
```
|
||||||
|
|
||||||
|
This method will pretty print data structures (like lists and dicts) as well as [Rich renderables](https://rich.readthedocs.io/en/stable/protocol.html). Here are some examples:
|
||||||
|
|
||||||
|
```python
|
||||||
|
log("Hello, World") # simple string
|
||||||
|
log(locals()) # Log local variables
|
||||||
|
log(children=self.children, pi=3.141592) # key/values
|
||||||
|
log(self.tree) # Rich renderables
|
||||||
|
```
|
||||||
|
|
||||||
|
Textual log messages may contain [console Markup](https://rich.readthedocs.io/en/stable/markup.html):
|
||||||
|
|
||||||
|
```python
|
||||||
|
log("[bold red]DANGER![/] We're having too much fun")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Log method
|
||||||
|
|
||||||
|
There's a convenient shortcut to `log` available on the App and Widget objects. This is useful in event handlers. Here's an example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from textual.app import App
|
||||||
|
|
||||||
|
class LogApp(App):
|
||||||
|
|
||||||
|
def on_load(self):
|
||||||
|
self.log("In the log handler!", pi=3.141529)
|
||||||
|
|
||||||
|
def on_mount(self):
|
||||||
|
self.log(self.tree)
|
||||||
|
|
||||||
|
app = LogApp()
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run()
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
## Events
|
## Events
|
||||||
|
|
||||||
|
TODO: events docs
|
||||||
|
|
||||||
|
- What are events
|
||||||
|
- Handling events
|
||||||
|
- Auto calling base classes
|
||||||
|
- Event bubbling
|
||||||
|
- Posting / emitting events
|
||||||
|
|
||||||
<div class="excalidraw">
|
<div class="excalidraw">
|
||||||
--8<-- "docs/images/test.excalidraw.svg"
|
--8<-- "docs/images/test.excalidraw.svg"
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
9
docs/guide/index.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Textual Guide
|
||||||
|
|
||||||
|
Welcome to the Textual Guide! An in-depth reference on how to build app with Textual.
|
||||||
|
|
||||||
|
## Example code
|
||||||
|
|
||||||
|
Most of the code in this guide is fully working—you could cut and paste it if you wanted to.
|
||||||
|
|
||||||
|
Although it is probably easier to check out the [Textual repository](https://github.com/Textualize/textual) and navigate to the `docs/examples/guide` directory and run the examples from there.
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Layout
|
||||||
|
|
||||||
|
In textual the *layout* defines how widgets will be arranged (or *layed out*) on the screen. Textual supports a number of layouts which can be set either via a widgets `styles` object or via CSS.
|
||||||
|
|
||||||
|
TODO: layout docs
|
||||||
|
|
||||||
|
## Vertical
|
||||||
|
|
||||||
|
A vertical layout will place new widgets below previous widgets, starting from the top of the screen.
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/layout/vertical.excalidraw.svg"
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
TODO: Explanation of vertical layout
|
||||||
|
|
||||||
|
|
||||||
|
## Horizontal
|
||||||
|
|
||||||
|
A horizontal layout will place the first widget at the top left of the screen, and new widgets will be place directly to the right of the previous widget.
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/layout/horizontal.excalidraw.svg"
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
TODO: Explantion of horizontal layout
|
||||||
|
|
||||||
|
## Center
|
||||||
|
|
||||||
|
A center widget will place the widget directly in the center of the screen. New widgets will also be placed in the center of the screen, overlapping previous widgets.
|
||||||
|
|
||||||
|
There probably isn't a practical use for such overlapping widgets. In practice this layout is probably only useful where you have a single child widget.
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/layout/center.excalidraw.svg"
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
TODO: Explanation of center layout
|
||||||
|
|
||||||
|
## Grid
|
||||||
|
|
||||||
|
A grid layout arranges widgets within a grid composed of columns and rows. Widgets can span multiple rows or columns to create more complex layouts.
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/layout/grid.excalidraw.svg"
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
TODO: Explanation of grid layout
|
||||||
|
|
||||||
|
|
||||||
|
## Docking
|
||||||
|
|
||||||
|
Widgets may be *docked*. Docking a widget removes it from the layout and fixes it position, aligned to either the top, right, bottom, or left edges of the screen. Docked widgets will not scroll, making them ideal for fixed headers / footers / sidebars.
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/layout/dock.excalidraw.svg"
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
TODO: Diagram
|
||||||
|
TODO: Explanation of dock
|
||||||
|
|
||||||
|
## Offsets
|
||||||
|
|
||||||
|
Widgets have a relative offset which is added to the widget's location, after its location has been determined via its layout.
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/layout/offset.excalidraw.svg"
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
TODO: Diagram
|
||||||
|
TODO: Offsets
|
||||||
|
|
||||||
|
|||||||
10
docs/guide/reactivity.md
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
# Reactivity
|
||||||
|
|
||||||
|
TODO: Reactivity docs
|
||||||
|
|
||||||
|
- What is reactivity
|
||||||
|
- Reactive variables
|
||||||
|
- Demo
|
||||||
|
- repaint vs layout
|
||||||
|
- Validation
|
||||||
|
- Watch methods
|
||||||
12
docs/guide/screens.md
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
# Screens
|
||||||
|
|
||||||
|
TODO: Screens docs
|
||||||
|
|
||||||
|
- Explanation of screens
|
||||||
|
- Screens API
|
||||||
|
- Install screen
|
||||||
|
- Uninstall screen
|
||||||
|
- Push screen
|
||||||
|
- Pop screen
|
||||||
|
- Switch Screen
|
||||||
|
- Screens example
|
||||||
15
docs/guide/styles.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
# Styles
|
||||||
|
|
||||||
|
TODO: Styles docs
|
||||||
|
|
||||||
|
- What are styles
|
||||||
|
- Styles object on widgets / app
|
||||||
|
- Setting styles via CSS
|
||||||
|
- Box model
|
||||||
|
- Color / Background
|
||||||
|
- Borders / Outline
|
||||||
|
|
||||||
|
|
||||||
|
<div class="excalidraw">
|
||||||
|
--8<-- "docs/images/styles/box.excalidraw.svg"
|
||||||
|
</div>
|
||||||
11
docs/guide/widgets.md
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Widgets
|
||||||
|
|
||||||
|
TODO: Widgets docs
|
||||||
|
|
||||||
|
- What is a widget
|
||||||
|
- Defining a basic widget
|
||||||
|
- Base classes Widget or Static
|
||||||
|
- Text widgets
|
||||||
|
- Rich renderable widgets
|
||||||
|
- Complete widget
|
||||||
|
- Render line widget API
|
||||||
1
docs/how-to/animation.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Animation
|
||||||
3
docs/how-to/index.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# How to ...
|
||||||
|
|
||||||
|
For those who want more focused information on Textual features.
|
||||||
1
docs/how-to/mouse-and-keyboard.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Mouse and Keyboard
|
||||||
1
docs/how-to/scroll.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Scroll
|
||||||
16
docs/images/layout/align.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
16
docs/images/layout/center.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
16
docs/images/layout/dock.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 55 KiB |
16
docs/images/layout/grid.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 46 KiB |
16
docs/images/layout/horizontal.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
16
docs/images/layout/offset.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
16
docs/images/layout/vertical.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 44 KiB |
16
docs/images/styles/box.excalidraw.svg
Normal file
|
After Width: | Height: | Size: 16 KiB |
@@ -4,7 +4,7 @@ Welcome to the [Textual](https://github.com/Textualize/textual) framework docume
|
|||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
Textual is a framework for building applications that run within your terminal. Such Text User Interfaces (TUIs) have a number of advantages over traditional web and desktop apps.
|
Textual is a framework for building applications that run within your terminal. Text User Interfaces (TUIs) have a number of advantages over web and desktop apps.
|
||||||
|
|
||||||
<div class="grid cards" markdown>
|
<div class="grid cards" markdown>
|
||||||
|
|
||||||
@@ -59,18 +59,10 @@ Textual is a framework for building applications that run within your terminal.
|
|||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
|
|
||||||
|
```{.textual path="docs/examples/demo.py" columns=100 lines=48}
|
||||||
|
|
||||||
<!-- TODO: More examples split in to tabs -->
|
```
|
||||||
|
|
||||||
=== "Example 1"
|
TODO: Add more example screenshots
|
||||||
|
|
||||||
```{.textual path="docs/examples/demo.py" columns=100 lines=48}
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
=== "Example 2"
|
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/timers.py"}
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|||||||
1
docs/reference/button.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
::: textual.widgets.Button
|
||||||
3
docs/reference/index.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Reference
|
||||||
|
|
||||||
|
A reference to the Textual public APIs.
|
||||||
1
docs/reference/reactive.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
::: textual.reactive.Reactive
|
||||||
3
docs/styles/index.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Styles
|
||||||
|
|
||||||
|
A reference to Widget [styles](../guide/styles.md).
|
||||||
@@ -2,19 +2,22 @@
|
|||||||
|
|
||||||
The `layout` property defines how a widget arranges its children.
|
The `layout` property defines how a widget arranges its children.
|
||||||
|
|
||||||
|
See [layout](../guide/layout.md) guide for more information.
|
||||||
|
|
||||||
## Syntax
|
## Syntax
|
||||||
|
|
||||||
```
|
```
|
||||||
layout: [vertical|horizontal|center];
|
layout: [center|grid|horizontal|vertical];
|
||||||
```
|
```
|
||||||
|
|
||||||
### Values
|
### Values
|
||||||
|
|
||||||
| Value | Description |
|
| Value | Description |
|
||||||
|----------------------|-------------------------------------------------------------------------------|
|
|----------------------|-------------------------------------------------------------------------------|
|
||||||
| `vertical` (default) | Child widgets will be arranged along the vertical axis, from top to bottom. |
|
|
||||||
| `horizontal` | Child widgets will be arranged along the horizontal axis, from left to right. |
|
|
||||||
| `center` | A single child widget will be placed in the center. |
|
| `center` | A single child widget will be placed in the center. |
|
||||||
|
| `grid` | Child widgets will be arranged in a grid. |
|
||||||
|
| `horizontal` | Child widgets will be arranged along the horizontal axis, from left to right. |
|
||||||
|
| `vertical` (default) | Child widgets will be arranged along the vertical axis, from top to bottom. |
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +1,31 @@
|
|||||||
# Introduction
|
# Tutorial
|
||||||
|
|
||||||
Welcome to the Textual Introduction!
|
Welcome to the Textual Tutorial!
|
||||||
|
|
||||||
By the end of this page you should have a solid understanding of app development with Textual.
|
By the end of this page you should have a solid understanding of app development with Textual.
|
||||||
|
|
||||||
!!! quote
|
!!! quote
|
||||||
|
|
||||||
This page goes in to more detail than you may expect from an introduction. I like documentation to have complete working examples and I wanted the first app to be realistic.
|
I've always thought the secret sauce in making a popular framework is for it to be fun.
|
||||||
|
|
||||||
— **Will McGugan** (creator of Rich and Textual)
|
— **Will McGugan** (creator of Rich and Textual)
|
||||||
|
|
||||||
|
|
||||||
## Stopwatch Application
|
## Stopwatch Application
|
||||||
|
|
||||||
We're going to build a stopwatch application. It should show a list of stopwatches with a time display the user can start, stop, and reset. We also want the user to be able to add and remove stopwatches as required.
|
We're going to build a stopwatch application. This application should show a list of stopwatches with a time display the user can start, stop, and reset. We also want the user to be able to add and remove stopwatches as required.
|
||||||
|
|
||||||
This will be a simple yet **fully featured** app — you could distribute this app if you wanted to!
|
This will be a simple yet **fully featured** app — you could distribute this app if you wanted to!
|
||||||
|
|
||||||
Here's what the finished app will look like:
|
Here's what the finished app will look like:
|
||||||
|
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch.py" press="tab,enter,_,tab,enter,_,tab,_,enter,_,tab,enter,_,_"}
|
```{.textual path="docs/examples/tutorial/stopwatch.py" press="tab,enter,_,tab,enter,_,tab,_,enter,_,tab,enter,_,_"}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Get the code
|
### Get the code
|
||||||
|
|
||||||
If you want to try the finished Stopwatch app and follow along with the code, first make sure you have [Textual installed](getting_started.md) and then check out the [Textual](https://github.com/Textualize/textual) GitHub repository:
|
If you want to try the finished Stopwatch app and follow along with the code, first make sure you have [Textual installed](getting_started.md) then check out the [Textual](https://github.com/Textualize/textual) repository:
|
||||||
|
|
||||||
=== "HTTPS"
|
=== "HTTPS"
|
||||||
|
|
||||||
@@ -45,10 +45,10 @@ If you want to try the finished Stopwatch app and follow along with the code, fi
|
|||||||
gh repo clone Textualize/textual
|
gh repo clone Textualize/textual
|
||||||
```
|
```
|
||||||
|
|
||||||
With the repository cloned, navigate to `docs/examples/introduction` and run `stopwatch.py`.
|
With the repository cloned, navigate to `docs/examples/tutorial` and run `stopwatch.py`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd textual/docs/examples/introduction
|
cd textual/docs/examples/tutorial
|
||||||
python stopwatch.py
|
python stopwatch.py
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ python stopwatch.py
|
|||||||
|
|
||||||
Type hints are entirely optional in Textual. We've included them in the example code but it's up to you whether you add them to your own projects.
|
Type hints are entirely optional in Textual. We've included them in the example code but it's up to you whether you add them to your own projects.
|
||||||
|
|
||||||
We're a big fan of Python type hints at Textualize. If you haven't encountered type hinting, it's a way to express the types of your data, parameters, and return values. Type hinting allows tools like [Mypy](https://mypy.readthedocs.io/en/stable/) to catch potential bugs before your code runs.
|
We're a big fan of Python type hints at Textualize. If you haven't encountered type hinting, it's a way to express the types of your data, parameters, and return values. Type hinting allows tools like [Mypy](https://mypy.readthedocs.io/en/stable/) to catch bugs before your code runs.
|
||||||
|
|
||||||
The following function contains type hints:
|
The following function contains type hints:
|
||||||
|
|
||||||
@@ -68,8 +68,9 @@ def repeat(text: str, count: int) -> str:
|
|||||||
return text * count
|
return text * count
|
||||||
```
|
```
|
||||||
|
|
||||||
- Parameter types follow a colon. So `text: str` indicates that `text` requires a string and `count: int` means that `count` requires an integer.
|
Parameter types follow a colon. So `text: str` indicates that `text` requires a string and `count: int` means that `count` requires an integer.
|
||||||
- Return types follow `->`. So `-> str:` indicates this method returns a string.
|
|
||||||
|
Return types follow `->`. So `-> str:` indicates this method returns a string.
|
||||||
|
|
||||||
|
|
||||||
## The App class
|
## The App class
|
||||||
@@ -77,18 +78,18 @@ def repeat(text: str, count: int) -> str:
|
|||||||
The first step in building a Textual app is to import and extend the `App` class. Here's our basic app class with a few methods we will cover below.
|
The first step in building a Textual app is to import and extend the `App` class. Here's our basic app class with a few methods we will cover below.
|
||||||
|
|
||||||
```python title="stopwatch01.py"
|
```python title="stopwatch01.py"
|
||||||
--8<-- "docs/examples/introduction/stopwatch01.py"
|
--8<-- "docs/examples/tutorial/stopwatch01.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
If you run this code, you should see something like the following:
|
If you run this code, you should see something like the following:
|
||||||
|
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch01.py"}
|
```{.textual path="docs/examples/tutorial/stopwatch01.py"}
|
||||||
```
|
```
|
||||||
|
|
||||||
Hit the ++d++ key to toggle dark mode.
|
Hit the ++d++ key to toggle dark mode.
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch01.py" press="d" title="TimerApp + dark"}
|
```{.textual path="docs/examples/tutorial/stopwatch01.py" press="d" title="TimerApp + dark"}
|
||||||
```
|
```
|
||||||
|
|
||||||
Hit ++ctrl+c++ to exit the app and return to the command prompt.
|
Hit ++ctrl+c++ to exit the app and return to the command prompt.
|
||||||
@@ -98,27 +99,27 @@ Hit ++ctrl+c++ to exit the app and return to the command prompt.
|
|||||||
Let's examine stopwatch01.py in more detail.
|
Let's examine stopwatch01.py in more detail.
|
||||||
|
|
||||||
```python title="stopwatch01.py" hl_lines="1 2"
|
```python title="stopwatch01.py" hl_lines="1 2"
|
||||||
--8<-- "docs/examples/introduction/stopwatch01.py"
|
--8<-- "docs/examples/tutorial/stopwatch01.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
The first line imports the Textual `App` class. The second line imports two builtin widgets: `Footer` which shows available keys and `Header` which shows a title and the current time.
|
The first line imports the Textual `App` class. The second line imports two builtin widgets: `Footer` which shows available keys and `Header` which shows a title and the current time.
|
||||||
|
|
||||||
Widgets are re-usable components responsible for managing a part of the screen. We will cover how to build such widgets in this introduction.
|
Widgets are re-usable components responsible for managing a part of the screen. We will cover how to build such widgets in this tutorial.
|
||||||
|
|
||||||
|
|
||||||
```python title="stopwatch01.py" hl_lines="5-19"
|
```python title="stopwatch01.py" hl_lines="5-19"
|
||||||
--8<-- "docs/examples/introduction/stopwatch01.py"
|
--8<-- "docs/examples/tutorial/stopwatch01.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
The App class is where most of the logic of Textual apps is written. It is responsible for loading configuration, setting up widgets, handling keys, and more.
|
The App class is where most of the logic of Textual apps is written. It is responsible for loading configuration, setting up widgets, handling keys, and more.
|
||||||
|
|
||||||
Currently, there are three methods in our stopwatch app.
|
Currently, there are three methods in our stopwatch app.
|
||||||
|
|
||||||
- **`compose()`** is where we construct a user interface with widgets. The `compose()` method may return a list of widgets, but it is generally easier to _yield_ them (making this method a generator). In the example code we yield instances of the widget classes we imported, i.e. the header and the footer.
|
- `compose()` is where we construct a user interface with widgets. The `compose()` method may return a list of widgets, but it is generally easier to _yield_ them (making this method a generator). In the example code we yield instances of the widget classes we imported, i.e. the header and the footer.
|
||||||
|
|
||||||
- **`on_load()`** is an _event handler_ method. Event handlers are called by Textual in response to external events like keys and mouse movements, and internal events needed to manage your application. Event handler methods begin with `on_` followed by the name of the event (in lower case). Hence, `on_load` is called in response to the Load event which is sent just after the app starts. We're using this event to call `App.bind()` which connects a key to an _action_.
|
- `on_load()` is an _event handler_ method. Event handlers are called by Textual in response to external events like keys and mouse movements, and internal events needed to manage your application. Event handler methods begin with `on_` followed by the name of the event (in lower case). Hence, `on_load` is called in response to the Load event which is sent just after the app starts. We're using this event to call `App.bind()` which connects a key to an _action_.
|
||||||
|
|
||||||
- **`action_toggle_dark()`** defines an _action_ method. Actions are methods beginning with `action_` followed by the name of the action. The call to `bind()` in `on_load()` binds this the ++d++ key to this action. The body of this method flips the state of the `dark` Boolean to toggle dark mode.
|
- `action_toggle_dark()` defines an _action_ method. Actions are methods beginning with `action_` followed by the name of the action. The call to `bind()` in `on_load()` binds this the ++d++ key to this action. The body of this method flips the state of the `dark` Boolean to toggle dark mode.
|
||||||
|
|
||||||
!!! note
|
!!! note
|
||||||
|
|
||||||
@@ -126,7 +127,7 @@ Currently, there are three methods in our stopwatch app.
|
|||||||
|
|
||||||
|
|
||||||
```python title="stopwatch01.py" hl_lines="22-24"
|
```python title="stopwatch01.py" hl_lines="22-24"
|
||||||
--8<-- "docs/examples/introduction/stopwatch01.py"
|
--8<-- "docs/examples/tutorial/stopwatch01.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
The last few lines create an instance of the app at the module scope. Followed by a call to `run()` within a `__name__ == "__main__"` block. This is so that we could import `app` if we want to. Or we could run it with `python stopwatch01.py`.
|
The last few lines create an instance of the app at the module scope. Followed by a call to `run()` within a `__name__ == "__main__"` block. This is so that we could import `app` if we want to. Or we could run it with `python stopwatch01.py`.
|
||||||
@@ -153,7 +154,7 @@ Textual has a builtin `Button` widget which takes care of the first three compon
|
|||||||
Let's add those to the app. Just a skeleton for now, we will add the rest of the features as we go.
|
Let's add those to the app. Just a skeleton for now, we will add the rest of the features as we go.
|
||||||
|
|
||||||
```python title="stopwatch02.py" hl_lines="3 6-7 10-18 28"
|
```python title="stopwatch02.py" hl_lines="3 6-7 10-18 28"
|
||||||
--8<-- "docs/examples/introduction/stopwatch02.py"
|
--8<-- "docs/examples/tutorial/stopwatch02.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Extending widget classes
|
### Extending widget classes
|
||||||
@@ -180,7 +181,7 @@ The new line in `Stopwatch.compose()` yields a single `Container` object which w
|
|||||||
|
|
||||||
Let's see what happens when we run "stopwatch02.py".
|
Let's see what happens when we run "stopwatch02.py".
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch02.py" title="stopwatch02.py"}
|
```{.textual path="docs/examples/tutorial/stopwatch02.py" title="stopwatch02.py"}
|
||||||
```
|
```
|
||||||
|
|
||||||
The elements of the stopwatch application are there. The buttons are clickable and you can scroll the container but it doesn't look like the sketch. This is because we have yet to apply any _styles_ to our new widgets.
|
The elements of the stopwatch application are there. The buttons are clickable and you can scroll the container but it doesn't look like the sketch. This is because we have yet to apply any _styles_ to our new widgets.
|
||||||
@@ -204,18 +205,18 @@ While it's possible to set all styles for an app this way, it is rarely necessar
|
|||||||
Let's add a CSS file to our application.
|
Let's add a CSS file to our application.
|
||||||
|
|
||||||
```python title="stopwatch03.py" hl_lines="39"
|
```python title="stopwatch03.py" hl_lines="39"
|
||||||
--8<-- "docs/examples/introduction/stopwatch03.py"
|
--8<-- "docs/examples/tutorial/stopwatch03.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
Adding the `css_path` attribute to the app constructor tells Textual to load the following file when it starts the app:
|
Adding the `css_path` attribute to the app constructor tells Textual to load the following file when it starts the app:
|
||||||
|
|
||||||
```sass title="stopwatch03.css"
|
```sass title="stopwatch03.css"
|
||||||
--8<-- "docs/examples/introduction/stopwatch03.css"
|
--8<-- "docs/examples/tutorial/stopwatch03.css"
|
||||||
```
|
```
|
||||||
|
|
||||||
If we run the app now, it will look *very* different.
|
If we run the app now, it will look *very* different.
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch03.py" title="stopwatch03.py"}
|
```{.textual path="docs/examples/tutorial/stopwatch03.py" title="stopwatch03.py"}
|
||||||
```
|
```
|
||||||
|
|
||||||
This app looks much more like our sketch. Textual has read style information from `stopwatch03.css` and applied it to the widgets.
|
This app looks much more like our sketch. Textual has read style information from `stopwatch03.css` and applied it to the widgets.
|
||||||
@@ -295,7 +296,7 @@ We can accomplish this with a CSS _class_. Not to be confused with a Python clas
|
|||||||
Here's the new CSS:
|
Here's the new CSS:
|
||||||
|
|
||||||
```sass title="stopwatch04.css" hl_lines="33-53"
|
```sass title="stopwatch04.css" hl_lines="33-53"
|
||||||
--8<-- "docs/examples/introduction/stopwatch04.css"
|
--8<-- "docs/examples/tutorial/stopwatch04.css"
|
||||||
```
|
```
|
||||||
|
|
||||||
These new rules are prefixed with `.started`. The `.` indicates that `.started` refers to a CSS class called "started". The new styles will be applied only to widgets that have this CSS class.
|
These new rules are prefixed with `.started`. The `.` indicates that `.started` refers to a CSS class called "started". The new styles will be applied only to widgets that have this CSS class.
|
||||||
@@ -323,24 +324,24 @@ You can add and remove CSS classes with the `add_class()` and `remove_class()` m
|
|||||||
The following code adds an event handler for the `Button.Pressed` event.
|
The following code adds an event handler for the `Button.Pressed` event.
|
||||||
|
|
||||||
```python title="stopwatch04.py" hl_lines="13-18"
|
```python title="stopwatch04.py" hl_lines="13-18"
|
||||||
--8<-- "docs/examples/introduction/stopwatch04.py"
|
--8<-- "docs/examples/tutorial/stopwatch04.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
The `on_button_pressed` event handler is called when the user clicks a button. This method adds the "started" class when the "start" button was clicked, and removes the class when the "stop" button is clicked.
|
The `on_button_pressed` event handler is called when the user clicks a button. This method adds the "started" class when the "start" button was clicked, and removes the class when the "stop" button is clicked.
|
||||||
|
|
||||||
If you run "stopwatch04.py" now you will be able to toggle between the two states by clicking the first button:
|
If you run "stopwatch04.py" now you will be able to toggle between the two states by clicking the first button:
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch04.py" title="stopwatch04.py" press="tab,tab,tab,enter"}
|
```{.textual path="docs/examples/tutorial/stopwatch04.py" title="stopwatch04.py" press="tab,tab,tab,enter"}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Reactive attributes
|
## Reactive attributes
|
||||||
|
|
||||||
A recurring theme in Textual is that you rarely need to explicitly update a widget. It is possible: you can call [`refresh()`][textual.widget.Widget.refresh] to display new data. However, Textual prefers to do this automatically via _reactive_ attributes.
|
A recurring theme in Textual is that you rarely need to explicitly update a widget. It is possible: you can call [`refresh()`][textual.widget.Widget.refresh] to display new data. However, Textual prefers to do this automatically via _reactive_ attributes.
|
||||||
|
|
||||||
You can declare a reactive attribute with `textual.reactive.Reactive`. Let's use this feature to create a timer that displays elapsed time and keeps it updated.
|
You can declare a reactive attribute with [Reactive][textual.reactive.Reactive]. Let's use this feature to create a timer that displays elapsed time and keeps it updated.
|
||||||
|
|
||||||
```python title="stopwatch04.py" hl_lines="1 5 12-27"
|
```python title="stopwatch04.py" hl_lines="1 5 12-27"
|
||||||
--8<-- "docs/examples/introduction/stopwatch05.py"
|
--8<-- "docs/examples/tutorial/stopwatch05.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
We have added two reactive attributes: `start_time` will contain the time in seconds when the stopwatch was started, and `time` will contain the time to be displayed on the Stopwatch.
|
We have added two reactive attributes: `start_time` will contain the time in seconds when the stopwatch was started, and `time` will contain the time to be displayed on the Stopwatch.
|
||||||
@@ -368,7 +369,7 @@ Because `watch_time` watches the `time` attribute, when we update `self.time` 60
|
|||||||
|
|
||||||
The end result is that the `Stopwatch` widgets show the time elapsed since the widget was created:
|
The end result is that the `Stopwatch` widgets show the time elapsed since the widget was created:
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch05.py" title="stopwatch05.py"}
|
```{.textual path="docs/examples/tutorial/stopwatch05.py" title="stopwatch05.py"}
|
||||||
```
|
```
|
||||||
|
|
||||||
We've seen how we can update widgets with a timer, but we still need to wire up the buttons so we can operate Stopwatches independently.
|
We've seen how we can update widgets with a timer, but we still need to wire up the buttons so we can operate Stopwatches independently.
|
||||||
@@ -379,7 +380,7 @@ We need to be able to start, stop, and reset each stopwatch independently. We ca
|
|||||||
|
|
||||||
|
|
||||||
```python title="stopwatch06.py" hl_lines="14-44 50-61"
|
```python title="stopwatch06.py" hl_lines="14-44 50-61"
|
||||||
--8<-- "docs/examples/introduction/stopwatch06.py"
|
--8<-- "docs/examples/tutorial/stopwatch06.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
Here's a summary of the changes made to `TimeDisplay`.
|
Here's a summary of the changes made to `TimeDisplay`.
|
||||||
@@ -415,7 +416,7 @@ This code supplies missing features and makes our app useful. We've made the fol
|
|||||||
|
|
||||||
If you run stopwatch06.py you will be able to use the stopwatches independently.
|
If you run stopwatch06.py you will be able to use the stopwatches independently.
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch06.py" title="stopwatch06.py" press="tab,enter,_,_,tab,enter,_,tab"}
|
```{.textual path="docs/examples/tutorial/stopwatch06.py" title="stopwatch06.py" press="tab,enter,_,_,tab,enter,_,tab"}
|
||||||
```
|
```
|
||||||
|
|
||||||
The only remaining feature of the Stopwatch app left to implement is the ability to add and remove timers.
|
The only remaining feature of the Stopwatch app left to implement is the ability to add and remove timers.
|
||||||
@@ -429,7 +430,7 @@ To add a new child widget call `mount()` on the parent. To remove a widget, call
|
|||||||
Let's use these to implement adding and removing stopwatches to our app.
|
Let's use these to implement adding and removing stopwatches to our app.
|
||||||
|
|
||||||
```python title="stopwatch.py" hl_lines="83-84 86-90 92-96"
|
```python title="stopwatch.py" hl_lines="83-84 86-90 92-96"
|
||||||
--8<-- "docs/examples/introduction/stopwatch.py"
|
--8<-- "docs/examples/tutorial/stopwatch.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
We've added two new actions: `action_add_stopwatch` to add a new stopwatch, and `action_remove_stopwatch` to remove the last stopwatch. The `on_load` handler binds these actions to the ++a++ and ++r++ keys.
|
We've added two new actions: `action_add_stopwatch` to add a new stopwatch, and `action_remove_stopwatch` to remove the last stopwatch. The `on_load` handler binds these actions to the ++a++ and ++r++ keys.
|
||||||
@@ -440,11 +441,11 @@ The `action_remove_stopwatch` calls `query` with a CSS selector of `"Stopwatch"`
|
|||||||
|
|
||||||
If you run `stopwatch.py` now you can add a new stopwatch with the ++a++ key and remove a stopwatch with ++r++.
|
If you run `stopwatch.py` now you can add a new stopwatch with the ++a++ key and remove a stopwatch with ++r++.
|
||||||
|
|
||||||
```{.textual path="docs/examples/introduction/stopwatch.py" press="d,a,a,a,a,a,a,a,tab,enter,_,_,_,_,tab,_"}
|
```{.textual path="docs/examples/tutorial/stopwatch.py" press="d,a,a,a,a,a,a,a,tab,enter,_,_,_,_,tab,_"}
|
||||||
```
|
```
|
||||||
|
|
||||||
## What next?
|
## What next?
|
||||||
|
|
||||||
Congratulations on building your first Textual application! This introduction has covered a lot of ground. If you are the type that prefers to learn a framework by coding, feel free. You could tweak stopwatch.py or look through the examples.
|
Congratulations on building your first Textual application! This tutorial has covered a lot of ground. If you are the type that prefers to learn a framework by coding, feel free. You could tweak stopwatch.py or look through the examples.
|
||||||
|
|
||||||
Read the guide for the full details on how to build sophisticated TUI applications with Textual.
|
Read the guide for the full details on how to build sophisticated TUI applications with Textual.
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
# Messages & Events
|
|
||||||
|
|
||||||
Each component of a Textual application has it its heart a queue of messages and a task which monitors this queue and calls Python code in response. The queue and task are collectively known as a _message pump_.
|
|
||||||
|
|
||||||
You will most often deal with _events_ which are a particular type of message that are created in response to user actions, such as key presses and mouse clicks, but also internal events such as timers. These events typically originate from a Driver class which sends them to an App class which is where you write code to respond to those events.
|
|
||||||
|
|
||||||
Lets write an _app_ which responds to a key event. This is probably the simplest Textual application that I can conceive of:
|
|
||||||
|
|
||||||
```python
|
|
||||||
from textual.app import App
|
|
||||||
|
|
||||||
|
|
||||||
class Beeper(App):
|
|
||||||
async def on_key(self, event):
|
|
||||||
self.console.bell()
|
|
||||||
|
|
||||||
|
|
||||||
Beeper.run()
|
|
||||||
```
|
|
||||||
|
|
||||||
If you run the above code, Textual will switch the terminal in to _application mode_. The terminal will go blank and the app will start processing events. If you hit any key you should hear a beep. Hit ctrl+C (control key and C key at the same time) to exit application mode and return to the terminal.
|
|
||||||
|
|
||||||
Although simple, this app follows the same pattern as more sophisticated applications. It starts by deriving a class from `App`; in this case `Beeper`. Calling the classmethod `run()` starts the application.
|
|
||||||
|
|
||||||
In our Beeper class there is a single event handler `on_key` which is called in response to a `Key` event. The method name is assumed by concatenating `on_` with the event name, hence `on_key` for a Key event, `on_timer` for a Timer event, etc. In Beeper, the on_key event calls `self.console.bell()` which is what plays the beep noise (if supported by your terminal).
|
|
||||||
|
|
||||||
The `on_key` method is preceded by the keyword `async` making it an asynchronous method. Textual is an asynchronous framework so event handlers and most methods are async.
|
|
||||||
|
|
||||||
Our Beeper app is missing typing information. Although completely optional, I recommend adding typing information which will help catch bugs (using tools such as [Mypy](https://mypy.readthedocs.io/en/stable/)). Here is the Beeper class with added typing:
|
|
||||||
|
|
||||||
```python
|
|
||||||
from textual.app import App
|
|
||||||
from textual import events
|
|
||||||
|
|
||||||
|
|
||||||
class Beeper(App):
|
|
||||||
async def on_key(self, event: events.Key) -> None:
|
|
||||||
self.console.bell()
|
|
||||||
|
|
||||||
|
|
||||||
Beeper.run()
|
|
||||||
```
|
|
||||||
1
docs/widgets/button.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Button
|
||||||
1
docs/widgets/data_table.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# DataTable
|
||||||
1
docs/widgets/footer.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Footer
|
||||||
1
docs/widgets/header.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Header
|
||||||
3
docs/widgets/index.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Widgets
|
||||||
|
|
||||||
|
A reference to the builtin [widgets](../guide/widgets.md).
|
||||||
1
docs/widgets/static.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Static
|
||||||
@@ -1 +0,0 @@
|
|||||||
::: textual.widgets.tabs.Tabs
|
|
||||||
1
docs/widgets/text_input.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# TextInput
|
||||||
1
docs/widgets/tree_control.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# TreeControl
|
||||||
@@ -3,11 +3,11 @@ Screen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#calculator {
|
#calculator {
|
||||||
layout: table;
|
layout: grid;
|
||||||
table-size: 4;
|
grid-size: 4;
|
||||||
table-gutter: 1 2;
|
grid-gutter: 1 2;
|
||||||
table-columns: 1fr;
|
grid-columns: 1fr;
|
||||||
table-rows: 2fr 1fr 1fr 1fr 1fr 1fr;
|
grid-rows: 2fr 1fr 1fr 1fr 1fr 1fr;
|
||||||
margin: 1 2;
|
margin: 1 2;
|
||||||
min-height:25;
|
min-height:25;
|
||||||
min-width: 26;
|
min-width: 26;
|
||||||
|
|||||||
39
mkdocs.yml
@@ -4,19 +4,31 @@ site_url: https://www.textualize.io/
|
|||||||
nav:
|
nav:
|
||||||
- "index.md"
|
- "index.md"
|
||||||
- "getting_started.md"
|
- "getting_started.md"
|
||||||
- "introduction.md"
|
- "tutorial.md"
|
||||||
- Guide:
|
- Guide:
|
||||||
|
- "guide/index.md"
|
||||||
- "guide/devtools.md"
|
- "guide/devtools.md"
|
||||||
|
- "guide/app.md"
|
||||||
|
- "guide/styles.md"
|
||||||
- "guide/CSS.md"
|
- "guide/CSS.md"
|
||||||
|
- "guide/layout.md"
|
||||||
- "guide/events.md"
|
- "guide/events.md"
|
||||||
|
- "guide/actions.md"
|
||||||
- "actions.md"
|
- "guide/reactivity.md"
|
||||||
|
- "guide/widgets.md"
|
||||||
|
- "guide/animator.md"
|
||||||
|
- "guide/screens.md"
|
||||||
|
- How to:
|
||||||
|
- "how-to/index.md"
|
||||||
|
- "how-to/animation.md"
|
||||||
|
- "how-to/mouse-and-keyboard.md"
|
||||||
|
- "how-to/scroll.md"
|
||||||
- Events:
|
- Events:
|
||||||
|
- "events/index.md"
|
||||||
- "events/blur.md"
|
- "events/blur.md"
|
||||||
- "events/descendant_blur.md"
|
- "events/descendant_blur.md"
|
||||||
- "events/descendant_focus.md"
|
- "events/descendant_focus.md"
|
||||||
- "events/enter.md"
|
- "events/enter.md"
|
||||||
- "events/enter.md"
|
|
||||||
- "events/focus.md"
|
- "events/focus.md"
|
||||||
- "events/hide.md"
|
- "events/hide.md"
|
||||||
- "events/key.md"
|
- "events/key.md"
|
||||||
@@ -37,6 +49,7 @@ nav:
|
|||||||
- "events/screen_suspend.md"
|
- "events/screen_suspend.md"
|
||||||
- "events/show.md"
|
- "events/show.md"
|
||||||
- Styles:
|
- Styles:
|
||||||
|
- "styles/index.md"
|
||||||
- "styles/background.md"
|
- "styles/background.md"
|
||||||
- "styles/border.md"
|
- "styles/border.md"
|
||||||
- "styles/box_sizing.md"
|
- "styles/box_sizing.md"
|
||||||
@@ -64,9 +77,19 @@ nav:
|
|||||||
- "styles/tint.md"
|
- "styles/tint.md"
|
||||||
- "styles/visibility.md"
|
- "styles/visibility.md"
|
||||||
- "styles/width.md"
|
- "styles/width.md"
|
||||||
- Widgets: "/widgets/"
|
- Widgets:
|
||||||
|
- "widgets/index.md"
|
||||||
|
- "widgets/button.md"
|
||||||
|
- "widgets/data_table.md"
|
||||||
|
- "widgets/footer.md"
|
||||||
|
- "widgets/header.md"
|
||||||
|
- "widgets/static.md"
|
||||||
|
- "widgets/text_input.md"
|
||||||
|
- "widgets/tree_control.md"
|
||||||
- Reference:
|
- Reference:
|
||||||
|
- "reference/index.md"
|
||||||
- "reference/app.md"
|
- "reference/app.md"
|
||||||
|
- "reference/button.md"
|
||||||
- "reference/color.md"
|
- "reference/color.md"
|
||||||
- "reference/dom_node.md"
|
- "reference/dom_node.md"
|
||||||
- "reference/events.md"
|
- "reference/events.md"
|
||||||
@@ -94,6 +117,7 @@ markdown_extensions:
|
|||||||
custom_checkbox: true
|
custom_checkbox: true
|
||||||
- pymdownx.highlight:
|
- pymdownx.highlight:
|
||||||
anchor_linenums: true
|
anchor_linenums: true
|
||||||
|
- pymdownx.inlinehilite
|
||||||
- pymdownx.superfences:
|
- pymdownx.superfences:
|
||||||
custom_fences:
|
custom_fences:
|
||||||
- name: textual
|
- name: textual
|
||||||
@@ -110,8 +134,9 @@ markdown_extensions:
|
|||||||
theme:
|
theme:
|
||||||
name: material
|
name: material
|
||||||
custom_dir: custom_theme
|
custom_dir: custom_theme
|
||||||
# features:
|
features:
|
||||||
# - navigation.tabs
|
- navigation.tabs
|
||||||
|
- navigation.indexes
|
||||||
palette:
|
palette:
|
||||||
- media: "(prefers-color-scheme: light)"
|
- media: "(prefers-color-scheme: light)"
|
||||||
scheme: default
|
scheme: default
|
||||||
|
|||||||
2
poetry.lock
generated
@@ -345,7 +345,7 @@ mkdocs = ">=1.1"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mkdocs-material"
|
name = "mkdocs-material"
|
||||||
version = "8.4.1"
|
version = "8.4.2"
|
||||||
description = "Documentation that simply works"
|
description = "Documentation that simply works"
|
||||||
category = "dev"
|
category = "dev"
|
||||||
optional = false
|
optional = false
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ Screen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#calculator {
|
#calculator {
|
||||||
layout: table;
|
layout: grid;
|
||||||
table-size: 4;
|
grid-size: 4;
|
||||||
table-gutter: 1 2;
|
grid-gutter: 1 2;
|
||||||
table-columns: 1fr;
|
grid-columns: 1fr;
|
||||||
table-rows: 2fr 1fr 1fr 1fr 1fr 1fr;
|
grid-rows: 2fr 1fr 1fr 1fr 1fr 1fr;
|
||||||
margin: 1 2;
|
margin: 1 2;
|
||||||
min-height:25;
|
min-height:25;
|
||||||
min-width: 26;
|
min-width: 26;
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
Screen {
|
Screen {
|
||||||
layout: table;
|
layout: grid;
|
||||||
table-columns: 2fr 1fr 1fr;
|
grid-columns: 2fr 1fr 1fr;
|
||||||
table-rows: 1fr 1fr;
|
grid-rows: 1fr 1fr;
|
||||||
table-gutter: 1 2;
|
grid-gutter: 1 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
Static {
|
Static {
|
||||||
|
|||||||
@@ -92,6 +92,11 @@ class Logger:
|
|||||||
"""An error logger."""
|
"""An error logger."""
|
||||||
return Logger(LogGroup.ERROR)
|
return Logger(LogGroup.ERROR)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def system(self) -> Logger:
|
||||||
|
"""A system logger."""
|
||||||
|
return Logger(LogGroup.SYSTEM)
|
||||||
|
|
||||||
|
|
||||||
log = Logger()
|
log = Logger()
|
||||||
|
|
||||||
|
|||||||
@@ -222,6 +222,7 @@ class Compositor:
|
|||||||
for y in range(region_y, region_y + height):
|
for y in range(region_y, region_y + height):
|
||||||
setdefault(y, []).append(span)
|
setdefault(y, []).append(span)
|
||||||
|
|
||||||
|
slice_remaining = slice(1, None)
|
||||||
for y, ranges in sorted(inline_ranges.items()):
|
for y, ranges in sorted(inline_ranges.items()):
|
||||||
if len(ranges) == 1:
|
if len(ranges) == 1:
|
||||||
# Special case of 1 span
|
# Special case of 1 span
|
||||||
@@ -229,7 +230,7 @@ class Compositor:
|
|||||||
else:
|
else:
|
||||||
ranges.sort()
|
ranges.sort()
|
||||||
x1, x2 = ranges[0]
|
x1, x2 = ranges[0]
|
||||||
for next_x1, next_x2 in ranges[1:]:
|
for next_x1, next_x2 in ranges[slice_remaining]:
|
||||||
if next_x1 <= x2:
|
if next_x1 <= x2:
|
||||||
if next_x2 > x2:
|
if next_x2 > x2:
|
||||||
x2 = next_x2
|
x2 = next_x2
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import runpy
|
||||||
import os
|
import os
|
||||||
from typing import cast, TYPE_CHECKING
|
from typing import cast, TYPE_CHECKING
|
||||||
|
|
||||||
@@ -11,36 +12,36 @@ if TYPE_CHECKING:
|
|||||||
def format_svg(source, language, css_class, options, md, attrs, **kwargs) -> str:
|
def format_svg(source, language, css_class, options, md, attrs, **kwargs) -> str:
|
||||||
"""A superfences formatter to insert a SVG screenshot."""
|
"""A superfences formatter to insert a SVG screenshot."""
|
||||||
|
|
||||||
path: str = attrs["path"]
|
|
||||||
_press = attrs.get("press", None)
|
|
||||||
press = [*_press.split(",")] if _press else ["_"]
|
|
||||||
title = attrs.get("title")
|
|
||||||
|
|
||||||
os.environ["COLUMNS"] = attrs.get("columns", "80")
|
|
||||||
os.environ["LINES"] = attrs.get("lines", "24")
|
|
||||||
|
|
||||||
print(f"screenshotting {path!r}")
|
|
||||||
|
|
||||||
cwd = os.getcwd()
|
|
||||||
examples_path, filename = os.path.split(path)
|
|
||||||
try:
|
try:
|
||||||
os.chdir(examples_path)
|
path: str = attrs["path"]
|
||||||
with open(filename, "rt") as python_code:
|
_press = attrs.get("press", None)
|
||||||
source = python_code.read()
|
press = [*_press.split(",")] if _press else ["_"]
|
||||||
app_vars: dict[str, object] = {}
|
title = attrs.get("title")
|
||||||
exec(source, app_vars)
|
|
||||||
|
|
||||||
app: App = cast("App", app_vars["app"])
|
os.environ["COLUMNS"] = attrs.get("columns", "80")
|
||||||
app.run(
|
os.environ["LINES"] = attrs.get("lines", "24")
|
||||||
quit_after=5,
|
|
||||||
press=press or ["ctrl+c"],
|
|
||||||
headless=True,
|
|
||||||
screenshot=True,
|
|
||||||
screenshot_title=title,
|
|
||||||
)
|
|
||||||
svg = app._screenshot
|
|
||||||
finally:
|
|
||||||
os.chdir(cwd)
|
|
||||||
|
|
||||||
assert svg is not None
|
print(f"screenshotting {path!r}")
|
||||||
return svg
|
|
||||||
|
cwd = os.getcwd()
|
||||||
|
try:
|
||||||
|
app_vars = runpy.run_path(path)
|
||||||
|
app: App = cast("App", app_vars["app"])
|
||||||
|
app.run(
|
||||||
|
quit_after=5,
|
||||||
|
press=press or ["ctrl+c"],
|
||||||
|
headless=True,
|
||||||
|
screenshot=True,
|
||||||
|
screenshot_title=title,
|
||||||
|
)
|
||||||
|
svg = app._screenshot
|
||||||
|
finally:
|
||||||
|
os.chdir(cwd)
|
||||||
|
|
||||||
|
assert svg is not None
|
||||||
|
return svg
|
||||||
|
|
||||||
|
except Exception as error:
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
traceback.print_exception(error)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ class LogGroup(Enum):
|
|||||||
WARNING = 4
|
WARNING = 4
|
||||||
ERROR = 5
|
ERROR = 5
|
||||||
PRINT = 6
|
PRINT = 6
|
||||||
|
SYSTEM = 7
|
||||||
|
|
||||||
|
|
||||||
class LogVerbosity(Enum):
|
class LogVerbosity(Enum):
|
||||||
|
|||||||
@@ -9,18 +9,9 @@ import sys
|
|||||||
import warnings
|
import warnings
|
||||||
from contextlib import redirect_stderr, redirect_stdout
|
from contextlib import redirect_stderr, redirect_stdout
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import PurePath, Path
|
from pathlib import Path, PurePath
|
||||||
from time import perf_counter
|
from time import perf_counter
|
||||||
from typing import (
|
from typing import Any, Generator, Generic, Iterable, Iterator, Type, TypeVar, cast
|
||||||
Any,
|
|
||||||
Generic,
|
|
||||||
Iterable,
|
|
||||||
Iterator,
|
|
||||||
TextIO,
|
|
||||||
Type,
|
|
||||||
TypeVar,
|
|
||||||
cast,
|
|
||||||
)
|
|
||||||
from weakref import WeakSet, WeakValueDictionary
|
from weakref import WeakSet, WeakValueDictionary
|
||||||
|
|
||||||
from ._ansi_sequences import SYNC_END, SYNC_START
|
from ._ansi_sequences import SYNC_END, SYNC_START
|
||||||
@@ -42,8 +33,8 @@ from rich.traceback import Traceback
|
|||||||
|
|
||||||
from . import (
|
from . import (
|
||||||
Logger,
|
Logger,
|
||||||
LogSeverity,
|
|
||||||
LogGroup,
|
LogGroup,
|
||||||
|
LogSeverity,
|
||||||
LogVerbosity,
|
LogVerbosity,
|
||||||
actions,
|
actions,
|
||||||
events,
|
events,
|
||||||
@@ -72,7 +63,6 @@ from .renderables.blank import Blank
|
|||||||
from .screen import Screen
|
from .screen import Screen
|
||||||
from .widget import Widget
|
from .widget import Widget
|
||||||
|
|
||||||
|
|
||||||
PLATFORM = platform.system()
|
PLATFORM = platform.system()
|
||||||
WINDOWS = PLATFORM == "Windows"
|
WINDOWS = PLATFORM == "Windows"
|
||||||
|
|
||||||
@@ -143,7 +133,6 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
driver_class (Type[Driver] | None, optional): Driver class or ``None`` to auto-detect. Defaults to None.
|
driver_class (Type[Driver] | None, optional): Driver class or ``None`` to auto-detect. Defaults to None.
|
||||||
log_verbosity (int, optional): Log verbosity from 0-3. Defaults to 1.
|
|
||||||
title (str | None, optional): Title of the application. If ``None``, the title is set to the name of the ``App`` subclass. Defaults to ``None``.
|
title (str | None, optional): Title of the application. If ``None``, the title is set to the name of the ``App`` subclass. Defaults to ``None``.
|
||||||
css_path (str | PurePath | None, optional): Path to CSS or ``None`` for no CSS file. Defaults to None.
|
css_path (str | PurePath | None, optional): Path to CSS or ``None`` for no CSS file. Defaults to None.
|
||||||
watch_css (bool, optional): Watch CSS for changes. Defaults to False.
|
watch_css (bool, optional): Watch CSS for changes. Defaults to False.
|
||||||
@@ -693,7 +682,9 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
stylesheet.read(self.css_path)
|
stylesheet.read(self.css_path)
|
||||||
stylesheet.parse()
|
stylesheet.parse()
|
||||||
elapsed = (perf_counter() - time) * 1000
|
elapsed = (perf_counter() - time) * 1000
|
||||||
self.log(f"<stylesheet> loaded {self.css_path!r} in {elapsed:.0f} ms")
|
self.log.system(
|
||||||
|
f"<stylesheet> loaded {self.css_path!r} in {elapsed:.0f} ms"
|
||||||
|
)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
# TODO: Catch specific exceptions
|
# TODO: Catch specific exceptions
|
||||||
self.log.error(error)
|
self.log.error(error)
|
||||||
@@ -803,10 +794,10 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
screen.post_message_no_wait(events.ScreenSuspend(self))
|
screen.post_message_no_wait(events.ScreenSuspend(self))
|
||||||
self.log(f"{screen} SUSPENDED")
|
self.log.system(f"{screen} SUSPENDED")
|
||||||
if not self.is_screen_installed(screen) and screen not in self._screen_stack:
|
if not self.is_screen_installed(screen) and screen not in self._screen_stack:
|
||||||
screen.remove()
|
screen.remove()
|
||||||
self.log(f"{screen} REMOVED")
|
self.log.system(f"{screen} REMOVED")
|
||||||
return screen
|
return screen
|
||||||
|
|
||||||
def push_screen(self, screen: Screen | str) -> None:
|
def push_screen(self, screen: Screen | str) -> None:
|
||||||
@@ -819,7 +810,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
next_screen = self.get_screen(screen)
|
next_screen = self.get_screen(screen)
|
||||||
self._screen_stack.append(next_screen)
|
self._screen_stack.append(next_screen)
|
||||||
self.screen.post_message_no_wait(events.ScreenResume(self))
|
self.screen.post_message_no_wait(events.ScreenResume(self))
|
||||||
self.log(f"{self.screen} is current (PUSHED)")
|
self.log.system(f"{self.screen} is current (PUSHED)")
|
||||||
|
|
||||||
def switch_screen(self, screen: Screen | str) -> None:
|
def switch_screen(self, screen: Screen | str) -> None:
|
||||||
"""Switch to a another screen by replacing the top of the screen stack with a new screen.
|
"""Switch to a another screen by replacing the top of the screen stack with a new screen.
|
||||||
@@ -833,7 +824,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
next_screen = self.get_screen(screen)
|
next_screen = self.get_screen(screen)
|
||||||
self._screen_stack.append(next_screen)
|
self._screen_stack.append(next_screen)
|
||||||
self.screen.post_message_no_wait(events.ScreenResume(self))
|
self.screen.post_message_no_wait(events.ScreenResume(self))
|
||||||
self.log(f"{self.screen} is current (SWITCHED)")
|
self.log.system(f"{self.screen} is current (SWITCHED)")
|
||||||
|
|
||||||
def install_screen(self, screen: Screen, name: str | None = None) -> str:
|
def install_screen(self, screen: Screen, name: str | None = None) -> str:
|
||||||
"""Install a screen.
|
"""Install a screen.
|
||||||
@@ -859,7 +850,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
)
|
)
|
||||||
self._installed_screens[name] = screen
|
self._installed_screens[name] = screen
|
||||||
self.get_screen(name) # Ensures screen is running
|
self.get_screen(name) # Ensures screen is running
|
||||||
self.log(f"{screen} INSTALLED name={name!r}")
|
self.log.system(f"{screen} INSTALLED name={name!r}")
|
||||||
return name
|
return name
|
||||||
|
|
||||||
def uninstall_screen(self, screen: Screen | str) -> str | None:
|
def uninstall_screen(self, screen: Screen | str) -> str | None:
|
||||||
@@ -879,7 +870,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
if uninstall_screen in self._screen_stack:
|
if uninstall_screen in self._screen_stack:
|
||||||
raise ScreenStackError("Can't uninstall screen in screen stack")
|
raise ScreenStackError("Can't uninstall screen in screen stack")
|
||||||
del self._installed_screens[screen]
|
del self._installed_screens[screen]
|
||||||
self.log(f"{uninstall_screen} UNINSTALLED name={screen!r}")
|
self.log.system(f"{uninstall_screen} UNINSTALLED name={screen!r}")
|
||||||
return screen
|
return screen
|
||||||
else:
|
else:
|
||||||
if screen in self._screen_stack:
|
if screen in self._screen_stack:
|
||||||
@@ -887,7 +878,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
for name, installed_screen in self._installed_screens.items():
|
for name, installed_screen in self._installed_screens.items():
|
||||||
if installed_screen is screen:
|
if installed_screen is screen:
|
||||||
self._installed_screens.pop(name)
|
self._installed_screens.pop(name)
|
||||||
self.log(f"{screen} UNINSTALLED name={name!r}")
|
self.log.system(f"{screen} UNINSTALLED name={name!r}")
|
||||||
return name
|
return name
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -905,7 +896,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
previous_screen = self._replace_screen(screen_stack.pop())
|
previous_screen = self._replace_screen(screen_stack.pop())
|
||||||
self.screen._screen_resized(self.size)
|
self.screen._screen_resized(self.size)
|
||||||
self.screen.post_message_no_wait(events.ScreenResume(self))
|
self.screen.post_message_no_wait(events.ScreenResume(self))
|
||||||
self.log(f"{self.screen} is active")
|
self.log.system(f"{self.screen} is active")
|
||||||
return previous_screen
|
return previous_screen
|
||||||
|
|
||||||
def set_focus(self, widget: Widget | None) -> None:
|
def set_focus(self, widget: Widget | None) -> None:
|
||||||
@@ -1045,15 +1036,15 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
if self.devtools_enabled:
|
if self.devtools_enabled:
|
||||||
try:
|
try:
|
||||||
await self.devtools.connect()
|
await self.devtools.connect()
|
||||||
self.log(f"Connected to devtools ( {self.devtools.url} )")
|
self.log.system(f"Connected to devtools ( {self.devtools.url} )")
|
||||||
except DevtoolsConnectionError:
|
except DevtoolsConnectionError:
|
||||||
self.log(f"Couldn't connect to devtools ( {self.devtools.url} )")
|
self.log.system(f"Couldn't connect to devtools ( {self.devtools.url} )")
|
||||||
|
|
||||||
self.log("---")
|
self.log.system("---")
|
||||||
|
|
||||||
self.log(driver=self.driver_class)
|
self.log.system(driver=self.driver_class)
|
||||||
self.log(loop=asyncio.get_running_loop())
|
self.log.system(loop=asyncio.get_running_loop())
|
||||||
self.log(features=self.features)
|
self.log.system(features=self.features)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if self.css_path is not None:
|
if self.css_path is not None:
|
||||||
@@ -1079,7 +1070,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
|
|
||||||
if self.css_monitor:
|
if self.css_monitor:
|
||||||
self.set_interval(0.25, self.css_monitor, name="css monitor")
|
self.set_interval(0.25, self.css_monitor, name="css monitor")
|
||||||
self.log("[b green]STARTED[/]", self.css_monitor)
|
self.log.system("[b green]STARTED[/]", self.css_monitor)
|
||||||
|
|
||||||
process_messages = super()._process_messages
|
process_messages = super()._process_messages
|
||||||
|
|
||||||
@@ -1188,9 +1179,7 @@ class App(Generic[ReturnType], DOMNode):
|
|||||||
parent (Widget): Parent Widget
|
parent (Widget): Parent Widget
|
||||||
"""
|
"""
|
||||||
if not anon_widgets and not widgets:
|
if not anon_widgets and not widgets:
|
||||||
raise AppError(
|
return
|
||||||
"Nothing to mount, did you forget parent as first positional arg?"
|
|
||||||
)
|
|
||||||
name_widgets: Iterable[tuple[str | None, Widget]]
|
name_widgets: Iterable[tuple[str | None, Widget]]
|
||||||
name_widgets = [*((None, widget) for widget in anon_widgets), *widgets.items()]
|
name_widgets = [*((None, widget) for widget in anon_widgets), *widgets.items()]
|
||||||
apply_stylesheet = self.stylesheet.apply
|
apply_stylesheet = self.stylesheet.apply
|
||||||
|
|||||||
@@ -847,7 +847,7 @@ class StylesBuilder:
|
|||||||
self.error(name, token, scrollbar_size_single_axis_help_text(name))
|
self.error(name, token, scrollbar_size_single_axis_help_text(name))
|
||||||
self.styles._rules["scrollbar_size_horizontal"] = value
|
self.styles._rules["scrollbar_size_horizontal"] = value
|
||||||
|
|
||||||
def _process_table_rows_or_columns(self, name: str, tokens: list[Token]) -> None:
|
def _process_grid_rows_or_columns(self, name: str, tokens: list[Token]) -> None:
|
||||||
scalars: list[Scalar] = []
|
scalars: list[Scalar] = []
|
||||||
for token in tokens:
|
for token in tokens:
|
||||||
if token.name == "number":
|
if token.name == "number":
|
||||||
@@ -867,8 +867,8 @@ class StylesBuilder:
|
|||||||
)
|
)
|
||||||
self.styles._rules[name.replace("-", "_")] = scalars
|
self.styles._rules[name.replace("-", "_")] = scalars
|
||||||
|
|
||||||
process_table_rows = _process_table_rows_or_columns
|
process_grid_rows = _process_grid_rows_or_columns
|
||||||
process_table_columns = _process_table_rows_or_columns
|
process_grid_columns = _process_grid_rows_or_columns
|
||||||
|
|
||||||
def _process_integer(self, name: str, tokens: list[Token]) -> None:
|
def _process_integer(self, name: str, tokens: list[Token]) -> None:
|
||||||
if not tokens:
|
if not tokens:
|
||||||
@@ -884,14 +884,14 @@ class StylesBuilder:
|
|||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
self.styles._rules[name.replace("-", "_")] = value
|
self.styles._rules[name.replace("-", "_")] = value
|
||||||
|
|
||||||
process_table_gutter_horizontal = _process_integer
|
process_grid_gutter_horizontal = _process_integer
|
||||||
process_table_gutter_vertical = _process_integer
|
process_grid_gutter_vertical = _process_integer
|
||||||
process_column_span = _process_integer
|
process_column_span = _process_integer
|
||||||
process_row_span = _process_integer
|
process_row_span = _process_integer
|
||||||
process_table_size_columns = _process_integer
|
process_grid_size_columns = _process_integer
|
||||||
process_table_size_rows = _process_integer
|
process_grid_size_rows = _process_integer
|
||||||
|
|
||||||
def process_table_gutter(self, name: str, tokens: list[Token]) -> None:
|
def process_grid_gutter(self, name: str, tokens: list[Token]) -> None:
|
||||||
if not tokens:
|
if not tokens:
|
||||||
return
|
return
|
||||||
if len(tokens) == 1:
|
if len(tokens) == 1:
|
||||||
@@ -899,25 +899,25 @@ class StylesBuilder:
|
|||||||
if token.name != "number":
|
if token.name != "number":
|
||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
value = max(0, int(token.value))
|
value = max(0, int(token.value))
|
||||||
self.styles._rules["table_gutter_horizontal"] = value
|
self.styles._rules["grid_gutter_horizontal"] = value
|
||||||
self.styles._rules["table_gutter_vertical"] = value
|
self.styles._rules["grid_gutter_vertical"] = value
|
||||||
|
|
||||||
elif len(tokens) == 2:
|
elif len(tokens) == 2:
|
||||||
token = tokens[0]
|
token = tokens[0]
|
||||||
if token.name != "number":
|
if token.name != "number":
|
||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
value = max(0, int(token.value))
|
value = max(0, int(token.value))
|
||||||
self.styles._rules["table_gutter_horizontal"] = value
|
self.styles._rules["grid_gutter_horizontal"] = value
|
||||||
token = tokens[1]
|
token = tokens[1]
|
||||||
if token.name != "number":
|
if token.name != "number":
|
||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
value = max(0, int(token.value))
|
value = max(0, int(token.value))
|
||||||
self.styles._rules["table_gutter_vertical"] = value
|
self.styles._rules["grid_gutter_vertical"] = value
|
||||||
|
|
||||||
else:
|
else:
|
||||||
self.error(name, tokens[0], "expected two integers here")
|
self.error(name, tokens[0], "expected two integers here")
|
||||||
|
|
||||||
def process_table_size(self, name: str, tokens: list[Token]) -> None:
|
def process_grid_size(self, name: str, tokens: list[Token]) -> None:
|
||||||
if not tokens:
|
if not tokens:
|
||||||
return
|
return
|
||||||
if len(tokens) == 1:
|
if len(tokens) == 1:
|
||||||
@@ -925,20 +925,20 @@ class StylesBuilder:
|
|||||||
if token.name != "number":
|
if token.name != "number":
|
||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
value = max(0, int(token.value))
|
value = max(0, int(token.value))
|
||||||
self.styles._rules["table_size_columns"] = value
|
self.styles._rules["grid_size_columns"] = value
|
||||||
self.styles._rules["table_size_rows"] = 0
|
self.styles._rules["grid_size_rows"] = 0
|
||||||
|
|
||||||
elif len(tokens) == 2:
|
elif len(tokens) == 2:
|
||||||
token = tokens[0]
|
token = tokens[0]
|
||||||
if token.name != "number":
|
if token.name != "number":
|
||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
value = max(0, int(token.value))
|
value = max(0, int(token.value))
|
||||||
self.styles._rules["table_size_columns"] = value
|
self.styles._rules["grid_size_columns"] = value
|
||||||
token = tokens[1]
|
token = tokens[1]
|
||||||
if token.name != "number":
|
if token.name != "number":
|
||||||
self.error(name, token, integer_help_text(name))
|
self.error(name, token, integer_help_text(name))
|
||||||
value = max(0, int(token.value))
|
value = max(0, int(token.value))
|
||||||
self.styles._rules["table_size_rows"] = value
|
self.styles._rules["grid_size_rows"] = value
|
||||||
|
|
||||||
else:
|
else:
|
||||||
self.error(name, tokens[0], "expected two integers here")
|
self.error(name, tokens[0], "expected two integers here")
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ VALID_BORDER: Final[set[EdgeType]] = {
|
|||||||
"wide",
|
"wide",
|
||||||
}
|
}
|
||||||
VALID_EDGE: Final = {"top", "right", "bottom", "left"}
|
VALID_EDGE: Final = {"top", "right", "bottom", "left"}
|
||||||
VALID_LAYOUT: Final = {"vertical", "horizontal", "center", "table"}
|
VALID_LAYOUT: Final = {"vertical", "horizontal", "center", "grid"}
|
||||||
|
|
||||||
VALID_BOX_SIZING: Final = {"border-box", "content-box"}
|
VALID_BOX_SIZING: Final = {"border-box", "content-box"}
|
||||||
VALID_OVERFLOW: Final = {"scroll", "hidden", "auto"}
|
VALID_OVERFLOW: Final = {"scroll", "hidden", "auto"}
|
||||||
|
|||||||
@@ -146,12 +146,12 @@ class RulesMap(TypedDict, total=False):
|
|||||||
content_align_horizontal: AlignHorizontal
|
content_align_horizontal: AlignHorizontal
|
||||||
content_align_vertical: AlignVertical
|
content_align_vertical: AlignVertical
|
||||||
|
|
||||||
table_size_rows: int
|
grid_size_rows: int
|
||||||
table_size_columns: int
|
grid_size_columns: int
|
||||||
table_gutter_horizontal: int
|
grid_gutter_horizontal: int
|
||||||
table_gutter_vertical: int
|
grid_gutter_vertical: int
|
||||||
table_rows: tuple[Scalar, ...]
|
grid_rows: tuple[Scalar, ...]
|
||||||
table_columns: tuple[Scalar, ...]
|
grid_columns: tuple[Scalar, ...]
|
||||||
|
|
||||||
row_span: int
|
row_span: int
|
||||||
column_span: int
|
column_span: int
|
||||||
@@ -267,13 +267,13 @@ class StylesBase(ABC):
|
|||||||
content_align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top")
|
content_align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top")
|
||||||
content_align = AlignProperty()
|
content_align = AlignProperty()
|
||||||
|
|
||||||
table_rows = ScalarListProperty()
|
grid_rows = ScalarListProperty()
|
||||||
table_columns = ScalarListProperty()
|
grid_columns = ScalarListProperty()
|
||||||
|
|
||||||
table_size_columns = IntegerProperty(default=1, layout=True)
|
grid_size_columns = IntegerProperty(default=1, layout=True)
|
||||||
table_size_rows = IntegerProperty(default=0, layout=True)
|
grid_size_rows = IntegerProperty(default=0, layout=True)
|
||||||
table_gutter_horizontal = IntegerProperty(default=0, layout=True)
|
grid_gutter_horizontal = IntegerProperty(default=0, layout=True)
|
||||||
table_gutter_vertical = IntegerProperty(default=0, layout=True)
|
grid_gutter_vertical = IntegerProperty(default=0, layout=True)
|
||||||
|
|
||||||
row_span = IntegerProperty(default=1, layout=True)
|
row_span = IntegerProperty(default=1, layout=True)
|
||||||
column_span = IntegerProperty(default=1, layout=True)
|
column_span = IntegerProperty(default=1, layout=True)
|
||||||
@@ -805,26 +805,26 @@ class Styles(StylesBase):
|
|||||||
)
|
)
|
||||||
elif has_rule("content_align_vertical"):
|
elif has_rule("content_align_vertical"):
|
||||||
append_declaration("content-align-vertical", self.content_align_vertical)
|
append_declaration("content-align-vertical", self.content_align_vertical)
|
||||||
elif has_rule("table_columns"):
|
elif has_rule("grid_columns"):
|
||||||
append_declaration(
|
append_declaration(
|
||||||
"table-columns",
|
"grid-columns",
|
||||||
" ".join(str(scalar) for scalar in self.table_columns or ()),
|
" ".join(str(scalar) for scalar in self.grid_columns or ()),
|
||||||
)
|
)
|
||||||
elif has_rule("table_rows"):
|
elif has_rule("grid_rows"):
|
||||||
append_declaration(
|
append_declaration(
|
||||||
"table-rows",
|
"grid-rows",
|
||||||
" ".join(str(scalar) for scalar in self.table_rows or ()),
|
" ".join(str(scalar) for scalar in self.grid_rows or ()),
|
||||||
)
|
)
|
||||||
elif has_rule("table_size_columns"):
|
elif has_rule("grid_size_columns"):
|
||||||
append_declaration("table-size-columns", str(self.table_size_columns))
|
append_declaration("grid-size-columns", str(self.grid_size_columns))
|
||||||
elif has_rule("table_size_rows"):
|
elif has_rule("grid_size_rows"):
|
||||||
append_declaration("table-size-rows", str(self.table_size_rows))
|
append_declaration("grid-size-rows", str(self.grid_size_rows))
|
||||||
elif has_rule("table_gutter_horizontal"):
|
elif has_rule("grid_gutter_horizontal"):
|
||||||
append_declaration(
|
append_declaration(
|
||||||
"table-gutter-horizontal", str(self.table_gutter_horizontal)
|
"grid-gutter-horizontal", str(self.grid_gutter_horizontal)
|
||||||
)
|
)
|
||||||
elif has_rule("table_gutter_vertical"):
|
elif has_rule("grid_gutter_vertical"):
|
||||||
append_declaration("table-gutter-vertical", str(self.table_gutter_vertical))
|
append_declaration("grid-gutter-vertical", str(self.grid_gutter_vertical))
|
||||||
elif has_rule("row_span"):
|
elif has_rule("row_span"):
|
||||||
append_declaration("row-span", str(self.row_span))
|
append_declaration("row-span", str(self.row_span))
|
||||||
elif has_rule("column_span"):
|
elif has_rule("column_span"):
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ from __future__ import annotations
|
|||||||
from .._layout import Layout
|
from .._layout import Layout
|
||||||
from .center import CenterLayout
|
from .center import CenterLayout
|
||||||
from .horizontal import HorizontalLayout
|
from .horizontal import HorizontalLayout
|
||||||
from .table import TableLayout
|
from .grid import GridLayout
|
||||||
from .vertical import VerticalLayout
|
from .vertical import VerticalLayout
|
||||||
|
|
||||||
LAYOUT_MAP: dict[str, type[Layout]] = {
|
LAYOUT_MAP: dict[str, type[Layout]] = {
|
||||||
"center": CenterLayout,
|
"center": CenterLayout,
|
||||||
"horizontal": HorizontalLayout,
|
"horizontal": HorizontalLayout,
|
||||||
"table": TableLayout,
|
"grid": GridLayout,
|
||||||
"vertical": VerticalLayout,
|
"vertical": VerticalLayout,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,21 +12,21 @@ if TYPE_CHECKING:
|
|||||||
from ..widget import Widget
|
from ..widget import Widget
|
||||||
|
|
||||||
|
|
||||||
class TableLayout(Layout):
|
class GridLayout(Layout):
|
||||||
"""Used to layout Widgets in to a table."""
|
"""Used to layout Widgets in to a grid."""
|
||||||
|
|
||||||
name = "table"
|
name = "grid"
|
||||||
|
|
||||||
def arrange(
|
def arrange(
|
||||||
self, parent: Widget, children: list[Widget], size: Size
|
self, parent: Widget, children: list[Widget], size: Size
|
||||||
) -> ArrangeResult:
|
) -> ArrangeResult:
|
||||||
styles = parent.styles
|
styles = parent.styles
|
||||||
row_scalars = styles.table_rows or [Scalar.parse("1fr")]
|
row_scalars = styles.grid_rows or [Scalar.parse("1fr")]
|
||||||
column_scalars = styles.table_columns or [Scalar.parse("1fr")]
|
column_scalars = styles.grid_columns or [Scalar.parse("1fr")]
|
||||||
gutter_horizontal = styles.table_gutter_horizontal
|
gutter_horizontal = styles.grid_gutter_horizontal
|
||||||
gutter_vertical = styles.table_gutter_vertical
|
gutter_vertical = styles.grid_gutter_vertical
|
||||||
table_size_columns = max(1, styles.table_size_columns)
|
table_size_columns = max(1, styles.grid_size_columns)
|
||||||
table_size_rows = styles.table_size_rows
|
table_size_rows = styles.grid_size_rows
|
||||||
viewport = parent.screen.size
|
viewport = parent.screen.size
|
||||||
|
|
||||||
def cell_coords(column_count: int) -> Iterable[tuple[int, int]]:
|
def cell_coords(column_count: int) -> Iterable[tuple[int, int]]:
|
||||||
@@ -112,6 +112,11 @@ class MessagePump(metaclass=MessagePumpMeta):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def log(self) -> Logger:
|
def log(self) -> Logger:
|
||||||
|
"""Get a logger for this object.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Logger: A logger.
|
||||||
|
"""
|
||||||
return self.app._logger
|
return self.app._logger
|
||||||
|
|
||||||
def _attach(self, parent: MessagePump) -> None:
|
def _attach(self, parent: MessagePump) -> None:
|
||||||
|
|||||||
@@ -1,19 +1,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from inspect import isawaitable
|
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from typing import (
|
from inspect import isawaitable
|
||||||
Any,
|
from typing import TYPE_CHECKING, Any, Callable, Generic, Type, TypeVar, Union
|
||||||
Callable,
|
|
||||||
Generic,
|
|
||||||
Type,
|
|
||||||
Union,
|
|
||||||
TypeVar,
|
|
||||||
TYPE_CHECKING,
|
|
||||||
)
|
|
||||||
|
|
||||||
from . import events
|
from . import events
|
||||||
|
|
||||||
from ._callback import count_parameters, invoke
|
from ._callback import count_parameters, invoke
|
||||||
from ._types import MessageTarget
|
from ._types import MessageTarget
|
||||||
|
|
||||||
@@ -31,7 +22,15 @@ T = TypeVar("T")
|
|||||||
|
|
||||||
|
|
||||||
class Reactive(Generic[ReactiveType]):
|
class Reactive(Generic[ReactiveType]):
|
||||||
"""Reactive descriptor."""
|
"""Reactive descriptor.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
default (ReactiveType | Callable[[], ReactiveType]): A default value or callable that returns a default.
|
||||||
|
layout (bool, optional): Perform a layout on change. Defaults to False.
|
||||||
|
repaint (bool, optional): Perform a repaint on change. Defaults to True.
|
||||||
|
init (bool, optional): Call watchers on initialize (post mount). Defaults to False.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -41,14 +40,6 @@ class Reactive(Generic[ReactiveType]):
|
|||||||
repaint: bool = True,
|
repaint: bool = True,
|
||||||
init: bool = False,
|
init: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Create a Reactive Widget attribute,
|
|
||||||
|
|
||||||
Args:
|
|
||||||
default (ReactiveType | Callable[[], ReactiveType]): A default value or callable that returns a default.
|
|
||||||
layout (bool, optional): Perform a layout on change. Defaults to False.
|
|
||||||
repaint (bool, optional): Perform a repaint on change. Defaults to True.
|
|
||||||
init (bool, optional): Call watchers on initialize (post mount). Defaults to False.
|
|
||||||
"""
|
|
||||||
self._default = default
|
self._default = default
|
||||||
self._layout = layout
|
self._layout = layout
|
||||||
self._repaint = repaint
|
self._repaint = repaint
|
||||||
@@ -138,12 +129,12 @@ class Reactive(Generic[ReactiveType]):
|
|||||||
if current_value != value or first_set:
|
if current_value != value or first_set:
|
||||||
setattr(obj, f"__first_set_{self.internal_name}", False)
|
setattr(obj, f"__first_set_{self.internal_name}", False)
|
||||||
setattr(obj, self.internal_name, value)
|
setattr(obj, self.internal_name, value)
|
||||||
self.check_watchers(obj, name, current_value)
|
self._check_watchers(obj, name, current_value)
|
||||||
if self._layout or self._repaint:
|
if self._layout or self._repaint:
|
||||||
obj.refresh(repaint=self._repaint, layout=self._layout)
|
obj.refresh(repaint=self._repaint, layout=self._layout)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def check_watchers(cls, obj: Reactable, name: str, old_value: Any) -> None:
|
def _check_watchers(cls, obj: Reactable, name: str, old_value: Any) -> None:
|
||||||
|
|
||||||
internal_name = f"_reactive_{name}"
|
internal_name = f"_reactive_{name}"
|
||||||
value = getattr(obj, internal_name)
|
value = getattr(obj, internal_name)
|
||||||
@@ -158,7 +149,7 @@ class Reactive(Generic[ReactiveType]):
|
|||||||
watch_result = watch_function(value)
|
watch_result = watch_function(value)
|
||||||
if isawaitable(watch_result):
|
if isawaitable(watch_result):
|
||||||
await watch_result
|
await watch_result
|
||||||
await Reactive.compute(obj)
|
await Reactive._compute(obj)
|
||||||
|
|
||||||
watch_function = getattr(obj, f"watch_{name}", None)
|
watch_function = getattr(obj, f"watch_{name}", None)
|
||||||
if callable(watch_function):
|
if callable(watch_function):
|
||||||
@@ -182,7 +173,7 @@ class Reactive(Generic[ReactiveType]):
|
|||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def compute(cls, obj: Reactable) -> None:
|
async def _compute(cls, obj: Reactable) -> None:
|
||||||
_rich_traceback_guard = True
|
_rich_traceback_guard = True
|
||||||
computes = getattr(obj, "__computes", [])
|
computes = getattr(obj, "__computes", [])
|
||||||
for compute in computes:
|
for compute in computes:
|
||||||
@@ -203,4 +194,4 @@ def watch(
|
|||||||
setattr(obj, watcher_name, set())
|
setattr(obj, watcher_name, set())
|
||||||
watchers = getattr(obj, watcher_name)
|
watchers = getattr(obj, watcher_name)
|
||||||
watchers.add(callback)
|
watchers.add(callback)
|
||||||
Reactive.check_watchers(obj, attribute_name, current_value)
|
Reactive._check_watchers(obj, attribute_name, current_value)
|
||||||
|
|||||||
@@ -4,16 +4,11 @@ from asyncio import Lock
|
|||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
from itertools import islice
|
from itertools import islice
|
||||||
from operator import attrgetter
|
from operator import attrgetter
|
||||||
from typing import (
|
from types import GeneratorType
|
||||||
TYPE_CHECKING,
|
from typing import TYPE_CHECKING, ClassVar, Collection, Iterable, NamedTuple
|
||||||
ClassVar,
|
|
||||||
Collection,
|
|
||||||
Iterable,
|
|
||||||
NamedTuple,
|
|
||||||
)
|
|
||||||
|
|
||||||
import rich.repr
|
import rich.repr
|
||||||
from rich.console import Console, RenderableType, JustifyMethod
|
from rich.console import Console, JustifyMethod, RenderableType
|
||||||
from rich.measure import Measurement
|
from rich.measure import Measurement
|
||||||
from rich.segment import Segment
|
from rich.segment import Segment
|
||||||
from rich.style import Style
|
from rich.style import Style
|
||||||
@@ -22,7 +17,7 @@ from rich.text import Text
|
|||||||
|
|
||||||
from . import errors, events, messages
|
from . import errors, events, messages
|
||||||
from ._animator import BoundAnimator
|
from ._animator import BoundAnimator
|
||||||
from ._arrange import arrange, DockArrangeResult
|
from ._arrange import DockArrangeResult, arrange
|
||||||
from ._context import active_app
|
from ._context import active_app
|
||||||
from ._layout import Layout
|
from ._layout import Layout
|
||||||
from ._segment_tools import align_lines
|
from ._segment_tools import align_lines
|
||||||
@@ -30,8 +25,7 @@ from ._styles_cache import StylesCache
|
|||||||
from ._types import Lines
|
from ._types import Lines
|
||||||
from .box_model import BoxModel, get_box_model
|
from .box_model import BoxModel, get_box_model
|
||||||
from .css.constants import VALID_TEXT_ALIGN
|
from .css.constants import VALID_TEXT_ALIGN
|
||||||
from .dom import DOMNode
|
from .dom import DOMNode, NoScreen
|
||||||
from .dom import NoScreen
|
|
||||||
from .geometry import Offset, Region, Size, Spacing, clamp
|
from .geometry import Offset, Region, Size, Spacing, clamp
|
||||||
from .layouts.vertical import VerticalLayout
|
from .layouts.vertical import VerticalLayout
|
||||||
from .message import Message
|
from .message import Message
|
||||||
@@ -41,12 +35,12 @@ if TYPE_CHECKING:
|
|||||||
from .app import App, ComposeResult
|
from .app import App, ComposeResult
|
||||||
from .scrollbar import (
|
from .scrollbar import (
|
||||||
ScrollBar,
|
ScrollBar,
|
||||||
|
ScrollBarCorner,
|
||||||
ScrollDown,
|
ScrollDown,
|
||||||
ScrollLeft,
|
ScrollLeft,
|
||||||
ScrollRight,
|
ScrollRight,
|
||||||
ScrollTo,
|
ScrollTo,
|
||||||
ScrollUp,
|
ScrollUp,
|
||||||
ScrollBarCorner,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -1458,10 +1452,9 @@ class Widget(DOMNode):
|
|||||||
await self.dispatch_key(event)
|
await self.dispatch_key(event)
|
||||||
|
|
||||||
def _on_mount(self, event: events.Mount) -> None:
|
def _on_mount(self, event: events.Mount) -> None:
|
||||||
widgets = list(self.compose())
|
widgets = self.compose()
|
||||||
if widgets:
|
self.mount(*widgets)
|
||||||
self.mount(*widgets)
|
self.screen.refresh(repaint=False, layout=True)
|
||||||
self.screen.refresh(repaint=False, layout=True)
|
|
||||||
|
|
||||||
def _on_leave(self, event: events.Leave) -> None:
|
def _on_leave(self, event: events.Leave) -> None:
|
||||||
self.mouse_over = False
|
self.mouse_over = False
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ __all__ = [
|
|||||||
"Static",
|
"Static",
|
||||||
"TextInput",
|
"TextInput",
|
||||||
"TreeControl",
|
"TreeControl",
|
||||||
|
"Welcome",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ from ._pretty import Pretty as Pretty
|
|||||||
from ._static import Static as Static
|
from ._static import Static as Static
|
||||||
from ._text_input import TextInput as TextInput
|
from ._text_input import TextInput as TextInput
|
||||||
from ._tree_control import TreeControl as TreeControl
|
from ._tree_control import TreeControl as TreeControl
|
||||||
|
from ._welcome import Welcome as Welcome
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ class Button(Widget, can_focus=True):
|
|||||||
DEFAULT_CSS = """
|
DEFAULT_CSS = """
|
||||||
Button {
|
Button {
|
||||||
width: auto;
|
width: auto;
|
||||||
min-width: 10;
|
min-width: 16;
|
||||||
|
width: auto;
|
||||||
height: 3;
|
height: 3;
|
||||||
background: $panel;
|
background: $panel;
|
||||||
color: $text-panel;
|
color: $text-panel;
|
||||||
@@ -43,6 +44,11 @@ class Button(Widget, can_focus=True):
|
|||||||
text-style: bold;
|
text-style: bold;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Button.-disabled {
|
||||||
|
opacity: 0.4;
|
||||||
|
text-opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
Button:focus {
|
Button:focus {
|
||||||
text-style: bold reverse;
|
text-style: bold reverse;
|
||||||
}
|
}
|
||||||
@@ -79,7 +85,6 @@ class Button(Widget, can_focus=True):
|
|||||||
background: $primary;
|
background: $primary;
|
||||||
border-bottom: tall $primary-lighten-3;
|
border-bottom: tall $primary-lighten-3;
|
||||||
border-top: tall $primary-darken-3;
|
border-top: tall $primary-darken-3;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -89,13 +94,11 @@ class Button(Widget, can_focus=True):
|
|||||||
color: $text-success;
|
color: $text-success;
|
||||||
border-top: tall $success-lighten-2;
|
border-top: tall $success-lighten-2;
|
||||||
border-bottom: tall $success-darken-3;
|
border-bottom: tall $success-darken-3;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Button.-success:hover {
|
Button.-success:hover {
|
||||||
background: $success-darken-2;
|
background: $success-darken-2;
|
||||||
color: $text-success-darken-2;
|
color: $text-success-darken-2;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Button.-success.-active {
|
Button.-success.-active {
|
||||||
@@ -182,22 +185,37 @@ class Button(Widget, can_focus=True):
|
|||||||
if label is None:
|
if label is None:
|
||||||
label = self.css_identifier_styled
|
label = self.css_identifier_styled
|
||||||
|
|
||||||
self.label: Text = label
|
self.label = label
|
||||||
|
|
||||||
self.disabled = disabled
|
self.disabled = disabled
|
||||||
if disabled:
|
if disabled:
|
||||||
self.add_class("-disabled")
|
self.add_class("-disabled")
|
||||||
|
|
||||||
if variant in _VALID_BUTTON_VARIANTS:
|
self.variant = variant
|
||||||
if variant != "default":
|
|
||||||
self.add_class(f"-{variant}")
|
|
||||||
|
|
||||||
else:
|
label: Reactive[RenderableType] = Reactive("")
|
||||||
|
variant = Reactive.init("default")
|
||||||
|
disabled = Reactive(False)
|
||||||
|
|
||||||
|
def watch_mouse_over(self, value: bool) -> None:
|
||||||
|
"""Update from CSS if mouse over state changes."""
|
||||||
|
if not self.disabled:
|
||||||
|
self.app.update_styles(self)
|
||||||
|
|
||||||
|
def validate_variant(self, variant: str) -> str:
|
||||||
|
if variant not in _VALID_BUTTON_VARIANTS:
|
||||||
raise InvalidButtonVariant(
|
raise InvalidButtonVariant(
|
||||||
f"Valid button variants are {friendly_list(_VALID_BUTTON_VARIANTS)}"
|
f"Valid button variants are {friendly_list(_VALID_BUTTON_VARIANTS)}"
|
||||||
)
|
)
|
||||||
|
return variant
|
||||||
|
|
||||||
label: Reactive[RenderableType] = Reactive("")
|
def watch_variant(self, old_variant: str, variant: str):
|
||||||
|
self.remove_class(f"_{old_variant}")
|
||||||
|
self.add_class(f"-{variant}")
|
||||||
|
|
||||||
|
def watch_disabled(self, disabled: bool) -> None:
|
||||||
|
self.set_class(disabled, "-disabled")
|
||||||
|
self.can_focus = not disabled
|
||||||
|
|
||||||
def validate_label(self, label: RenderableType) -> RenderableType:
|
def validate_label(self, label: RenderableType) -> RenderableType:
|
||||||
"""Parse markup for self.label"""
|
"""Parse markup for self.label"""
|
||||||
|
|||||||
58
src/textual/widgets/_welcome.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
from ..app import ComposeResult
|
||||||
|
from ._static import Static
|
||||||
|
from ._button import Button
|
||||||
|
from ..layout import Container
|
||||||
|
|
||||||
|
from rich.markdown import Markdown
|
||||||
|
|
||||||
|
WELCOME_MD = """\
|
||||||
|
# Welcome!
|
||||||
|
|
||||||
|
Textual is a TUI, or *Text User Interface*, framework for Python inspired by modern web development. **We hope you enjoy using Textual!**
|
||||||
|
|
||||||
|
## Dune quote
|
||||||
|
|
||||||
|
> "I must not fear.
|
||||||
|
Fear is the mind-killer.
|
||||||
|
Fear is the little-death that brings total obliteration.
|
||||||
|
I will face my fear.
|
||||||
|
I will permit it to pass over me and through me.
|
||||||
|
And when it has gone past, I will turn the inner eye to see its path.
|
||||||
|
Where the fear has gone there will be nothing. Only I will remain."
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class Welcome(Static):
|
||||||
|
|
||||||
|
DEFAULT_CSS = """
|
||||||
|
|
||||||
|
Welcome {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
margin: 1 2;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
Welcome Container {
|
||||||
|
padding: 1;
|
||||||
|
background: $panel;
|
||||||
|
color: $text-panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
Welcome #text {
|
||||||
|
margin: 0 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Welcome #close {
|
||||||
|
dock: bottom;
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
|
||||||
|
yield Container(Static(Markdown(WELCOME_MD), id="text"), id="md")
|
||||||
|
yield Button("OK", id="close", variant="success")
|
||||||