This page follows one entry of a game’s script from the moment the engine reaches it to the moment the game waits for the player again, and the machinery around that: how actions are registered and mounted, how a click or a key becomes a proceed(), and what auto-play and skip do. It goes one level below Architecture, with the function names in the order they run. Rolling back is only touched here; State, Storage and Rollback follows it in full.

What it’s for

A game’s script is data: labels holding lists of statements. A statement is a string ('show scene forest with fadeIn'), an object ({ Choice: { … } }) or a JavaScript function. An action is the class that knows how to run one kind of statement: Dialog runs lines of text, Jump moves to another label, Choice shows buttons.

This subsystem is everything between the two:

  • the list of registered actions, and the order that decides which one takes a statement;
  • the mount: the engine’s init(), which runs every action’s setup(), bind() and init() once, before the player sees anything;
  • run(), which builds an instance of the matching action and runs its willApply(), apply() and didApply();
  • next() and proceed(), which move the game one statement forward when the player clicks, presses a key, or auto-play or skip ask for it;
  • the listeners: named callbacks that data-action buttons and keyboard shortcuts run.

The rest of the engine sits on top of it. A rollback runs the same actions backwards through their revert() methods (State, Storage and Rollback). A load restores the state and runs the saved statement again with run() (Saving and Loading). Dialog, the action that takes every string nothing else takes, is the subject of Text and the Type-Writer.

The files

File What it does Cypress specs
src/lib/Action.ts The Action base class: the statics the engine reads (id, _experimental, _configuration, loadingOrder, engine, blocking), every static hook (mount, proceed and rollback checks, onStart, onLoad, reset, beforeRun…) and every instance hook (willApply to didRevert). Its top comment describes the life cycle. every spec in actions/
src/engine/lifecycle.ts prepareAction(), run(), next(), proceed(), shouldProceed(), willProceed(), assertAsync(), stopTyping(), and the rollback side (rollback(), shouldRollback(), willRollback(), previous(), revert()) every spec in actions/ (through cy.proceed() and cy.rollback()); actions/next.spec.js, actions/wait.spec.js, actions/functions.spec.js, actions/reversible_functions.spec.js
src/index.ts The built-in lists: Monogatari._actions in matching order with Dialog last, Monogatari._components, Monogatari._translations every spec (the engine they load)
src/monogatari.ts The engine object: registerAction(), unregisterAction(), actions(), action(), the mount (init(), setup(), bind()), the engine’s own listeners (start, open-screen, skip, auto-play…), and thin wrappers that pass this to the functions in src/engine/ main_menu_after_load.spec.js (the boot); every spec
src/engine/input.ts keyboardShortcut() (Mousetrap), registerListener(), unregisterListener(), runListener() components/save-screen.spec.js, components/load-screen.spec.js (they click data-action buttons)
src/engine/ui.ts autoPlay(), skip(), distractionFree(), and the boot’s last step: displayInitialScreen(), showSplashScreen(), showMainScreen(). The screen functions are covered in Components and Screens. none for auto-play, skip or distraction-free
src/components/game-screen/index.ts The click on the game screen that calls proceed(), the back listener (left arrow), and the check that refuses to proceed while the game screen is hidden every spec in actions/ (indirectly)
src/actions/Next.ts, Wait.ts Advance at once; wait for a click or for some milliseconds actions/next.spec.js, actions/wait.spec.js
src/actions/Jump.ts, End.ts Move to another label; end the game and go back to the main screen none for jump; many specs end their script with end
src/actions/Conditional.ts, Choice.ts Run one of several nested statements, decided by a function or by the player actions/conditionals.spec.js, actions/choices.spec.js
src/actions/Function.ts, Placeholder.ts { Function: { Apply, Revert } } statements; $ name statements that run a statement saved with monogatari.$() actions/reversible_functions.spec.js; actions/choices.spec.js (its choices are placeholders)
src/lib/types/Action.ts, src/lib/types/index.ts StaticAction, ActionInstance, ActionApplyResult, ActionRevertResult, ActionRunContext, GlobalsMap none (types)

How it works

The mount: from init() to the main screen

js/main.js in the starter game calls monogatari.init('#monogatari') once the page is ready. Everything the engine knows about actions has to be registered before that call: init() mounts the actions in the list at that moment and never looks for late ones.

flowchart TD main["js/main.js: monogatari.init('#monogatari')"] --> registry["_setupRegistry(), then the willInit event"] registry --> storage["setupStorage(), if Storage has no name yet"] storage --> setup["setup(): read the 'Settings' key into the preferences"] setup --> define["Registry.register() every component"] define --> sw["Register service-worker.js (ServiceWorkers setting)"] sw --> listeners["Save storageStructure; register the start, open-screen,<br/>dismiss-alert, distraction-free, skip and auto-play listeners"] listeners --> setups["Every component's and action's setup(), in parallel;<br/>each action gets its engine reference here"] setups --> bind["bind(): the data-action click handler, the right, space, esc,<br/>shift+s and shift+l keys, every component's and action's bind(),<br/>then the keys of every listener registered so far"] bind --> init["Localize the page, set state.label from the Label setting,<br/>start the autosave interval, every component's and action's init()"] init --> initial{"MultiLanguage and LanguageSelectionScreen<br/>on a first run?"} initial -- yes --> language["Show the language selection screen"] initial -- no --> display["displayInitialScreen(): preload(), then the splash label,<br/>the main screen, or the game itself"]

