Reading the Code
The engine is about 186 files in src/, but you only need a handful to understand how it works. This page gives you a reading order, a map of the biggest file, and searches that take you from something you see in a game to the code behind it. Line numbers are those of the v2.8.1 tag.
Where to start
Read these in order. Each one takes a few minutes and the next builds on it.
src/index.ts. What the engine is made of: it imports the 18 translations, the 27 components and the 36 actions, and assigns them toMonogatari._translations,Monogatari._componentsandMonogatari._actions. The order of_actionsis the order statements are matched in, which is whyDialogis last.src/lib/Action.ts. The comment at the top describes the three cycles of an action (mounting, application, reverting), and the class lists every method an action can implement, each with a comment.src/engine/lifecycle.ts. How a statement runs (run()), how one is undone (revert()), and what a click asks before it moves the game (proceed(),shouldProceed()). It’s under 800 lines and most of the engine’s behavior hangs from it.src/actions/ShowImage.ts. A complete, short action: matching,apply(), recording itself instateandhistoryindidApply(), undoing itself inrevert()anddidRevert(), rebuilding itself on a load inonLoad(), and cleaning up inreset().src/components/game-screen/index.ts. A short component: the click listener that callsproceed(), the left-arrow listener that callsrollback(), and arender().src/monogatari.ts, frominit()(line 2376) backwards tobind()(line 2123) andsetup()(line 1913): how the game boots.
Architecture draws what these files do together.
Finding your way around the engine object
src/monogatari.ts is one class, Monogatari, whose members are all static. A game’s monogatari is the class itself (src/browser.ts sets window.monogatari = Monogatari.default), so there is exactly one engine per page. The file is 2,519 lines long, in this order:
| Lines | What’s there |
|---|---|
| 1–157 | Imports, including every function the class wraps from src/engine/, and the comment describing the setup, bind and init steps |
| 171–642 | The data: _actions, _components, _script, _characters, _storage, the caches, Storage, the screenshot callbacks, _mediaPlayers, _state, _history, _assets, the default _settings and _preferences, _globals, _listeners, _configuration (the main menu’s and quick menu’s buttons), version |
| 653–710 | onStart() and onLoad(), which call every action’s and component’s own |
| 718–765 | width(), height(), the debug getter, string() |
| 783–842 | history() and state() |
| 852–972 | Registering and finding actions and components |
| 985–1186 | Assets and caches, characters, translations (wrappers over src/engine/assets.ts, characters.ts and i18n.ts) |
| 1192–1305 | setting(), settings(), preference(), preferences(), configuration(), storage() |
| 1307–1395 | script(), label(), fn(), $() |
| 1397–1497 | globals(), global(), template(), the media players, temp() |
| 1504–1725 | localize(), preload(), translate(), replaceVariables() |
| 1740–1911 | Wrappers over persistence.ts, input.ts, lifecycle.ts and ui.ts |
| 1913–2093 | setup(): preferences from storage, defining the components, the service worker, the built-in listeners (start, open-screen, skip…), every component’s and action’s setup() |
| 2123–2247 | bind(): the data-action click handler, the keyboard shortcuts, the aspect ratio, every bind() |
| 2261–2334 | element(), on(), off(), trigger() |
| 2347–2479 | _setupRegistry() and init() |
| 2487–2519 | random(), then a line that checks at compile time that the class matches the VisualNovelEngine interface in src/lib/types/Monogatari.ts |
When you add a public method to the class, add it to VisualNovelEngine too: const _engineTypeCheck: VisualNovelEngine = Monogatari; makes bun run check fail until the two agree, and the interface is what the engine passes to every function in src/engine/ and what dist/types/ publishes.
The two sides of an action
An action class has a static side and an instance side, and they do different jobs:
| Static (one per action) | Instance (one per statement run) |
|---|---|
id, _configuration, loadingOrder, blocking, _experimental, engine |
the constructor, which receives the statement split into words (or the object) |
setup(), bind(), init(): once, when the game boots |
willApply(), apply(), didApply(): when the statement runs |
matchString(), matchObject(): does this action take the statement? |
willRevert(), revert(), didRevert(): when the player goes back past it |
shouldProceed(), willProceed(), shouldRollback(), willRollback(): on every click and every rollback |
_statement, _cycle ('Application' or 'Revert'), _extras |
onStart(), onLoad(), onSave(), reset() |
|
beforeRun(), afterRun(), beforeRevert(), afterRevert(): around every statement, whichever action runs it |
So Dialog.shouldProceed() runs on every click even when the current statement is a scene, and a new instance of ShowImage is made for every show image statement, including the one a rollback reverts.
Components follow Pandora’s model: the static side has the same mounting methods (setup(), bind(), init()) and checks (shouldProceed()…), which by default ask every instance on the page; the instance side has Pandora’s life cycle (willMount(), render(), didMount(), onStateUpdate(), onPropsUpdate()…). How Each Part Works covers both.
Naming conventions
- Action ids use
::for words:'Show::Character','Hide::TextBox','Notification'.monogatari.action(id)lowercases both sides, somonogatari.action('show::character')finds it. - State keys are plural, history keys singular:
state('images')lists what is on screen now;history('image')lists what was shown, for reverting. - A global with a leading underscore is internal:
_engine_block,_didSetup,_restoring_state.blockand_executing_sub_actionare deprecated in favor of each action’sblockingflag (commit14494a78), andshouldProceed()still checks them. - Component tags are set with
static override tag = 'save-screen'or after the class (GameScreen.tag = 'game-screen'). Screens getdata-screenfrom their tag minus-screeninScreenComponent.willMount(). - Data attributes tie the markup to the code:
data-action(a button’s listener),data-screen,data-component,data-content(a part of a component, found withcontent(name)),data-ui,data-string(a translated string). - Files: actions are named after their class (
InputModal.tsholds the action whose id is'Input'), component folders after their tag, translation files after the language (Espanol.ts,日本語.ts). - The house style is
@aegis-framework/eslint-config, the one every Aegis Framework project uses: two-space indentation, no space before parentheses (this.state('step')), single quotes and semicolons, braces on everyif,elseand loop, a blank line around every block, arrow functions, constants at the top of their file in uppercase, and imports in three sorted groups.bun run lintchecks all of it, andbunx eslint . --fixapplies almost all of it. 2.9.0 formatted the whole repository with it, so older commits look different: tabs, and a space before call parentheses (this.state ('step')).
Search recipes
Which action takes a statement. In the browser console of a running game (see Debugging the Engine):
monogatari.prepareAction('show scen beach', { cycle: 'Application' }).constructor.id;This prints "Dialog": nothing else matches the misspelled statement, so it would be shown as a line of narration. 'show scene beach' prints "Scene". monogatari.actions().map((action) => action.id) lists the actions in matching order; the two experimental ones (Show::Character::Layer, Hide::Character::Layer) are missing from it unless the game sets ExperimentalFeatures: true.
Where an error dialog comes from. Every dialog has an id like action:jump:label_not_found. The engine shows it with FancyError.show() and the debug module holds its text:
grep -rn "action:jump:label_not_found" src debugWhat a button does. Find its data-action (<button data-action="save">), then the listener of that name:
grep -rn "registerListener *('save'" srcThat finds src/components/save-screen/index.ts. The listeners start, open-screen, dismiss-alert, distraction-free, skip and auto-play are registered in setup() in src/monogatari.ts.
Who writes a state key. grep -rn "images:" src/actions lists the places that set state.images.
Who listens to an event. grep -rn "'didUpdateState'" src.
Where a CSS rule comes from. Component styles are in src/components/<tag>/index.css, the engine’s general ones in src/style/monogatari.css, the variables in src/style/variables.css. Search src/, never dist/engine/core/monogatari.css, which is minified build output.
When and why something changed. git log -S '<code>' -- <file> finds the commits that added or removed a piece of code; git log --follow -- <file> follows a file across renames. Commit messages are short, so read the diff (git show <commit>) too.
The specs are documentation
The Cypress specs in cypress/e2e/ are the closest thing v2 has to an executable description of each action. cypress/e2e/actions/show_character.spec.js shows every form of show character the engine supports and what lands in the page for each; cypress/e2e/actions/reversible_functions.spec.js shows what a rollback undoes. When a behavior isn’t documented, find the spec that covers it before you read the action. Testing the Engine lists them.
Exercises
- Without running anything, say which action takes
{ 'Choice': { … } }and how the engine finds it. - A game is loaded. Which action rebuilds its part of the screen first, and why?
Answers
Choice.prepareAction()insrc/engine/lifecycle.tssees an object, so it callsmatchObject()on every action in order.Choice.matchObject()returnstypeof statement.Choice !== 'undefined'.Conditional(statement.Conditional) andInput(statement.Input) match the same way on their own keys.Scene, which hasloadingOrder = -2.onLoad()insrc/monogatari.ts(line 676) groups the actions byloadingOrderand runs the groups one after another, lowest first, so the scene is drawn before the characters and images that go on it.ShowCharacterLayer(order 1) runs last. Every other action has the default, 0. Read line 682 closely: the orders are sorted with.sort()and no compare function, which compares them as text. That gives the right order for -2, 0 and 1, but would put 10 before 2 and -1 before -2.