Skip to content

Code Map

Where each part of CascadeUI lives, the order a view's parts are looked up in, the path one click takes through the code, and where the tests for each part sit. Start here before opening a module you have not worked in.

The Repository

Folder Holds
cascadeui/ the package
tests/ the test suite, one file per area
examples/ the Example Cogs
docs/ this site, built with MkDocs from mkdocs.yml
.github/workflows/ CI (ci.yml), the docs deploy (docs.yml), and the PyPI publish (publish.yml)

The Package

Each module and what it owns. A name that starts with an underscore is private and can change in any release (Stability Policy).

Top Level

Module Owns
__init__.py the public names, gathered from every subpackage
__main__.py python -m cascadeui, the version and environment report
setup.py setup_middleware(), the one call that installs middleware
exceptions.py InstanceLimitError and the PersistenceError family
validation.py ValidationResult, the validator factories, and validate_field()
devtools.py InspectorView and DevToolsCog, the /cascadeui commands
tracing.py the dispatch trace setup_logging(trace=True) installs
testing.py stand-ins for test code: StubClient, StubInteraction, and StubMessage

views/

Module Owns
view.py StatefulView, the V1 view
layout.py StatefulLayoutView, the V2 view, and DisplayLayoutView
persistent.py PersistentView, PersistentLayoutView, and the _PersistentMixin they share
base.py and the _*.py mixin modules _StatefulMixin and the mixins it is built from, listed in the next section
_common.py names two or more mixin modules share, such as RenderOutcome
_placement.py validate_placement(), the checks a tree passes before it is sent
_custom_ids.py the ids the library gives a control, which name what it does rather than where it sits

views/patterns/

Module Owns
menu.py MenuView and MenuLayoutView
form.py FormView and FormLayoutView
wizard.py WizardView and WizardLayoutView
tabs.py TabView and TabLayoutView
paginated.py PaginatedView and PaginatedLayoutView
leaderboard.py LeaderboardLayoutView and PersistentLeaderboardLayoutView
roles.py RolesLayoutView and PersistentRolesLayoutView
types.py FormField, WizardStep, RoleCategory, and the schemas

components/

Module Owns
base.py StatefulButton, StatefulSelect, DynamicPersistentButton, and the wrapper every stateful control's callback runs through
buttons.py the styled buttons and ToggleButton
selects.py Dropdown and the role, channel, user, and mentionable selects
inputs.py Modal and its five inputs
wrappers.py with_loading_state, with_confirmation, and with_cooldown
types.py EmojiInput, MediaInput, and Discord's limits as constants
v1_composition.py CompositeComponent
patterns/v1.py ConfirmationButtons, PaginationControls, ToggleGroup, and ProgressBar
patterns/v2.py the V2 builders (card(), choice_row(), emoji_grid(), and the rest), PaginatedRegion, and Collapsible

state/

Module Owns
store.py StateStore: dispatch, the middleware chain, subscribers, batching, and the registry of live views
reducers.py the built-in reducers
actions.py ActionCreators
computed.py @computed
slots.py access_slot(), read_slot(), and slot_property
_batching.py which batch a dispatch joins, task by task
singleton.py get_store()
types.py the type aliases the state code uses
middleware/logging.py LoggingMiddleware
middleware/undo.py UndoMiddleware
middleware/persistence.py PersistenceMiddleware

persistence/

Module Owns
manager.py PersistenceManager: loading at start, saving, restoring panels, and pruning
protocols.py PersistenceBackend and Capability
config.py SlotPolicy, RegistryPersistence, and ApplicationPersistence
migrations.py register_migrator(), register_kwargs_migrator(), and the code that runs them
schema.py the table names, the schema versions, and the SQLite tables
schema_postgres.py the PostgreSQL tables
backends/memory.py InMemoryBackend
backends/sqlite.py SQLiteBackend
backends/postgres.py PostgresBackend

theming/

Module Owns
core.py Theme and the registry register_theme() fills
themes.py the three built-in themes
context.py theme_context() and get_current_theme()

utils/

Module Owns
tasks.py TaskManager and _bounded_wait(), the library's one bound on an await
responses.py respond_safe(), open_modal_safe(), and DISCORD_CALL_ERRORS
hooks.py await_maybe(), is_async_callable(), and the checks on a callable's arguments
guards.py input checks shared by several modules, and Discord's private limits
coercion.py coerce_snowflake_id(), which turns a Member into its id
decorators.py cascade_reducer() and cascade_component()
deprecation.py warn_deprecated() and renamed_from
overrides.py check_private_names(), which every library class built to be subclassed runs on a class that replaces one of its private names
errors.py with_error_boundary(), with_retry(), and safe_execute()
fetch.py fetch_as_file()
logging.py setup_logging()
strings.py slugify() and is_emoji()
identity.py _holds() and _drop(), which compare objects by identity, never by a class's own ==

The View Mixins

StatefulLayoutView is _StatefulMixin followed by discord.py's LayoutView, and StatefulView the same with View. The mixin comes first, so its __init__ takes CascadeUI's keywords before discord.py's sees them. _StatefulMixin is built from one mixin per concern, and Python looks a name up through them in this order:

Mixin Module Concern
1 _StatefulMixin base.py construction, defaults, dispatch(), selectors, and scoped state
2 _AttributesMixin _attributes.py checking class attributes, and set_class_attribute()
3 _AccessMixin _access.py who may click, and instance and participant limits
4 _SessionMixin _session.py participants, shared data, and attached views
5 _SendingMixin _sending.py the send pipeline and its rollback
6 _LoadingMixin _loading.py on_load(), load(), reload(), and renders a state change starts
7 _RenderOrderMixin _render_order.py when a render may run, and renders held for later
8 _RefreshMixin _refresh.py refresh(): the cooldown, rate limits, and bounded edits
9 _TreeMixin _tree.py the component tree: ids, the digest, freezing, and the placement checks
10 _ClosingMixin _closing.py exit(), timeouts, and teardown
11 _RegistrationMixin _registration.py the persistent registrations a view carries
12 _HandoffMixin _handoff.py the ephemeral Continue button
13 _InteractionMixin _interaction.py clicks, and respond(), open_modal(), and safe_defer()
14 _NavigationMixin _navigation.py push(), pop(), and replace()

Pillars 1 and 2 of The Five Pillars live in _access.py, pillar 4 in _session.py, and pillar 5 in _navigation.py. Pillar 3, a view's life, is split by phase across the rest.

Two things to know before you change one of them:

  • Each module that logs does so under its own name (cascadeui.views._refresh), so a level set on cascadeui.views covers them all.
  • base.py re-exports names that live in the other views/ modules, such as RenderOutcome, so an import from base.py still finds them. A test that patches one of those names patches the module that defines it: patching the copy in base.py changes a name the code never reads.

Where a Click Goes

Animation: Kael clicks +1 on the counter, which shows 2. discord.py's ViewStore.dispatch_view finds the view holding the button. In views/_interaction.py, _scheduled_task starts the 2.5-second backstop. views/_access.py's interaction_check checks who may click. _run_click_callback runs the click inside the view's lock, and components/base.py's stateful_callback binds the click and calls the button's callback. Your increment() calls dispatch_scoped(), which hands a SCOPED_UPDATE action to the store. state/store.py runs the middleware and then the reducer, and _notify_subscribers renders the clicked view at once. views/_loading.py's on_state_changed calls your build_ui() and then refresh(), and views/_refresh.py sends the edit as the click's answer, in one request. The counter shows 3.

The click is Kael's +1 on the counter from Adding Shared State, recorded as it ran.

  1. discord.py's ViewStore.dispatch_view finds the view that holds the clicked button on that message, and hands the click to the view's _scheduled_task (views/_interaction.py).
  2. _scheduled_task starts the backstop that acknowledges a click still running after 2.5 seconds, then asks interaction_check (views/_access.py) whether this person may click.
  3. _run_click_callback runs the click inside the view's lock, so clicks on one view run one at a time.
  4. The button's stateful_callback (components/base.py) binds the click, so a render it causes can answer it, and calls your callback.
  5. Your callback dispatches. dispatch() (views/base.py) hands the action to StateStore.dispatch (state/store.py), which runs the middleware and then the reducer.
  6. _notify_subscribers renders the clicked view at once and gives every other listening view a task of its own.
  7. The view's on_state_changed() (views/_loading.py) calls build_ui() and then refresh() (views/_refresh.py), which sends the edit with interaction.response.edit_message: the edit is the click's answer, in one request.

To watch the same path on a running bot, turn on setup_logging(level="DEBUG"): the log shows each dispatch and each dropped click, and /cascadeui trace on adds each click discord.py routes (DevTools).

The Tests

tests/ holds one file per area. The commands that run them are on Contributing. Three files hold what the rest lean on:

  • conftest.py: the switches CI sets (CASCADEUI_EAGER_TASKS, CASCADEUI_REQUIRE_POSTGRES), and the group that keeps every PostgreSQL test on one worker.
  • helpers.py: stand-ins for Discord, such as make_interaction(), whose is_done() turns true once something answers it, and RenderableLayoutView.
  • _pg_helpers.py: the PostgreSQL database each backend test gets, created and dropped around it.

Two files check the code itself rather than its behavior. test_invariants.py reads the library's source and fails on shapes that have caused bugs before, such as an asyncio.wait_for in the library. test_public_api.py checks that every name a subpackage makes public also imports from cascadeui.

Area Test files
Views test_view_init.py, test_layout_view.py, test_auto_defer.py, test_owner_only.py, test_instance_limit.py, test_five_pillars.py, test_pillar_isolation.py, test_update_coalescing.py, test_render_interleavings.py, test_message_cleanup.py, test_ephemeral_refresh.py
Navigation test_navigation.py, test_navigation_matrix.py, test_navigation_interleavings.py, test_navigation_artifact_restore.py, test_nav_version.py, test_rebuild_callback.py
Components test_components.py, test_selects.py, test_inputs.py, test_wrappers.py, test_v2_helpers.py, test_button_grid.py, test_emoji_grid.py, test_placement.py, test_dynamic_persistent_button.py
Patterns test_menu_patterns.py, test_form_patterns.py, test_wizard_patterns.py, test_tab_patterns.py, test_paginated_patterns.py, test_pagination.py, test_layout_pagination.py, test_layout_patterns.py, test_leaderboard_patterns.py, test_roles_patterns.py
State test_state_store.py, test_reducers.py, test_batching.py, test_computed.py, test_undo.py, test_middleware.py, test_logging_middleware.py, test_scoping.py, test_state_slots.py, test_hooks.py
Persistence test_persistence.py, test_persistence_middleware.py, test_persistent_views.py, test_layout_persistent.py, test_backends.py, test_backends_raw_sql.py, test_backends_postgres.py
Everything else test_devtools.py, test_theming.py, test_validation.py, test_input_coercion.py, test_task_manager.py, test_fetch.py, test_examples.py, test_invariants.py, test_public_api.py

A fix comes with a test that fails without it. Run the test against the code before your fix and watch it fail: a test that passes either way checks nothing.