What each step guarantees, in order:

  1. init() stores the selector, turns on ExperimentalFeatures when window.Cypress exists (so the specs always run with experimental actions on), calls _setupRegistry() (Errors and the Debug Module), and triggers willInit. It creates the Storage space with setupStorage() if nothing configured one (Saving and Loading).
  2. setup() first reads the player’s preferences from the Settings key. Only then does it define the components with Pandora’s Registry.register() (Components and Screens), register the service worker, save storageStructure (the storage as the game declared it, as JSON, so resetGame() can put it back), and register the engine’s own listeners. Last, it calls the static setup() of every component and every action in actions(), all at once, and sets the global _didSetup. That loop is also where each built-in action gets action.engine. A failure anywhere in setup() is caught and printed as Initialization error, and init() goes on.
  3. bind() adds the handlers that turn the player’s input into calls (next section), applies ForceAspectRatio, and calls every component’s and action’s static bind(selector). After those, it binds the keys of every listener registered so far, and sets _didBind.
  4. The init phase creates the ambient audio player, localizes every data-string element, sets state.label from the Label setting, shows the orientation warning if needed, starts the autosave interval when AutoSave is above 0, and awaits every component’s and action’s static init(selector). It sets _didInit and triggers didInit.
  5. displayInitialScreen() (in src/engine/ui.ts) runs preload() (Media and Assets). When it settles, failed or not, it checks that the start label exists (or shows engine:script:label_not_found) and calls showSplashScreen(): when a label named like the SplashScreenLabel setting exists, it plays that label on the game screen. Otherwise showMainScreen() opens the main screen, or, with ShowMainScreen: false, starts the game at once.

The game starts for real when the player presses Start: the start listener sets playing, calls onStart() on every component and action, closes every screen, opens the game screen, and runs the statement at state.label and state.step with run().

The engine triggers an event around each phase (willInit, willSetup, didSetup, willBind, didBind, didInit). Events lists them all.

Matching: prepareAction()

prepareAction(engine, statement, { cycle, extras }) finds the action that takes a statement and builds an instance of it, without running anything.

flowchart TD statement(["A statement"]) --> kind{"Its type?"} kind -- "string" --> interp["replaceVariables(): _(Key) translations,<br/>then {{name}} from storage"] interp --> split["split(' '): an array of words"] split --> strings{"Next action in actions():<br/>matchString(words)?"} strings -- no --> strings strings -- yes --> build["new Action(words)"] kind -- "object" --> objects{"Next action in actions():<br/>matchObject(statement)?"} objects -- no --> objects objects -- yes --> buildObject["new Action(statement)"] kind -- "function" --> none["null: run() calls the function itself"] build --> record["_setStatement(statement), _setCycle(cycle),<br/>setContext(engine), setExtras(extras)"] buildObject --> record
  • A string is interpolated first with engine.replaceVariables(): _(Key) becomes the translation and {{name}} the value in storage (Translations and Strings). Then it is split at every single space, split(' '), and actions().find() asks each action’s static matchString(words) in order. The first true wins.
  • An object goes to each action’s static matchObject(statement). Every object action in v2 looks for its key: Choice, Conditional, Function, Input.
  • A function matches nothing, and run() handles it itself.

actions() is _actions without the actions marked _experimental, unless the ExperimentalFeatures setting is on. The two experimental actions in 2.9.0 are Show::Character::Layer and Hide::Character::Layer. The static match() the base class declares is never called, and is marked @deprecated.

The order of _actions in src/index.ts is the order of precedence:

Canvas, Choice, Clear, Conditional, End, Function, Gallery, Hide::Canvas, Hide::Character,
Hide::Character::Layer, Hide::Image, Hide::Particles, Hide::TextBox, Hide::Video, Input, Jump,
Message, Next, Notification, Particles, Pause, Play, Placeholder, Preload, Scene,
Show::Background, Show::Character, Show::Character::Layer, Show::Image, Show::TextBox, Stop,
Unload, Vibrate, Video, Wait, Dialog

Those are the ids; the files have class names (Notify.ts is Notification, InputModal.ts is Input). Dialog.matchString() returns true for anything, so it must stay last: a string no other action takes becomes a line of dialog. Most matchers only compare the first one or two words, and they are case-sensitive.

Once an action matched, prepareAction() calls its constructor with the words (strings) or the object, then records the statement as written (_statement), the cycle ('Application' to run, 'Revert' to roll back), the engine as the deprecated context, and the extras object.

prepareAction() is not only used by run(). revert() builds the previous statement’s action with the 'Revert' cycle, Placeholder builds the action of the statement it stands for, and Choice builds its Dialog line directly. A constructor can’t know which of these called it.

One statement’s run: run()

run(engine, statement, shouldAdvance = true) in src/engine/lifecycle.ts runs one statement and resolves with { advance }. It first records initialStep and initialLabel, the position it started at.

sequenceDiagram participant Caller as next() or a caller participant Run as run() participant All as every registered action participant Prep as prepareAction() participant Act as the action instance Caller->>Run: run(statement, shouldAdvance) Run->>All: beforeRun({ advance: shouldAdvance }) Run->>Prep: prepareAction(statement, { cycle: 'Application' }) Prep-->>Run: instance, or null (throws "did not match") Run->>Run: trigger willRunAction { action } Run->>Act: willApply() Note over Run,Act: a throw stops the run, is reported and rethrown Run->>Act: apply() Run->>Act: didApply() Act-->>Run: { advance } Run->>Run: trigger didRunAction { action } Run->>All: afterRun({ advance }) alt advance and shouldAdvance and still at initialLabel / initialStep Run->>Caller: await engine.next() else Run-->>Caller: { advance }: the game waits end

