This page follows one line of dialog from the script to the screen: how the Dialog action reads it, which element shows it, how the <type-writer> reveals it one character at a time with its markers and effects, and what a click does while it is still typing. It also covers the parts that keep text consistent when the player goes back: the NVL history, the clear statement and the dialog log. Read Architecture first, and Statements and Actions for how a statement reaches its action.

What it’s for

Most of a visual novel is text. Any string statement that no other action takes is a line of dialog, so Dialog is the last action in the list and matches everything. It decides who speaks (a character, the narrator, a centered line or an NVL line), writes the name, the side image and the classes on the text box, adds the line to the dialog log, and hands the text to a <type-writer>.

The type-writer turns the text into one <type-character> element per visible character, reveals them on a timer, runs the inline markers ({pause:500}, {speed:200}) at their positions and applies the enclosed effects ({shake}…{/shake}). While it types, the global finished_typing is false, and Dialog.shouldProceed() turns the next click into “finish this line” instead of “go to the next statement”.

Three more actions belong here: clear empties the text box, and hide textbox / show textbox hide it for a stretch of the script.

The files

File What it does Cypress specs
src/actions/Dialog.ts The Dialog action: parsing id:expression:classes, the narrator, nvl and centered lines, the name, color and side image, the dialog log entry, ADV and NVL display, its shouldProceed(), willProceed(), willRollback(), reset() and revert() actions/dialog.spec.js, components/text-box-scroll.spec.js, components/dialog-log-scroll.spec.js
src/actions/Clear.ts clear: empties the text box through Dialog.reset({ keepNVL: true, saveNVL: true }), records the mode in the clear history actions/clear.spec.js
src/actions/HideTextBox.ts hide textbox: sets the text box’s hidden state and state.textboxHidden, restores it on load actions/hide_textbox.spec.js
src/actions/ShowTextBox.ts show textbox: the opposite actions/show_textbox.spec.js
src/components/text-box/index.ts, index.css <text-box>: the name, side image and text areas, the mode property (adv or nvl), the hidden state, show() and checkUnread() components/text-box.spec.js, components/text-box-scroll.spec.js, actions/hide_textbox.spec.js, actions/show_textbox.spec.js
src/components/type-writer/index.ts <type-writer>: the marker registry (action(), actions(), stripActionMarkers()), parsing a line into characters and markers, the timing loop, setContent(), finish(), stop(), start(), destroy() components/type-writer.spec.js, actions/dialog.spec.js (the “Text Effects” block and the typing tests)
src/components/type-writer/index.css The CSS for every built-in effect, keyed on type-character[data-effect-<name>], the --effect-* custom properties, and the rules that hide a data-untyped character components/type-writer.spec.js, actions/dialog.spec.js
src/components/type-character/index.ts, index.css <type-character>: one character or one void element (<br>, <hr>, <img>); turns its special state into data-effect-* attributes and sets --char-index; the cursor actions/dialog.spec.js
src/components/centered-dialog/index.ts, index.css <centered-dialog>: a floating box with its own type-writer, created for each centered line and removed on the next proceed or rollback components/centered-dialog.spec.js, actions/dialog.spec.js
src/components/dialog-log/index.ts, index.css <dialog-log>: the log modal, its quick-menu button, write() and pop() components/dialog-log.spec.js, components/dialog-log-scroll.spec.js, actions/dialog.spec.js
src/lib/typing-utils.ts humanizeSpeed(), mirrorTextSpeed() (the Text Speed slider’s direction), WHITESPACE_PATTERN and the TypingCallbacks type. Its getLeafNodes() and parseBasicString() helpers are not used by anything components/settings-screen.spec.js
src/lib/types/TypeWriterEffects.ts Type names for the built-in effects (TextEffect, EFFECT_CATEGORIES, isValidEffect()). Exported, never used at runtime: the registry in type-writer/index.ts is what counts none
src/engine/lifecycle.ts stopTyping(): reads InstantText and calls the type-writer’s finish() actions/dialog.spec.js
src/monogatari.ts The defaults: the TypeAnimation, NVLTypeAnimation, NarratorTypeAnimation, CenteredTypeAnimation and InstantText settings, the TextSpeed preference none
src/components/settings-screen/index.ts The text speed slider ([data-action="set-text-speed"], min="1" max="50") none
src/style/variables.css --character-name-color and the --cursor-* variables none
dist/js/options.js The starter game’s settings: it turns InstantText on none

How it works

From a string to a Dialog

A string statement is interpolated and split before any action sees it: prepareAction() calls engine.replaceVariables() (_(Key) translations, then {{name}} from storage) and splits the result at every single space (Statements and Actions, Translations and Strings). Dialog sets static escapeInterpolatedValues = true, so once it has matched, prepareAction() interpolates the statement again with the values escaped, and Dialog’s constructor gets those words: a value’s < reaches the type-writer as &lt; and shows as text. Every other action declines; Dialog.matchString() returns true for anything, and src/index.ts registers Dialog last for that reason.

The constructor receives the words. It takes the first one apart at its colons:

y:happy:loud|big Hello there.
^ ^     ^        ^
| |     |        the rest of the words, joined with spaces: this.dialog
| |     classes, split at "|": this.classes
| expression: this.expression and this.image
character id: this.id

