This page follows the interface of a v2 game from the custom tags in dist/index.html to the screen the player sees: how a component class becomes a working element, when the engine defines each tag, how screens open and close, how menus get their buttons, and how a component takes part in the decision to advance the game. It goes one level below Architecture, with the function names and the order they run in. Read Statements and Actions first: components share the action’s mounting cycle, and the clicks they receive are routed by the input code described there.

What it’s for

Everything the player sees and clicks in a v2 game is a component: a custom HTML element (<main-menu>, <text-box>, <save-screen>) whose class holds its markup, its behavior and its part in the engine’s life cycle. Monogatari builds them on Pandora 0.5, the web components library of the Aegis Framework, and adds the engine on top: a static engine reference, the mounting hooks (setup, bind, init), game events (onStart, onLoad, onReset) and a vote in every proceed and rollback.

This subsystem is that layer: the component base classes in src/lib/, the registry of components on the engine object, the moment the engine defines each tag, the screens and how one is shown, the menus and their configuration, and the two modal dialogs the engine uses to ask and to tell. The individual components that draw text live in Text and the Type-Writer; the save and load screens in Saving and Loading; the error dialogs a failing component produces in Errors and the Debug Module.

The files

File What it does Cypress specs
node_modules/@aegis-framework/pandora/ Pandora 0.5.1: Component (props, state, the mount cycle, rendering), ShadowComponent, Registry (defines tags, reports mounts and errors). The package ships a bundle; its TypeScript sources are inside dist/pandora.js.map. all of them, indirectly
src/lib/Component.ts Monogatari’s Component: Pandora’s Component plus the static engine, the mounting hooks, the game events, the static fan-out of shouldProceed/willProceed/shouldRollback/willRollback/onReset to every instance, content(), element(), and the animated class all of them, indirectly
src/lib/ShadowComponent.ts The same additions on Pandora’s ShadowComponent (shadow DOM). No built-in component uses it. none
src/lib/ScreenComponent.ts Base for screens: the open state, data-screen from the tag, the active class main_menu_after_load.spec.js, actions/play.spec.js
src/lib/MenuComponent.ts Base for menus: buttons read from engine.configuration(tag), addButton(), addButtonAfter(), addButtonBefore(), removeButton(), buttons(), button(), onConfigurationUpdate() none
src/lib/types/Component.ts StaticComponent and ComponentInstance, the shapes the engine types its registry with none
src/index.ts The _components list: the 27 built-in components the engine starts with. Also exports Component, ShadowComponent, ScreenComponent and MenuComponent on the Monogatari global. all of them, indirectly
src/monogatari.ts registerComponent(), unregisterComponent(), components(), component(), configuration() and the default main-menu/quick-menu buttons, setup() (where every tag is defined), bind() (the [data-action] click handler and the back button), init(), _setupRegistry(), element(), on(), trigger() all of them, indirectly
src/engine/ui.ts showScreen(), hideScreens(), goBack(), showAlert()/dismissAlert(), showMainScreen(), showSplashScreen(), displayInitialScreen(), distractionFree() actions/play.spec.js, components/save-screen.spec.js
src/components/visual-novel/ <visual-novel>: the root element. engine.element() finds it, and engine events are dispatched on it. all of them, indirectly
src/components/main-screen/, game-screen/, loading-screen/, language-selection-screen/, settings-screen/, help-screen/, credits-screen/, gallery-screen/ The screens in the starter game’s markup. game-screen also owns the click that advances the game and the back listener. main_menu_after_load.spec.js, actions/play.spec.js
src/components/main-menu/, quick-menu/ The two menus, built on MenuComponent actions/show_textbox.spec.js, actions/play.spec.js
src/components/alert-modal/, message-modal/ The confirmation dialog engine.alert() creates, and the dialog the Message action creates components/save-screen.spec.js
src/style/monogatari.css [data-screen] { display: none } and [data-screen].active { display: flex }, and the .modal styles all of them, indirectly
dist/index.html The starter game’s markup: which components live in the page from the start all of them: cy.open() visits it

Each component folder holds index.ts (the class) and index.css (its styles, imported by src/index.css).

How it works

Pandora 0.5: what a component is

A Pandora Component extends HTMLElement. Read its sources from the source map when you need the details:

python3 -c "import json; m = json.load(open('node_modules/@aegis-framework/pandora/dist/pandora.js.map')); [print(s) for s in m['sources']]"

What Monogatari relies on:

  • Props and state. this.props and this.state are read-only proxies. Assigning this.props = {…} or this.state = {…} works only while the element isn’t connected, which is why constructors set their defaults that way. Once connected, setProps() and setState() are the only way to change them; a write like this.state.count = 1 throws Component state should be set using the setState function instead. A prop that isn’t set falls back to the element’s attribute of the same name ('true', 'false' and numbers are converted).

  • Updates don’t render. setState() and setProps() merge the change and call updateCallback() for each key: willUpdate(), update(), then onStateUpdate() or onPropsUpdate(), then didUpdate(). Nothing in that chain renders. A component that wants new markup after a change updates its own DOM in onStateUpdate()/onPropsUpdate() or calls forceRender(). setProps() also writes string, number and boolean props back as attributes. An attribute in observedAttributes that changes calls updateCallback() with the origin 'attribute'.

  • The mount cycle runs in connectedCallback(), when the element enters the document (or when its tag is defined while it’s already there):

    1. sets data-component to the tag;
    2. the first time, looks for <template id="<tag>"> in the document and, if there is one, makes it the class’s template;
    3. on the first mount, stores the element’s current innerHTML as _children;
    4. writes the initial props as attributes;
    5. await willMount(), await _render(), then await didMount() (the first time) or await didReconnect();
    6. marks the element ready, runs the callbacks queued with ready(), and tells the Registry it mounted.

    Monogatari’s Component adds one step before all of that: it adds the class animated, which animate.css’s compatibility stylesheet needs to give an animation class such as fadeIn a duration. A TODO above that line in src/lib/Component.ts questions doing it for every component.

  • Rendering. _render() uses the class’s template when one was set (Component.template() or a <template id>), and render() otherwise. A lit-html result is rendered with lit. A string replaces innerHTML, and then, if _children isn’t empty and the new markup doesn’t already contain it, _children is appended. An empty string renders nothing and leaves the element’s children alone.

  • Unmounting. disconnectedCallback() runs willUnmount(), unmount() and didUnmount(), and clears the ready state.

  • The Registry. Registry.register(tag, Class) calls customElements.define() and throws if the tag was registered before; a tag can never be defined twice in a page. Registry.onError(), onMount() and onUnmount() receive what the mount and unmount cycles report. Monogatari doesn’t export the Registry: a game can’t reach it.