In order:

  1. beforeRun() on every registered action. It is a broadcast, not a call on the action that will run: every action in actions() gets it, for every statement. Conditional uses it to clean up its rollback bookkeeping.
  2. A null statement throws Statement was null.; an undefined one (a label with no statement at this step, like an empty label after a jump) shows engine:script:label_ended and throws.
  3. A function runs with the engine as this through Artemis’ Util.callAsync(), which awaits it if it returns a promise. While it runs, the deprecated global block is true. If it returns anything but false and the position didn’t change meanwhile, the run calls engine.next(); false leaves the game waiting for the player. If it throws, block is cleared, the debug module shows engine:run:function_error and the run resolves with { advance: false }.
  4. prepareAction(), then the willRunAction event with { action } as its detail. prepareAction() puts the statement and the cycle in the action class’s _preparing while the constructor runs, so the base Action constructor sets this._statement and this._cycle before a subclass’s constructor body reads them. An object statement no action matches shows engine:run:no_action and throws.
  5. willApply(), apply(), didApply(), each awaited. A throw in any of them (or in the constructor) is logged, reported and rethrown: the run rejects, and nothing after it happens. Throwing from willApply() is how an action refuses a statement, usually after showing its own error (Jump does it for a label that doesn’t exist). So the report, engine:run:statement_failed, only opens when no other error dialog opened while the statement ran: run() counts the open [data-error] dialogs and FancyError.queue when it starts.
  6. didApply() returns { advance }. A result that isn’t an object counts as { advance: false }, with a warning on the console. The didRunAction event fires, then afterRun({ advance }) on every action.

When the statement is the one at the current position (label[step] is the statement itself, not a choice’s Do or a sub-action), run() also records whether it failed, in a set of failed positions ("label::step") kept per engine in src/engine/lifecycle.ts. A later success at the same position removes it. Going back uses the set. 7. Advancing. When advance is true, the caller allowed it (shouldAdvance), and the state is still at initialLabel and initialStep, the run awaits engine.next(). The position check is there because an action can await something long (a notification’s permission prompt) while the player clicks ahead.

So a statement that advances on its own (next, wait 500, show scene, a function) holds its run open until the next one settles, and a chain of them resolves from the inside out.

Moving forward: next()

next(engine) adds one to state.step and runs the statement at the new position, from a setTimeout(…, 0). The timer empties the call stack between statements: a long chain of statements that advance on their own would otherwise overflow it (commit c81a3760, “Prevent stack overflows”).

Whether the run resolves or rejects, next() sets the global _engine_block back to false and resolves. That matters, because proceed() is what set it (next section), and a game whose _engine_block stayed true could neither proceed nor roll back. A failed statement is reported by run(), so next() only releases the lock: the step stays at the failed statement, and the next click runs the one after it.

Before it moves, next() checks the end of the label. When the next step would be past the last statement, it shows engine:script:label_ended, releases the lock and stays where it is, so the game keeps showing the last statement and Back still works. Every label should end in end or jump.

Going back over a failed statement

revert() undoes label[step - 1]. When that position is in the set of failed positions, the statement never finished applying, and its revert() would fail or undo something else (a Jump that never moved would pop the history of an earlier jump). So revert() steps over it: it calls afterRevert() on every action, moves step back, and reverts the statement before it, as an action that returns { advance: true, step: true } would. A failed first statement of the game (step 0, with no jump into its label) has nothing before it, so revert() leaves the game where it is.

The player moves the game: proceed()

Everything that moves the game forward at the player’s request goes through proceed(engine, { userInitiated, skip, autoPlay }):

Caller How Options
A click on the game screen GameScreen.bind(): any element inside [data-screen="game"] that isn’t a data-choice, data-action or data-delete element, nor inside one userInitiated: true
The right arrow and space keys keyboardShortcut(['right', 'space']) in bind() userInitiated: true
Auto-play the timer in autoPlay() autoPlay: true
Skip the timer in skip(), only while the game screen is visible and playing is set skip: true
Actions Message when the player closes it, Input once the player’s answer passes its Validation function and Save has run, Video when a video that should advance ends userInitiated: true (Video: all false)

proceed() awaits shouldProceed(), sets _engine_block to true, awaits willProceed(), then calls next(). The checks are asynchronous, so between the first check and setting the lock the engine is marked as checking (a WeakSet in lifecycle.ts): a second proceed() or rollback() in that moment throws Another proceed or rollback is being checked., and a double click moves the game once. When willProceed() rejects, proceed() clears _engine_block, shows engine:lifecycle:will_proceed_error and rethrows. rollback() does the same around shouldRollback() and willRollback().

shouldProceed() refuses (rejects with Extra condition check failed.) at once if any of these holds:

  • an element with the class modal is visible (an alert, a message, the debug module’s error dialog);
  • distraction_free is set (the player hid the text box with Hide or h);
  • the deprecated block or _executing_sub_action globals are set;
  • _engine_block is set: a proceed is still running.

Otherwise it calls every action’s static shouldProceed(options) and every component’s, and rejects if any of them rejects. The ones that refuse in 2.9.0:

  • Dialog while the type-writer is still typing: it finishes the text (stopTyping()) and refuses, so the first click completes the line and the second moves on (Text and the Type-Writer);
  • Choice, Conditional, Input, Message, Video and Wait while their static blocking is true (Notification has the same check, but since 2.9.0 never sets the flag: it doesn’t wait for the permission question);
  • the game-screen component while the game screen is hidden;
  • the instances of choice-container, message-modal and text-input while they are on screen (the base Component.shouldProceed() asks every instance).

willProceed() calls every action’s and component’s willProceed(). Dialog removes a centered dialog there.

With the debug level at 4 or above (the starter game’s js/main.js sets 5), the console shows one collapsed group per check, shouldProceed Check, with an OK or FAIL line for every action and component, and Run Cycle [Wait] around each run. That’s the first place to look when a click does nothing (Debugging the Engine).

Waiting for the player: blocking

An action that must hold the game until the player does something (pick a choice, close a message, wait out a timer) keeps a static flag and refuses in its static shouldProceed() while it’s set:

static override async shouldProceed(): Promise<void> {
  if (Choice.blocking) {
    throw new Error ('Choice is waiting for input');
  }
}