Then it decides who speaks, in this order:

  1. A character. When engine.character(id) exists, _setCharacter() stores it, takes its nvl flag, and picks the side image: the expression named in the statement, or default_expression (an expression name or a file name).
  2. centered. this.id = 'centered'.
  3. Anything else is the narrator (this.id = '_narrator'). If the game defined a _narrator character, _setCharacter('_narrator', …) uses it. The first word is then consumed when it is nvl (which also sets this.nvl = true) or narrator; for any other word it was part of the sentence, and it is put back in front of the text.

this.clearDialog is the text with every marker removed (TypeWriter.stripActionMarkers()): that is what goes into the dialog log.

NOTE

The character test comes first, so a game with a character whose id is a turns 'a cat sat on the mat.' into that character saying “cat sat on the mat.” Short character ids are a known trap for writers.

Applying a line

sequenceDiagram participant Run as run() participant D as Dialog instance participant Log as dialog-log participant TB as text-box participant TW as type-writer participant TC as type-characters Run->>D: willApply() Note over D: unfocus sprites, hide the face,<br/>clear the name Run->>D: apply() D->>Log: write() (Application cycle only) D->>TB: classes, show(), name, color, side image<br/>(character and narrator lines) alt nvl line D->>TB: append div[data-spoke] with a new type-writer else centered line D->>TB: hide() D->>TW: new centered-dialog, wrapper type-writer else adv line D->>TB: empty [data-ui="say"] end D->>TW: setContent(text, animate) TW->>TW: initiate(): setDisplay() parses the line TW->>TC: one element per character, opacity 0 loop each frame until the delay has passed TW->>TC: reveal the next character, run its markers end TW-->>Run: finished_typing = true, didFinishTyping Run->>D: didApply(): _dialog_pending_revert = true D-->>Run: advance false: wait for the player

willApply() removes the focus class from every [data-character] sprite, hides the side image ([data-ui="face"]), empties the name ([data-ui="who"]) and removes the text box’s data-expression.

apply({ updateLog = true }) then:

  1. writes the line to every <dialog-log> (DialogLog.instances().each(… write({ id, character, dialog: clearDialog }))), but only in the 'Application' cycle: a revert re-applies a line without writing it twice;
  2. reports the action:dialog:textbox_hidden error when the text box’s hidden state is true (a hide textbox is in effect), and goes on anyway. The error dialog appears only while the debug level is above none (actions/hide_textbox.spec.js tests both cases; Errors and the Debug Module explains why);
  3. takes one of three paths:
    • a character: _handleCustomClasses() on the text box, show(), then characterDialog(): the name through replaceVariables() (unless the line is NVL), the focus class on [data-character="<id>"], the name color (character.color, or var(--character-name-color)), the side image at <AssetsPath.root>/<AssetsPath.characters>/<directory>/<image> (the directory part only when the character has one) with data-expression on the text box, unless the line is NVL, and finally displayDialog() animated unless the character says type_animation: false;
    • centered: displayCenteredDialog() with the CenteredTypeAnimation setting;
    • the narrator: the classes, show(), then displayDialog() with the NarratorTypeAnimation setting.

didApply() sets _dialog_pending_revert to true and returns { advance: false }: a line always waits for the player.

When a line is animated depends on four settings and one character property. Each layer can only turn the animation off:

Line Typed when
A character, ADV TypeAnimation and the character’s type_animation (default true)
A character, NVL TypeAnimation, NVLTypeAnimation and type_animation
The narrator, ADV TypeAnimation and NarratorTypeAnimation
The narrator, NVL (nvl …) TypeAnimation, NVLTypeAnimation and NarratorTypeAnimation
centered TypeAnimation and CenteredTypeAnimation

With a _narrator character defined, narrator lines take the character path: its name shows, and NarratorTypeAnimation is no longer read (its type_animation is).

The three displays

ADV (displayDialog() with this.nvl === false). If the box was in NVL mode, its whole page (textBox.content('dialog').html()) is pushed onto history('nvl') first, so rollback can bring it back; this only happens in the 'Application' cycle and outside a load (_restoring_state === false). Then the box gets mode: 'adv', any NVL entry type-writers are destroyed, [data-ui="say"] is emptied, data-speaking is set, and the text box’s own type-writer gets setContent(dialog, animation).

NVL (displayNvlDialog()). Switching into NVL calls Dialog.reset() (which empties the box) and sets mode: 'nvl'. Each line is then appended as an entry inside [data-ui="say"]:

<div data-spoke="m" class="named"><span style="color:#c0ffee;">Mina: </span><type-writer></type-writer></div>
<div data-spoke="m"><type-writer></type-writer></div>
<div data-spoke="_narrator" class="unnamed"><type-writer></type-writer></div>

The name is written only when the speaker changes, and the previous speaker’s last entry gets the nvl-dialog-footer class. The new entry’s type-writer receives the text once it is mounted (ready()), the text area scrolls to the bottom, and checkUnread() adds unread to the box when there is more below than fits.

[data-ui="say"] is the ADV type-writer itself. The text box’s render() leaves that type-writer out in NVL mode, but setProps({ mode }) only changes the mode attribute without rendering again (the comments in displayNvlDialog() and displayDialog() say so), so the element stays and holds the entries. The CSS switches on text-box[mode="nvl"].

Centered (displayCenteredDialog()). The text box’s type-writer gets setState({ ignore: true, strings: [] }), which clears its strings without starting anything (the ignore flag swallows one strings update), the box is hidden, and a new <centered-dialog> is appended to the game screen with the line’s classes. Its inner type-writer ([data-content="wrapper"]) receives the text when it is ready. Dialog.willProceed() removes it on the next proceed, and the component’s own willRollback() removes it on a rollback.

