Choice and Toggle Controls¶
These builders make the controls a settings panel is made of: a row of buttons, a set of options to pick
from, an on/off button, a button that steps through values, and a row of tabs. Each returns a standard
discord.py component, ready for add_item() or a card.
This panel lets someone pick a difficulty and switch ranked play on and off:
from discord.ui import ActionRow
from cascadeui import StatefulLayoutView, card, choice_row, toggle_button
class MatchSettings(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.difficulty = "Normal"
self.ranked = False
self.build_ui()
def build_ui(self):
self.clear_items()
self.add_item(card(
"## Match Settings",
choice_row(
{"Easy": "Easy", "Normal": "Normal", "Hard": "Hard"},
selected=self.difficulty,
on_select=self.set_difficulty,
),
ActionRow(toggle_button(
active=self.ranked,
on_toggle=self.set_ranked,
labels=("Ranked", "Casual"),
)),
))
async def set_difficulty(self, interaction, value): # (1)!
self.difficulty = value
self.build_ui()
await self.refresh()
async def set_ranked(self, interaction, active): # (2)!
self.ranked = active
- Receives the value of the option picked. The row shows what
selectedsays, so the view stores the pick and draws again. - The toggle changes its own label and color. The view stores the state so the next redraw keeps it.
A Row of Buttons¶
button_row()
turns labels and callbacks into one row of buttons, in the order given:
from cascadeui import button_row
self.add_item(button_row({
"First": self._first,
"Second": self._second,
"Third": self._third,
}))
Every button takes the row's style (grey by default) and emoji. Each callback takes the interaction
alone, since these buttons send no value. One that needs a second argument raises TypeError when the row is
built. A row holds up to five buttons, Discord's limit, and more, or none, raises ValueError.
For buttons that differ, pass RowButton entries. Each sets its own
emoji and style (left unset, it takes the row's), disabled, and a key that keeps its id in a
persistent panel:
from cascadeui import RowButton, button_row
self.add_item(button_row(
[
RowButton("Wins", self._wins, emoji="💰", key="wins"),
RowButton("Near Miss", self._near, emoji="🎯", key="near_miss"),
RowButton("Full Record", self._full, emoji="📋", key="full"),
],
custom_id="feed",
))
A RowButton with None as its label shows its emoji alone. A button with neither raises ValueError,
since Discord refuses one.
Picking One Option¶
choice_row()
draws a set of options that share one callback. The option matching selected is highlighted and greyed
out, since picking it again would change nothing:
from cascadeui import choice_row
self.add_item(choice_row(
{"Easy": Difficulty.EASY, "Normal": Difficulty.NORMAL, "Hard": Difficulty.HARD},
selected=self.difficulty,
on_select=self._set_difficulty,
))
on_select takes (interaction, value) and receives the picked option's value, whatever Python object it
is: the builder turns values into the strings Discord needs and back. A callback that takes only the
interaction raises TypeError when the row is built.
More than five options turn into a dropdown, up to 25 (MAX_SELECT_OPTIONS, Discord's limit for a select).
More than 25 raise ValueError:
Pass Choice entries when an option needs an emoji, a line of description
under it in the dropdown (buttons have no room for one), or a key:
from cascadeui import Choice, choice_row
self.add_item(choice_row(
[
Choice("Goals", Event.GOAL, emoji="⚽", description="Match goals"),
Choice("Cards", Event.CARD, emoji="🟨", description="Yellow and red cards"),
],
selected=self.event,
on_select=self._set_event,
button_threshold=0, # (1)!
))
- Two options would draw as buttons, which show no description.
0draws a dropdown whatever the count.
The View Keeps the Selection¶
choice_row shows what selected says and remembers nothing, so on_select stores the pick and draws the
view again, as set_difficulty does in the first example. Left undrawn, the buttons keep showing the old
pick, and a dropdown goes back to it as soon as the pick is answered.
To make a pick of the active option do something, reopening its editor say, pass allow_reselect=True: the
active option stays clickable, and picking it calls on_select again, as buttons or as a dropdown.
Picking Several¶
With multi=True, any number of options can be active. selected is then a collection of values, each
option turns on or off when clicked, and on_select receives the whole new selection as a list. Values need
not be hashable, so a list or a dict works as an option's value.
min_values sets the fewest options that may stay picked. The dropdown hands it to Discord, and the buttons
grey out the active options while the selection is at that minimum, so the last one cannot be turned off. A
selection that starts below it can still grow to it:
choice_row(
{"Round 1": 1, "Round 2": 2, "Round 3": 3},
selected=lambda: self.rounds,
multi=True,
min_values=1,
on_select=self._set_rounds,
)
Toggles clicked in quick succession all count: a toggle that waited behind another reads the other options
from the newest drawing of the row. A view that draws through state can have that drawing held back while
another task runs reload(), so it passes selected as a function, as above, and each toggle reads the
selection the view holds when it lands.
An On/Off Button¶
toggle_button()
shows a green Enabled button when active is true and a red Disabled one when it is false:
from discord.ui import ActionRow
from cascadeui import toggle_button
self.add_item(ActionRow(toggle_button(active=self.notify, on_toggle=self._set_notify)))
on_toggle takes (interaction, active) and receives the new state, and one that takes only the interaction
raises TypeError when the button is built. Each click flips the button's label and color, and a click the
callback leaves unanswered is answered with the panel (one the library acknowledged first is redrawn with an
edit), so the change shows without a refresh(). Store the
state and pass it as active when the view draws again, or the redraw puts the old state back.
labels=("On", "Off") changes the two words, and emoji= adds an emoji.
For a line of text with the switch beside it, use
toggle_section(). For a button that holds its own state and turns
green with a check mark, use ToggleButton.
A Button That Steps Through Values¶
cycle_button()
moves to the next value with each click, and back to the first after the last:
from discord.ui import ActionRow
from cascadeui import StatefulLayoutView, card, cycle_button
RANGES = ["Daily", "Weekly", "Monthly"]
class ReportView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.range = "Daily"
self.build_ui()
def build_ui(self):
self.clear_items()
self.add_item(card(f"## Report\nShowing the {self.range.lower()} totals."))
self.add_item(ActionRow(cycle_button(
values=RANGES,
selected=self.range, # (1)!
on_change=self.set_range,
)))
async def set_range(self, interaction, value):
self.range = value
self.build_ui()
await self.refresh()
- The value the button shows when it is built. Left out, every redraw goes back to the first value.
on_change takes (interaction, value) and receives the new value, and one that takes only the interaction
raises TypeError when the button is built. A selected that is not one of the values raises ValueError.
labels= sets the text shown for each value (str(value) by default), and start= takes a position in
place of selected. Like the toggle, the button changes its own label, and the change shows without a
refresh().
Tabs¶
tab_nav()
draws a row of tabs. The tab active names is highlighted in blurple and the rest are grey, and each
callback shows its tab's content:
from cascadeui import tab_nav
self.add_item(tab_nav(
{
"Overview": self._show_overview,
"Members": self._show_members,
"Settings": self._show_settings,
},
active="Overview",
))
tab_nav draws the row and nothing else: the content below it is the view's own. Left out, active is the
first tab.
Each callback takes the interaction alone. One that needs a second argument raises TypeError when the row
is built. A row holds up to five tabs. For more, or for tabs whose content loads when they are opened, use
the tab pattern.
Tabs also take RowButton entries, for an emoji, disabled, or a key. A tab's color follows active, so a
RowButton style raises ValueError. active names a tab by its key or its label, and raises ValueError
when it names none or more than one, so tabs that show an emoji alone are named by their keys:
from cascadeui import RowButton, tab_nav
self.add_item(tab_nav(
[
RowButton(None, self._show_home, emoji="🏠", key="home"),
RowButton(None, self._show_settings, emoji="⚙️", key="settings"),
],
active="home",
))
Ids in a Persistent Panel¶
In an ordinary view each button's id comes from what it does, so none of these builders needs one. A
persistent panel keeps its ids across restarts, so give each control in it a
custom_id. The view refuses a button without one when it is sent. choice_row has "choice" as its own,
so a persistent view with two needs a different one for each.
For a row, the custom_id is a base: each button's id is {custom_id}_{key}, or {custom_id}_{position}
for one without a key. A position names whichever button sits there now. Remove the first button and the
second takes its id, so a click on a copy of the message drawn before the change reaches the wrong button.
Give each a key and its id stays with it.
The same goes for tab_nav tabs and choice_row options. A dropdown option carries its key, or its
position, as its value:
choice_row(
[Choice(name, name, key=name.lower()) for name in self.maps],
on_select=self._pick_map,
custom_id="map",
)
A dropdown pick naming an option the control no longer has runs nothing and is answered with the panel as
it is now. Two entries that would share an id (a key used twice, or a key equal to another entry's
position), or a key too long for {custom_id}_{key} to fit Discord's 100 characters, raise ValueError.
toggle_button and cycle_button take a custom_id of their own.
Less common cases
Dropdown or buttons. button_threshold= sets how many options still show as buttons, from 0 to 5,
and 0 always draws a dropdown. placeholder= sets the dropdown's text before a pick, and active_style=
and inactive_style= the colors of the buttons.
Greyed out. choice_row(disabled=True) greys out the whole control while still showing the
selection, for a locked or closed setting. A RowButton(disabled=True) greys out one button or tab.
Double clicks. When someone clicks a button again while their first click on it is still running,
the second is dropped, as for every button (see Double Clicks).
button_row(allow_double_click=True) runs every click on the row. A toggle, a cycle button, and an
option of a multi-select also drop anyone's click that arrives while the control's last click is still
running.
Other selects. For a dropdown with a max_values of its own, or a select of roles, channels, or
users, use a select from Buttons and Selects.
Refused when built. Besides the cases above:
- a
selectedlist withoutmulti=True, or a string as a multi-select'sselected - a
min_valuesabove 1 withoutmulti=True, or above the options' distinct values - a
button_thresholdoutside 0 to 5 - a
cycle_buttonwith no values, alabelslist of the wrong length, or astartout of range
Related¶
- Buttons and Selects: single buttons, selects, and
ToggleButton. - Layout Builders: cards, sections, and
toggle_section(). - Tabs: a full tabbed view whose tabs load their own content.
- Components reference: every parameter.