flowchart TD connected["connectedCallback()"] --> animated["Monogatari: add class 'animated'"] animated --> tag["data-component = tag"] tag --> tpl{"First time and a template id = tag in the page?"} tpl -- yes --> settpl["use it as the class template"] tpl -- no --> children settpl --> children["first mount: _children = innerHTML"] children --> attrs["props written as attributes"] attrs --> willMount["await willMount()"] willMount --> render["await _render(): template() or render(), then append _children"] render --> didMount["await didMount() or didReconnect()"] didMount --> ready["ready callbacks, Registry onMount: componentDidMount event"] willMount -. "throws" .-> error["Registry onError: engine:component:lifecycle_error"] render -. "throws" .-> error didMount -. "throws" .-> error update["setState() / setProps()"] --> cb["updateCallback(): willUpdate, update, onStateUpdate or onPropsUpdate, didUpdate"] cb --> norender["no render: the component updates its DOM itself or calls forceRender()"]

Monogatari’s base classes

Class Adds Built-ins that use it
Component (src/lib/Component.ts) The static engine (a getter on instances), _configuration and configuration(), _experimental, the static hooks setup, bind, init, onStart, onLoad, onSave, onReset, the static shouldProceed/willProceed/shouldRollback/willRollback that call the same method on every instance in the page (instances() is $_(tag)), the instance versions (allowing by default), element() (the element wrapped in Artemis), content(name) (finds [data-content="name"] inside), remove() Most of them
ScreenComponent state.open (false), willMount() that sets data-screen to the tag without -screen (settings-screen → settings), onStateUpdate() that adds or removes the class active when open changes, and an empty render() Every *-screen component
MenuComponent Buttons stored in the engine’s configuration under the menu’s tag, the static helpers to change them, onConfigurationUpdate() to redraw, and a render() that turns each button into an element main-menu, quick-menu
ShadowComponent The Component additions on a shadow-DOM element; its content() searches the shadow root none

_priority (deprecated in 2.9.0) and parent() exist on Component but the engine never uses them (Pitfalls and history). The static get(id) and the instance’s instance(id) find the component’s elements whose data-instance is id; the engine doesn’t use them either.

The registry and when every tag is defined

src/index.ts assigns the built-ins to Monogatari._components, in this order: alert-modal, canvas-container, centered-dialog, character-sprite, choice-container, credits-screen, dialog-log, gallery-screen, game-screen, help-screen, language-selection-screen, load-screen, loading-screen, main-menu, main-screen, message-modal, quick-menu, save-screen, save-slot, settings-screen, slot-container, text-box, text-input, timer-display, visual-novel, type-writer, type-character. Assigning the array doesn’t define anything. Right after the lists of components and actions, src/index.ts sets every built-in class’s engine, so their static helpers (a menu’s addButton(), configuration()) work in a game’s js/ files before init().

monogatari.registerComponent(Class) behaves differently before and after setup:

When The tag is new The tag is already in the list
Before setup() finished (a game’s main.js, outside $_ready) Added to the list; defined in setup() with the others The old class is removed (unregisterComponent()) and the new one added at the end: the replacement wins
After setup() (_didSetup is true) Added and defined at once with Registry.register(). Elements already in the page upgrade and mount. Its static setup, bind and init never run: those loops are over. engine:component:already_registered is shown and the class isn’t added: the page and the list keep the old class

At any time, a tag the browser has already defined (by the engine, or by the game’s own customElements.define()) can’t take another class: registerComponent() shows engine:component:already_registered and returns without adding it. Before 2.9.0 it added the class anyway, so the list held two classes for the tag and every fan-out called both.

unregisterComponent(tag) works only before setup, and leaves the other components, experimental ones included, in the list; afterwards it shows engine:component:unregister_after_setup and changes nothing. components() returns the list without experimental components (unless ExperimentalFeatures is on), and component(tag) finds one by its lowercase tag.

setup() in src/monogatari.ts is where the tags come alive:

  1. It reads the player’s preferences (Storage.get('Settings')), and waits for that to finish.
  2. For every component in the list it sets component.engine and calls Registry.register(tag, component). A tag that is already defined throws, and the catch shows engine:component:already_registered. Each define() upgrades the matching elements already in the page, so their connectedCallback() starts right there, before any static hook.
  3. It registers the service worker, stores the storage structure, and registers the engine’s own listeners (open-screen, start, dismiss-alert, distraction-free, skip, auto-play).
  4. It runs every component’s static setup(selector), then every action’s, all at once, and sets _didSetup when they all resolve.

Until step 2, the tags in the page are undefined elements with no markup. A menu helper called then changes the configuration and redraws nothing (onConfigurationUpdate() skips elements the browser hasn’t upgraded); the menu’s first render reads the new list (recipes).