Inside the type-writer

setContent(text, animate) is the entry point every display uses:

  • When animate is false or the TypeAnimation setting is off, a line without markers is written as HTML into .type-writer-container. A line with markers is built into <type-character> elements the same way a typed line is (_prepareDisplay()), and all of them are revealed at once (_revealAll()), so its effects show; no marker in this.actions runs. Either way it sets finished_typing to true and fires didFinishTyping.
  • Otherwise it sets finished_typing to false and sets strings: [text]. onStateUpdate('strings') renders the empty container again, calls destroy() on the previous run and then initiate(), which fires didStartTyping through preStringTyped.

initiate() builds its default configuration again for every line (the TextSpeed preference as typeSpeed, the TypingCursor setting as showCursor, and the callbacks preStringTyped, onStringTyped and onDestroy, which keep finished_typing and the didStartTyping/didFinishTyping events right) and puts the game’s own configuration on top: whatever a game gave it with setState({ config }), which the type-writer tells apart from the configuration it built itself by comparing the object (_gameConfig, _builtConfig). A configuration set while a line types is merged the same way in onStateUpdate('config'), so the callbacks survive it. Then initiate() resets its counters and calls _prepareDisplay(), which rebuilds the marker pattern when the registry changed (patternCacheVersion) and calls setDisplay().

setDisplay() parses the line as HTML into a detached <div> and walks the parts the line is typed in (_getTypingUnits()): its text nodes, the elements with nothing inside, and each <svg> as a whole:

  • a void element (<br>, <hr>, <img>) becomes one <type-character> that renders it, with its attributes copied into its state (checkVoidTags());
  • another element with nothing inside (an icon’s <i>, an empty <span>) or an <svg> is moved inside a <type-character> that renders nothing of its own (_wrapElement()), with the effects open around it;
  • a comment is dropped;
  • a text node goes through parseStringToFragment(): the text is split with the cached marker pattern, every non-space character becomes a <type-character letter="…"> hidden with opacity: 0 and the data-untyped attribute, with a charIndex, white space stays a text node, and each marker is parsed by _parseActionSection() and added to the list for its position, the index of the character it comes before. Markers written side by side ({pause:500}{speed:50}) all come before the same character, so they share a list, in the order they were written. setDisplay() adds the number of type-characters before that text node, so this.actions[position] counts characters across the whole line. Before 2.9.0 each position held one marker and side-by-side markers took the slots after it, which belonged to the next characters, so the second one ran again one character later.

An enclosed marker is queued in actions too, and its function runs (every built-in one is empty), but its effect comes from somewhere else: while one is open, its id (<name>-<parseIndex>) sits on this.enclosedID, and every character created meanwhile gets special: { 'shake-12': true }. <type-character> turns that state into a data-effect-shake attribute (_applyEffectAttributes()), and the CSS in type-writer/index.css animates type-character[data-effect-shake]. A closing marker must match the innermost open one; one that doesn’t is reported with engine.debug.error('Mismatched closing action:', …) and ignored, so both effects stay open. enclosedID belongs to the instance and is not reset between leaf nodes, which is why an effect can span HTML tags.

typewrite() runs the markers listed at the current position, once (_runActionsAt() remembers the last position it ran, so typing that stops and starts again doesn’t repeat them), then sets the wait for the next character: the pending {pause} value, or humanizeSpeed(this.speed), a random value between the speed and one and a half times it. _animationLoop() counts elapsed time with requestAnimationFrame and calls _revealNextCharacter(), which clears the character’s opacity and its data-untyped attribute (_revealTyped()) and moves on. While a character has data-untyped, type-writer/index.css keeps it visibility: hidden, whatever its effect animates, and gives the effects that play as a letter appears (fade, blur, impact…) animation-name: none, so they start when the letter is typed. After the last character it calls onStringTyped: finished_typing becomes true and didFinishTyping fires. A negative wait reveals everything left in one loop.

The built-in markers:

Marker Type What it does
{pause:N} or {pause N} number Waits N milliseconds before the next character, in place of its normal delay
{speed:N} or {speed N} number Sets the delay to floor(current × 100 / N): 200 halves the current delay, 50 doubles it, 0 makes it 0. It is relative to the current speed, so {speed:100} changes nothing
{shake}…{/shake} and 42 more enclosed Adds data-effect-<name> to the characters inside. The list is the _configuration.actions object in type-writer/index.ts
{name/} instance Runs the registered function at that position. No built-in uses this type

A marker whose name isn’t registered stays in the text as typed characters.

What a click does while a line types

flowchart TD click(["Click, Space or Right arrow"]) --> proceed["engine.proceed()"] proceed --> should["shouldProceed(): every action and component"] should --> dialog{"Dialog.shouldProceed():<br/>finished_typing false<br/>and the writer has strings?"} dialog -- no --> others{"Any other refusal?"} others -- no --> next["willProceed(), then next():<br/>the next statement runs"] others -- yes --> wait(["The game stays on the line"]) dialog -- yes --> stop["engine.stopTyping(writer)"] stop --> instant{"InstantText setting?"} instant -- true --> finishTrue["finish(true): destroy(), write the line<br/>with markers stripped, onStringTyped"] instant -- false --> finishFalse["finish(false): delay 0 (or minTextSpeed<br/>when below 0), ignore pauses"] finishTrue --> refuse["throw: proceed is refused"] finishFalse --> refuse refuse --> wait

