Skip to content

Undo and Redo

A view with undo on keeps a history of the changes its actions make. undo() takes the last one back and redo() puts it back again, one step at a time.

Turning It On

Undo needs two things: UndoMiddleware installed once, and enable_undo = True on the view. A notifications panel whose toggles can be taken back:

from functools import partial

import discord

from cascadeui import (
    StatefulButton,
    StatefulLayoutView,
    UndoMiddleware,
    card,
    cascade_reducer,
    read_slot,
    setup_middleware,
)

DEFAULTS = {"Mentions": True, "Direct messages": False, "Weekly digest": True}


@cascade_reducer("NOTIFY_TOGGLED")
def toggle_notification(action, state):
    prefs = state["application"].setdefault("notify", {}).setdefault(action["payload"]["user"], {})
    name = action["payload"]["name"]
    prefs[name] = not prefs.get(name, DEFAULTS[name])
    return state


class NotificationsPanel(StatefulLayoutView):
    enable_undo = True  # (1)!
    subscribed_actions = {"NOTIFY_TOGGLED"}

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.build_ui()

    def build_ui(self):
        saved = read_slot(self.state_store.state, "notify", str(self.user_id), default={})
        lines = [f"**{name}:** {'On' if saved.get(name, on) else 'Off'}" for name, on in DEFAULTS.items()]
        self.clear_items()
        self.add_item(card(
            "## Notifications", *lines, f"-# Undo: {self.undo_depth} | Redo: {self.redo_depth}",  # (2)!
        ))
        self.add_item(discord.ui.ActionRow(*(
            StatefulButton(label=name, callback=partial(self.toggle, name)) for name in DEFAULTS
        )))
        self.add_item(discord.ui.ActionRow(
            StatefulButton(label="Undo", callback=self.undo_last, disabled=not self.undo_depth),
            StatefulButton(label="Redo", callback=self.redo_last, disabled=not self.redo_depth),
        ))

    async def toggle(self, name, interaction):
        await self.dispatch("NOTIFY_TOGGLED", {"user": str(self.user_id), "name": name})

    async def undo_last(self, interaction):
        await self.undo()  # (3)!

    async def redo_last(self, interaction):
        await self.redo()
  1. The view records a step for each change its actions make. Install the middleware once, in the bot's setup_hook: await setup_middleware(UndoMiddleware()).
  2. undo_depth and redo_depth count the steps that can be taken back and put back, read as the panel draws.
  3. The panel hears its own undo and redraws, so the toggle shows its old value and the counts move.

Animation: the page's notifications panel, with its undo and redo history beside it. Kael turns Direct messages on, and one step goes on the Undo side. Kael turns Mentions off, a second step. Undo puts Mentions back On and moves its step to the Redo side. Undo again puts Direct messages back Off. Redo turns Direct messages On again and moves its step back. Each click is answered by one edit of the panel.

Click Mentions Direct messages Undo / Redo
Opened On Off 0 / 0
Direct messages On On 1 / 0
Mentions Off On 2 / 0
Undo On On 1 / 1
Undo On Off 0 / 2
Redo On On 1 / 1

A change made after an undo starts a new history from there: the steps that could have been redone are gone, as in any editor.

Without the middleware there is nothing to undo, so undo() and redo() raise RuntimeError naming setup_middleware(UndoMiddleware()). With enable_undo left False, the view records nothing and undo() does nothing.

What a Step Holds

Diagram: what one step holds. Before Kael's click, the notify slot holds Kael's settings, Mentions On and Direct messages Off, and Mira's, Mentions Off, and the session's theme is dark. Kael's Direct messages click records a step that holds one key, Kael's Direct messages, with its old value Off. Then Mira turns Mentions on and a second panel in Kael's session sets the theme to light. Kael's undo puts back Off for Kael's Direct messages and leaves Mira's Mentions and the light theme as they are.

