tabs widget (#2020)

* tabs widget

* click underline

* color tweak

* docs

* docs update

* expose Tab

* added remove_tab and clear

* fix cycling

* add animation

* docs

* changelog

* remove recompose

* docstrings

* Update docs/guide/actions.md

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

* Rodrigoed the tabs

* Update docs/widgets/tabs.md

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

* Update docs/widgets/tabs.md

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

* copy

* docstrings

* docstring

* docstring

* Apply suggestions from code review

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

* stop click

* docstring

* auto assign consistent IDs

* Apply suggestions from code review

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

* Document bindings

* document bindings

* Apply suggestions from code review

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

* Apply suggestions from code review

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

---------

Co-authored-by: Rodrigo Girão Serrão <5621605+rodrigogiraoserrao@users.noreply.github.com>
This commit is contained in:
Will McGugan
2023-03-13 14:39:15 +00:00
committed by GitHub
parent 5983d88aa6
commit b0f5c35782
19 changed files with 695 additions and 24 deletions

2
docs/api/tabs.md Normal file
View File

@@ -0,0 +1,2 @@
::: textual.widgets.Tab
::: textual.widgets.Tabs

View File

@@ -1,5 +1,5 @@
from textual.app import App
from textual import events
from textual.app import App
class ActionsApp(App):
@@ -8,7 +8,7 @@ class ActionsApp(App):
async def on_key(self, event: events.Key) -> None:
if event.key == "r":
await self.action("set_background('red')")
await self.run_action("set_background('red')")
if __name__ == "__main__":

View File

@@ -0,0 +1,82 @@
from textual.app import App, ComposeResult
from textual.widgets import Footer, Label, Tabs
NAMES = [
"Paul Atreidies",
"Duke Leto Atreides",
"Lady Jessica",
"Gurney Halleck",
"Baron Vladimir Harkonnen",
"Glossu Rabban",
"Chani",
"Silgar",
]
class TabsApp(App):
"""Demonstrates the Tabs widget."""
CSS = """
Tabs {
dock: top;
}
Screen {
align: center middle;
}
Label {
margin:1 1;
width: 100%;
height: 100%;
background: $panel;
border: tall $primary;
content-align: center middle;
}
"""
BINDINGS = [
("a", "add", "Add tab"),
("r", "remove", "Remove active tab"),
("c", "clear", "Clear tabs"),
]
def compose(self) -> ComposeResult:
yield Tabs(NAMES[0])
yield Label()
yield Footer()
def on_mount(self) -> None:
"""Focus the tabs when the app starts."""
self.query_one(Tabs).focus()
def on_tabs_tab_activated(self, event: Tabs.TabActivated) -> None:
"""Handle TabActivated message sent by Tabs."""
label = self.query_one(Label)
if event.tab is None:
# When the tabs are cleared, event.tab will be None
label.visible = False
else:
label.visible = True
label.update(event.tab.label)
def action_add(self) -> None:
"""Add a new tab."""
tabs = self.query_one(Tabs)
# Cycle the names
NAMES[:] = [*NAMES[1:], NAMES[0]]
tabs.add_tab(NAMES[0])
def action_remove(self) -> None:
"""Remove active tab."""
tabs = self.query_one(Tabs)
active_tab = tabs.active_tab
if active_tab is not None:
tabs.remove_tab(active_tab.id)
def action_clear(self) -> None:
"""Clear the tabs."""
self.query_one(Tabs).clear()
if __name__ == "__main__":
app = TabsApp()
app.run()

View File

@@ -20,13 +20,13 @@ The `action_set_background` method is an action which sets the background of the
Although it is possible (and occasionally useful) to call action methods in this way, they are intended to be parsed from an _action string_. For instance, the string `"set_background('red')"` is an action string which would call `self.action_set_background('red')`.
The following example replaces the immediate call with a call to [action()][textual.widgets.Widget.action] which parses an action string and dispatches it to the appropriate method.
The following example replaces the immediate call with a call to [run_action()][textual.widgets.Widget.run_action] which parses an action string and dispatches it to the appropriate method.
```python title="actions02.py" hl_lines="9-11"
--8<-- "docs/examples/guide/actions/actions02.py"
```
Note that the `action()` method is a coroutine so `on_key` needs to be prefixed with the `async` keyword.
Note that the `run_action()` method is a coroutine so `on_key` needs to be prefixed with the `async` keyword.
You will not typically need this in a real app as Textual will run actions in links or key bindings. Before we discuss these, let's have a closer look at the syntax for action strings.
@@ -36,7 +36,7 @@ Action strings have a simple syntax, which for the most part replicates Python's
!!! important
As much as they *look* like Python code, Textual does **not** call Python's `eval` function or similar to compile action strings.
As much as they *look* like Python code, Textual does **not** call Python's `eval` function to compile action strings.
Action strings have the following format:
@@ -50,7 +50,7 @@ Action strings have the following format:
### Parameters
If the action string contains parameters, these must be valid Python literals. Which means you can include numbers, strings, dicts, lists etc. but you can't include variables or references to any other python symbol.
If the action string contains parameters, these must be valid Python literals. Which means you can include numbers, strings, dicts, lists etc. but you can't include variables or references to any other Python symbols.
Consequently `"set_background('blue')"` is a valid action string, but `"set_background(new_color)"` is not &mdash; because `new_color` is a variable and not a literal.

View File

@@ -185,6 +185,16 @@ A on / off control, inspired by toggle buttons.
```{.textual path="docs/examples/widgets/switch.py"}
```
## Tabs
A row of tabs you can select with the mouse or navigate with keys.
[Tabs reference](./widgets/tabs.md){ .md-button .md-button--primary }
```{.textual path="docs/examples/widgets/tabs.py" press="a,a,a,a,right,right"}
```
## TextLog
Display and update text in a scrolling panel.

View File

@@ -29,7 +29,7 @@ The example below shows check boxes in various states.
## Reactive Attributes
| Name | Type | Default | Description |
|---------|--------|---------|----------------------------|
| ------- | ------ | ------- | -------------------------- |
| `value` | `bool` | `False` | The value of the checkbox. |
## Bindings

View File

@@ -38,7 +38,7 @@ The example below shows how you might create a simple form using two `Input` wid
## Bindings
The input widget defines directly the following bindings:
The Input widget defines the following bindings:
::: textual.widgets.Input.BINDINGS
options:

75
docs/widgets/tabs.md Normal file
View File

@@ -0,0 +1,75 @@
# Tabs
Displays a number of tab headers which may be activated with a click or navigated with cursor keys.
- [x] Focusable
- [ ] Container
Construct a `Tabs` widget with strings or [Text][rich.text.Text] objects as positional arguments, which will set the labels in the tabs. Here's an example with three tabs:
```python
def compose(self) -> ComposeResult:
yield Tabs("First tab", "Second tab", Text.from_markup("[u]Third[/u] tab"))
```
This will create [Tab][textual.widgets.Tab] widgets internally, with auto-incrementing `id` attributes (`"tab-1"`, `"tab-2"` etc).
You can also supply `Tab` objects directly in the constructor, which will allow you to explicitly set an `id`. Here's an example:
```python
def compose(self) -> ComposeResult:
yield Tabs(
Tab("First tab", id="one"),
Tab("Second tab", id="two"),
)
```
When the user switches to a tab by clicking or pressing keys, then `Tabs` will send a [Tabs.TabActivated][textual.widgets.Tabs.TabActivated] message which contains the `tab` that was activated.
You can then use `event.tab.id` attribute to perform any related actions.
## Clearing tabs
Clear tabs by calling the [clear][textual.widgets.Tabs.clear] method. Clearing the tabs will send a [Tabs.TabActivated][textual.widgets.Tabs.TabActivated] message with the `tab` attribute set to `None`.
## Adding tabs
Tabs may be added dynamically with the [add_tab][textual.widgets.Tabs.add_tab] method, which accepts strings, [Text][rich.text.Text], or [Tab][textual.widgets.Tab] objects.
## Example
The following example adds a `Tabs` widget above a text label. Press ++a++ to add a tab, ++c++ to clear the tabs.
=== "Output"
```{.textual path="docs/examples/widgets/tabs.py" press="a,a,a,a,right,right"}
```
=== "tabs.py"
```python
--8<-- "docs/examples/widgets/tabs.py"
```
## Reactive Attributes
| Name | Type | Default | Description |
| -------- | ----- | ------- | ---------------------------------------------------------------------------------- |
| `active` | `str` | `""` | The ID of the active tab. Set this attribute to a tab ID to change the active tab. |
## Messages
### ::: textual.widgets.Tabs.TabActivated
## Bindings
The Tabs widget defines the following bindings:
::: textual.widgets.Tabs.BINDINGS
options:
show_root_heading: false
show_root_toc_entry: false
## See Also
- [Tabs](../api/tabs.md) code reference