Skip to content

Session Data

Session data is a dict that the screens of one panel share: the panel as it was sent, every screen it pushes, and the panel pop() brings back. self.shared_data reads it and update_session() writes it. It is kept in memory while any screen of the panel is open, and it ends with the panel.

Animation: Kael's /settings hub shows English picked, and its session's data is empty. Kael picks French: update_session() writes lang fr into the session's data, and the hub hears SESSION_UPDATED and redraws with French picked. Kael opens Profile: push() builds it in the same session, and it reads the language and says Bonjour. Kael clicks Back: pop() builds a new hub, which reads French from the session.

A Language Every Screen Reads

A settings panel lets a person pick a language, and the screen it opens greets them in it:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, card, choice_row

GREETINGS = {"en": "Hello", "fr": "Bonjour"}


class SettingsHub(StatefulLayoutView):
    subscribed_actions = {"SESSION_UPDATED"}  # (1)!

    def state_selector(self, state):
        session = state["sessions"].get(self.session_id, {})
        return session.get("shared_data", {}).get("lang")

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

    def build_ui(self):
        lang = self.shared_data.get("lang", "en")  # (2)!
        self.clear_items()
        self.add_item(card(
            "## Settings",
            choice_row({"English": "en", "French": "fr"}, selected=lang, on_select=self.set_language),
        ))
        self.add_item(discord.ui.ActionRow(StatefulButton(label="Profile", callback=self.open_profile)))

    async def set_language(self, interaction, value):
        await self.update_session(lang=value)  # (3)!

    async def open_profile(self, interaction):
        await self.push(ProfileScreen, interaction)


class ProfileScreen(StatefulLayoutView):
    auto_back_button = True

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        lang = self.shared_data.get("lang", "en")  # (4)!
        self.add_item(card(f"## {GREETINGS[lang]}!", f"Language: `{lang}`"))
  1. update_session() dispatches SESSION_UPDATED. The selector keeps the hub to its own session's language, so another person's pick does not redraw it.
  2. The session's data: {} until the first write.
  3. Merges lang into the session's data. The hub hears it and redraws.
  4. A pushed screen joins the session of the screen that pushed it, so it reads what the hub wrote.

Kael picks French. The hub redraws with French picked, Profile greets them with "Bonjour!", and Back brings the hub back with French still picked, since pop() builds it again from the session as it is then. A second /settings, Kael's or anyone's, opens a session of its own and starts in English.

Reading and Writing

self.shared_data is the session's dict as the store holds it, not a copy. Read from it anywhere, and change it through update_session(): a key set on the dict directly reaches no listener, and undo cannot put it back.

update_session(**data) merges data into the session's data one level deep. A key given replaces the key stored, and keys left out stay. A dict given again replaces the old one whole, and None is stored as a value, not as a removal:

await self.update_session(lang="fr", prefs={"theme": "dark", "size": "large"})
await self.update_session(prefs={"theme": "light"})
# shared_data is now {"lang": "fr", "prefs": {"theme": "light"}}

A write redraws only the screens that list SESSION_UPDATED, the one that made it included (see Redrawing on a Write).

Before the Send

The session opens when the panel is sent. A write made earlier, in on_load() or between building the view and calling send(), waits on the view: shared_data reads it back, and the session opens with it. A hub that loads a saved language does it in on_load(), which runs at the send, and draws after it:

async def on_load(self):
    if "lang" not in self.shared_data:  # (1)!
        await self.update_session(lang=await load_language(self.user_id))
    self.build_ui()
  1. on_load() runs again on every push and pop, so the language is loaded once per session.

A view that draws only in __init__ has drawn before such a write, and its first render does not show it.

A write after the panel's last screen has closed goes nowhere: the session has ended, and shared_data reads {}.

Which Views Share a Session

Every view has a session from the moment it is built, including a panel posted to a channel with no owner.

View Its session
A screen reached by push(), and the one pop() brings back the panel's
The panel replace() hands over to the panel's
A second open of the same command its own
A view sent with parent= its own

The id is self.session_id: <module>.<Class>:user_<owner id>:<8 hex digits> for a view with an owner, and <module>.<Class>:<8 hex digits> for one without. The hex part is new for each open. A screen a panel with no owner pushes has no owner either, and shares the panel's session as any screen does (see Opening a Screen and Going Back).

One Session Across Opens

session_continuity = True gives a person's opens of a view one session while any of them is open:

class SettingsHub(StatefulLayoutView):
    session_continuity = True

Diagram: by default, Kael's two opens of /settings have a session each, the same name with a different suffix: the first holds lang fr, the second nothing. With session_continuity = True, both of Kael's opens share cogs.settings.SettingsHub:user_100, which holds lang fr, and Mira's open has cogs.settings.SettingsHub:user_200 of its own.

Kael's second /settings then opens with French picked, and a pick in either panel reaches both. The data goes when the last of them closes, so the next open starts empty. Another person's opens share a session of their own.

A panel with no owner, such as one sent to a channel, continues per server: that server's opens of the class share one session, and another server's share their own. A panel with neither an owner nor a server has a session of its own each time.

It suits a view that is one surface a person keeps coming back to. A wizard, a form, or a panel where each open is a task of its own keeps the default. The library reads it when the view is built, so set it on the class: set_class_attribute() refuses it.

Redrawing on a Write

A view hears update_session() when it lists SESSION_UPDATED, as with any action (see What a View Hears). The selector keeps it to its own session:

def state_selector(self, state):
    session = state["sessions"].get(self.session_id, {})
    return session.get("shared_data", {}).get("lang")

Without it, every session write in the bot, from any person's panel, redraws the view.

One screen of a panel is on the message at a time, and pop() builds the screens below it again from the data as it is then, so they need no listener. The views that list it are a screen that shows what it writes, as the hub does, and panels that share a session through session_continuity, which redraw together.

Undo

A view with enable_undo = True records each update_session() as a step (see Undo and Redo), and an undo puts back the keys that step changed. Each panel undoes only its own steps: with session_continuity, an undo in one panel leaves a key only the other panel wrote, and puts back a key both wrote (What a Step Holds). The steps go with the panel when it closes, and a write made before the send is not a step.

Session Data or Something Else

Session data is one of four places a value can be kept. Where Data Lives compares them: who each one reaches, and what each keeps through a push and pop, a close, a restart, and an undo.

Session data suits a choice one screen makes for the screens after it: a template picked before the steps that use it, the rules of one game, a filter kept while a person moves between screens. What a single screen should get back on pop() goes in its navigation state (see What Comes Back on pop()).

Across a Restart

Session data is kept in memory only, and a restart ends it. A persistent panel restored after a restart rejoins the session it was registered with and finds it empty. Data that must outlive a restart goes in scoped state or a slot saved by persistence.