Dialog.shouldProceed() finds the writer that counts: the centered dialog’s wrapper when one is on screen, or else the last <type-writer> inside <visual-novel> (the newest NVL entry, or the text box’s own). When it is still typing, it calls engine.stopTyping() and throws, so the whole proceed is refused. The second click finds finished_typing true and advances.

stopTyping() in src/engine/lifecycle.ts passes the InstantText setting to finish():

  • InstantText: true (the starter game’s js/options.js sets this): finish(true) destroys the animation, reveals every <type-character> of the line in place (_revealAll(), which also leaves the cursor after the last one when it shows) and calls onStringTyped. The line is complete at once with its effects; the markers still queued in this.actions don’t run. If the line wasn’t built yet (a click right after setContent()), it’s built and revealed whole.
  • InstantText: false (the engine’s default): finish(false) sets the delay to 0 and ignores pauses, so the rest is revealed one character per animation frame (about 60 a second on a 60 Hz screen), with every marker still run and every effect kept. The minTextSpeed setting changes that: when it is below 0, the delay becomes negative and the rest appears in one go. Dialog.init() reads minTextSpeed and maxTextSpeed from the min and max attributes of the settings screen’s [data-action="set-text-speed"] slider (1 and 50 in the stock markup), so a game gets the semi-instant behavior by giving that slider a negative min.

The same check runs for every proceed, including auto-play and skip: an auto-play tick that arrives while a line is typing finishes the line and is refused.

Speed

The delay starts from the TextSpeed preference (default 20 milliseconds, humanized up to 30). Every type-writer reads it in initiate() for each line, so a change from the settings slider or from code applies from the next line. The slider reads as a speed: Dialog.bind() turns its position into a delay with mirrorTextSpeed() (src/lib/typing-utils.ts: min + max - value), clamps it between minTextSpeed and maxTextSpeed and stores it, and the settings screen places the slider with the same function when the game starts. The right end is the smallest delay.

The dialog log

<dialog-log> sits in the game screen of dist/index.html. Its static setup() adds a “Log” button after “Hide” in the quick menu (addButtonAfter()), and bind() registers the dialog-log listener that toggles its active state (the modal--active class). write() appends an entry (data-spoke with the id, the name in the character’s color, the text in a <p>) and removes the placeholder; pop() removes the last entry; onReset() puts the placeholder back.

Keeping it in step with the screen is the job of _dialog_pending_revert: Dialog.didApply() sets it, Dialog.willProceed() clears it, and Dialog.willRollback() (a static hook every rollback calls, whatever statement is reverted) pops the last entry when it is set, then clears it. A line re-applied in the revert cycle doesn’t write to the log, and Dialog.didRevert() sets the flag again for the next rollback, on the ADV and the NVL paths alike.

Going back: NVL pages and clear

State, Storage and Rollback explains the revert cycle. For text, Dialog.willRollback() first marks typing finished, shows the text box, removes a centered dialog, empties the name and pops the log. Then Dialog.revert() brings back the line before:

flowchart TD start(["Dialog.revert() for the line being returned to"]) --> isNvl{"An NVL line?"} isNvl -- no --> adv["apply() and didApply() again,<br/>in the Revert cycle: no log write,<br/>no NVL history push"] isNvl -- yes --> mode{"Is the box in NVL mode now?"} mode -- yes --> restore{"_should_restore_nvl set by clear?"} restore -- no --> removeLast["Remove the last [data-spoke] entry"] restore -- yes --> hasPage{"Is there a page in history('nvl')?"} mode -- no --> hasPage hasPage -- yes --> putBack["mode nvl, put back history('nvl').pop()"] hasPage -- no --> fail["throw: the revert fails,<br/>the current statement runs again"]

The NVL history stores each page as HTML, nested type-writers, characters and effect attributes included, and putting it back with html() restores them as they were.

clear calls Dialog.reset({ keepNVL: true, saveNVL: true }): in NVL mode the page is pushed onto history('nvl') first, then the name, text, side image, data-speaking and classes are emptied, and the mode is kept. Clear.didApply() pushes the mode onto history('clear') and advances. Its revert() pops that history and, when the mode was nvl, sets _should_restore_nvl, so the NVL line reverted next puts the whole page back instead of removing one entry. Clear.didRevert() returns { advance: true }, so the revert goes on to that line at once.

Hiding the text box

hide textbox and show textbox set the text box’s hidden state (onStateUpdate() hides it or shows it as a grid) and state.textboxHidden; HideTextBox.onLoad() hides it again after a load. TextBox.show() does nothing while hidden is true, which is why Dialog.apply() can call it on every line. The quick menu’s Hide button is a different thing: distraction-free mode hides the element directly and sets the distraction_free global, which also refuses every proceed (Components and Screens).

The data

The type-writer’s marker registry and parse results, from src/components/type-writer/index.ts:

export type ActionType = 'number' | 'enclosed' | 'instance';

export interface TypeWriterAction {
  name: string;
  type: ActionType;
  action: (this: TypeWriter, ...args: unknown[]) => void;
}

export interface ParsedAction {
  action: string;
  n?: string;
  options?: Record<string, string> | string[];
  text?: string;
  id?: string;
}

A number action receives n (a string); an instance action receives nothing. Both run with the type-writer as this, so they can read this.speed, this.nextPause, this.nodeCounter and this.elements.

The type-writer’s properties and state:

export interface TypeWriterProps extends Properties {
  string: string | false;
  typeSpeed?: number;
  loop?: boolean | number;
  showCursor?: boolean;
  hideCursorOnEnd?: boolean;
  delay?: number;
  start?: boolean;
}