The flag is static because there is one engine per page and the engine only asks the class. The action sets it in apply(), returns { advance: false } from didApply(), and clears it when the player acts: Choice’s [data-choice] click handler runs the chosen option’s Do statement and clears the flag once that run settles, and Message clears it and calls proceed() when the player closes the message. Each also clears it in willRollback(), so going back isn’t blocked by something the rollback removes. Before commit 14494a78 (December 2025), actions set the shared globals block and _executing_sub_action instead; those are deprecated and nothing in 2.9.0 sets _executing_sub_action any more.

Statements inside statements

Choice, Conditional and Placeholder run statements nested in their own:

  • Conditional calls its Condition function (with the engine as this) in pickBranch(), then await engine.run(branch) on the branch it returned: True for true, False for false, the branch named by a string, or '0', '1'… for a whole number. A branch it doesn’t have runs 'next' instead. Its didApply() always returns { advance: false }: the branch’s own run already advanced if it wanted to. Only an error in the Condition picks False; an error in the branch it ran fails the Conditional like any statement.
  • Choice builds its Dialog line with prepareAction() and drives its life cycle directly, then puts a choice-container on screen. When the player clicks an option, its handler calls the option’s onChosen function, if any, then engine.run(option.Do) ('next' when the Do isn’t text), then records the pick in history('choice') and history('choiceOutcome'). With every option hidden, didApply() returns { advance: true } and the menu never shows.
  • Placeholder ($ name) takes the statement saved with monogatari.$('name', statement), builds its action with prepareAction(), and forwards willApply(), apply() and didApply() to it. A name starting with _ is a function: it is called with the remaining words as arguments, and what it returns is the statement.

Jump works differently: its apply() records the jump in the jump history, sets state to the new label at step 0, and calls engine.run() on its first statement without awaiting it. Its own didApply() returns { advance: false }.

All of these call engine.run(). v2 has no separate call for nested statements: nothing marks them, and how they are undone is each action’s own business in revert() (State, Storage and Rollback).

Listeners and keys

A listener is a named callback in engine._listeners. registerListener(name, { keys, callback }, replace) adds one; with replace: true it replaces the first one with that name instead. runListener(name, event, element) runs every listener with that name (there can be several), each through Util.callAsync() with the engine as this.

Two things run listeners:

  • Clicks on data-action elements. The handler bind() installs on the visual-novel element stops the click from bubbling (so it never reaches the game screen’s proceed handler) and calls runListener(element.data('action'), event, element). A click on an icon’s inner path is redirected to the nearest [data-action] (a fix for Font Awesome’s SVG icons).
  • Keys. A listener with keys (a Mousetrap combination such as 'shift+q') is bound with keyboardShortcut(): in bind() for the listeners registered by then, or at once for a listener registered after _didBind. Keys pressed inside an input element are ignored.

If a callback returns a falsy value, runListener() stops the event’s propagation and calls preventDefault(). The built-in listeners return nothing, so their clicks stop there.

The listeners 2.9.0 registers:

Listener Registered in Key
start, open-screen, dismiss-alert, auto-play setup() in src/monogatari.ts none
distraction-free, skip setup() in src/monogatari.ts h, s
back GameScreen.bind(), only when AllowRollback is on left arrow
end, quit End.bind() Shift+q for end
jump Jump.bind(): runs jump to the label in the element’s data-jump none
set-volume Play.bind() none
save, overwrite-slot, delete-slot, dialog-log the save screen, slot container, save slot and dialog log components none

Esc (settings), Shift+s (save) and Shift+l (load) are plain shortcuts bound in bind(), not listeners.

Auto-play, skip and distraction-free

These live in src/engine/ui.ts and only call proceed() on a timer:

  • autoPlay(true) stores a timer function in the global _auto_play_timer and schedules it every AutoPlaySpeed seconds (a preference), correcting for drift. Each tick calls proceed({ autoPlay: true }) and schedules the next one whether the proceed passed or was refused, so auto-play waits through choices without stopping. The auto-play listener toggles it.
  • skip(true) works only when the Skip setting is above 0: it schedules proceed({ skip: true }) every Skip milliseconds and stores the timeout in the global skip. The quick menu removes its Skip button in QuickMenu.init() when Skip is 0.
  • distractionFree() hides the text box, makes the quick menu transparent, and sets distraction_free, which makes shouldProceed() refuse until the player shows the text box again.

Opening any screen with showScreen() turns auto-play and skip off.

The data

The statics the engine reads from an action class, from StaticAction in src/lib/types/Action.ts (doc comments removed):

export interface StaticAction {
  id: string;
  _experimental: boolean;
  _configuration: Configuration;
  loadingOrder: number;
  blocking: boolean;
  engine: VisualNovelEngine;

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

  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>;
  reset: (options?: unknown) => Promise<void>;

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

  match: (statement: unknown) => boolean;
  matchString: (statement: string[]) => boolean;
  matchObject: (statement: Record<string, unknown>) => boolean;

  beforeRun: (context: ActionRunContext) => Promise<void>;
  afterRun: (context: ActionRunContext) => Promise<void>;
  beforeRevert: (context: ActionRevertContext) => Promise<void>;
  afterRevert: (context: ActionRevertContext) => Promise<void>;

  new (...args: any[]): ActionInstance;
}

What an instance carries, from ActionInstance in the same file:

export interface ActionInstance {
  _statement: string | string[] | Record<string, unknown> | ((...args: unknown[]) => unknown) | undefined;
  _cycle: 'Application' | 'Revert' | undefined;
  _extras: Record<string, unknown> | undefined;
  context: VisualNovelEngine | undefined;
  engine: VisualNovelEngine;

  setContext: (context: VisualNovelEngine) => void;
  _setStatement: (statement: string | Record<string, unknown> | ((...args: unknown[]) => unknown)) => void;
  _setCycle: (cycle: 'Application' | 'Revert') => void;
  setExtras: (extras: Record<string, unknown>) => Record<string, unknown>;

  willApply: () => Promise<void>;
  apply: (options?: { updateLog?: boolean; updateHistory?: boolean; updateState?: boolean }) => Promise<void>;
  didApply: (options?: { updateHistory?: boolean; updateState?: boolean }) => Promise<ActionApplyResult>;