sequenceDiagram participant Main as js/main.js participant Init as init() participant Setup as setup() participant Reg as Pandora Registry participant El as elements in the page participant UI as src/engine/ui.ts Main->>Init: monogatari.init('#monogatari') Init->>Init: _setupRegistry(): onError, onMount, onUnmount Init->>Setup: setup(selector) Setup->>Setup: await Storage.get('Settings') loop every component in _components Setup->>Reg: Registry.register(tag, Class) Reg->>El: customElements.define: upgrade, connectedCallback() end Setup->>Setup: engine listeners, then static setup() of components and actions Init->>Init: bind(): click handlers, keys, static bind() Init->>Init: localize(), static init() of components and actions Init->>UI: displayInitialScreen() UI->>UI: preload(): loading-screen opens and closes on the asset events UI->>UI: showSplashScreen(), else showMainScreen() UI->>El: showScreen('main') or, without a main screen, the game

Who calls the static hooks

Hook Called by When
setup() setup() in src/monogatari.ts Once, after every tag is defined
bind(selector) bind() Once, after the engine’s own click handlers and keys
init(selector) init() Once, after localize(); didInit fires when all resolve
onStart() the start listener, through engine.onStart() The player starts a new game
onLoad() loadFromSlot(), through engine.onLoad() A save is loaded (components run alongside the actions)
onReset() resetGame() in src/engine/persistence.ts A game ends (End) or before a load; the static version calls every instance’s onReset()
shouldProceed(), willProceed() shouldProceed()/willProceed() in src/engine/lifecycle.ts Every attempt to advance; a rejection anywhere refuses it
shouldRollback(), willRollback() shouldRollback()/willRollback() Every attempt to go back
onSave(slot) saveTo() in src/engine/persistence.ts, through runSaveHooks() A game was saved and the slot written (never called before 2.9.0)

The engine calls these on every class in components(), never on elements it doesn’t know: a custom element defined with customElements.define() instead of registerComponent() never gets a vote.

The markup and the root element

The starter game’s dist/index.html holds the persistent components:

<div id="monogatari">
  <visual-novel>
    <language-selection-screen></language-selection-screen>
    <loading-screen></loading-screen>
    <main-screen>
      <main-menu></main-menu>
    </main-screen>
    <game-screen>
      <dialog-log></dialog-log>
      <text-box></text-box>
      <quick-menu></quick-menu>
    </game-screen>
    <gallery-screen></gallery-screen>
    <credits-screen></credits-screen>
    <load-screen></load-screen>
    <save-screen></save-screen>
    <settings-screen></settings-screen>
    <help-screen></help-screen>
  </visual-novel>
</div>

The others are created when needed: alert-modal by engine.alert(), message-modal by the Message action, choice-container and timer-display by Choice, text-input by InputModal, canvas-container by Canvas, character-sprite by ShowCharacter, centered-dialog and the NVL type-writers by Dialog, type-writer by the text box, type-character by the type-writer, slot-container by the save and load screens, and save-slot by the slot container.

<visual-novel> is the root. engine.element() is $_('visual-novel') (any <visual-novel> in the document, whatever selector init() received); engine.on(event, …) listens on it, and engine.trigger(name, detail) dispatches a non-bubbling CustomEvent on it. The selector given to init() is passed to every component’s and action’s setup, bind and init, and used by the back buttons, Esc and ForceAspectRatio (parentElement()); element() doesn’t use it.

Two things in this markup change at init. gallery-screen’s static init() removes every <gallery-screen> when the game declared no gallery assets. And game-screen renders its own [data-content="visuals"] and then appends _children, the dialog-log, text-box and quick-menu markup it captured, so those three are new elements built from that markup: a reference to <text-box> taken before init points to an element no longer in the page. main-screen renders an empty string, so its main-menu stays the same node.

Screens

A screen is a ScreenComponent inside <visual-novel>. Its data-screen attribute (set in willMount()) is how the engine finds it, and its open state is the only switch: open: true adds the class active, and the stylesheet shows [data-screen].active and hides every other [data-screen].

showScreen(name) in src/engine/ui.ts:

  1. If the screen is save, the Screenshots setting is on, the game is playing and the game screen is visible, it starts a screenshot of the game screen first and reveals the save screen when the capture settles (Saving and Loading). Opening any other screen drops a pending capture.
  2. revealScreen() calls hideScreens(), which sets open: false on every [data-screen] in the game, then sets open: true on [data-screen="<name>"].
  3. It turns auto-play and skip off.

A name with no matching element hides everything and shows nothing. The class changes land a few microtasks later, because setState() goes through updateCallback()’s awaits.

The rest of the screen flow:

  • Start. The start listener (the main menu’s Start button) runs every onStart(), sets open: false on every screen and open: true on the game screen directly (not through showScreen()), and runs the statement at the current label and step.
  • Back buttons. bind() registers a click handler for [data-screen]:not([data-screen="game"]) [data-action="back"] before the generic [data-action] handler. goBack() stops the event with stopImmediatePropagation(), so the back listener (rollback) never sees it, hides every screen, and opens the game if the player is playing (or on the splash screen) and the main screen otherwise.
  • Keys. Esc switches between the game and settings while playing; Shift+S and Shift+L open save and load.
  • The main screen plays the MainScreenMusic when it opens and stops it when it closes during a game (MainScreen.onStateUpdate()).
  • The loading screen opens and closes itself from the willPreloadAssets, assetQueued, assetLoaded, assetFailed and didPreloadAssets events.
  • The game screen refuses every proceed while it isn’t visible (its static shouldProceed()). Its static bind() registers the click that advances the game and, when AllowRollback is on, the back listener (←).