export interface TypeWriterState extends Properties {
  config: Partial<TypedConfig>;
  strings: string[];
  cursor: Record<string, string>;
  ignore?: boolean;
  special?: Record<string, boolean>;
}

typeSpeed as a property wins over the configuration; start makes a type-writer type its string as soon as it mounts (a component of a game’s own can use it); cursor entries become --cursor-<key> custom properties on the element.

One character, from src/components/type-character/index.ts:

export interface TypeCharacterProps extends Properties {
  letter: string | false;
  br?: boolean;
  hr?: boolean;
  img?: boolean;
  charIndex?: number;
}

export interface TypeCharacterState extends Properties {
  special?: Record<string, boolean>;
  [key: string]: unknown;
}

The text box, from src/components/text-box/index.ts, and a log entry, from src/components/dialog-log/index.ts:

interface TextBoxProps extends Properties {
  mode: 'adv' | 'nvl';
}

interface TextBoxState extends Properties {
  hidden: boolean;
}

export interface DialogEntry {
  id: string;
  character: Character;
  dialog: string;
}

The character properties Dialog reads, from Character in src/lib/types/index.ts: name, color, directory, expressions, default_expression, type_animation and nvl.

The stores this subsystem uses:

Store Key Written by Holds
global() finished_typing the type-writer’s callbacks, setContent(), Dialog.willRollback() whether the current line is fully shown
global() _dialog_pending_revert Dialog.didApply(), willProceed(), willRollback() whether the next rollback pops the dialog log
global() _should_restore_nvl Clear.revert(), Dialog.revert() whether the next NVL revert restores a whole page
history() nvl Dialog (ADV after NVL), Dialog.reset({ saveNVL }) NVL pages as HTML strings
history() clear Clear.didApply() the mode ('adv' or 'nvl') at each clear
state() textboxHidden HideTextBox, ShowTextBox whether hide textbox is in effect, saved with the game

And the settings and preference, from GameSettings and PlayerPreferences with their defaults in src/monogatari.ts:

Name Kind Engine default Starter game (js/options.js)
TypeAnimation setting true true
NVLTypeAnimation setting true true
NarratorTypeAnimation setting true true
CenteredTypeAnimation setting true true
InstantText setting false true
TypingCursor setting false false
TextSpeed preference (saved with the player’s settings) 20 20
minTextSpeed, maxTextSpeed settings created by Dialog.init() read from the slider 1, 50

Rules and why

  • Dialog stays last. Its matchString() accepts every string. A new built-in action goes before it in the _actions list in src/index.ts.
  • Markers act only in the animation. Every path that doesn’t animate (any of the settings above turned off, a character’s type_animation: false, finish(true)) shows the line’s characters at once: effects show, but number and instance markers never run. A marker can decorate a line; it must never carry something the story depends on.
  • finished_typing is the contract between the type-writer and Dialog.shouldProceed(). Every way a line can end (typed to the end, finish(true), destroy(), setContent() without animation) sets it to true. A new way to end a line has to set it too, or the game never advances.
  • Lines are HTML. The type-writer and the dialog log write the text with innerHTML, so <b>, <br> and <img> in a line work. Values interpolated with {{name}} are inserted the same way, unescaped: a value the player typed becomes markup.
  • Dialog never renders the text box again. NVL entries live inside the ADV type-writer, which survives only because setProps({ mode }) doesn’t re-render. Calling forceRender() on the text box in NVL mode would leave the entries nowhere to go.
  • The revert cycle doesn’t record. apply() checks this._cycle === 'Application' before writing the log, and displayDialog() checks it before pushing the NVL history: a line re-applied on rollback must not be recorded a second time.
  • hidden is the script’s, distraction_free is the player’s. TextBox.show() respects only hidden, so a line never shows a box the script hid.

How to make the common changes

Add a built-in text effect

An effect is an enclosed entry with an empty function and a CSS rule:

  1. Add it to _configuration.actions in src/components/type-writer/index.ts:

    'spotlight': {
      name: 'spotlight',
      type: 'enclosed',
      action: () => {},
    },
  2. Style it in src/components/type-writer/index.css, with the character index when it should ripple:

    type-character[data-effect-spotlight] {
      display: inline-block;
      animation: spotlight 1.2s ease-in-out infinite;
      animation-delay: calc(var(--char-index, 0) * 0.05s);
    }
    
    @keyframes spotlight {
      50% {
        text-shadow: 0 0 0.4em currentColor;
      }
    }
  3. Add the name to TextEffect and EFFECT_CATEGORIES in src/lib/types/TypeWriterEffects.ts, so the types list it.

  4. Add a test to the “Text Effects” block of cypress/e2e/actions/dialog.spec.js that looks for type-character[data-effect-spotlight], rebuild (bun build.ts --browser while you work), and document it on the type-writer and dialogs pages.

Check the name against the existing ones: the enclosed pattern accepts anything after the name (\{/?(?:names).*?\}), so a name that starts with an existing one is read as that one with options. {fadeout} would be fade.

Add a marker that does something

A game or a plugin registers markers at runtime through the component class, before the line is typed; the change reaches running type-writers through patternCacheVersion:

monogatari.component('type-writer').action({
  name: 'flash',
  type: 'number',
  action: function(n) {
    // `this` is the type-writer. n is the number as a string.
    this.engine.element().find('[data-screen="game"]').addClass('flash');
    setTimeout(() => this.engine.element().find('[data-screen="game"]').removeClass('flash'), Number(n));
  },
});