  willRevert: () => Promise<void>;
  revert: () => Promise<void>;
  didRevert: () => Promise<ActionRevertResult>;

  interrupt: () => Promise<void>;
}

The instance’s engine is a getter that returns the class’s static engine; setting it throws.

What the life cycle passes around, from src/lib/types/index.ts:

export interface ActionApplyResult {
  advance?: boolean;
}

export interface ActionRevertResult {
  advance: boolean;
  step: boolean;
}

export interface ActionRunContext {
  advance: boolean;
}

export interface ActionRevertContext {
  advance: boolean;
  step: boolean;
}

The globals this subsystem reads and writes, from GlobalsMap in the same file (the rest of the map belongs to other pages):

export interface GlobalsMap {
  playing: boolean;

  /** @deprecated Each action should use its `blocking` attribute */
  block: boolean;

  distraction_free: boolean;
  on_splash_screen: boolean;
  _engine_block: boolean;

  /** @deprecated Each action should use its `blocking` attribute */
  _executing_sub_action: boolean;

  _didSetup: boolean;
  _didBind: boolean;
  _didInit: boolean;
  _first_run: boolean;
  _auto_play_timer: ReturnType<typeof setTimeout> | (() => void) | null;
  skip: ReturnType<typeof setTimeout> | null;

  // …
}

A listener, as engine._listeners stores it (src/monogatari.ts):

{ name: string; keys?: string | string[]; callback: (this: VisualNovelEngine, event: Event, element: DOM) => unknown }

NOTE

global(key) returns this._globals?.[key] ?? undefined: a global holding null reads back as undefined. Compare globals with a truthiness check, never with === null. The skip toggle got this wrong (pitfalls).

Rules and why

  • Dialog stays last in _actions. It matches every string, so anything after it can never take a string statement. registerAction(action, true) appends, which puts a game’s action after Dialog.
  • Order decides, so place a new action by its words. The first action whose matcher says yes wins. A new built-in must come before every action that would also take its statements, and its matcher must not take statements that belong to an action placed after it. ShowCharacter and ShowCharacterLayer split show character between them by checking for a : in the third word.
  • Matchers are cheap, pure, and read only the words they need. They run for every string the engine runs (and every one a rollback reverts), against every action until one matches. A matcher that calls a method on a word that isn’t there throws, and the statement fails: show character with no name throws in ShowCharacter.matchString().
  • Constructors only read. prepareAction() builds an instance for running, for reverting, and from inside Choice and Placeholder. Doing work in the constructor (DOM, state, error dialogs) does it at the wrong time. Do it in willApply() or apply().
  • didApply() returns an object. run() destructures { advance } from it. An override that returns nothing throws a TypeError that leaves the game stuck.
  • Never wait for the player inside apply(). run() awaits apply(), and when the run came from proceed(), _engine_block stays set until it resolves: the player can’t proceed or go back meanwhile. Return from apply(), set a static blocking flag, refuse in shouldProceed(), and continue from the player’s event.
  • Whatever a statement puts on screen, it removes on rollback. A rollback reverts the statement before the current one, never the current one. A button or a timer the current statement added has to go in a static willRollback() (as Wait and Choice clear their flags, and choice-container removes itself).
  • Register before init(). init() mounts the actions in the list at that moment. An action registered later gets an engine reference from registerAction(), but its setup(), bind() and init() never run.
  • Built-ins get engine in setup(). Code that builds a built-in action before the engine’s setup finished (a test that runs right after the page loads) fails inside the constructor with Cannot read properties of undefined.

How to make the common changes

Add a built-in action

  1. Create src/actions/Ring.ts. Start from the closest real action: Next.ts for one that advances, Wait.ts for one that blocks, ShowImage.ts for one that shows something and has to undo it.

    import { ActionApplyResult, ActionRevertResult } from '../lib/types';
    import Action from './../lib/Action';
    
    export class Ring extends Action {
      static override id = 'Ring';
    
      static override matchString([action]: string[]): boolean {
        return action === 'ring';
      }
    
      sound: string;
    
      constructor([action, sound]: string[]) {
        super();
        this.sound = sound;
      }
    
      override async apply(): Promise<void> {
        // The work: elements, media, state
      }
    
      override async didApply(): Promise<ActionApplyResult> {
        return { advance: true };
      }
    
      override async didRevert(): Promise<ActionRevertResult> {
        return { advance: true, step: true };
      }
    }
    
    export default Ring;
  2. Import it in src/index.ts and add it to Monogatari._actions, before Dialog and before any action whose matcher would take its statements (the list is roughly alphabetical; the position is what counts).

  3. Write its revert() and decide its { advance, step } (State, Storage and Rollback), and its onLoad() if it shows something a load must restore (Saving and Loading).

  4. Add cypress/e2e/actions/ring.spec.js, written like next.spec.js: run it forward, roll it back, and save and load if it keeps state (Testing).

  5. Run bun run build (lint, type check and build) and commit the rebuilt dist/engine/core/monogatari.js with the source (Building and Packaging).

  6. Write its page in docs/script-actions/.

Register a game’s action without a build

A game adds actions from its own files, before init(): in js/script.js, or in js/main.js above the $_ready call.

class Ring extends Monogatari.Action {
  static id = 'Ring';

  static matchString([action]) {
    return action === 'ring';
  }

  async didApply() {
    return { advance: true };
  }
}

monogatari.registerAction(Ring);

registerAction(action) puts the action at the front of the list, ahead of every built-in: it can take statements that start with a built-in’s keyword. Extending Monogatari covers this from the game developer’s side.

Put an action before Dialog but behind the built-ins

There is no position argument for “before Dialog”. Take Dialog out and put it back after:

const dialog = monogatari.action('Dialog');