A menu’s buttons are not in the component: they’re in the engine’s configuration, under the menu’s tag. src/monogatari.ts declares the defaults in _configuration: main-menu has Start, Load, Settings and Help; quick-menu has Back, Hide, AutoPlay, Skip, Save, Load, Settings and Quit. Other components change them during the mounting cycle:

  • dialog-log’s static setup() adds Log after Hide in the quick menu;
  • quick-menu’s static init() removes Skip when the Skip setting is 0 or less (the default) and Back when AllowRollback is off;
  • credits-screen’s and gallery-screen’s static init() add Credits and Gallery to the main menu when the game has credits or gallery images.

render() builds one element per button (a button unless the button names another element), copies data into data-* attributes, sets string, tabindex="0" and, when the button has one, icon, and fills it with <span class="<icon>"> (only with an icon) and a <span> for the label from translateLabel() (src/engine/i18n.ts): <span data-string="<string>"> with the translated text when string is the name of an interface string, or the string as written, without data-string, when it isn’t. Before 2.9.0 it always used engine.string(string), so a label that wasn’t a key showed “undefined”. Font Awesome, imported by the engine, then replaces the icon spans with <svg> elements, which is why runListener() walks up from a clicked <path> to the element with the data-action.

The helpers addButton(), addButtonAfter(), addButtonBefore() and removeButton() write a new buttons array with engine.configuration(tag, { buttons }). engine.configuration(key, object) then calls the static onConfigurationUpdate() of the component registered under key, when it has one, and only menus do: it calls forceRender() on every menu element on the page. That goes through Pandora’s _render(), so a template set for the menu is used and the markup written inside the tag is kept; until 2.9.0 it set innerHTML to render() directly and dropped both. The menu’s own static configuration() reaches the same list: configuration('buttons') returns it, and configuration('buttons', list) or configuration({ buttons: list }) replaces it and redraws, through setButtons(); other keys work as on any component. engine.configuration() merges with deeply, which replaces arrays rather than merging them, and fires configurationElementUpdate::<tag>. Until 2.9.0 nothing redrew the menu after a direct monogatari.configuration('main-menu', …): the helpers called onConfigurationUpdate() themselves, and the engine didn’t. A subclass a game uses under a tag another class is registered for still redraws itself from the helpers.

Modals

Two components are dialogs, and both carry the classes modal modal--active:

  • engine.alert(id, options) (showAlert()) creates an alert-modal, sets data-alert-id, passes options as props and prepends it to <visual-novel>. It shows the translated message, an optional context (an input when editable is true) and one button per action, each a data-action that runs the named listener. engine.dismissAlert(id) removes the one with that id, or every alert without an id; the dismiss-alert listener removes the alert its button is in (closest('alert-modal')). Before the components are defined (an alert() from js/options.js), showAlert() waits for customElements.whenDefined('alert-modal'). The slot overwrite and delete confirmations and the quit confirmation use it.
  • message-modal is created by the Message action. Its instance shouldProceed() always rejects, its willProceed() and willRollback() remove it, and its Close button is handled by a click handler the Message action’s bind() adds, which removes the dialog and proceeds.

shouldProceed() in src/engine/lifecycle.ts refuses to advance while any .modal is visible, before it asks a single action or component. So any visible modal holds the game: an alert, a message, the dialog log (always a .modal, visible while it’s open) and the debug module’s error dialogs.

Errors in components

_setupRegistry() runs at the start of init(). It turns on the Registry’s console logging when the debug module is loaded ([Pandora] Registered: <tag>), and connects the Registry’s callbacks:

  • onError shows engine:component:lifecycle_error (“Error in component during connectedCallback”) and logs the error. Pandora reports errors thrown during connectedCallback() (so in willMount(), render(), didMount()) and disconnectedCallback(). An error in onStateUpdate() or onPropsUpdate() isn’t caught by anything: it becomes an unhandled rejection in the console.
  • onMount and onUnmount trigger the engine events componentDidMount and componentDidUnmount, with { component, tag } as the detail.

Errors and the Debug Module explains how those dialogs render, and why they only appear with the debug module loaded.

The data

From src/lib/types/Component.ts, the shape of a component class as the engine sees it:

export interface StaticComponent extends PandoraComponentClass {
  tag: string;
  _experimental: boolean;
  _configuration: Configuration;
  _priority: number;
  engine: VisualNovelEngine;

  configuration: (object?: string | Configuration | null) => Configuration | unknown;

  all: () => DOM;
  get: (id: string) => DOM;
  instances: (callback?: ((instance: ComponentInstance) => void) | null) => DOM;

  setup: (selector?: string) => Promise<void>;
  bind: (selector?: string) => Promise<void>;
  init: (selector?: string) => Promise<void>;

  onStart: () => Promise<void>;
  onLoad: () => Promise<void>;
  onSave: (slot?: SaveSlot) => Promise<void>;
  onReset: () => Promise<void[]>;

  shouldProceed: (options?: { userInitiated?: boolean; skip?: boolean; autoPlay?: boolean }) => Promise<void[] | void>;
  willProceed: () => Promise<void[]>;
  shouldRollback: () => Promise<void[]>;
  willRollback: () => Promise<void[]>;
}

The static shouldProceed() receives the proceed options, but the base class calls each instance’s shouldProceed() without them.

A screen’s state, from src/lib/ScreenComponent.ts:

export interface ScreenState extends Properties {
  open: boolean;
}

A menu button, from src/lib/types/index.ts:

export interface MenuButton {
  string: string;
  icon: string;
  element?: string;
  data?: Record<string, string>;
}

string is a translation key: it is the label (through engine.string()) and the name addButtonAfter(), addButtonBefore(), removeButton() and button() look buttons up by. icon is optional: the default main menu buttons have none and render no icon <span> (before 2.9.0 they rendered icon="undefined" and <span class="undefined">).

The default configuration, from _configuration in src/monogatari.ts (abridged):

