Wizard¶
A wizard walks a person through a task one screen at a time. Back and Next move between the steps, a step can hold the person until its part is done, and Finish hands you what they chose.
from cascadeui import WizardLayoutView, card, choice_row
class SignupWizard(WizardLayoutView):
finish_button_label = "Sign Up"
def __init__(self, **kwargs):
super().__init__(
steps=[ # (1)!
{"name": "Welcome", "builder": self.build_welcome},
{"name": "Role", "builder": self.build_role, "validator": self.check_role},
{"name": "Confirm", "builder": self.build_confirm},
],
**kwargs,
)
def build_welcome(self): # (2)!
return card("Three quick steps and you're in.")
def build_role(self):
return card(
"Pick the role you play.",
choice_row(
{"Player": "player", "Coach": "coach"},
on_select=self.pick_role,
selected=self.answers.get("role"),
),
)
async def pick_role(self, interaction, value):
self.answers["role"] = value # (3)!
await self.refresh_content()
def check_role(self): # (4)!
if "role" not in self.answers:
return False, "Pick a role first."
return True, None
def build_confirm(self):
return card(f"Role: **{self.answers['role']}**")
async def on_finish(self, interaction): # (5)!
await self.respond(interaction, f"Signed up as a {self.answers['role']}.", ephemeral=True)
await self.exit()
- Each step has a name, a builder that draws it, and here one validator. The name shows above the progress bar.
- A builder runs every time its step is drawn, so it shows what the person has chosen so far.
answersis a dict for what the steps collect. Redraw the step after changing it.- Runs when the person clicks Next.
(False, message)keeps them on the step and tells them why. - Runs when the person clicks the last step's button, here Sign Up.
The panel is one card: the step's name over a progress bar, a line, then the step. Below it are Back, a
Step 1/3 counter, and Next. On the last step Next becomes Sign Up. Send it like any view:
await SignupWizard(interaction=interaction).send().
Steps¶
Pass the steps as a list to steps=. Each is a dict with these keys, or a WizardStep (below):
| Key | What it does |
|---|---|
name |
The step's name, shown above the progress bar. |
builder |
Draws the step. Takes no arguments, plain or async. A step with no builder shows its buttons alone, under the progress header (on a WizardView, under the embed send() was given, if any). |
validator |
Optional. Runs on Next and on Finish (see Holding a Step). |
condition |
Optional. Takes the view. The step is skipped while it returns False (see Steps That Come and Go). |
A builder returns what the step shows: a component such as a card(), a list or tuple of them, text (shown as
a card() in the theme's accent; inside a list, as plain text), or None for nothing. Anything else raises
TypeError naming the step.
The wizard checks its steps when it is built, so a mistake raises there and never in front of the person:
- no steps at all, or
stepswritten in the class body, which the wizard does not read - a key a letter or two off one above, such as
"validate"(keys of your own are left alone) - a builder or validator that cannot be called with no arguments, or a condition that cannot take the view or
is
async
Typed steps with WizardStep and WizardSchema
WizardStep takes the same keys as the dict, and your editor completes them. It requires a name and a
builder, where a dict may leave either out. A WizardSchema gathers the steps in a class of their own,
passed as schema= in place of steps= (passing both raises ValueError):
from cascadeui import WizardSchema, WizardStep
class SignupSteps(WizardSchema):
def __init__(self, view):
self.view = view
def get_steps(self):
return [
WizardStep(name="Welcome", builder=self.view.build_welcome),
WizardStep(name="Role", builder=self.view.build_role, validator=self.view.check_role),
WizardStep(name="Confirm", builder=self.view.build_confirm),
]
# In SignupWizard.__init__:
# super().__init__(schema=SignupSteps(self), **kwargs)
Moving Between Steps¶
Next runs the step's validator, then moves to the next step the person should see. Back moves to the one before, and is greyed out on the first. On the last step Next becomes Finish, with a label, emoji, and style of its own. The counter between them counts only the steps the person moves through.
Each move draws the new step from its builder and answers the click with one edit of the message. A move that never reaches Discord is undone, so the wizard stays on the step the person can still see.
A double-click on Next moves one step and runs the validator once: the second click was made on the step the
first one left, so it is dropped. A double-click on Finish runs on_finish() once.
Holding a Step Until It Is Done¶
A validator runs when the person clicks Next, or Finish on the last step. It takes no arguments, may be
async, and returns one of:
(True, None): the step passes.(False, "message"): the person stays on the step, and a reply only they see shows the message.TrueorFalsealone: the same, withvalidation_failed_messageas the reply. Its default is "Finish this step first." Set it toNoneto send nothing.
Any other return raises TypeError naming the step. A validator that raises keeps the person on the step too,
and they get the view's error reply (see When a Callback Raises).
To show the problem on the step rather than in a reply, override on_validation_failed() (see
Hooks).
Steps That Come and Go¶
A step with a condition shows only while the condition returns True. It takes the view, so it can read what
earlier steps collected:
steps = [
{"name": "Role", "builder": self.build_role},
{"name": "Team", "builder": self.build_team, "condition": lambda v: v.answers.get("role") == "coach"},
{"name": "Confirm", "builder": self.build_confirm},
]
Conditions are read each time a step is drawn and on every Back and Next. The counter and the progress bar count
only the steps that will show, and Next becomes Finish when none is left after the current one. A control that
changes what a condition reads should redraw the step with refresh_content(), so the new count shows at once.
The wizard opens on the first step whose condition passes. A condition must answer at once, so an async one is
refused when the step is declared, and one that raises is logged and its step shown.
Keeping Answers¶
answers is a dict for what the steps collect. It starts empty, or keeps a dict you set before calling
super().__init__().
A wizard that pushes to another screen is built again from its class when the person comes back with Back (see
Navigation). answers and the current step come back with it, and any other attribute you
set starts over. An ephemeral wizard's
Continue button brings back the wizard itself, so
there everything stays.
Redrawing a Step¶
Call refresh_content() after a callback changes what the current step's builder reads, as pick_role() does
above. It draws the step again in place.
reload() runs on_load() first, for data loaded there. A redraw made while a reload() runs waits for it and
draws from the reloaded data. A state change the view receives (see Redrawing When State
Changes) draws the step again too.
| Name | What it is |
|---|---|
current_step |
The index of the step on screen, counting steps a condition hides. Read-only. |
step_count |
How many steps the wizard has, hidden ones included. |
refresh_content() |
Draws the current step again in place. |
When Finish Is Clicked¶
on_finish(interaction) runs when the person clicks Finish and the last step's validator passes. Save the
answers, reply, and close, as the example does. The default only closes the wizard: under the default
exit_policy its controls are disabled (a WizardView loses them, see
What a Closed Panel Looks Like), and exit_policy = "delete" removes the message (see
Closing a View). A click that on_finish() leaves unanswered is
acknowledged for you.
An override may leave the wizard open, to refuse or to show a result in place. An exception it raises reaches
on_error(), so the person gets the error reply.
Hooks¶
| Hook | Runs |
|---|---|
on_step_exited(step_index) |
On Back or Next, before the wizard leaves the step. |
on_step_entered(step_index) |
Right after the move, before the new step is drawn. |
on_validation_failed(step_index, error, interaction) |
When a validator refuses. The default sends the reply. |
A move runs them in that order, and the click waits for each. on_step_exited() and on_step_entered() run
only on a move: not when the wizard first opens, on a redraw, when it comes back after a push, on Finish, or
again for a move that is undone. An exception in any of the three is logged, and the wizard goes on. An
override that cannot take the arguments above is refused when its class is defined.
Overriding on_validation_failed() replaces the reply. Call super() or reply yourself, or a refused step says
nothing:
async def on_validation_failed(self, step_index, error, interaction):
self.failed_attempts += 1
await super().on_validation_failed(step_index, error, interaction)
Customizing¶
| Attribute | Default | What it does |
|---|---|---|
back_button_label / _emoji / _style |
None (shows "Back"), None, ButtonStyle.secondary |
The Back button. |
next_button_label / _emoji / _style |
None (shows "Next"), None, ButtonStyle.primary |
The Next button. |
finish_button_label / _emoji / _style |
None (shows "Finish"), None, ButtonStyle.success |
The last step's button. |
step_indicator_label |
None |
A function (position, count) -> str that writes the counter. None shows Step 2/3. |
validation_failed_message |
"Finish this step first." |
The reply to a validator's bare False. None sends nothing. |
show_progress_bar |
True |
Shows the progress header (see below). |
nav_inside_container |
False |
V2 only. Puts the step buttons inside the step's card (see Buttons Inside the Card). |
nav_divider |
False |
V2 only. With the buttons inside the card, a line above them. |
auto_exit_button |
False |
Adds an Exit button, below the step buttons (beside them on V1). |
A label set to "" beside the button's emoji shows the emoji alone; None keeps the word beside it.
A function in a class body is called with self first, so a counter function that takes only the position and
the count is wrapped in staticmethod:
class SignupWizard(WizardLayoutView):
step_indicator_label = staticmethod(lambda position, count: f"Part {position} of {count}")
build_extra_items() adds controls of your own. The wizard calls it when built and keeps what it adds on
every step.
Progress Header¶
A WizardLayoutView draws each step as one card: the step's name over a progress bar, a line, then what
the step's builder returns. The header shows while more than one step is counted, and show_progress_bar = False
turns it off.
The step joins the header's card when its builder returns one card, which keeps its own color, or components
with no card among them. A step that returns a card beside other items, two cards, or a Container subclass
keeps its own layout under the header's card. A row of buttons joins when it sits inside the step's card, as the
Role step's choice_row() does above.
Override build_progress_header(visible_indices) to draw your own. It returns a component, a list of them, text,
or None for no header on that render. A header of one card joins the step the same way; anything else keeps its
own place above the step. visible_indices holds the steps the person moves through, the one on screen included,
so its position there is the step's place:
from cascadeui import card, progress_bar
class SignupWizard(WizardLayoutView):
def build_progress_header(self, visible_indices):
position = visible_indices.index(self.current_step) + 1
return card(
f"### Step {position} of {len(visible_indices)}",
progress_bar(position, len(visible_indices)),
)
A joined card takes the step card's look, so above a step card only a card() in the theme's color joins. A
header built with discord.ui.Container, or given a color, a spoiler, or an id, stays a card of its own, as
plain discord.py draws it, and so does any header above a step card marked as a spoiler, which would hide it. A step that
fits Discord's 40 components only as separate cards
is drawn as separate cards.
Buttons Inside the Card¶
nav_inside_container = True puts Back, the counter, and Next inside the step's card, under its content, as a
paginator's One Card does. nav_divider = True adds a line above them.
Controls from build_extra_items() and the Exit button stay below the card, and a step that cannot join the card,
or whose card is marked as a spoiler, keeps the buttons on a row of their own.
V1 and V2¶
WizardView is the same wizard on a StatefulView. Its builders return a discord.Embed, a list of up to ten,
or None. Text raises TypeError naming the step: put it in an embed's description.
Back, the counter, and Next share the last of Discord's five rows, with the Exit button beside them. It has no progress header.
A WizardLayoutView draws its step in on_load(), since a builder may be async. An override of on_load()
that loads what a builder reads need not call super():
- The step is drawn after this returns. Calling
super().on_load()at the end does the same, and calling it first draws the step before the data is loaded.
Related¶
- Form: one screen of fields, checked together on Submit.
- Navigation: opening another screen from a step and coming back.
- Choice and Toggle Controls:
choice_row()and the other pickers. WizardLayoutViewandWizardView: every parameter.