monogatari.unregisterAction('Dialog');
monogatari.registerAction(Ring, true);
monogatari.registerAction(dialog, true);

unregisterAction(id) removes every action with that id, compared without case. Exercise 1 checks all three placements.

Add a button that does something

Register a listener and give an element its name in data-action:

monogatari.registerListener('ring-bell', {
  keys: 'b',
  callback() {
    this.run('ring bell', false);
  },
});
<button data-action="ring-bell">Ring</button>

The click never reaches the game screen, so it doesn’t advance the game. run(statement, false) runs the statement without letting it advance; Jump’s jump listener does the same.

Make an action wait for the player

Set a static flag in apply(), refuse in shouldProceed(), clear the flag and remove what you added in willRollback(), and continue from the player’s event with proceed(). Exercise 2 builds one.

Pitfalls and history

  • Lowercase dialog that starts with a keyword isn’t dialog. 'next time, then.' is taken by Next and skipped; 'wait for me' is a Wait that leaves the previous line on screen and waits for a click; 'end of the line' ends the game. Matchers are case-sensitive, so 'Next time, then.' is dialog. Game developers hit this; it is the order of precedence working as designed.
  • Two spaces turn a statement into dialog. split(' ') keeps empty words, so 'show scene #224466' is ['show', '', 'scene', '', '#224466']: no matcher takes it, and Dialog shows it as text.
  • A failed statement locked the game until 2.9.0. next() didn’t clear _engine_block when the run rejected, so any statement that proceed() started and that threw (a jump to a label that doesn’t exist, a label without end, a custom didApply() that forgot to return) left clicks and Back doing nothing. A function statement that threw did the same through block, which run() only cleared when the function succeeded; actions/functions.spec.js checked that the error showed, not that the game went on, which is why it was missed. Exercise 4 rebuilds that fix on the v2.8.1 tag; engine/failed-statements.spec.js covers every case now.
  • The Skip button and the s key never turned skipping on, until 2.9.0. The skip listener in setup() checked this.global('skip') !== null, but since the TypeScript migration (bbc0c637, December 2025) global() returns undefined for null, so the listener always called skip(false). A global that holds null reads as undefined, so never compare one with null: the auto-play listener compares with undefined, and the fixed skip listener checks truthiness. Exercise 3 rebuilds the fix on the v2.8.1 tag.
  • Stopping auto-play let one more statement through, until 2.9.0. autoPlay(true) stored the timer function in _auto_play_timer, and autoPlay(false) passed that function to clearTimeout(), which ignored it, so the pending tick still fired once. The function stays in _auto_play_timer (games read it to know auto-play is on); the timeout id now lives in a WeakMap in src/engine/ui.ts, and a tick only schedules the next one while _auto_play_timer still holds its own function.
  • A button on the game screen could advance the game, until 2.9.0. The game screen’s click listener is delegated with [data-screen="game"] *:not([data-action])…, and Artemis calls it with the closest element that matches. For a click on the button itself, that’s the button’s parent, which isn’t inside a data-action element, so the game advanced unless the engine’s own data-action listener stopped the event first (only for a real click whose listener returned something falsy). The listener now checks the element that was clicked.
  • onStart() only runs from the Start button. With ShowMainScreen: false (or a game started some other way), showMainScreen() runs the first statement without calling onStart(). No built-in action implements onStart(), so nothing in the engine notices.
  • Hooks the engine never calls. interrupt() and the static match() are declared in Action.ts and described in the old docs, but no code calls them; 2.9.0 marks both @deprecated rather than removing them in a minor release. onSave() was in the same list until 2.9.0, which calls it after every save. monogatari.fn() stores functions in _functions that nothing reads.
  • Replacing a listener doesn’t rebind its key. registerListener(name, listener, true) swaps the entry in _listeners and returns, but Mousetrap still holds the old callback. After init(), a replaced distraction-free runs the new callback on a click and the old one on h. Unregister it (which unbinds the key) and register it again instead.
  • The type comment of registerAction() was backwards until 2.9.0: src/lib/types/Monogatari.ts said naturalPosition: true inserts “at natural priority position” and false appends. The code does the opposite: true appends (after Dialog), false prepends.
  • The specs run with experimental actions on, games don’t. init() turns ExperimentalFeatures on under Cypress, and the starter game’s js/options.js sets it to false. In a real game, show character y:body happy is a line of dialog, because Show::Character::Layer is filtered out of actions().
  • Conditional swallowed its branch’s errors until 2.9.0. Its apply() wrapped everything in one try, so a True branch that failed (a jump to a missing label) ran the False branch as well, after the error dialog.
  • Statements were changed in place until 2.9.0: Choice.apply() wrote _key into each option of the script’s own object, Input’s constructor filled in its defaults, and Function.willApply() copied a v1 Reverse into Revert. The three actions work on copies now. Nothing freezes statements in v2, so a new action must not write into its statement either.
  • How the code got here. The setTimeout in next() came with c81a3760 (2018, “Prevent stack overflows”); _engine_block with 49760ac1 (2019); beforeRun, afterRun, beforeRevert and afterRevert with d2aff1d8 (2020); a function’s false return as the advance signal with 66b87239 (2020); the per-action blocking flags replaced the shared block global in 14494a78 (December 2025); the position check in run() arrived with 0d2e4b12 (March 2026), and eb1ea6bf (“Split the engine”, March 2026) moved this code from src/monogatari.ts into src/engine/lifecycle.ts, input.ts and ui.ts. 88425293 (March 2026) made data-action clicks stop bubbling and taught the game screen to ignore clicks inside data-action and data-delete elements, so a button on the game screen no longer advances the game (except for a click on the button itself, until 2.9.0, as the pitfall above explains).

Exercises

Each exercise ends in a Cypress spec. Work in a scratch copy of the repository (How Each Part Works), put the spec in cypress/e2e/exercises/, run it, and delete it when you’re done:

bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/action-order.spec.js'