static _configuration: Record<string, unknown> = {
  'main-menu': {
    buttons: [
      { string: 'Start', data: { action: 'start' } },
      { string: 'Load', data: { action: 'open-screen', open: 'load' } },
      { string: 'Settings', data: { action: 'open-screen', open: 'settings' } },
      { string: 'Help', data: { action: 'open-screen', open: 'help' } },
    ]
  },
  'quick-menu': {
    buttons: [
      { string: 'Back', icon: 'fas fa-arrow-left', link: '#', data: { action: 'back' } },
      { string: 'Hide', icon: 'fas fa-eye', data: { action: 'distraction-free' } },
      { string: 'AutoPlay', icon: 'fas fa-play-circle', data: { action: 'auto-play' } },
      { string: 'Skip', icon: 'fas fa-fast-forward', data: { action: 'skip' } },
      { string: 'Save', icon: 'fas fa-save', data: { action: 'open-screen', open: 'save' } },
      { string: 'Load', icon: 'fas fa-undo', data: { action: 'open-screen', open: 'load' } },
      { string: 'Settings', icon: 'fas fa-cog', data: { action: 'open-screen', open: 'settings' } },
      { string: 'Quit', icon: 'fas fa-times-circle', data: { action: 'end' } },
    ]
  },
  credits: {}
};

The props of alert-modal (the options of engine.alert()), from its constructor in src/components/alert-modal/index.ts:

this.props = {
  active: true,
  message: '', // a translation key
  context: null, // text under the message
  editable: false, // show context in an input with data-content="context"
  actions: [], // [{ label: 'Cancel', listener: 'dismiss-alert' }]
};

Rules and why

  • Register and replace components before init(). A tag can be defined once per page (customElements.define()), and setup() defines them all. After it, a replacement shows engine:component:already_registered and isn’t added, and a new component misses its static setup, bind and init. Never register a component from another component’s setup() hook: it is added to the list after the definition loop and before _didSetup, so it’s never defined.
  • Before init(), the elements aren’t there yet. The built-in classes have their engine from the start (src/index.ts), so configuration(), template(), registerComponent() and the MenuComponent helpers work in a game’s js/ files. Code that needs the elements, or the buttons the engine adds during the mounting cycle, belongs after init(). A new built-in component is listed in _components, which is what gives it its engine early: keep it there rather than registering it from code.
  • A constructor sets props and state, nothing else. An element whose constructor adds a class or an attribute can’t be created by document.createElement(): the browser reports “The result must not have attributes” and returns an unknown element instead. Classes and attributes go in willMount(), as ScreenComponent and alert-modal do.
  • Changing state doesn’t redraw. Pandora 0.5 calls onStateUpdate()/onPropsUpdate() and stops. Update the DOM there, or call forceRender().
  • A screen is found by data-screen and shown by open. Build screens on ScreenComponent, name the tag <name>-screen, and open it with showScreen() or a data-action="open-screen" data-open="<name>" button. A screen outside <visual-novel> is invisible to hideScreens() and showScreen().
  • Anything clickable in the game screen carries data-action (or data-choice, data-delete). The game screen advances on any other click inside it. See Statements and Actions for how listeners run.
  • Every string a menu or screen shows needs a translation. engine.string() shows engine:translation:key_not_found for a missing key, and with the debug module loaded that dialog is a modal over the screen.
  • A visible .modal holds the game. Use the class for dialogs that must block, and never for anything that stays on screen.
  • Only registered components take part. The proceed, rollback and reset fan-outs loop over components().

How to make the common changes

Change the markup of a built-in component

Three ways, from the lightest:

  1. A <template> in the page. Pandora uses <template id="<tag>"> as the class’s template the first time an element of that tag mounts. It goes in index.html, so it needs no JavaScript:

    <template id="help-screen">
      <button class="top left" data-action="back"><span class="fas fa-arrow-left"></span></button>
      <h2 data-string="Help">Help</h2>
      <p>Click or press the space bar to continue.</p>
    </template>
  2. template(), from main.js, before or after init(). Afterwards it redraws the elements that are already mounted:

    monogatari.component('game-screen').template(() => `
      <h1>My Title</h1>
      <div data-content="visuals">
        <div id="tsparticles" data-ui="particles"></div>
        <div id="background" data-ui="background"></div>
      </div>
    `);

    Keep every data-content and data-ui the engine looks for. A menu is the exception: addButton() and its siblings redraw with render() and drop the template, and the credits and gallery screens call addButton() at init when the game has credits or gallery images.

  3. A subclass, registered before init(), when the behavior changes too:

    const HelpScreen = monogatari.component('help-screen');
    
    class MyHelpScreen extends HelpScreen {
      render() {
        return `${super.render()}<p data-content="extra">Saved games stay in this browser.</p>`;
      }
    }
    
    monogatari.registerComponent(MyHelpScreen);

    The subclass inherits the tag, so registerComponent() replaces the built-in. The replacement goes to the end of the list, which only changes the order the static hooks start in.

Add a screen

class AboutScreen extends Monogatari.ScreenComponent {
  render() {
    return `
      <button class="top left" data-action="back"><span class="fas fa-arrow-left"></span></button>
      <h2 data-string="About">About</h2>
      <p>Made with Monogatari.</p>
    `;
  }
}

AboutScreen.tag = 'about-screen';

monogatari.registerComponent(AboutScreen);
monogatari.translation ('English', { About: 'About' });

Put <about-screen></about-screen> inside <visual-novel> in index.html, and open it with a button whose data is { action: 'open-screen', open: 'about' } or with monogatari.showScreen ('about'). The back button works with no code: goBack() handles any [data-action="back"] outside the game screen.

Add, remove or reorder menu buttons

Use the helpers, before or after init(); they redraw the menu when it’s on the page:

const quickMenu = monogatari.component('quick-menu');