{flash:300} then runs at its position in the line. A built-in marker goes into _configuration.actions like the effect above. Remember the first rule: with the animation off, or after an instant finish, it doesn’t run.

Change what the first click does

The decision is in Dialog.shouldProceed() and stopTyping(). A game changes it with settings: InstantText, or a negative min on the text speed slider for a rush that ends at once. In the engine, keep the throw: removing it turns the first click into “finish and advance in one go”, and exercise 1 shows the tests that catch it.

Add a speaker keyword

Speaker keywords (centered, nvl, narrator) are the branches of the constructor’s else. A new one is a branch there plus a display method, and it has to come after the character test, so a character with the same id still wins. Give it a revert path as well, and a log entry: write() treats every id other than _narrator and centered as a character and reads its name and color.

Listen to typing from outside

didStartTyping and didFinishTyping are engine events (Events):

monogatari.on('didFinishTyping', () => {
  monogatari.element().find('[data-ui="who"]').addClass('done');
});

didStartTyping fires once for each typed line, from preStringTyped when the typing starts; a line shown at once fires only didFinishTyping.

Pitfalls and history

  • The typing code was replaced twice. Until August 2024 the engine typed with typed.js; fc176c43 replaced it with its own MonoTyped script “to fix word snapping”, a0955f36 (September 2024) turned that into the mono-typist and no-letter components (its message lists “addAction only accepts number types” as a known issue), and 3a832a34 (November 2024) renamed them type-writer and type-character. 670e0a96 added stopTyping() and the ignore state while fixing centered lines; 8e2e75ba (December 2025) added the 43 enclosed effects and the data-effect-* attributes they work through.
  • The opening marker changed. In 8e2e75ba an effect opened and closed with the same {/effect} marker, a toggle. d4e306f2 (“TypeScript Engine Update”, the next day) made {effect} the opening one, and ab8481fc updated the tests; the header comments followed in 2.9.0. A line written the old way shows no effect (the first marker is read as a closing one without an opening, reported only through engine.debug.error()).
  • Characters are in the layout from the start. bb2ebe94 switched hidden characters from visibility to opacity to stop words jumping between lines as they typed. The full line is in the DOM, invisible, from the first frame, so cy.get('text-box').contains(…) passes before a single character shows. Test finished_typing, or a character’s data-untyped attribute. 2.9.0 added that attribute because an effect’s animation overrides the inline opacity: 0: before it, fade, glitch-hard and the others showed their letters before they were typed.
  • {speed:N} is relative. It divides the current delay, so {speed:50} followed by {speed:200} is back to normal, not twice as fast. The old type-writer and dialogs pages describe 100 as “normal”.
  • The configuration used to stick. Until 2.9.0, initiate() merged its defaults under the previous line’s state.config, so the text box kept the speed of its first line, and the slider wrote config.typeSpeed to get around it (12d315a4). That write replaced the whole configuration, callbacks included, which dropped a game’s showCursor and could leave a line that was typing without its onStringTyped. cb8a5272 added minTextSpeed.
  • InstantText has two defaults. The engine’s is false; the starter game’s js/options.js sets true. Tests load dist/index.html, so they run with true unless they set it.
  • Auto-play cuts lines short. The comment on AutoPlaySpeed in src/monogatari.ts says the count “starts after the text is completely displayed”; the code in src/engine/ui.ts proceeds on a fixed interval, and Dialog.shouldProceed() finishes a line that is still typing. Checked in Chromium: with AutoPlaySpeed: 1 and a long line, the line completes at about 1 s and the game advances at about 2 s.
  • The dialog log fell out of step on NVL rollbacks until 2.9.0: the NVL branches of Dialog.revert() returned before anything set _dialog_pending_revert. Exercise 4 finds it on the v2.8.1 tag.
  • A load keeps one NVL line. The dialog log and the NVL page are not saved: after a load the log and the page hold only the line that ran again. Rolling back from there removes that entry; since 2.9.0 the NVL revert then shows the line it returns to again, instead of leaving the box empty, so the page grows back one line at a time.
  • Going back from a statement that waits after an NVL line removed that line until 2.9.0. The NVL revert always removed the last entry, which belongs to the next line when the player goes back from an NVL line, but to the line itself when they go back from a choice, an input or another statement that waits. Each NVL entry now carries data-position="<label>:<step>", the statement that wrote it, and the revert removes only the entries after the one of the line the game goes back to. A page put back from the NVL history, or a line shown from elsewhere, has no matching entry, and the revert removes the last one as before.
  • Short character ids capture narrator lines. See the note in “From a string to a Dialog”.
  • Every character is a component. A 100-character line mounts 100 <type-character> elements, and with the debug module loaded Pandora’s registry logs [Pandora] Mounted: <type-character> for each one, whatever the debug level.
  • _handleCustomClasses() removes every class but unread from the text box, including the animated class Component.connectedCallback() adds, before adding the line’s own.
  • The specs set a setting nothing reads. Several tests in actions/dialog.spec.js call setting('TypeAnimationSpeed', …); the speed comes from the TextSpeed preference.
  • The _narrator character (c72b8e00) gives narrator lines defaults (a name, a color), and with it NarratorTypeAnimation stops applying.
  • NVL became a property. 855201ed (2020) replaced the nvl class on the text box with the mode property, which is why the CSS reads text-box[mode="nvl"].

Exercises

Each check is a Cypress spec you put in cypress/e2e/exercises/ and run with bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/<name>.spec.js' (How Each Part Works explains the setup). Delete the files when you’re done, and undo any engine change with git checkout -- src dist/engine/core.