Exercises 3 and 4 change src/. Cypress loads dist/index.html, which loads the built bundle, so rebuild it before running the spec, and put both back afterwards:

bun build.ts --browser
git checkout -- src dist/engine/core

Testing explains the custom commands (cy.open(), cy.start(), cy.proceed(), cy.rollback()) and why every test is a function () {}.

Exercise 1: decide who takes a statement

What to do. Write a game action Bell that matches bell … and wait bell …. Register it three ways: at the front, at the end, and right before Dialog but behind the built-ins. For each, find out which action takes bell and which takes wait bell.

Hint. registerAction() takes a second argument. monogatari.prepareAction(statement, { cycle: 'Application' }) builds the action a statement goes to without running it; its constructor.id names it. Wait for init() to finish before you build anything.

Check. At the front, Bell takes both. At the end, Dialog takes bell and Wait takes wait bell. Right before Dialog, Bell takes bell, Wait still takes wait bell, and Hello there. is still Dialog’s.

Solution

cypress/e2e/exercises/action-order.spec.js:

context ('Exercise: who takes a statement', function() {

  beforeEach(() => {
    cy.open();

    // The built-in actions get their engine reference in setup (), so wait for init () to finish
    cy.get ('@monogatari').invoke ('global', '_didInit').should ('equal', true);
  });

  // Matches "bell …" and "wait bell …"
  const defineBell = (win) => {
    return class Bell extends win.Monogatari.Action {
      static id = 'Bell';

      static matchString([first, second]) {
        return first === 'bell' || (first === 'wait' && second === 'bell');
      }

      async didApply() {
        return { advance: true };
      }
    };
  };

  const takenBy = (engine, statement) => {
    return engine.prepareAction(statement, { cycle: 'Application' }).constructor.id;
  };

  it ('Takes both statements when registered at the front', function() {
    cy.window().then((win) => {
      this.monogatari.registerAction(defineBell(win));

      expect(takenBy(this.monogatari, 'bell')).to.equal ('Bell');
      expect(takenBy(this.monogatari, 'wait bell')).to.equal ('Bell');
    });
  });

  it ('Takes no string at all when registered at the end', function() {
    cy.window().then((win) => {
      this.monogatari.registerAction(defineBell(win), true);

      expect(takenBy(this.monogatari, 'bell')).to.equal ('Dialog');
      expect(takenBy(this.monogatari, 'wait bell')).to.equal ('Wait');
    });
  });

  it ('Loses only to the built-ins when placed right before Dialog', function() {
    cy.window().then((win) => {
      const dialog = this.monogatari.action ('Dialog');

      this.monogatari.unregisterAction ('Dialog');
      this.monogatari.registerAction(defineBell(win), true);
      this.monogatari.registerAction(dialog, true);

      expect(takenBy(this.monogatari, 'bell')).to.equal ('Bell');
      expect(takenBy(this.monogatari, 'wait bell')).to.equal ('Wait');
      expect(takenBy(this.monogatari, 'Hello there.')).to.equal ('Dialog');
    });
  });
});

The class extends the page’s Monogatari.Action (win.Monogatari), not a class from the spec’s own window. Without the _didInit wait, the second test fails inside Dialog’s constructor: the spec runs before setup() gave Dialog its engine.

Exercise 2: hold the game until the player acts

What to do. Write a gate statement that puts an Open the gate button on the game screen and holds the game until the player clicks it. A click anywhere else must not advance. Going back from the gate must remove the button.

Hint. Read Wait.ts: a static blocking flag and a static shouldProceed() that throws while it’s set. Give the button a data-action and register a listener for it, so its click doesn’t reach the game screen. A rollback never reverts the statement on screen: clean up in willRollback().

Check. After the gate runs, cy.proceed() leaves the game on the line before it, at step 1. Clicking the button removes it and shows the next line. Rolling back from the gate removes the button and shows the line before it again. Remove shouldProceed() and willRollback() and both tests fail.

Solution

cypress/e2e/exercises/gate.spec.js:

context ('Exercise: an action that holds the game', function() {

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

  const defineGate = (win) => {
    class Gate extends win.Monogatari.Action {
      static id = 'Gate';

      static blocking = false;

      static matchString([action]) {
        return action === 'gate';
      }

      static async shouldProceed() {
        if (Gate.blocking) {
          throw new Error ('The gate is closed.');
        }
      }

      static async willRollback() {
        Gate.blocking = false;
        this.engine.element().find ('[data-gate]').remove();
      }

      async apply() {
        const button = win.document.createElement ('button');

        button.dataset.gate = '';
        button.dataset.action = 'open-gate';
        button.textContent = 'Open the gate';
        button.style.cssText = 'position: absolute; top: 40%; left: 50%; transform: translateX(-50%); z-index: 10;';

        this.engine.element().find ('[data-screen="game"]').append(button);
        Gate.blocking = true;
      }

      async didApply() {
        return { advance: false };
      }
    }

    return Gate;
  };

  it ('Holds the game until the gate is opened', function() {
    cy.window().then((win) => {
      const Gate = defineGate(win);

      this.monogatari.registerAction(Gate);
      this.monogatari.registerListener ('open-gate', {
        callback: () => {
          this.monogatari.element().find ('[data-gate]').remove();
          Gate.blocking = false;
          this.monogatari.proceed({ userInitiated: true, skip: false, autoPlay: false });
        }
      });
    });

    this.monogatari.setting ('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'Before the gate.',
        'gate',
        'Through the gate.',
        'end'
      ]
    });

    cy.start();
    cy.get ('text-box').contains ('Before the gate.');
    cy.proceed();
    cy.get ('[data-gate]').should ('be.visible');

    // A click anywhere else is refused while the gate is closed
    cy.proceed();
    cy.get ('text-box').contains ('Before the gate.');
    cy.get ('@monogatari').invoke ('state', 'step').should ('equal', 1);

    cy.get ('[data-gate]').click();
    cy.get ('[data-gate]').should ('not.exist');
    cy.get ('text-box').contains ('Through the gate.');
  });

  it ('Clears the gate when the player goes back', function() {
    cy.window().then((win) => {
      this.monogatari.registerAction(defineGate(win));
    });

    this.monogatari.setting ('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'Before the gate.',
        'gate',
        'Through the gate.',
        'end'
      ]
    });

    cy.start();
    cy.proceed();
    cy.get ('[data-gate]').should ('be.visible');
    cy.rollback();
    cy.get ('[data-gate]').should ('not.exist');
    cy.get ('text-box').contains ('Before the gate.');
    cy.get ('@monogatari').invoke ('state', 'step').should ('equal', 0);
    cy.proceed();
    cy.get ('[data-gate]').should ('be.visible');
  });
});

