Layout Builders¶
Builders are functions that return prebuilt pieces of a V2 panel: a card, a line of text with a button
beside it, a status alert, a progress bar. Each returns a standard discord.py component, so it goes anywhere
add_item() takes one, and the builders refuse shapes Discord would reject while you build them, not when
the panel is sent.
This settings panel is built from five of them:
from cascadeui import StatefulLayoutView, action_section, card, divider, key_value, toggle_section
class SettingsView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.notify = True
self.build_ui()
def build_ui(self):
self.clear_items()
self.add_item(card(
"## Settings", # (1)!
key_value({"Region": "EU West", "Tier": "Gold"}),
divider(),
toggle_section("Notifications", active=self.notify, callback=self.toggle_notify),
action_section("Put every setting back.", label="Reset", callback=self.reset),
))
async def toggle_notify(self, interaction, active): # (2)!
self.notify = active
self.build_ui()
await self.refresh()
async def reset(self, interaction):
self.notify = True
self.build_ui()
await self.refresh()
- A string becomes a text block, and
##makes it a heading. - Receives the state the click asks for, so it assigns it.
Cards¶
card() wraps its children in a Container,
the box with a colored stripe that holds most V2 panels. A string child becomes a text block, so headings
and body text go in as plain strings:
import discord
from cascadeui import card
self.add_item(card(
"## Card",
"A container with an accent stripe.",
color=discord.Color.blurple(),
))
Leave color out and the card takes the view's theme accent when the panel is drawn, so a
theme change shows on the next redraw. spoiler=True hides the whole card behind a spoiler.
A card cannot hold another card. Discord refuses a Container inside a Container, so card() raises
ValueError when a child is one. alert() and stats_card() return cards too: add them beside the card,
not inside it.
Labeled Values¶
key_value() turns labels and values into one text block, with a
bold label on each line:
from cascadeui import card, key_value
self.add_item(card("## Key Value", key_value({"Region": "EU West", "Tier": "Gold", "Rank": 14})))
It takes a dict or a list of (label, value) pairs. Given pairs, a label can appear more than once and
each pair keeps its own line. Values are shown through str().
stats_card() puts the
same block in a card under a heading:
from cascadeui import stats_card
self.add_item(stats_card("Season Stats", {"Wins": 24, "Losses": 7, "Streak": "5W"}))
The title becomes a ## heading unless it already starts with #, with a thin line beneath it, and
footer= adds a line of small text at the bottom. An empty title leaves out the heading and the line, so a
computed title that comes back blank still gives a working card. Like card(), it takes the theme's accent
when color is left out.
Text With a Control Beside It¶
A Section is a line of text with one thing beside it, called its accessory: a button, a link, or a small image. Four builders make one, each ready to go inside a card.
A Button¶
action_section()
puts a button beside the text:
from cascadeui import action_section, card
self.add_item(card(
"## Action Section",
action_section("Text on the left, a button on the right.", label="Open", callback=self.open),
))
The callback takes the interaction alone, since this button sends no value. One that needs a second
argument raises TypeError when the section is built. style= and emoji= dress the button, and
disabled=True greys it out.
An On/Off Switch¶
toggle_section()
draws a green Enabled button when active is true and a red Disabled one when it is false:
from cascadeui import card, toggle_section
self.add_item(card(
"## Toggle Section",
toggle_section("Notifications", active=self.notify, callback=self.toggle_notify),
))
The callback takes (interaction) or (interaction, active). The second form receives the state the click
asks for, the opposite of what was drawn, so the handler assigns it instead of working it out, as
toggle_notify does in the first example. A callback that can take neither raises TypeError when the
section is built.
The section shows what active says, so the callback redraws the view for the switch to change.
labels=("On", "Off") changes the two words, emoji= adds an emoji, and disabled=True greys it out.
A Link¶
link_section() puts a link
button beside the text. Discord opens the address itself, so no callback runs and the bot hears nothing:
from cascadeui import card, link_section
self.add_item(card(
"## Link Section",
link_section(
"A section whose accessory is a link button.",
label="Docs",
url="https://hollowthesilver.github.io/CascadeUI/",
),
))
A Thumbnail¶
image_section()
puts a small image beside up to three lines of text:
from cascadeui import card, image_section
self.add_item(card(image_section(f"**{member.display_name}**", "Admin", url=member.display_avatar)))
url takes a web address, an uploaded file, or anything with a .url such as a member's avatar (see
MediaInput), and Files and Media covers uploads. Empty lines
are skipped, so an optional second line can be left blank. description= sets the image's alt text, up to
1024 characters, and spoiler=True blurs it. Left out, both come from a discord.File passed as url.
Both an Image and a Button¶
A Section has one accessory, so a line of text cannot show both a thumbnail and its own button. Two layouts come close:
- Keep the thumbnail. Use
image_sectionfor each row, number the rows in their text, and put onechoice_rowunder the list with options labeled to match. It costs the same at four rows or twenty, and it turns into a dropdown on its own past itsbutton_threshold. Passallow_reselect=Truewhen picking a row does something rather than marking it as the choice, or the last pick stays disabled. - Keep the button. Use
action_sectionfor each row and show the images full width withgallery()above or below. The images no longer read as belonging to their rows, which is usually why the first layout wins.
A row of image_section with its own ActionRow of buttons also works, but costs five components a row,
so eight rows fill Discord's 40-component budget (seven inside a card, which counts as one).
Asking to Confirm¶
confirm_section()
returns a prompt and a row of two buttons as a list, so * spreads them into a card:
from cascadeui import card, confirm_section
self.add_item(card(
"## Confirm Section",
*confirm_section(
"Delete this panel?",
on_confirm=self._do_delete,
on_cancel=self._do_cancel,
),
))
Each callback takes the interaction alone, and one that needs a second argument raises TypeError when the
prompt is built. The prompt takes one answer: once one button's callback runs, a click on either button sent
before it finishes is dropped, whoever sent it.
By default Confirm is green with a check and Cancel red with a cross, which suits a prompt that adds something. A prompt that destroys something, like this one, reads better with the styles swapped, so the button that deletes is not the green one:
confirm_section(
"Delete this panel?",
on_confirm=self._do_delete,
on_cancel=self._do_cancel,
confirm_style=discord.ButtonStyle.danger,
cancel_style=discord.ButtonStyle.secondary,
)
confirm_label, cancel_label, confirm_emoji, and cancel_emoji change the rest.
Status Messages¶
alert() returns a card with an emoji and a colored stripe
for its level:
| Level | Emoji | Stripe |
|---|---|---|
"success" |
✅ | green |
"warning" |
⚠️ | gold |
"error" |
❌ | red |
"info" (the default) |
ℹ️ | blurple |
Any other level raises ValueError. An alert is a card, so it goes beside other cards, not inside one.
Progress Bars¶
progress_bar()
draws a text bar with the percentage after it:
from cascadeui import card, progress_bar
self.add_item(card("## Progress Bar", progress_bar(7, 10))) # [██████████████░░░░░░] 70%
A value past either end is held to it, so 12 out of 10 draws a full bar. The cells and the percentage round
to the nearest whole, halves up, so 5 out of 8 reads 63%. A bar shows full and 100% only once the value
reaches the end, so 199 out of 200 reads 99%. width= sets the number of cells
(20 by default), filled= and empty= change the two characters, and show_percent=False drops the
percentage.
To put a bar inside a line of text, use
render_progress(),
which returns the same bar as a string:
from cascadeui import render_progress
def format_secondary(self, rank, user_id, stats):
bar = render_progress(stats["wins"], stats["games"] or 1, width=6)
return f"{stats['mmr']} MMR {bar}"
progress_bar() is built from it, so a bar inside a line and a bar on its own look the same.
Spacing¶
divider() draws a thin line between blocks, and
gap() leaves the same space with no line:
large=True gives either one more room. Left unset, both follow the theme's separator_spacing.
Images and Files¶
gallery() shows up to 10 images
in a grid:
from cascadeui import card, gallery
self.add_item(card(
"## Gallery",
gallery(
"https://example.com/cover.png",
"https://example.com/map.png",
"https://example.com/team.png",
descriptions=["Cover art", None, None],
),
))
Each image takes the same references as a thumbnail. descriptions= and spoilers= take one entry per
image, None or False for the ones without. A discord.File whose entry is None gives its own.
file_attachment() shows a file people can
download, inside the panel:
from cascadeui import card, file_attachment
self.add_item(card(
"## Quarterly Report",
file_attachment("attachment://q1_2026.pdf"), # (1)!
"Released April 15.",
))
- Names a file sent with the panel, as Files and Media shows.
Discord shows a file here only when it was uploaded with the message, so file_attachment() takes an
attachment:// name or the discord.File itself, and raises ValueError for a web address. Use gallery()
for images to look at, and file_attachment() for files to download.
Less common cases
A builder's id=. Every builder takes id=, Discord's number for a component within its message
(1 to 2147483647, unrelated to custom_id). Discord numbers any component left without one.
Persistent panels. Inside a persistent view, give action_section, toggle_section, and
confirm_section a custom_id=. The view refuses a button without one when it is sent, since after a
restart nothing could route its clicks. See Panels That Survive Restarts.
Double clicks. When someone clicks one of these buttons again while their first click on it is
still running, the second is dropped, as for every button (see
Double Clicks). action_section(allow_double_click=True) runs
every click. A toggle or confirm button has no such setting, and also drops anyone's click that arrives
while its last click is still running.
Refused when built. Each of these raises where the builder is called:
- empty text, or an empty media reference
- more than three lines in an
image_section - more than 10 gallery images, or a
descriptions=orspoilers=of the wrong length - an
id=out of range
Related¶
- Choice and Toggle Controls: rows of buttons, choices, toggles, and tabs.
- Files and Media: sending the files an
attachment://name points at. - Layout Rules and Limits: what goes where in a V2 panel, and the 40-component budget.
- Components reference: every builder's parameters.