quickMenu.addButtonAfter('Save', { string: 'Bookmark', icon: 'fas fa-bookmark', data: { action: 'bookmark' } });
quickMenu.removeButton('Quit');

To replace the whole list, give it to the menu:

monogatari.component('main-menu').configuration('buttons', [
  ...monogatari.component('main-menu').buttons(),
  { string: 'About', icon: 'fas fa-info-circle', data: { action: 'open-screen', open: 'about' } },
]);

Buttons the engine adds or removes during the mounting cycle (Log, Credits, Gallery; Skip and Back when they’re off) are in the list only after init(), so a change that names one of them goes inside monogatari.init ('#monogatari').then (…). A change through monogatari.configuration ('main-menu', …) after init needs monogatari.component ('main-menu').onConfigurationUpdate () to show.

Add a built-in component to the engine

  1. Create src/components/<tag>/index.ts and index.css. Start from the closest built-in: help-screen for a static screen, loading-screen for one that listens to engine events, alert-modal for a dialog, quick-menu for a menu.
  2. Import the class in src/index.ts and add it to Monogatari._components.
  3. @import its stylesheet in src/index.css.
  4. If it lives in the page from the start, add its tag to dist/index.html. If an action creates it, create it with document.createElement ('<tag>') and set props with setProps() before appending it.
  5. Build (bun run build, see Building and Packaging) and commit what it rebuilt (dist/engine/core/, dist/types/, lib/) with the change.
  6. Add a spec in cypress/e2e/components/ (Testing) and a page in docs/components/<tag>.md.

Hold the game from a component

Reject from the instance’s shouldProceed(). The base class’s static shouldProceed() asks every element of the tag in the page:

class HoldBanner extends Monogatari.Component {
  async shouldProceed() {
    throw new Error('The hold banner is still open.');
  }
}

Release it by removing the element (or by resolving once a condition is met). willRollback() and onReset() are where a component that must not survive a rollback or a new game removes itself, as message-modal does.

Ask the player to confirm

monogatari.registerListener('skip-chapter', {
  callback() {
    this.dismissAlert('skip-chapter');
    this.run('jump Chapter2');
  },
});

monogatari.alert('skip-chapter', {
  message: 'SkipChapter',
  actions: [
    { label: 'OK', listener: 'skip-chapter' },
    { label: 'Cancel', listener: 'dismiss-alert' },
  ],
});

message and each label are translation keys. OK and Cancel exist in every bundled translation; add SkipChapter with monogatari.translation ('English', { SkipChapter: 'Skip to chapter two?' }). Read a key’s text before you use it as a label: Confirm is the quit question (“Do you want to quit?” in English). While the alert is visible the game can’t advance.

Pitfalls and history

  • “Lit is in dev mode” in the console. Pandora 0.5.0’s bundle (dist/pandora.js) included lit-html’s development build, which printed that warning on every page load. Pandora 0.5.1 is the same code built with --production, and package.json asks for ^0.5.1, so the warning is gone from 2.9.0. If it comes back, check the installed Pandora (bun.lock), not the engine’s build flags.
  • addButton() in main.js threw until 2.9.0. The old component docs show monogatari.component ('main-menu').addButton (…) with no word on when to call it; outside $_ready it failed with Cannot read properties of undefined (reading 'configuration'), because the built-ins got their engine only in setup(). 2.9.0 sets it in src/index.ts; Exercise 4 has you find that fix on the v2.8.1 tag.
  • A menu’s template didn’t survive addButton() until 2.9.0. MenuComponent.onConfigurationUpdate() wrote render() into innerHTML directly, so a game with a main menu template and credits lost the template at init. It calls forceRender() now.
  • The game screen rebuilds its children. Code that grabs <text-box> or <quick-menu> before init, or that sets innerHTML on the game screen, works with elements that are gone or about to be duplicated. Pandora once duplicated those children when a component rendered again (365b2123, “Update pandora to fix children duplication”, 2020-05-29); today’s _render() appends _children only when the new markup doesn’t already contain it.
  • Clicks inside the game screen. The handler in GameScreen.bind() listens to clicks on elements of the game screen that have no data-action, data-choice or data-delete, then checks the element that was really clicked (event.target): when it is, or sits inside, a [data-action], [data-delete] or [data-choice] element of the game screen, the game doesn’t move on. That holds whatever the button’s own listener returns, and for a script’s button.click() too. Until 2.9.0 the handler only checked the element it matched, which for a click on a quick-menu button’s own box (its padding, or Enter on it) is <quick-menu>, so what stopped the game was runListener() calling stopImmediatePropagation() when a listener returned nothing; a listener that returned true, or button.click(), advanced the game as well. The event.stopPropagation() in the [data-action] handler (in setup() in src/monogatari.ts) never helped: both handlers listen on <visual-novel>. This was reworked in 88425293 (“Add show and hide textbox actions”, 2026-03-21); Statements and Actions covers the listener side.
  • History. v1 kept the whole interface as plain markup in index.html. v2 moved it into components (2018–2019: “Quick Menu as a Component allowing the addition of more buttons” 4b3e63af, “Move core component functionality to external library” 9bc0d6a8), moved menu buttons from each component into the engine’s configuration (8c8a9d10, 2019-07-20), added shadow components (1a7bb83a, 2019-11-30) and late registration with the _didSetup guard (a562c5ec, 2020-02-11). The TypeScript migration (bbc0c637, 2025-12-08) moved to Pandora 0.4, and “Keep up with bun migration” (0d2e4b12, 2026-03-18) to Pandora 0.5 and the Registry callbacks. “Split the engine” (eb1ea6bf) moved the screen functions into src/engine/ui.ts, and the save screenshots (78cfbcda, 4b5fff30) made showScreen('save') wait for a capture.
  • Helpers that didn’t do what their names said. Until 2.9.0, Component.get(id) looked for [data-instance] inside the component, not on it, and instance(id) built a selector from the class name, which the minified bundle renames (MainMenu becomes something like Ey). Both find the component’s own elements by data-instance now. _priority is read by nothing (2.9.0 marks it deprecated). onSave(), in the same list before 2.9.0, now runs after every save.
  • The Help screen promised a key that doesn’t exist. Until 2.9.0 it listed A for auto-play, but the auto-play listener has no keys. It also listed Skip and Back when the game turned them off; it leaves them out now, as the quick menu does.
  • Duplicates in the list. Until 2.9.0, a class registered for a tag already defined was pushed anyway, so components() held two classes for the tag and the fan-outs called both.
  • unregisterComponent() before setup filtered through components() until 2.9.0, which leaves out experimental components: unregistering anything dropped every experimental component from the list. No built-in component is experimental.
  • The [data-action] handler returns action === 'set-volume' (in setup() in src/monogatari.ts), which does nothing: Artemis ignores what a delegated handler returns.

