Composites¶
A composite keeps its own state inside a view. PaginatedRegion pages one list while the rest of the panel
stays put, and Collapsible keeps a section closed behind a button until someone opens it. The view builds
each one once, in __init__, and adds what it returns on every redraw. That puts a composite between the two
other shapes: a layout builder returns components and keeps nothing, and a
paginated view owns the whole message.
This panel pages a list of standings inside the card between its header and its footer:
from cascadeui import PaginatedRegion, StatefulLayoutView, card, key_value
class Standings(StatefulLayoutView):
def __init__(self, *, standings, **kwargs):
super().__init__(**kwargs)
self.pager = PaginatedRegion(items=standings, per_page=5) # (1)!
self.build_ui()
def build_ui(self):
self.clear_items()
self.add_item(card("## Season 4 Standings", key_value({"Region": "EU West"})))
first = self.pager.page * 5 + 1
rows = "\n".join(
f"**{first + i}.** {name}, {mmr} MMR" for i, (name, mmr) in enumerate(self.pager.page_items)
)
self.add_item(card(rows or "No results yet.", *self.pager.controls(self))) # (2)!
self.add_item(card("-# Only the middle card turns pages."))
- Built once and kept. One built anew inside
build_ui()works too: it takes the page of the one before it (see Built on every redraw). - The page buttons, inside the card they page. A click moves the page and runs
build_ui()again.
Paging One Section¶
PaginatedRegion(items=, per_page=10, key="page") holds a list and the page it is on. page_items is the
current page's slice, page its number counting from 0, and page_count how many pages there are (at
least 1). The view renders the slice however it likes. The region only slices it, which is why it takes no
formatter where a paginated view does.
controls(view) returns the page buttons as one action row, or nothing when everything fits on one page.
Put the row in the card it pages, as above, or add it to the view. A click moves the page and redraws the
view through the same path as before: a view with build_ui() runs it, a view that builds in on_load()
loads again, and a tab view rebuilds its open tab. The edit answers the click in one request.
Data that loads in on_load() is set there, before the view reads page_items:
items takes a list or any other sequence, and reads a generator into a list. Text is refused, since it
would page one letter at a time.
The Page Buttons¶
Under five pages the row is ◀, a disabled "Page 1/3" label, and ▶. From five pages on, it adds ⏮ and ⏭ for the ends, and the page number becomes a button that opens a box to type a page into. A number past either end goes to the first or last page, and anything that is not a number is answered with a short note. A button with nowhere to go is disabled.
controls(view, compact=True) gives three buttons at any count: ◀, the page number that opens the box, and
▶. control_buttons() takes the same arguments and returns the buttons without their row, so the pager can
share a row of five with Back and Exit:
from discord.ui import ActionRow
self.add_item(
ActionRow(
*self.pager.control_buttons(self, compact=True),
self.make_back_button(),
self.make_exit_button(),
)
)
◀ and ▶ take a quick second click as a second page turn, as a paginated view's do.
Changing the Buttons¶
Subclass the region and set class attributes, as on a paginated view. Each of the five buttons (first,
prev, indicator, next, last) has a _button_label, _button_emoji, and _button_style.
indicator_button_format writes the page label from {page} and {total}, and jump_threshold is the page
count at which the end buttons and the box appear (None never shows them):
from cascadeui import PaginatedRegion
class Pager(PaginatedRegion):
prev_button_label = "Back"
next_button_label = "Next"
indicator_button_format = "{page} of {total}"
jump_threshold = None
These raise when the subclass is defined:
- a misspelled placeholder in the format
- a link or premium style
- a label over 80 characters, or a label or emoji of the wrong type
- a
jump_thresholdthat is not a whole number of at least 1
Moving the Page From Code¶
set_page(n)moves the page and draws nothing. Use it before the first render or inrestore_nav_state(). A negativencounts from the end, as a list index does, and a number past either end stops there.await show_page(n)moves the page and redraws the view, for a button of your own such as "Find me". Before the view's first render has calledcontrols(), the region has no view to redraw and raisesRuntimeError.notify=Falseleaves outon_page_changed, for a move the person did not ask for.on_page_changed(page), overridden in a subclass, runs after each move and before the redraw.self.hostis the view. An override that cannot takepageis refused when the subclass is defined.
Two Regions in One View¶
Each region keeps its own page. Give each a key, since the button ids are built from it
(region_page_next for the default): two regions with the same key are refused at send, naming the repeated
id.
self.left = PaginatedRegion(items=home_players, per_page=5, key="home")
self.right = PaginatedRegion(items=away_players, per_page=5, key="away")
Opening a Section¶
Collapsible puts a button above a section and shows the section only while it is open. It shows more
controls in place, where pushing a new screen or sending a reply would take the person away from the panel:
from cascadeui import Collapsible, StatefulLayoutView, card, choice_row, key_value
REGIONS = {"Europe": "EU", "North America": "NA", "Asia": "AS"}
class Filters(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.region = "EU"
self.picker = Collapsible(
label="Edit Region",
expanded_label="Done",
reveal=lambda: choice_row(REGIONS, selected=self.region, on_select=self.pick), # (1)!
)
self.build_ui()
def build_ui(self):
self.clear_items()
self.add_item(card("## Filters", key_value({"Region": self.region}), *self.picker.render(self)))
async def pick(self, interaction, value):
self.region = value
self.picker.collapse() # (2)!
self.build_ui()
await self.refresh()
- Called on every redraw while open, so the row shows the region picked now.
- Closing after a pick is the view's choice. Leave it out to keep the section open.
render(view)returns the button alone while closed, and the button with whatreveal()returns while open. Spread it into a card, as above, or add each item to the view.- A click opens or closes the section, shows
expanded_labelon the button while it is open (andexpanded_styleandexpanded_emoji, when given), and redraws the view as a page button does. A quick second click is dropped, so it cannot close what the first click opened. revealreturns a component, text, a list or other iterable of them, orNonefor nothing yet. Text shows as aTextDisplay, and anything else, a dict included, raisesTypeErrornamingreveal.revealis called with no arguments and cannot beasync: one that takes an argument or isasync defraisesTypeErrorwhen the collapsible is built. Load data in the view'son_load()and letrevealread it.expand()andcollapse()open and close it from code,expandedsays which it is, and anon_toggle(expanded)override in a subclass runs after each open or close, before the redraw. One that cannot takeexpandedis refused when the subclass is defined.
A Summary Beside the Button¶
Give summary and the button sits beside a line of text, in a section, instead of in a row of its own. That
is the shape for a disclosure inside a card:
self.details = Collapsible(
label="Show",
expanded_label="Hide",
summary=lambda: f"**Match {self.match.number}**, {self.match.tier}",
reveal=lambda: key_value({"Score": self.match.score, "Duration": self.match.duration}),
key="details",
)
def build_ui(self):
self.clear_items()
self.add_item(card("## Match", *self.details.render(self)))
summary is the text, or a function that returns it, called on every redraw like reveal. When it returns
nothing (the data has not loaded yet), the button falls back to a row of its own.
Two in One View¶
A collapsible's button id is {key}_trigger, collapsible_trigger by default, so two in one view each need
their own key. Two with the same key are refused at send, naming the repeated id.
Less common cases
The button below the section. trigger_first=False puts the button under what it reveals, for a
"Cancel" that closes a section above it.
Built on every redraw. A composite made while the view redraws (inside
build_ui(), on_load(), or a tab or step builder) takes the page or the open state of the one the view
last showed under the same key in the same tab or step, and a click hands its change on to the one the
redraw makes. A collapsible given expanded= takes the view's value on every redraw instead. So does each
one a build makes after setting the state itself with expand(), collapse(), or set_page(): it starts
as built, so if self.open: picker.expand() closes the picker once self.open is false.
When the build's state undoes a click, one warning says so. Two made up front, in __init__, keep their
own state even when they share a key.
Made in a pattern's hooks. A composite made in a pattern's own hooks is drawn again on its click
too: the click runs build_extra_items() again, rebuilds a leaderboard's pages (fetching the entries,
as reload(force=True) does), or composes a paginator's page again. A view whose render never draws
it again gets one warning naming the fix.
Coming back with Back. The page and the open state live on the objects the view built, and a pop()
builds the view again, so they come back as a fresh open shows them. Name them in get_nav_state() to
bring them back (see What Comes Back on pop()).
A panel that survives a restart. The button ids come from key alone, so the buttons keep working
on a persistent panel. The page and the open state start over
when the panel is restored: the first page, closed.
Paging from inside on_load(). A view without build_ui() redraws by running on_load() again, so
show_page() inside that view's own on_load() raises and the page goes back. Call set_page() there,
before the tree is built.
Refused when built.
- a
per_pagethat is not a whole number of at least 1 (aboolincluded) itemsgiven as text- an empty
key, or one too long for its ids (83 characters for a region, 92 for a collapsible) - an empty
label, or a link or premium style - a
revealorsummarythat is async or takes arguments - a page number for
set_page()orshow_page()that is not anint
Related¶
- Paginated views: when the list is the whole message.
- Controls Inside a Card: what a card holds.
- Loading Data:
on_load()and when it runs. PaginatedRegionandCollapsible: every parameter.