Everything you see in a Monogatari game is a component: the text box, the menus, the save slots, the choice buttons, the screens. A component is a custom element, an HTML tag of its own like <text-box>, with its own markup and behavior.

You can write components of your own, and change or replace the built-in ones. This page writes three: a meter that’s on screen all game, a screen of your own, and a card an action puts on screen. The next pages go deeper:

The Components section documents each built-in component.

Two kinds of components

Kind Examples Who puts it on the page
Persistent: screens, menus and interface that exist for the whole game <main-screen>, <main-menu>, <game-screen>, <text-box>, <quick-menu> You, in index.html.
Created by an action: interface that exists while a statement needs it <choice-container>, <message-modal>, <text-input>, <centered-dialog>, <timer-display> The action that needs it, from its apply().

The base classes

Every component class extends one of Monogatari’s base classes, which are on the Monogatari global:

Class Use it for What it adds
Monogatari.Component Most components. The engine as this.engine, the game hooks, and helpers for the page such as this.element() and this.content(). It renders into the light DOM, so style/main.css reaches everything inside it.
Monogatari.ShadowComponent A self-contained widget whose styles shouldn’t mix with the page’s. The same, rendered into a shadow root.
Monogatari.ScreenComponent A full screen that opens and closes, like <settings-screen>. An open state that adds the active class, and a data-screen attribute: the tag without -screen.
Monogatari.MenuComponent A row of buttons, like <main-menu> and <quick-menu>. Buttons kept in the engine’s configuration, with addButton(), removeButton() and the other menu methods.

They’re built on Pandora 0.5, the component library Monogatari 2 uses, which provides the element’s life cycle and its rendering. See Core Libraries.

Write your first component

This component shows how much a character likes the player: an “Affection” badge in the corner of the game screen, kept up to date as the story changes the affection variable.

Add the class to js/main.js, above $_ready(…):

class AffectionMeter extends Monogatari.Component {
  // The tag you write in index.html. It must contain a hyphen.
  static tag = 'affection-meter';

  // Draws the meter again. An arrow function keeps `this` pointing at the
  // element when the engine calls it.
  refresh = () => {
    this.forceRender();
  };

  // Runs once the element is on the page and has rendered for the first time.
  async didMount() {
    // didUpdateState fires whenever the game's state changes: every
    // statement, going back, loading a save, quitting.
    this.engine.on('didUpdateState', this.refresh);
  }

  // Runs when the element is taken off the page.
  async willUnmount() {
    this.engine.off('didUpdateState', this.refresh);
  }

  // The markup inside <affection-meter>.
  render() {
    const affection = this.engine.storage('affection');
    const max = this.props.max || 10;

    return `
      <span class="affection-meter__label">Affection</span>
      <span class="affection-meter__value">${affection} / ${max}</span>
    `;
  }
}

monogatari.registerComponent(AffectionMeter);

Place it in index.html, inside <game-screen>, so it shows while the game is played:

<game-screen>
  <dialog-log></dialog-log>
  <text-box></text-box>
  <quick-menu></quick-menu>
  <affection-meter max="5"></affection-meter>
</game-screen>

Style it in style/main.css:

affection-meter {
  position: absolute;
  top: 1rem;
  right: 1rem;
  z-index: 11;
  display: flex;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  background: var(--main-color);
  color: #ffffff;
}

Give the variable a starting value in js/storage.js, next to the variables already there:

monogatari.storage({
  player: {
    name: '',
  },
  affection: 0,
});

And change it from the script, with a function the player can go back past:

monogatari.script({
  'Start': [
    'show scene afternoon',
    'show character m happy at left',
    'You hold the door open for her.',
    { 'Function': {
      'Apply': function() {
        this.storage({ affection: this.storage('affection') + 1 });
      },
      'Revert': function() {
        this.storage({ affection: this.storage('affection') - 1 });
      },
    } },
    'show character m smiling at left',
    'She smiles.',
    'end',
  ],
});

Start the game: the badge reads “Affection 0 / 5”, and “Affection 1 / 5” when “She smiles.” shows. Press Back and it reads 0 again.

Mio smiling on the left, in front of the Palacio de Bellas Artes, with a badge reading "Affection 1 / 5" in the top right corner and the line "She smiles." in the text box
The AffectionMeter component in the tutorial's game

What each part does:

  • render() returns the component’s markup as text. The engine renders it when the element goes on the page, and again each time forceRender() is called. Changing the variable doesn’t re-render anything by itself.
  • this.props.max reads the max attribute written in index.html. Pandora turns attribute text that looks like a number into a number, and "true" and "false" into booleans, so max="5" reads as 5.
  • didMount() and willUnmount() come in a pair. The engine’s <game-screen> renders its own markup when the game starts and puts the elements written inside it back after it, so your <affection-meter> is taken off the page and a new one is created: willUnmount() removes the old element’s listener, and the new element’s didMount() adds its own.
  • didUpdateState is an engine event that fires every time the game’s state changes, which happens on every statement, so the meter shows the variable’s value from the next statement on.

Registering a component