Exercises

Each check is a Cypress spec. Save it in cypress/e2e/exercises/ of a scratch copy of the repository (How Each Part Works) and run it with:

bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/<name>.spec.js'

Delete the folder when you’re done. Two things specific to components:

  • cy.open() visits dist/index.html and returns before monogatari.init() finishes. When a test needs the engine set up (to use a menu helper, for example), wait for it first: cy.get ('@monogatari').invoke ('global', '_didInit').should ('equal', true);.

  • To run code before init(), the way a game’s main.js does, add a DOMContentLoaded listener in onBeforeLoad: it’s registered before main.js adds its own $_ready() callback, so it runs first.

    const beforeInit = (callback) => ({
      onBeforeLoad(win) {
        win.document.addEventListener('DOMContentLoaded', () => callback(win));
      },
    });
    
    cy.visit('./dist/index.html', beforeInit((win) => { /* register here */ }));

    Classes you define in the spec extend the page’s classes (win.Monogatari.ScreenComponent), and elements you create must come from the page’s document (win.document.createElement).

Exercise 1: add an About screen

What to do. Before init(), register an about-screen with a back button, put an <about-screen> in <visual-novel>, and add an About button to the main menu that opens it.

Hint. Which base class gives an element a data-screen and an active class? What does the main menu do with a button’s string? Read showScreen() and goBack() in src/engine/ui.ts.

Check. Clicking About shows the About screen, it is the only [data-screen] with active, and its back button returns to the main menu. Build the screen on Monogatari.Component instead and the check fails (no [data-screen="about"]); leave out the translation and it fails too (the error dialog covers the menu).

Solution
const beforeInit = (callback) => ({
  onBeforeLoad(win) {
    win.document.addEventListener ('DOMContentLoaded', () => callback(win));
  }
});

context ('About screen', function() {

  beforeEach(() => {
    cy.visit ('./dist/index.html', beforeInit((win) => {
      const { ScreenComponent } = win.Monogatari;
      const monogatari = win.Monogatari.default;

      class AboutScreen extends ScreenComponent {
        render() {
          return `
            <button class="top left" data-action="back"><span class="fas fa-arrow-left"></span></button>
            <h2 data-string="About">About</h2>
            <p data-content="credits">Made with Monogatari.</p>
          `;
        }
      }

      AboutScreen.tag = 'about-screen';

      monogatari.registerComponent(AboutScreen);
      monogatari.translation ('English', { About: 'About' });

      monogatari.configuration ('main-menu', {
        buttons: [
          ...monogatari.configuration ('main-menu').buttons,
          { string: 'About', icon: 'fas fa-info-circle', data: { action: 'open-screen', open: 'about' } }
        ]
      });

      win.document.querySelector ('visual-novel').append(win.document.createElement ('about-screen'));
    }));

    cy.window().its ('Monogatari.default').as ('monogatari');
  });

  it ('Opens from the main menu and goes back', function() {
    cy.get ('main-menu [data-open="about"]').click();
    cy.get ('[data-screen="about"]').should ('have.class', 'active').and ('be.visible');
    cy.get ('[data-screen="main"]').should ('not.have.class', 'active');
    cy.get ('[data-screen].active').should ('have.length', 1);

    cy.get ('[data-screen="about"] [data-action="back"]').click();
    cy.get ('[data-screen="main"]').should ('be.visible');
    cy.get ('[data-screen="about"]').should ('not.be.visible');
  });
});

ScreenComponent.willMount() turns about-screen into data-screen="about", which is what the open-screen listener passes to showScreen(). The button goes through the configuration; since 2.9.0, monogatari.component ('main-menu').addButton (…) works there too.

Exercise 2: a quick-menu button that doesn’t advance the game

What to do. After init(), add a Bookmark button after Save in the quick menu. Clicking it stores the current label and step in storage('bookmark') and leaves the game on the same line.

Hint. registerListener() and a button whose data has an action. Read the click handler in GameScreen.bind(): which clicks inside the game screen advance it?

Check. After the click, storage('bookmark') is { label: 'Start', step: 0 } and the text box still shows the first line; the next proceed shows the second. Give the button data: { bookmark: '' } and handle the click with monogatari.on ('click', '[data-bookmark]', …) instead, and the check fails: the game moves to the second line.

