Skip to content

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."))
  1. 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).
  2. The page buttons, inside the card they page. A click moves the page and runs build_ui() again.

Animation: Kael uses /standings and the panel shows three cards: Season 4 Standings with Region EU West, the middle card listing ranks 1 to 5 over a disabled ◀, a disabled Page 1/3 label and ▶, and a footer card. Kael clicks ▶: the region moves to page 2, build_ui() runs again, and one request shows ranks 6 to 10 in the middle card while the header and footer cards stay as they were. Kael clicks ▶ again: ranks 11 to 15, Page 3/3, and ▶ disabled

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:

async def on_load(self):
    self.pager.items = await self.db.fetch_standings()

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(),
    )
)

Four rows of page buttons. controls(view) at three pages is ◀, a disabled Page 1/3 label, and ▶. At eight pages it is ⏮, ◀, a 1/8 button that opens a box, ▶, and ⏭. controls(view, compact=True) is ◀, 1/8, and ▶ at any count, and control_buttons(view, compact=True) shares one row with Back and Exit

◀ 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_threshold that 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 in restore_nav_state(). A negative n counts 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 called controls(), the region has no view to redraw and raises RuntimeError. notify=False leaves out on_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.host is the view. An override that cannot take page is 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")

Animation: Kael uses /lineups and the panel shows two cards, Home and Away, each listing players 1 to 5 over its own row of page buttons. The keys go into the ids, so the ▶ buttons are region_home_next and region_away_next. Kael clicks ▶ under Away: only Away turns to players 6 to 10, in one request, and Home stays on its page. Kael clicks ▶ under Home: only Home turns

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()
  1. Called on every redraw while open, so the row shows the region picked now.
  2. Closing after a pick is the view's choice. Leave it out to keep the section open.

Animation: Kael uses /filters and the Filters card shows Region: EU over an Edit Region button. Kael clicks Edit Region: the section opens inside the card, the button reads Done, and a row of Europe, North America and Asia appears under it, Europe picked, in one request. Kael picks North America: pick() stores NA, closes the section and redraws, so one request shows Region: NA over Edit Region again

  • render(view) returns the button alone while closed, and the button with what reveal() 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_label on the button while it is open (and expanded_style and expanded_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.
  • reveal returns a component, text, a list or other iterable of them, or None for nothing yet. Text shows as a TextDisplay, and anything else, a dict included, raises TypeError naming reveal.
  • reveal is called with no arguments and cannot be async: one that takes an argument or is async def raises TypeError when the collapsible is built. Load data in the view's on_load() and let reveal read it.
  • expand() and collapse() open and close it from code, expanded says which it is, and an on_toggle(expanded) override in a subclass runs after each open or close, before the redraw. One that cannot take expanded is 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.

Two Filters cards, each open on its row of Europe, North America, and Asia. With trigger_first=True, the default, the Done button sits above the row. With trigger_first=False it sits under the row, labeled Cancel

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_page that is not a whole number of at least 1 (a bool included)
  • items given 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 reveal or summary that is async or takes arguments
  • a page number for set_page() or show_page() that is not an int