Navigation¶
A panel can lead to other screens and back on the same message: push() opens a screen, pop() returns to the
one before it, and replace() swaps the panel for a new message. This page covers the stack of screens, what a
screen gets back when you return to it, and the rules while a navigation is running.
Opening a Screen and Going Back¶
import discord
from cascadeui import StatefulButton, StatefulLayoutView, card
class HubView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_item(card("## Hub"))
self.add_item(
discord.ui.ActionRow(StatefulButton(label="Settings", callback=self.open_settings))
)
async def open_settings(self, interaction: discord.Interaction):
await self.push(SettingsView, interaction) # (1)!
class SettingsView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_item(card("## Settings"))
self.add_item(self.make_nav_row()) # (2)!
- Builds a
SettingsViewand edits the message to show it, as the answer to the click. make_nav_row()comes with every V2 view: a Back button and an Exit button. Back callspop().
push(view_class, interaction, **kwargs)builds the new screen with the keywords you pass, puts the current screen on the stack, and edits the message to show the new one.pop(interaction)builds the screen below again and edits the message back to it. It returnsNonewhen nothing is below.replace()swaps the panel for a new message, with no way back.
The screens of one stack share a session, so session data reaches all of them, and the
instance limit counts them as one panel (see How Many Can Exist).
They share the panel's owner too. A panel posted to a channel has none, so neither do the screens it pushes,
and who may click each follows its own class. A screen about the person who clicked names them:
push(MyStats, interaction, user_id=interaction.user.id).
nav_depth says how many screens sit below this one: 0 on a view that was sent, 1 on the first push.
One View Owns the Message¶
push() and pop() return the view now on the panel. Carry on with that one: once the edit lands, the
message belongs to it.
- The old view's
messagereadsNone, and its tasks are cancelled. A task of its own that made the call carries on as the new view's. push(),pop(), orreplace()on the old view raisesRuntimeError, and itsexit()does nothing.- Code that kept a reference to the panel reaches the screen now on it through
current_view. - An owner, guild, or participant set on the old view while the new screen loads goes to the new screen,
unless the call passed its own
user_id=or the new screen set its own.
What the Screen Shows¶
The new screen's on_load() runs before the edit, on every push and pop. A screen that loads data loads it
each time it is shown, and Back shows the parent with fresh data (see Loading Data).
A screen that draws itself in __init__ or on_load() needs nothing more.
For setup that is not loading data, pass rebuild=, a function the library calls with the new view after its
on_load() and before the edit. A view set up the same way every time names its own as nav_rebuild, which
runs whenever the call passes none, as Back does. Either can be a plain function or async def.
A StatefulView keeps its content in its embed, outside its components, so its edit needs the embed too.
nav_rebuild returns the keywords the edit sends with the view:
from cascadeui import StatefulView
class SettingsView(StatefulView):
nav_rebuild = staticmethod(lambda v: {"embed": v.build_embed()}) # (1)!
def build_embed(self):
return discord.Embed(title="Settings")
- The V1 patterns (
PaginatedView,TabView,WizardView,FormView,MenuView) set their own.
A StatefulView with no nav_rebuild sends the dict its build_ui() returns, as its first send() does.
on_load() and the rebuild hooks run inside the navigation, so they cannot start another one: push(),
pop(), replace(), exit(), reload(), and load() called from there raise RuntimeError. Decide where to
go before navigating, and pass anything the load reads as a constructor keyword.
What Comes Back on pop()¶
pop() does not hand back the view you left. It builds a new one from the keywords the first was built with,
then runs its on_load() again. The data is fresh and the keywords are intact, but anything the view picked
since it was built starts over from its default:
class PolicyView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.severity = "high" # (1)!
- Not a keyword. Someone picks "low", opens another screen, and clicks Back: the rebuilt view shows "high".
Name what should come back in get_nav_state(). The library hands it to restore_nav_state() on the rebuilt
view, before its on_load(), so the load reads the restored value:
def get_nav_state(self):
return {"severity": self.severity}
def restore_nav_state(self, state):
self.severity = state.get("severity", self.severity)
The mapping stays in memory with the stack and is never saved, so it can hold any object. Read every key as optional.
| What should come back | Where it goes |
|---|---|
| Something this view picked: a page, a tab, a level | get_nav_state() and restore_nav_state() |
| Something several screens read | Session data, which outlives every screen of the stack |
| Setup that is not data | rebuild= or nav_rebuild |
The patterns bring their own place back: a paginated view
returns on the page the person left, tabs on the open tab, a wizard on its step, and a form with what was typed.
The page of a PaginatedRegion and the state of a Collapsible belong to the view that built them, which
decides whether a return resumes or starts fresh. Named nothing, they come back as a fresh open shows them: a
region on its first page. Name them to bring them back:
def get_nav_state(self):
return {"page": self.pager.page}
def restore_nav_state(self, state):
self.pager.set_page(state.get("page", 0))
Back Buttons¶
There are three ways to give a screen a Back button:
make_nav_row()returns a row with Back and Exit, as in the first example.back=Falseorexit=Falseleaves one out, andback_label,back_emoji, andback_style(with theirexit_matches) change the buttons.StatefulLayoutViewonly.make_back_button()returns a Back button alone, to place in a row of your own.auto_back_button = Trueadds a Back button whenever the view has somewhere to go back to, apop()that returns to it included, and keeps it through every redraw. A V1 Back goes on row 4, or the first row with room. A view with no room left draws without it and logs a warning once per class.
A Back button with nothing below it shows disabled, and a click on it does nothing.
Leaving Back Out¶
A screen that is sometimes pushed and sometimes opened by its own command can leave Back out when there is nowhere to go back to:
def build_ui(self):
self.clear_items()
self.add_item(card("## Settings"))
self.add_item(self.make_nav_row(back=bool(self.nav_depth)))
Pushing a View You Built¶
push() and replace() also take a view you built, for the views a classmethod builds:
from_data(), which you await, or from_cursor(), which you
call without awaiting.
async def open_inventory(self, interaction: discord.Interaction):
inventory = await InventoryView.from_data(
items=ITEMS, per_page=10, formatter=format_page, interaction=interaction
)
await self.push(inventory, interaction)
The view goes as it is, so keywords passed beside it raise TypeError. A view goes on one message only: one
already sent, pushed, or closed raises RuntimeError, so build a new one each time.
Replacing the Panel¶
replace() closes the current view and starts a new panel on a new message, with no way back. The new view has
no message yet, so send it:
async def finish_setup(self, interaction: discord.Interaction):
dashboard = await self.replace(DashboardView, interaction)
await dashboard.send()
The current view closes as its exit() would, by its exit_policy. If the swap
fails, the current view keeps working.
push() |
replace() |
|
|---|---|---|
| Message | The same one, edited | A new one, which you send |
| The current view | Its class and keywords wait on the stack for pop() |
Closes, as its exit() would |
| Back | Yes | No |
| Session | Shared | Shared |
Between StatefulView and StatefulLayoutView |
Not allowed | Allowed |
Between the Two Kinds of View¶
push() and pop() between a StatefulView and a StatefulLayoutView raise TypeError. They keep one
message, and Discord does not let a message sent as a component layout go back to embeds, which a pop() would
need. replace() sends a new message, so it can move between the two.
While a Navigation Runs¶
Only the navigation edits the message while it runs.
- The current view stays live until the edit lands. If the edit fails, it stays on the message with its tasks
running and shows anything it was asked to render meanwhile.
push()still returns the new view, and pushing from it or sending it raisesRuntimeError. When Discord refused the new view's contents (an embed description past 4096 characters, for one),push()raises Discord's error instead, once the current view has the message back, so a click gets theon_error()reply. - The new view renders nothing until its edit lands.
- A click that reaches a view after it moved on or closed, such as a second click on Back, is acknowledged and
dropped.
exit(), a timeout, or a parent closing its children waits for the navigation to finish. - A view that has closed cannot navigate:
push()orpop()afterexit(), a timeout, orstop()raisesRuntimeError.
Less common cases
During a send. A click can reach a view as soon as its message is posted, while send() is still
finishing, and a push or pop then waits for the send. From inside the send itself (the view's on_load(),
seed_initial_state(), or another hook the send runs), push() and pop() raise RuntimeError: the view
has no message to hand over yet.
With no click to answer. A push or pop from a background task, or on a view sent to a channel, loads the new screen and edits the message through the channel.
On a persistent panel. A screen pushed onto a persistent panel returns to the panel when it times out,
unless it defines its own on_timeout(). See Timeout.
Screens That Load From a Database¶
A screen that shows rows from a database loads them in on_load(), so every push and pop reads them fresh:
class TaskListView(StatefulLayoutView):
def __init__(self, *, db, **kwargs):
super().__init__(**kwargs)
self.db = db # (1)!
self.rows = []
async def on_load(self):
self.rows = await self.db.list_tasks(self.user_id)
self.build_ui()
def build_ui(self):
self.clear_items()
lines = "\n".join(f"- {row['title']}" for row in self.rows) or "No tasks yet."
self.add_item(card("## Tasks", lines))
self.add_item(self.make_nav_row())
- A keyword of your own:
pop()builds the view again from its keywords, so the handle comes back with it.
The parent passes the handle on:
async def open_tasks(self, interaction: discord.Interaction):
await self.push(TaskListView, interaction, db=self.db)
Back rebuilds the parent, whose on_load() reads its own data again before the message changes. For
reload(), load(), and the names a keyword must not use, see Loading Data.
examples/v2_db_navigation.py
is a runnable cog.
Related¶
- Building and Sending: drawing a screen, and
on_load(). - Lifecycle and Closing: closing a view, and the views attached to it.
- How Many Can Exist: how a pushed screen counts.
- Session Data: data the screens of one stack share.