Exercise 1: prove the first click finishes the line

What to do. Write a spec that shows a long line, proceeds while it types, and checks that the game stays on the line until it is complete and advances on the next proceed. Cover both values of InstantText. Then remove the throw from Dialog.shouldProceed(), rebuild with bun build.ts --browser, and watch your spec catch it.

Hint. cy.proceed() calls proceed() directly. cy.contains() can’t tell a typed line from an untyped one; global('finished_typing'), state('step') and a character’s style.opacity can. A TextSpeed of 50 gives you about five seconds.

Check. Both tests pass on the engine as it is, and both fail (“expected 1 to equal 0”) once the throw is gone.

Solution

cypress/e2e/exercises/first-click.spec.js:

context ('Exercise: the first click finishes the line', function() {

  const LONG_LINE = 'This line is long enough that it is still being typed when the player clicks.';

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

  it ('rushes through the rest of the line when InstantText is off', function() {
    this.monogatari.setting ('InstantText', false);
    this.monogatari.preference ('TextSpeed', 50);
    this.monogatari.script({
      'Start': [
        LONG_LINE,
        'Second line.',
        'end'
      ]
    });

    cy.start();
    cy.wrap(this.monogatari).invoke ('global', 'finished_typing').should ('equal', false);

    // The first click finishes the line instead of advancing
    cy.proceed();
    cy.wrap(this.monogatari).invoke ('state', 'step').should ('equal', 0);

    // The rest of the line is revealed one character per frame, effects kept
    cy.wrap(this.monogatari).invoke ('global', 'finished_typing').should ('equal', true);
    cy.get ('text-box type-character').last().should(($character) => {
      expect($character[0].style.opacity).to.equal ('');
    });

    // The second click advances
    cy.proceed();
    cy.wrap(this.monogatari).invoke ('state', 'step').should ('equal', 1);
    cy.get ('text-box').contains ('Second line.');
  });

  it ('replaces the characters with the plain line when InstantText is on', function() {
    this.monogatari.setting ('InstantText', true);
    this.monogatari.preference ('TextSpeed', 50);
    this.monogatari.script({
      'Start': [
        LONG_LINE,
        'Second line.',
        'end'
      ]
    });

    cy.start();
    cy.proceed();

    cy.wrap(this.monogatari).invoke ('state', 'step').should ('equal', 0);
    cy.wrap(this.monogatari).invoke ('global', 'finished_typing').should ('equal', true);
    cy.get ('text-box type-character').should ('not.exist');
    cy.get ('text-box [data-ui="say"]').should ('have.text', LONG_LINE);

    cy.proceed();
    cy.wrap(this.monogatari).invoke ('state', 'step').should ('equal', 1);
  });
});

The rush takes about a second for the 70-odd characters left, well inside Cypress’s four-second retry. With the throw removed, stopTyping() still runs, but nothing refuses the proceed, so the first proceed() finishes the line and advances to step 1 in the same click.

Exercise 2: add a highlight effect

What to do. Register an enclosed effect named highlight, style it with a background color, and show that Look at {highlight}this{/highlight} word. marks exactly the four letters of “this” and shows no marker. Then run the same spec without the registration.

Hint. monogatari.component('type-writer') returns the component class, which has the static action(). The attribute a character gets is data-effect-<name>. In the spec, a <style> element added to the document stands in for the game’s style/main.css.

Check. The spec passes with the registration. Without it, {highlight} stays in the line as typed text and the spec fails (“never found text-box [data-effect-highlight]”).

Solution

cypress/e2e/exercises/highlight-effect.spec.js:

context ('Exercise: a highlight effect', function() {

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

  it ('marks the enclosed characters and styles them', function() {
    const TypeWriter = this.monogatari.component ('type-writer');

    TypeWriter.action({
      name: 'highlight',
      type: 'enclosed',
      action: () => {}
    });

    // What a game would put in style/main.css
    cy.document().then((document) => {
      const style = document.createElement ('style');

      style.textContent = 'type-character[data-effect-highlight] { background-color: rgb(255, 230, 0); }';
      document.head.append(style);
    });

    this.monogatari.preference ('TextSpeed', 1);
    this.monogatari.script({
      'Start': [
        'Look at {highlight}this{/highlight} word.',
        'end'
      ]
    });

    cy.start();
    cy.wrap(this.monogatari).invoke ('global', 'finished_typing').should ('equal', true);

    cy.get ('text-box [data-effect-highlight]').should ('have.length', 4).then(($characters) => {
      expect($characters.text()).to.equal ('this');
    });
    cy.get ('text-box [data-effect-highlight]').first().should ('have.css', 'background-color', 'rgb(255, 230, 0)');
    cy.get ('text-box [data-ui="say"]').should ('not.contain', '{highlight}');
  });
});

The function of an enclosed action never runs for its effect; what matters is that the name is in the registry, so the parser recognizes the marker and puts highlight-<n> in the special state of the characters inside.

Exercise 3: find out when a marker doesn’t run

What to do. Register an instance marker {ding/} that adds one to a global counter, put it near the end of a long line, and find the cases where it runs and where it doesn’t: typed to the end, clicked early with InstantText off, clicked early with it on, and TypeAnimation off.

Hint. An instance marker’s function runs with the type-writer as this, so this.engine.global() is there. Compare finish(true) and finish(false) in the type-writer, and setContent() without animation.

