Tabs¶
A tab view keeps a few sections of one panel a click apart. A row of tab buttons sits on top, and clicking one draws its section below, in the same message.
from cascadeui import TabLayoutView, card, divider, image_section, key_value
class ProfileView(TabLayoutView):
def __init__(self, **kwargs):
super().__init__(
tabs={ # (1)!
"Overview": self.build_overview,
"Stats": self.build_stats,
"Badges": self.build_badges,
},
**kwargs,
)
def build_overview(self): # (2)!
member = self.interaction.user
return card(
image_section(
f"## {member.display_name}", "-# Member since March", url=member.display_avatar.url
),
divider(),
key_value({"Level": 12, "Games": 15, "Win rate": "80%"}),
)
async def build_stats(self): # (3)!
return card("## Stats", key_value({"Wins": 12, "Losses": 3}))
def build_badges(self):
return card("## Badges", "First Win, Ten Games")
- Each tab is a name and a builder. The names become the buttons, in this order.
- A builder draws its tab. It runs each time the tab is drawn and takes no arguments. This one shows the member's avatar beside their name, over three numbers.
- A builder may be
async, to load what it shows from a database.
The panel shows the tab buttons with the open tab highlighted, then that tab's card. It opens on the first tab.
Send it like any view: await ProfileView(interaction=interaction).send().
Tabs suit a few sections of one subject that a person moves between often: a profile, a dashboard, a settings
panel. To open a screen and come back from it, such as one item's details from a list, use
push and pop. For a row of tab-styled buttons in a view of your own, or inside one tab,
use tab_nav().
Tabs and Builders¶
Pass the tabs to tabs=, as a dict of names and builders or as a list of (name, builder) pairs. The order is the
order of the buttons, and two tabs may not share a name.
A builder takes no arguments and may be plain or async. Tabs that differ only in what they show can share one
builder, with the difference bound in by functools.partial:
from functools import partial
tabs = {name: partial(self.build_channel, name) for name in ("News", "Events", "Help")}
A builder returns what its tab shows: a component such as a card(), a list or tuple of them, text (shown as a
card() in the theme's accent; inside a list, as plain text), or None for nothing. Anything else raises
TypeError naming the tab. A tab can hold a
PaginatedRegion or a Collapsible: turning its page or opening it draws the tab
again.
A tab's name is its button's label, as written, so an emoji goes in the name ("📊 Overview"). The view checks
its tabs when it is built, so a mistake raises there and never in front of the person:
- no tabs at all, or
tabswritten in the class body, which the view does not read - a builder that cannot be called with no arguments
- a name Discord cannot show as a label: empty,
None, or over 80 characters
The tab buttons take the ids tab_0, tab_1, and so on. A component of your own with one of those ids is
refused when the view is sent.
Switching Tabs¶
A click on a tab draws it: its button takes active_tab_style, the others inactive_tab_style, and its content
replaces the last tab's. One edit of the message answers the click. A click on the tab already open draws it
again, so it shows what its builder reads now.
A switch whose drawing fails leaves the panel on the tab the person can still see. When the builder raises, they get the view's error reply (see When a Callback Raises).
switch_tab(name) opens a tab from code, and active_tab is the name of the tab that is open. A name the view
does not have raises ValueError listing the tabs. Called before send(), switch_tab() opens the view on that
tab:
view = ProfileView(interaction=interaction)
await view.switch_tab("Stats", notify=False)
await view.send()
notify=False leaves out on_tab_switched() (below), for a switch the person did not ask for.
A tab view that opens another screen with push() comes back on the tab it showed when the person clicks Back
(see Navigation).
Redrawing a Tab¶
Call refresh_content() after a callback changes what the open tab's builder reads. It draws the tab again in
place.
reload() runs on_load() first, for data loaded there. A redraw made while a reload() runs waits for it and
draws from the reloaded data. A state change the view receives (see Redrawing When State
Changes) draws the open tab again too.
| Name | What it is |
|---|---|
active_tab |
The open tab's name. Read-only. |
switch_tab(name, *, notify=True) |
Opens the tab named name and draws it. |
refresh_content() |
Draws the open tab again in place. |
When the Tab Changes¶
on_tab_switched(index) runs when the open tab moves to another, before the new tab is drawn. index is the new
tab's position, and active_tab already names it. Use it to count visits or to load what the new tab shows:
async def on_tab_switched(self, index):
if self.active_tab == "Stats":
self.record = await self.db.record(self.user_id)
The default does nothing.
An override may be plain or async, and the click waits for it. It cannot stop the switch: an exception it
raises is logged and the tab opens. It does not run when the view first opens, on a click on the tab already
open, or with notify=False, and a switch that fails after it ran does not run it again. An override that cannot
take index is refused when its class is defined.
Customizing¶
| Attribute | Default | What it does |
|---|---|---|
active_tab_style |
ButtonStyle.primary |
The open tab's button. |
inactive_tab_style |
ButtonStyle.secondary |
The other tabs' buttons. |
tab_overflow_policy |
"fill" |
How the tab buttons fill their rows (see below). |
auto_exit_button |
False |
Adds an Exit button below the content (on row 4 on V1). |
A link or premium style is refused when the class is defined, since those buttons send no click.
build_extra_items() adds controls of your own. The view calls it when built and keeps what it adds on every
tab, below the tab's content.
Many Tabs¶
A row holds five buttons, so tabs past five take more rows. tab_overflow_policy chooses how:
| Value | The rows |
|---|---|
"fill" |
Five to a row, in order. |
"balance" |
As many rows as "fill", evened out: seven tabs make rows of four and three. |
"pin_first" |
The first tab alone on the first row, the rest filled below it. |
"pin_last" |
The last tab alone on the last row. |
a tuple, such as (3, 3) |
That many tabs on each row. |
Each one applies at any number of tabs: "pin_first" with three tabs gives a row of one and a row of two. A tuple
that does not add up to the number of tabs is adjusted, with a warning in the log: tabs left over fill rows after
it, and widths past the last tab are dropped.
A V2 message holds 40 components, and each tab button and each row of them counts, as does the content: with no
content that is 33 tabs. A V1 message holds five rows, so 25 tabs, 21 under "pin_first" or "pin_last", and
fewer when your own controls or the Exit button take a row. Too many tabs raise when the view is built, naming the
count.
Laying Out the Rows Yourself¶
For a layout no value above gives, override build_tab_rows(buttons). It gets the tab buttons in order and
returns the rows, each a list of buttons:
def build_tab_rows(self, buttons):
# The first two tabs on a row of their own, the rest five to a row.
return [buttons[:2], *(buttons[i:i + 5] for i in range(2, len(buttons), 5))]
Every button goes in exactly once, and a row holds at most five. The view checks the rows when it is built, so a row of six, a tab left out or placed twice, or a button that is not one of the tabs raises there, naming the row or the tab.
A V2 row may not be empty. An empty V1 row leaves that row free for your own controls. A button of your own
belongs in build_extra_items().
V1 and V2¶
TabView is the same pattern on a StatefulView. Its builders return a discord.Embed, a list of up to ten, or
None. Text raises TypeError naming the tab: put it in an embed's description.
The tab buttons fill rows from the top, and the Exit button sits on row 4. Give your own controls a row the
tabs leave free: without one, discord.py puts each in the first row with room, which can be a row of tabs.
A TabLayoutView draws its open tab in on_load(), since a builder may be async. An override of on_load()
that loads what a builder reads need not call super():
- The tab is drawn after this returns. Calling
super().on_load()at the end does the same, and calling it first draws the tab before the data is loaded.
Related¶
- Navigation: opening another screen from a tab and coming back.
- Choice and Toggle Controls:
tab_nav(), a row of tab-styled buttons you switch yourself. - Composites:
PaginatedRegionandCollapsible, which work inside a tab. TabLayoutViewandTabView: every parameter.