Paginated¶
A paginated view shows a list a page at a time. Buttons under the page turn it, and every page is drawn in the same message.
import discord
from cascadeui import PaginatedLayoutView, card, divider
class InventoryView(PaginatedLayoutView):
auto_exit_button = True # (1)!
nav_inside_container = True # (2)!
nav_divider = True
def format_page(items): # (3)!
total = sum(item["value"] for item in inventory)
lines = [f"{item['emoji']} **{item['name']}**\n-# {item['value']}g" for item in items]
return card(
"## Inventory", f"-# {len(inventory)} items ยท {total:,}g in all", divider(), "\n".join(lines)
)
inventory = [ # (4)!
{"name": "Iron Sword", "emoji": "โ๏ธ", "value": 120},
{"name": "Oak Shield", "emoji": "๐ก๏ธ", "value": 80},
{"name": "Healing Potion", "emoji": "๐งช", "value": 25},
{"name": "Rope", "emoji": "๐ชข", "value": 5},
{"name": "Lantern", "emoji": "๐ฎ", "value": 15},
{"name": "Silver Ring", "emoji": "๐", "value": 200},
{"name": "Map of the Coast", "emoji": "๐บ๏ธ", "value": 40},
{"name": "Torch", "emoji": "๐ฅ", "value": 3},
{"name": "Dragon Scale", "emoji": "๐", "value": 900},
{"name": "Old Key", "emoji": "๐๏ธ", "value": 1},
]
@bot.tree.command(name="inventory", description="Show your inventory")
async def show_inventory(interaction: discord.Interaction):
view = await InventoryView.from_data( # (5)!
inventory, per_page=4, formatter=format_page, interaction=interaction
)
await view.send()
- Adds an Exit button below the page, kept on every page.
- Puts the page and its buttons in one card, with a line between them. See One Card.
- The formatter draws one page from that page's items: each item's emoji and name, over its value in grey. The
count line reads the whole sample list. A list that differs between views reaches the formatter as
Per-Page Settings shows. The formatter may be
async. - Ten items, three pages of four. A real inventory comes from the bot's own records.
from_data()splits the list four items to a page and runs the formatter over each page before the view is built, so it is awaited.
The panel is one card: the title over a count of the whole list, the page's four items, and under a line the
previous-page arrow, the page indicator (Page 1/3), and the next-page arrow. Exit sits below the card. An arrow greys out at the end it
points past.
A paginated view suits a list the person reads through: an inventory, search results, a log. For a list inside a
panel that shows other things too, use a PaginatedRegion, which pages one part
of a view.
Pages¶
from_data() builds the pages for you. To give them yourself, pass a list to pages=, one entry per page:
view = PaginatedLayoutView(
pages=["Welcome to the guide.", card("## Rules", rules_text), [card("## Roles"), roles_row]],
interaction=interaction,
)
A page is text (shown as a card() in the theme's accent color),
a component, a list or tuple of components (text among them shows as a TextDisplay), or a function taking
no arguments that returns one of those. A function, plain and not async, runs each time its page
is drawn, so it shows what it reads at that moment. The view checks its pages when
it is built, so a page of another kind (a dict, a number, a generator) raises TypeError there, naming its place
in pages. A page function that returns None raises when its page is drawn.
From a List¶
from_data(items, per_page, formatter, **kwargs) takes any sequence, or any other iterable (read into a list
first). A dict is refused, since paging it would page its keys. Every other keyword goes to the view, as
interaction= above.
The formatter gets one page's items and returns the page. One that returns None raises TypeError naming the
page, since a page of None would show nothing. Arguments it cannot take fail inside from_data(), with your own
line in the traceback.
refresh_data(items) pages a new list with the same per_page and formatter and draws the page the person is
on. A view past the new last page moves to it, and an empty list shows a "No pages." card.
From a Database¶
For a list too long to load at once, from_cursor() fetches each page as the person reaches it:
async def fetch_users(offset, limit): # (1)!
return await db.fetch(
"SELECT name FROM users ORDER BY name LIMIT $1 OFFSET $2", limit, offset
)
total = await db.fetchval("SELECT count(*) FROM users")
view = UserList.from_cursor( # (2)!
fetch_users, total=total, per_page=10, formatter=format_users, interaction=interaction
)
await view.send()
fetch_fn(offset, limit)returns one page's items:offsetcounts items from the start,limitisper_page.- Not awaited: nothing is fetched until the view is sent, which loads the first page.
total is the number of items, which sets the page count the indicator and the jump buttons show. Up to
cache_size pages (default 10) stay loaded, the least recently shown dropped first. The page on screen is never
dropped.
A fetch_fn or formatter that cannot take what it will be given raises TypeError when from_cursor() is
called. So does a total, per_page, or cache_size that is not an int, and one out of range raises
ValueError. A formatter that returns None raises when its page loads.
When the rows change, call refresh_pages(). It empties the cache and fetches the page on screen again. Pass
new_total= when rows were added or removed: the page count follows it, and a view past the new last page moves
to it.
refresh_data() works only on a view built with from_data(), and refresh_pages() only on one built with
from_cursor(). Each raises RuntimeError naming the other when called on the wrong one.
Turning Pages¶
The arrows step one page. From jump_threshold pages (default 5) the row also has first-page and last-page
buttons, and the indicator becomes a button that opens a "Go to Page" box: the person types a page number, and a
number past either end lands on the first or last page. Text that is not a number gets a private reply naming it.
Quick repeated clicks on an arrow each turn a page. A double-click on the other buttons counts once. A turn whose edit does not reach Discord puts the view back on the page the person still sees.
set_page(n) turns to a page from code. n counts from 0, and a number past either end lands on the first or
last page:
n must be a whole number (a bool or float raises TypeError). current_page reads the page shown, and
assigning it moves the view without redrawing, so use set_page(). A state change the view receives (see
Redrawing When State Changes) draws the current page again,
and a view that opens another screen with push() comes back on the same page.
| Name | What it is |
|---|---|
pages |
The pages, in order. |
current_page |
The page shown, counting from 0. |
set_page(n, *, notify=True) |
Turns to page n and draws it. |
refresh_data(items) |
Pages a new list (from_data() views). |
refresh_pages(*, new_total=None) |
Fetches again (from_cursor() views). |
When the Page Changes¶
on_page_changed(page) runs on each turn, after current_page moves and before the page is drawn. page
counts from 0. Use it to count views or to start loading what comes next:
The default does nothing. It cannot stop the turn: an exception it raises is logged and the page turns.
set_page(n, notify=False) leaves it out, for a turn the person did not ask for. An override that cannot take
page raises TypeError when its class is defined.
It runs before the page is drawn
It reports the turn the person asked for. If the edit never lands, the view goes back to the page still on
screen and the hook is not called again, so an override that counts turns has counted one the person never
saw. Read refresh_degraded after the turn if that matters (see
A Request That Never Reaches Discord).
Customizing¶
Each of the four arrows has a label, emoji, and style, named for the arrow:
| Attribute | Default | What it does |
|---|---|---|
first_button_label, prev_button_label, next_button_label, last_button_label |
"โฎ", "โ", "โถ", "โญ" |
The arrows' text. |
first_button_emoji and the others |
None |
An emoji on the arrow. |
first_button_style and the others |
ButtonStyle.secondary |
The arrow's color. |
indicator_button_label |
None |
Fixed text for the indicator (below). |
indicator_button_format |
None |
A template for the indicator's text (below). |
indicator_button_emoji |
None |
An emoji on the go-to button. |
indicator_button_style |
ButtonStyle.primary |
The go-to button's color. |
jump_threshold |
5 |
The page count from which the first, last, and go-to buttons appear. None never shows them. |
auto_exit_button |
False |
Adds an Exit button, kept on every page. |
An arrow given an emoji and no label of its own shows the emoji alone, which is how a server's custom emoji
becomes an arrow. Below jump_threshold the indicator is a greyed button that is always secondary and shows
no emoji, since a greyed button in color reads as one that is broken. Its text still follows the two attributes
below.
The Page Indicator¶
The indicator reads Page 3/12, and the go-to button 3/12. indicator_button_format sets both from a template,
where {page} and {total} count from 1:
class Results(PaginatedLayoutView):
indicator_button_format = "{page} of {total}"
jump_threshold = None # (1)!
- Keeps the row at three buttons on any number of pages.
indicator_button_label sets fixed text instead, the same on every page, and wins over the format. A template
that cannot fill in (a misspelled {pages}, a lone {, or {}) raises ValueError when the class is defined.
Controls of Your Own¶
build_extra_items() adds controls of your own. The view calls it when built and keeps what it adds on every
page, below the buttons:
from discord.ui import ActionRow
from cascadeui import StatefulButton
def build_extra_items(self):
self.add_item(ActionRow(StatefulButton(label="Refresh", callback=self.on_refresh)))
async def on_refresh(self, interaction):
await self.refresh_data(await self.db.inventory(self.user_id))
A page with no room beside its buttons and these controls raises ValueError naming the page when the pages
are given, so the view is refused before anyone turns to it.
One Card¶
nav_inside_container = True puts the page and its buttons in one card. A page that is one card, text included,
keeps its color in it, and a page of components with no card is wrapped in a new one in the theme's accent.
nav_divider = True adds a
line between the page and the buttons. Controls from build_extra_items() stay below the card.
A page that already holds a card beside other things, or a card of a Container subclass, keeps its own layout
with the buttons below it, since Discord does not take a card inside a card. So does a page card marked as a
spoiler, which would hide the buttons until the page is revealed, and a page that fits Discord's
40 components only beside its buttons, since the
card is one more. A view of one page has no buttons, so the setting changes nothing there.
Per-Page Settings in a Formatter¶
A formatter gets only the page's items. For a value that differs between views, such as a title, a color, or the whole list a count is taken from, build the formatter in a function that takes it:
def make_formatter(title, color):
def format_page(items):
return card(f"## {title}", "\n".join(items), color=color)
return format_page
view = await CategoryList.from_data(
books, 3, make_formatter("Books", discord.Color.blurple()), interaction=interaction
)
examples/v2_library.py opens one such list per category, each with its own title and color.
V1 and V2¶
PaginatedView is the same pattern on a StatefulView. A page is a discord.Embed, text, or a dict giving any
of embed, embeds (up to ten), and content. Its other keys are left alone, except one a letter or two off
those three (contnet), which raises. A page of another kind raises TypeError when the view is built, naming the
page.
A page turn shows exactly the new page: it clears what the last page put on the message and the new one does not.
Text passed to send() shows above the first page and comes back on any page that sets no text of its own. For
pages of another type, override page_kwargs(page) to return the message keywords for a page.
The buttons sit on row 0 and the Exit button on row 4. Give your own controls row=1 or later: without a row,
discord.py puts each in the first row with room, which is the buttons' row below jump_threshold. A V1 view
shows its arrows even on one page, greyed, where a V2 view of one page shows none. With no pages it says
"No pages." and the indicator reads Page 0/0.
A PaginatedLayoutView draws its page in on_load(), and for from_cursor() that is where the page is fetched.
An override of on_load() need not call super(): the page is drawn after it returns.
Related¶
- Composites:
PaginatedRegion, to page one part of a larger panel. - Leaderboard: a paginated ranking built on this view.
- Navigation: opening a screen from a page and coming back to it.
- Coming from discord.py: how a hand-written paginator maps onto this one.
PaginatedLayoutViewandPaginatedView: every parameter.