Skip to content

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.

Kael clicks the next-page arrow: the card shows page 2 of the inventory and the indicator reads Page 2/3. Kael clicks it again: page 3, and the next-page arrow greys out

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()
  1. Adds an Exit button below the page, kept on every page.
  2. Puts the page and its buttons in one card, with a line between them. See One Card.
  3. 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.
  4. Ten items, three pages of four. A real inventory comes from the bot's own records.
  5. 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()
  1. fetch_fn(offset, limit) returns one page's items: offset counts items from the start, limit is per_page.
  2. 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.

The page's UserList run with cache_size=3. from_cursor() fetches nothing, send() fetches page 1, and each next page fetches the page it shows. Reaching page 4 drops page 1, the least recently shown. Going back to page 3 needs no fetch. refresh_pages() empties the cache and fetches page 3 again

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:

async def show_last(self, interaction):
    await self.set_page(len(self.pages) - 1)

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:

async def on_page_changed(self, page):
    await self.dispatch("PAGE_VIEWED", {"page": page})

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)!
  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.

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.