Statements and Actions
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’ssetup(),bind()andinit()once, before the player sees anything; run(), which builds an instance of the matching action and runs itswillApply(),apply()anddidApply();next()andproceed(), 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-actionbuttons 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.
What each step guarantees, in order:
init()stores the selector, turns onExperimentalFeatureswhenwindow.Cypressexists (so the specs always run with experimental actions on), calls_setupRegistry()(Errors and the Debug Module), and triggerswillInit. It creates theStoragespace withsetupStorage()if nothing configured one (Saving and Loading).setup()first reads the player’s preferences from theSettingskey. Only then does it define the components with Pandora’sRegistry.register()(Components and Screens), register the service worker, savestorageStructure(the storage as the game declared it, as JSON, soresetGame()can put it back), and register the engine’s own listeners. Last, it calls the staticsetup()of every component and every action inactions(), all at once, and sets the global_didSetup. That loop is also where each built-in action getsaction.engine. A failure anywhere insetup()is caught and printed asInitialization error, andinit()goes on.bind()adds the handlers that turn the player’s input into calls (next section), appliesForceAspectRatio, and calls every component’s and action’s staticbind(selector). After those, it binds the keys of every listener registered so far, and sets_didBind.- The
initphase creates the ambient audio player, localizes everydata-stringelement, setsstate.labelfrom theLabelsetting, shows the orientation warning if needed, starts the autosave interval whenAutoSaveis above 0, and awaits every component’s and action’s staticinit(selector). It sets_didInitand triggersdidInit. displayInitialScreen()(insrc/engine/ui.ts) runspreload()(Media and Assets). When it settles, failed or not, it checks that the start label exists (or showsengine:script:label_not_found) and callsshowSplashScreen(): when a label named like theSplashScreenLabelsetting exists, it plays that label on the game screen. OtherwiseshowMainScreen()opens the main screen, or, withShowMainScreen: 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.
- 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(' '), andactions().find()asks each action’s staticmatchString(words)in order. The firsttruewins. - 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, DialogThose 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.
In order:
beforeRun()on every registered action. It is a broadcast, not a call on the action that will run: every action inactions()gets it, for every statement.Conditionaluses it to clean up its rollback bookkeeping.- A
nullstatement throwsStatement was null.; anundefinedone (a label with no statement at this step, like an empty label after ajump) showsengine:script:label_endedand throws. - A function runs with the engine as
thisthrough Artemis’Util.callAsync(), which awaits it if it returns a promise. While it runs, the deprecated globalblockistrue. If it returns anything butfalseand the position didn’t change meanwhile, the run callsengine.next();falseleaves the game waiting for the player. If it throws,blockis cleared, the debug module showsengine:run:function_errorand the run resolves with{ advance: false }. prepareAction(), then thewillRunActionevent with{ action }as its detail.prepareAction()puts the statement and the cycle in the action class’s_preparingwhile the constructor runs, so the baseActionconstructor setsthis._statementandthis._cyclebefore a subclass’s constructor body reads them. An object statement no action matches showsengine:run:no_actionand throws.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 fromwillApply()is how an action refuses a statement, usually after showing its own error (Jumpdoes 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 andFancyError.queuewhen it starts.didApply()returns{ advance }. A result that isn’t an object counts as{ advance: false }, with a warning on the console. ThedidRunActionevent fires, thenafterRun({ 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
modalis visible (an alert, a message, the debug module’s error dialog); distraction_freeis set (the player hid the text box with Hide or h);- the deprecated
blockor_executing_sub_actionglobals are set; _engine_blockis 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:
Dialogwhile 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,VideoandWaitwhile their staticblockingistrue(Notificationhas the same check, but since 2.9.0 never sets the flag: it doesn’t wait for the permission question);- the
game-screencomponent while the game screen is hidden; - the instances of
choice-container,message-modalandtext-inputwhile they are on screen (the baseComponent.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:
Conditionalcalls itsConditionfunction (with the engine asthis) inpickBranch(), thenawait engine.run(branch)on the branch it returned:Truefortrue,Falseforfalse, the branch named by a string, or'0','1'… for a whole number. A branch it doesn’t have runs'next'instead. ItsdidApply()always returns{ advance: false }: the branch’s own run already advanced if it wanted to. Only an error in theConditionpicksFalse; an error in the branch it ran fails the Conditional like any statement.Choicebuilds itsDialogline withprepareAction()and drives its life cycle directly, then puts achoice-containeron screen. When the player clicks an option, its handler calls the option’sonChosenfunction, if any, thenengine.run(option.Do)('next'when theDoisn’t text), then records the pick inhistory('choice')andhistory('choiceOutcome'). With every option hidden,didApply()returns{ advance: true }and the menu never shows.Placeholder($ name) takes the statement saved withmonogatari.$('name', statement), builds its action withprepareAction(), and forwardswillApply(),apply()anddidApply()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-actionelements. The handlerbind()installs on thevisual-novelelement stops the click from bubbling (so it never reaches the game screen’s proceed handler) and callsrunListener(element.data('action'), event, element). A click on an icon’s innerpathis 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 withkeyboardShortcut(): inbind()for the listeners registered by then, or at once for a listener registered after_didBind. Keys pressed inside aninputelement 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_timerand schedules it everyAutoPlaySpeedseconds (a preference), correcting for drift. Each tick callsproceed({ autoPlay: true })and schedules the next one whether the proceed passed or was refused, so auto-play waits through choices without stopping. Theauto-playlistener toggles it.skip(true)works only when theSkipsetting is above 0: it schedulesproceed({ skip: true })everySkipmilliseconds and stores the timeout in the globalskip. The quick menu removes its Skip button inQuickMenu.init()whenSkipis 0.distractionFree()hides the text box, makes the quick menu transparent, and setsdistraction_free, which makesshouldProceed()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
Dialogstays 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 afterDialog.- 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.
ShowCharacterandShowCharacterLayersplitshow characterbetween 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 characterwith no name throws inShowCharacter.matchString(). - Constructors only read.
prepareAction()builds an instance for running, for reverting, and from insideChoiceandPlaceholder. Doing work in the constructor (DOM, state, error dialogs) does it at the wrong time. Do it inwillApply()orapply(). didApply()returns an object.run()destructures{ advance }from it. An override that returns nothing throws aTypeErrorthat leaves the game stuck.- Never wait for the player inside
apply().run()awaitsapply(), and when the run came fromproceed(),_engine_blockstays set until it resolves: the player can’t proceed or go back meanwhile. Return fromapply(), set a staticblockingflag, refuse inshouldProceed(), 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()(asWaitandChoiceclear their flags, andchoice-containerremoves itself). - Register before
init().init()mounts the actions in the list at that moment. An action registered later gets anenginereference fromregisterAction(), but itssetup(),bind()andinit()never run. - Built-ins get
engineinsetup(). 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 withCannot read properties of undefined.
How to make the common changes
Add a built-in action
Create
src/actions/Ring.ts. Start from the closest real action:Next.tsfor one that advances,Wait.tsfor one that blocks,ShowImage.tsfor 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;Import it in
src/index.tsand add it toMonogatari._actions, beforeDialogand before any action whose matcher would take its statements (the list is roughly alphabetical; the position is what counts).Write its
revert()and decide its{ advance, step }(State, Storage and Rollback), and itsonLoad()if it shows something a load must restore (Saving and Loading).Add
cypress/e2e/actions/ring.spec.js, written likenext.spec.js: run it forward, roll it back, and save and load if it keeps state (Testing).Run
bun run build(lint, type check and build) and commit the rebuiltdist/engine/core/monogatari.jswith the source (Building and Packaging).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 byNextand skipped;'wait for me'is aWaitthat 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, andDialogshows it as text. - A failed statement locked the game until 2.9.0.
next()didn’t clear_engine_blockwhen the run rejected, so any statement thatproceed()started and that threw (ajumpto a label that doesn’t exist, a label withoutend, a customdidApply()that forgot to return) left clicks and Back doing nothing. A function statement that threw did the same throughblock, whichrun()only cleared when the function succeeded;actions/functions.spec.jschecked that the error showed, not that the game went on, which is why it was missed. Exercise 4 rebuilds that fix on thev2.8.1tag;engine/failed-statements.spec.jscovers every case now. - The Skip button and the s key never turned skipping on, until 2.9.0. The
skiplistener insetup()checkedthis.global('skip') !== null, but since the TypeScript migration (bbc0c637, December 2025)global()returnsundefinedfornull, so the listener always calledskip(false). A global that holdsnullreads asundefined, so never compare one withnull: theauto-playlistener compares withundefined, and the fixedskiplistener checks truthiness. Exercise 3 rebuilds the fix on thev2.8.1tag. - Stopping auto-play let one more statement through, until 2.9.0.
autoPlay(true)stored the timer function in_auto_play_timer, andautoPlay(false)passed that function toclearTimeout(), 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 aWeakMapinsrc/engine/ui.ts, and a tick only schedules the next one while_auto_play_timerstill 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 adata-actionelement, so the game advanced unless the engine’s owndata-actionlistener 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. WithShowMainScreen: false(or a game started some other way),showMainScreen()runs the first statement without callingonStart(). No built-in action implementsonStart(), so nothing in the engine notices.- Hooks the engine never calls.
interrupt()and the staticmatch()are declared inAction.tsand described in the old docs, but no code calls them; 2.9.0 marks both@deprecatedrather 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_functionsthat nothing reads. - Replacing a listener doesn’t rebind its key.
registerListener(name, listener, true)swaps the entry in_listenersand returns, but Mousetrap still holds the old callback. Afterinit(), a replaceddistraction-freeruns 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.tssaidnaturalPosition: trueinserts “at natural priority position” andfalseappends. The code does the opposite:trueappends (afterDialog),falseprepends. - The specs run with experimental actions on, games don’t.
init()turnsExperimentalFeatureson under Cypress, and the starter game’sjs/options.jssets it tofalse. In a real game,show character y:body happyis a line of dialog, becauseShow::Character::Layeris filtered out ofactions(). Conditionalswallowed its branch’s errors until 2.9.0. Itsapply()wrapped everything in onetry, so aTruebranch that failed (ajumpto a missing label) ran theFalsebranch as well, after the error dialog.- Statements were changed in place until 2.9.0:
Choice.apply()wrote_keyinto each option of the script’s own object,Input’s constructor filled in its defaults, andFunction.willApply()copied a v1ReverseintoRevert. 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
setTimeoutinnext()came withc81a3760(2018, “Prevent stack overflows”);_engine_blockwith49760ac1(2019);beforeRun,afterRun,beforeRevertandafterRevertwithd2aff1d8(2020); a function’sfalsereturn as the advance signal with66b87239(2020); the per-actionblockingflags replaced the sharedblockglobal in14494a78(December 2025); the position check inrun()arrived with0d2e4b12(March 2026), andeb1ea6bf(“Split the engine”, March 2026) moved this code fromsrc/monogatari.tsintosrc/engine/lifecycle.ts,input.tsandui.ts.88425293(March 2026) madedata-actionclicks stop bubbling and taught the game screen to ignore clicks insidedata-actionanddata-deleteelements, 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/coreTesting 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.
Related pages
- Architecture: the whole engine, and a statement from a click to the screen.
- State, Storage and Rollback:
revert(),{ advance, step }, the histories each action keeps. - Saving and Loading:
onLoad(),loadingOrder, and therun()that follows a load. - Text and the Type-Writer:
Dialog, the catch-all action, and why the first click finishes the text. - Components and Screens: the components’ static hooks, which
shouldProceed()asks too, and the screensshowScreen()opens. - Errors and the Debug Module: the dialogs
run()and the actions show, and the debug log. - Testing and Debugging the Engine: running the specs, reading the console groups.
- For game developers: Script Actions (every statement, including Jump, End, Next, Wait, Choices, Conditionals, JavaScript functions and Placeholders), The Script and Labels, Extending Monogatari, the Engine API and its Events, and Configuration for
Skip,AllowRollback,ShowMainScreenandExperimentalFeatures.