Solution
context('Bookmark button', () => {
  beforeEach(() => {
    cy.open();

    // cy.open () doesn't wait for monogatari.init (): menus need the engine set up
    cy.get('@monogatari').invoke('global', '_didInit').should('equal', true);
  });

  it('Records the line without advancing the game', function() {
    const monogatari = this.monogatari;

    monogatari.setting('TypeAnimation', false);
    monogatari.script({
      'Start': [
        'One',
        'Two',
        'end',
      ],
    });

    monogatari.translation('English', { Bookmark: 'Bookmark' });

    monogatari.registerListener('bookmark', {
      callback() {
        this.storage({ bookmark: { label: this.state('label'), step: this.state('step') } });
      },
    });

    monogatari.component('quick-menu').addButtonAfter('Save', {
      string: 'Bookmark',
      icon: 'fas fa-bookmark',
      data: { action: 'bookmark' },
    });

    cy.start();
    cy.get('text-box').contains('One');

    cy.get('quick-menu [data-action="bookmark"] [data-string]').click();
    cy.wrap(monogatari).invoke('storage', 'bookmark').should('deep.equal', { label: 'Start', step: 0 });
    cy.get('text-box').contains('One');

    cy.proceed();
    cy.get('text-box').contains('Two');
  });
});

The game screen ignores any click inside an element with data-action. The callback returns nothing on purpose: return true and a click on the button’s padding advances the game as well (Pitfalls and history).

Exercise 3: a component that holds the game

What to do. Register a hold-banner component. While one is in the game screen, the player can’t advance; its Continue button removes it.

Hint. Read shouldProceed() in src/engine/lifecycle.ts: whom does it ask, and what does Component’s static shouldProceed() do with the question? Keep the class modal off the banner, or you’re testing a different rule.

Check. With the banner on screen, a click on the text box leaves the first line; after Continue, a click shows the second. Remove the instance’s shouldProceed() and the check fails. Define the tag with win.customElements.define() instead of registerComponent() and it fails too: the engine never asks a component it doesn’t know.

Solution
context ('Hold banner', function() {

  beforeEach(() => {
    cy.open();
    cy.get ('@monogatari').invoke ('global', '_didInit').should ('equal', true);
  });

  it ('Holds the game until the player closes it', function() {
    const monogatari = this.monogatari;

    cy.window().then((win) => {
      class HoldBanner extends win.Monogatari.Component {
        async shouldProceed() {
          throw new Error ('The hold banner is still open.');
        }

        async willMount() {
          this.style.cssText = 'position: absolute; top: 1rem; left: 1rem; z-index: 10; background: white; padding: 1rem;';
        }

        render() {
          return '<p>Take a breath.</p><button data-action="release-hold">Continue</button>';
        }
      }

      HoldBanner.tag = 'hold-banner';

      monogatari.registerComponent(HoldBanner);

      monogatari.registerListener ('release-hold', {
        callback() {
          this.element().find ('hold-banner').remove();
        }
      });
    });

    monogatari.setting ('TypeAnimation', false);
    monogatari.script({
      'Start': [
        'One',
        'Two',
        'end'
      ]
    });

    cy.start();
    cy.get ('text-box').contains ('One');

    cy.get ('game-screen').then(($screen) => {
      $screen.get(0).append($screen.get(0).ownerDocument.createElement ('hold-banner'));
    });

    cy.get ('hold-banner button').should ('be.visible');
    cy.get ('text-box').click();
    cy.wait(150);
    cy.get ('text-box').contains ('One');

    cy.get ('hold-banner button').click();
    cy.get ('hold-banner').should ('not.exist');
    cy.get ('text-box').click();
    cy.get ('text-box').contains ('Two');
  });
});

Registered after init(), the component is defined at once and joins components(), which is all the proceed check needs; its static hooks would not have run, but it has none. The style goes in willMount(): set in the constructor, it would make createElement() fail.

Exercise 4: make the menu helpers work before init

What to do. This one is a real bug of 2.8.1, so do it on the tag: in your scratch worktree, git switch --detach v2.8.1 and rebuild. Change the engine so that monogatari.component ('main-menu').addButton (…) works in main.js before init(), the way the old docs show it.

Hint. The error is Cannot read properties of undefined (reading 'configuration'). Which this is undefined, and where does src/monogatari.ts set it? Built-ins are listed in src/index.ts long before setup() runs. Rebuild the browser bundle (bun build.ts --browser) before you run the spec, and restore it afterwards (git checkout -- src dist/engine/core).

Check. The spec below adds a Website button before init(). Against the unchanged engine it fails with the TypeError; with your change the main menu shows five buttons, the fifth being Website. bunx tsc --noEmit still passes, and so do main_menu_after_load.spec.js and the specs in cypress/e2e/components/ that passed before.

Solution

The spec:

const beforeInit = (callback) => ({
  onBeforeLoad(win) {
    win.document.addEventListener('DOMContentLoaded', () => callback(win));
  },
});

context('Menu buttons added before init', () => {
  it('Adds a main menu button from main.js', () => {
    cy.visit('./dist/index.html', beforeInit((win) => {
      const monogatari = win.Monogatari.default;

      monogatari.translation('English', { Website: 'Website' });

      monogatari.component('main-menu').addButton({
        string: 'Website',
        icon: 'fas fa-globe',
        data: { action: 'open-website' },
      });
    }));

    cy.get('main-menu [data-action="open-website"]').should('contain', 'Website');
    cy.get('main-menu button').should('have.length', 5);
  });
});

The change, in src/index.ts, right after the _components list:

] as unknown as StaticComponent[];

// Give the built-in components their engine now, so their static helpers
// (a menu's addButton (), configuration ()) work before init () runs setup ().
for (const component of Monogatari._components) {
  component.engine = Monogatari as unknown as StaticComponent['engine'];
}

registerComponent() already sets engine on the classes a game registers; the built-ins only got it in setup(). Before init, onConfigurationUpdate() finds the <main-menu> element not upgraded yet (instanceof Component is false) and skips it, and the first render reads the new configuration. On the tag, load-screen.spec.js has one test (“Gives priority to the last known background”) that fails with or without the change: compare against a run before you edit anything.

2.9.0 fixed it the same way, in src/index.ts, for the built-in actions as well, and its cypress/e2e/components/main-menu.spec.js has this check.