Check. The counter is 1, 1, 0 and 0. Without the registration, the first, second and fourth tests fail.

Solution

cypress/e2e/exercises/instance-marker.spec.js:

context('Exercise: an instance marker', () => {
  const LINE = 'A line long enough for the player to click before the marker. {ding/}After.';

  const registerDing = (monogatari) => {
    monogatari.global('dings', 0);
    monogatari.component('type-writer').action({
      name: 'ding',
      type: 'instance',
      action: function() {
        this.engine.global('dings', this.engine.global('dings') + 1);
      },
    });
  };

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

  it('runs once when the line is typed to the end', function() {
    registerDing(this.monogatari);
    this.monogatari.preference('TextSpeed', 1);
    this.monogatari.script({ 'Start': [LINE, 'end'] });

    cy.start();
    cy.wrap(this.monogatari).invoke('global', 'finished_typing').should('equal', true);
    cy.wrap(this.monogatari).invoke('global', 'dings').should('equal', 1);
    cy.get('text-box [data-ui="say"]').should('not.contain', '{ding/}');
  });

  it('runs during the rush when InstantText is off', function() {
    registerDing(this.monogatari);
    this.monogatari.setting('InstantText', false);
    this.monogatari.preference('TextSpeed', 50);
    this.monogatari.script({ 'Start': [LINE, 'end'] });

    cy.start();
    cy.proceed();
    cy.wrap(this.monogatari).invoke('global', 'finished_typing').should('equal', true);
    cy.wrap(this.monogatari).invoke('global', 'dings').should('equal', 1);
  });

  it('never runs when InstantText is on and the player clicks first', function() {
    registerDing(this.monogatari);
    this.monogatari.setting('InstantText', true);
    this.monogatari.preference('TextSpeed', 50);
    this.monogatari.script({ 'Start': [LINE, 'end'] });

    cy.start();
    cy.proceed();
    cy.wrap(this.monogatari).invoke('global', 'finished_typing').should('equal', true);
    cy.wrap(this.monogatari).invoke('global', 'dings').should('equal', 0);
  });

  it('never runs without the type animation', function() {
    registerDing(this.monogatari);
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({ 'Start': [LINE, 'end'] });

    cy.start();
    cy.get('text-box [data-ui="say"]').should('have.text', 'A line long enough for the player to click before the marker. After.');
    cy.wrap(this.monogatari).invoke('global', 'dings').should('equal', 0);
  });
});

finish(false) keeps the animation loop running with no delay, so typewrite() still meets the marker. finish(true) and setContent(text, false) reveal the line’s characters at once instead: the marker is parsed out of the text, but typewrite() never reaches its position, so its function is never called. This is the first rule of this page in a test.

Exercise 4: keep the dialog log in step on NVL rollbacks

This exercise uses the v2.8.1 tag, where the bug still is: do it in a scratch worktree (git worktree add ../monogatari-2.8.1 v2.8.1, then bun install there).

What to do. Write a spec with three NVL lines: proceed to the third, roll back twice, and after each step check that the dialog log has as many entries as the text box. Run it, see it fail, and fix src/actions/Dialog.ts so it passes. Make sure the existing text specs still pass.

Hint. Follow _dialog_pending_revert through didApply(), willProceed(), willRollback() and both branches of revert(). Which path leaves it false when the line it brought back is in the log?

Check. Before the fix the spec fails at the second rollback (“Found ‘2’, expected ‘1’”). After it, the spec passes, and so do actions/dialog.spec.js, actions/clear.spec.js, components/dialog-log-scroll.spec.js and components/text-box-scroll.spec.js (70 tests).

Solution

cypress/e2e/exercises/nvl-log-rollback.spec.js:

context('Exercise: the dialog log on NVL rollback', () => {
  beforeEach(() => {
    cy.open();
  });

  it('keeps one log entry for each line on screen', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'nvl One.',
        'nvl Two.',
        'nvl Three.',
        'end',
      ],
    });

    cy.start();
    cy.proceed();
    cy.proceed();
    cy.get('text-box [data-spoke]').should('have.length', 3);
    cy.get('dialog-log [data-spoke]').should('have.length', 3);

    cy.rollback();
    cy.get('text-box [data-spoke]').should('have.length', 2);
    cy.get('dialog-log [data-spoke]').should('have.length', 2);

    cy.rollback();
    cy.get('text-box [data-spoke]').should('have.length', 1);
    cy.get('dialog-log [data-spoke]').should('have.length', 1);
    cy.get('dialog-log [data-spoke]').last().should('contain', 'One.');
  });
});

The first rollback works: the flag was set by the third line’s didApply(), so willRollback() pops “Three.” and clears it. The revert of the NVL line then removes the last entry and returns, without the didApply() the ADV branch calls, so the flag stays false and the second rollback pops nothing. Set it where every successful revert passes, in didRevert():

 	override async didRevert(): Promise<ActionRevertResult> {
+		// The line on screen now has its entry at the end of the dialog log,
+		// so the next rollback must remove it. The ADV path already set this
+		// flag through didApply(); the NVL paths return before reaching it.
+		this.engine.global('_dialog_pending_revert', true);
+
 		return { advance: false, step: true };
 	}

Rebuild with bun build.ts --browser and run the spec with the four existing ones. The clear path is covered too: after Clear.revert(), the NVL line that puts the page back also ends in didRevert().

2.9.0 made the same change in Dialog.didRevert(); its test is “Keeps the dialog log in step on NVL rollbacks” in cypress/e2e/actions/dialog.spec.js.