A step is one action that changed something, and it holds only what that action changed: the slots it wrote in state["application"], and inside a dictionary only the keys that changed, at any depth. An undo puts those keys back and leaves every other key as it stands now.

  • Custom reducers, dispatch_scoped(), and update_session() all record steps. The session's data is undone key by key too, so an undo in one panel leaves a key only another panel in the same session wrote.
  • Every user's scoped state shares one slot, so one user's undo puts back that user's keys and no one else's.
  • An action that changes nothing records nothing, so it takes no place in the history and pushes no older step out.
  • The library's own actions (a send, a push, a close) are not steps.
  • A key the action wrote and another view wrote again since is put back to its value from before the action.
  • One change is not recorded: replacing a value with an equal one of another type, such as 1 with 1.0 or True, when nothing else in the same dictionary changes. Undo compares each dictionary with == before walking it, since walking every unchanged value one by one makes each dispatch more than ten times slower once a slot holds a thousand users.

A step that changes a persistent slot is saved like any other change, so an undo and a redo reach the database too.

Undo, Redo, and the Limit

undo() takes back the newest step and redo() puts back the newest step taken back. Each returns None, and does nothing when there is no step to take.

undo_limit caps how many steps the view keeps, 20 by default. Past it the oldest step is dropped, so a panel with undo_limit = 3 that takes five changes can undo the last three. undo_limit = None keeps every step. A value that is not a positive whole number or None raises when the class is defined, and set_class_attribute() changes it for one view.

Who Redraws After an Undo

An undo or redo is heard by the view whose history it is, and by every view whose subscribed_actions names an action the step takes back, as that action reached them. A view that never heard the action does not hear it undone, so an undo in one panel costs nothing in panels elsewhere.

One undo of a NOTIFY_TOGGLED step Hears it
The panel that made the change Yes
A view with NOTIFY_TOGGLED in subscribed_actions Yes, then its state_selector() decides as for any action
A view that lists other actions No

Inside a batch, these views hear the batch's BATCH_COMPLETE, as for any action in it.

Batches

A batch is one step when it ends, so one undo() takes back every change made inside it. A batch that ends with everything as it found it adds no step.

  • The step sits in the history where the batch's first change was made. A change another task makes from the same view while the batch is open is undone first, and the batch's step puts each key back to its value from before whichever of the two wrote it first.
  • undo() or redo() called while another task's batch is still open, on the view or on a screen that has since pushed or popped to it, waits for that batch for up to 30 seconds, and then goes ahead with a warning. Called from inside the batch, or from a task it started, it runs at once.
  • The wait is made again when the undo reaches its reducer, so a batch that opened while a middleware held the undo is waited for too. When that middleware passed on a state it built itself, the undo is skipped with a warning instead, since reducing that state after the wait would erase the batch's writes. Undo again once the batch ends.

The History Follows the Panel

Diagram: where the history goes. A notifications hub with two steps pushes a screen, which takes the two steps and adds one of its own, three in all. Back pops to the hub, which has all three. replace() opens a screen with no steps. After that screen's exit(), the panel opened again starts with none, and so does every panel after a restart.

  • push() and pop() carry the history to the screen they bring in, so an undo on a pushed screen can take back a change made before the push. A batch that pushes leaves its step on the screen the panel moved to.
  • replace() opens its screen with no history, and a new open of a view starts with none.
  • On a closed view undo() does nothing.
  • The history lives in memory. A restart starts every view with none, even where the changes it took back are saved.

Undo Middleware

UndoMiddleware records the steps. Install it once, in the bot's setup_hook:

from cascadeui import UndoMiddleware, setup_middleware

await setup_middleware(UndoMiddleware())

It takes no arguments. As each action's reducer commits, it records what the action changed for the view that dispatched it, if that view has enable_undo = True, so steps follow the order the store applied the changes even when another middleware awaits around it. Inside a batch it gathers the changes and records one step when the batch ends. Code that needs to know whether undo is installed can ask the store: store.has_middleware(UndoMiddleware).

Full Example

v2_settings.py is a settings panel with undo and redo next to its controls.