The inline style keeps the button above the particles layer and clear of the quick menu, where Cypress could click it. The listener clears the flag before it calls proceed(), or Gate.shouldProceed() would refuse its own click. Going back from the gate reverts 'Before the gate.' (the statement before it), and willRollback() is the only hook that runs for the gate itself.

Exercise 3: make the skip toggle work

This exercise fixes a 2.8.1 bug that 2.9.0 fixed, so make the scratch copy from the tag: git worktree add --detach ../monogatari-exercises v2.8.1.

What to do. In a game with Skip above 0, the quick menu’s Skip button and the s key should turn skipping on, and pressing them again should turn it off. Find why they don’t in 2.8.1, and fix it.

Hint. Both run the skip listener registered in setup() in src/monogatari.ts. Compare what it checks with what global() returns for a global that holds null, and with how the auto-play listener next to it checks its timer.

Check. The spec below fails on an unchanged 2.8.1 (the text never reaches Four.). With your fix and the bundle rebuilt, it passes.

Solution

The listener compares with null, and global('skip') returns undefined when the global holds null, so the first branch always runs. Check the value’s truthiness instead (a running skip holds a timeout id, which is never 0 in a browser):

       this.registerListener ('skip', {
         keys: 's',
         callback: () => {
           if (this.global ('playing')) {
-            if (this.global ('skip') !== null) {
+            if (this.global ('skip')) {
               this.skip (false);
             } else {
               this.skip (true);
             }
           }
         }
       });

cypress/e2e/exercises/skip-toggle.spec.js:

context('Exercise: the skip toggle', () => {
  beforeEach(() => {
    cy.open();
    cy.get('@monogatari').invoke('global', '_didInit').should('equal', true);
  });

  it('Turns skipping on and off with the s key', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.setting('Skip', 100);
    this.monogatari.script({
      'Start': [
        'One.',
        'Two.',
        'Three.',
        'Four.',
        'Five.',
        'Six.',
        'Seven.',
        'Eight.',
        'end',
      ],
    });

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

    cy.get('body').type('s');
    cy.get('text-box').contains('Four.');

    cy.get('body').type('s');
    cy.get('@monogatari').invoke('global', 'skip').should('equal', undefined);

    cy.get('@monogatari').invoke('state', 'step').then((step) => {
      cy.wait(500);
      cy.get('@monogatari').invoke('state', 'step').should('equal', step);
    });
  });
});

The spec presses the key because the starter game’s Skip is 0 when the quick menu initializes, so its Skip button isn’t there; the button runs the same listener. Run actions/next.spec.js, actions/wait.spec.js and actions/choices.spec.js too: they pass with the fix. 2.9.0 has the same fix in src/monogatari.ts, and engine/skip-and-auto-play.spec.js tests the button too, by changing the Skip setting before the engine starts.

Exercise 4: let the game go on after a function fails

This exercise fixes a 2.8.1 bug that 2.9.0 fixed, so make the scratch copy from the tag: git worktree add --detach ../monogatari-exercises v2.8.1.

What to do. Play 'Before.', then a function statement that throws, then 'After.'. Close the error dialog and click: the game should show 'After.'. Find why 2.8.1 stays on 'Before.', and fix it.

Hint. Read the function branch of run() in src/engine/lifecycle.ts: which global does it set before calling the function, and on which paths does it clear it? Then read the first check in shouldProceed().

Check. The spec below fails on an unchanged 2.8.1 (block is still true). With your fix and the bundle rebuilt, it passes, and so does actions/functions.spec.js.

Solution

run() sets block to true before it calls the function and sets it back only after the function returns. When the function throws, the catch shows engine:run:function_error and returns, with block still set. Clear it there too:

 		} catch (e: unknown) {
+			engine.global ('block', false);
+
 			const error: FancyErrorProps = {
 				'Label': String(engine.state ('label')),
 				'Step': Number(engine.state ('step')),

cypress/e2e/exercises/function-error.spec.js:

context('Exercise: a function statement that throws', () => {
  beforeEach(() => {
    cy.open();
    cy.get('@monogatari').invoke('global', '_didInit').should('equal', true);
  });

  it('Lets the player go on once the error is dismissed', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'Before.',
        () => {
          throw new Error('Broken on purpose');
        },
        'After.',
        'end',
      ],
    });

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

    // The debug module shows the error; the player closes it
    cy.get('.fancy-error').contains('An error occurred while trying to run a Function.');
    cy.get('.fancy-error button').contains('Ok').click();
    cy.get('.fancy-error').should('not.exist');

    cy.get('@monogatari').invoke('global', 'block').should('equal', false);
    cy.proceed();
    cy.get('text-box').contains('After.');
  });
});

After the error, the game stays at step 1, the function’s own step, until the next click: the catch resolves the run with { advance: false }, so it doesn’t advance on its own. The same lock happens through _engine_block when an action’s run rejects inside next(). Fixing that one meant deciding what the game does after a failed statement; 2.9.0’s answer is in Moving forward: the game waits on the failed statement, the next click goes on, and going back steps over it.