monogatari.registerComponent(AffectionMeter);
  • Give it a static tag with a hyphen in it: it’s the name of its HTML element, and the browser only accepts names with a hyphen. Without one, Pandora makes the tag from the class’s name (AffectionMeter becomes affection-meter), which breaks as soon as the class is renamed.
  • Register before monogatari.init(): in js/main.js above $_ready(…), or in a file index.html loads before js/main.js.
  • The engine defines every registered component when monogatari.init() sets up, after it reads the player’s saved preferences. Until then, <affection-meter> in index.html is an empty, unknown element.
  • A component registered later is defined right away, but its class’s setup methods don’t run.
  • Registering a tag a second time, before monogatari.init(), replaces the first. That’s how you replace a built-in component. After monogatari.init(), the browser keeps the first definition, and the debug module shows an “Unable to register component” error.
  • monogatari.unregisterComponent('affection-meter') only works before monogatari.init(). After it, the debug module shows an “Unable to unregister component” error.

A screen of your own

Screens are the full-page views of the game: the main menu, settings, saves, help. This one tells the player about the game, and a button in the main menu opens it.

Add the class to js/main.js, above $_ready(…):

class AboutScreen extends Monogatari.ScreenComponent {
  // A tag ending in -screen gets data-screen="about".
  static tag = 'about-screen';

  render() {
    return `
      <button class="top left" data-action="back"><span class="fas fa-arrow-left"></span></button>
      <h2 data-string="About">${this.engine.string('About')}</h2>
      <p>A short story written for a weekend game jam.</p>
    `;
  }
}

monogatari.registerComponent(AboutScreen);

// The text of the menu button and of the screen's title, in English.
monogatari.translation('English', {
  'About': 'About'
});

Place it in index.html, inside <visual-novel>, next to the other screens:

<settings-screen></settings-screen>
<help-screen></help-screen>
<about-screen></about-screen>

Then add the button to the main menu inside monogatari.init()’s .then(…), at the bottom of js/main.js:

$_ready(() => {
  monogatari.init('#monogatari').then(() => {
    monogatari.component('main-menu').addButtonAfter('Settings', {
      string: 'About',
      data: {
        action: 'open-screen',
        open: 'about',
      },
    });
  });
});

The main menu now reads Start, Load, Settings, About, Help. About opens the screen, and its arrow button goes back to the main menu.

A screen with a round back arrow in its top left corner, the title "About" and the sentence "A short story written for a weekend game jam."
The AboutScreen component, opened from the main menu

  • data-action="open-screen" with data-open="about" opens the screen whose data-screen is about, and data-action="back" on a screen goes back to where the player came from. Both are handled by the engine, so the screen needs no code of its own for them.
  • addButtonAfter() works above $_ready(…) too. Inside .then(…), the buttons the engine adds when the game starts are already there, so you can add after Credits or Gallery.
  • data-string="About" and this.engine.string('About') give the title in the player’s language. Each language your game offers needs an About string: see Translating the Interface.

Components an action creates

A component an action creates doesn’t go in index.html. The action builds the element in apply(), gives it its props, and puts it on the page. This pair shows a chapter title over the game screen until the player clicks:

class TitleCard extends Monogatari.Component {
  static tag = 'title-card';

  render() {
    return `<h2>${this.props.text}</h2>`;
  }
}

monogatari.registerComponent(TitleCard);

class ShowTitleCard extends Monogatari.Action {
  static id = 'TitleCard';

  // The player moves on: take the card away.
  static async willProceed() {
    this.engine.element().find('title-card').remove();
  }

  static async willRollback() {
    this.engine.element().find('title-card').remove();
  }

  static async reset() {
    this.engine.element().find('title-card').remove();
  }

  static matchString([keyword]) {
    return keyword === 'title-card';
  }

  constructor([keyword, ...text]) {
    super();
    this.text = text.join(' ');
  }

  async apply() {
    const card = document.createElement('title-card');

    // Set props before the element goes on the page: its first render reads them.
    card.setProps({ text: this.text });

    this.engine.element().find('[data-screen="game"]').append(card);
  }

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

  async revert() {
    await this.apply();
  }

  async didRevert() {
    return { advance: false, step: true };
  }
}

monogatari.registerAction(ShowTitleCard);
title-card {
  position: absolute;
  top: 40%;
  width: 100%;
  z-index: 11;
  color: #ffffff;
  text-align: center;
}

'title-card Chapter One' in the script shows “Chapter One” across the game screen, and the next click takes it away and shows the next line. Going back to it shows it again.

WARNING

A component's constructor must not set attributes, and setProps() sets one for every text, number or boolean prop. Called in the constructor, it breaks document.createElement('title-card'): the browser reports “The result must not have attributes” and returns an element that isn’t your component. Give props their starting values with this.props = { … } in the constructor instead, as the built-in <text-box> does, and call setProps() once the element exists, as apply() does above.

Light DOM and shadow DOM

A Component renders into the light DOM: its markup is ordinary children of the element, and style/main.css reaches all of it. That’s what every built-in component does, and what you want most of the time.

A ShadowComponent renders into a shadow root, a separate tree the page’s stylesheets don’t reach. Give it its styles with setStyle():

class ShadowNote extends Monogatari.ShadowComponent {
  static tag = 'shadow-note';

  async willMount() {
    // true replaces the styles instead of adding to them.
    this.setStyle(':host { display: block; color: rgb(200, 0, 0); } p { margin: 0; }', true);
  }

  render() {
    return '<p>Shadow text</p><slot></slot>';
  }
}

monogatari.registerComponent(ShadowNote);

<shadow-note><b>Slotted</b></shadow-note> shows “Shadow text” in red, followed by the bold “Slotted”. The children written between the tags stay outside the shadow root; the <slot> in render() is where they show. In a Component, a <slot> does nothing of the kind: use this.slotContent there.