Mod Creation/Mod Context API Reference

Revision as of 19:41, 15 October 2022 by Buttchouda (talk | contribs) (API reference guide for the mod context object.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Accessing the Mod Context Object

All examples in this guide will assume a mod context object ctx is in the current scope.

From a Module

If the module is defined as the "setup" for your mod in manifest.json, the exported setup function will receive the context object as a sole parameter:

export function setup(ctx) {
  // ...
}

Otherwise, use the global mod.getContext method, passing in your module's meta object:

const ctx = mod.getContext(import.meta);

From a Script

The recommended approach for scripts is to use the global mod.register method. This only works in scripts injected via the "load" property of manifest.json or the loadScript method of the context object.

mod.register(ctx => {
  // ...
});

From a Lifecycle Method

All game lifecycle method callbacks will also receive their respective mod's context object as a sole parameter.

onCharacterLoaded(ctx => {
  // ...
});

From the Dev Context

For easier prototyping, you can use the global mod.getDevContext method to get a special dev mod context object. This should not be used in a mod, but only for development purposes (via the console). Any APIs that require resources will not work as the dev "mod" does not contain any resources.

const devCtx = mod.getDevContext();

Loading Resources

🚨 All resource file paths must be relative to the root of your mod 🚨

getResourceUrl(path: string): string

Retrieves a usable URL for any resource packaged in your mod.

Parameters

path: string The relative path to the resource to generate a URL for

Returns

string The URL to the requested resource

Example

const url = ctx.getResourceUrl('sea-shanty-2.ogg');
const song = new Audio(url);
song.loop = true;
song.play();

loadModule(path: string): Promise<any>

Dynamically imports a JavaScript module.

Parameters

path: string The relative path to the module resource

Returns

Promise<any> A promise that resolves to an object containing all exported features from the module

Example

// my-module.mjs
export function greet(name) {
  console.log(`Hello, ${name}!`);
}
const myModule = await ctx.loadModule('my-module.mjs');
myModule.greet('Melvor'); // Hello, Melvor!

loadScript(path: string): Promise<void>

Injects a JavaScript file into the page.

Parameters

path: string The relative path to the script resource

Returns

Promise<void> A promise that resolves when the injected script has finished running

Example

// Await call if wanting the script to run before continuing
await ctx.loadScript('my-script.js');
// my-script.js has run

// Don't await if no dependency on script
ctx.loadScript('my-independednt-script.js');
// my-independent-script.js has NOT run yet

loadStylesheet(path: string): void

Injects a CSS stylesheet into the page.

Parameters

path: string The relative path to the stylesheet resource

Example

ctx.loadStylesheet('my-styles.css');

loadData(path: string): Promise<any>

Loads data from a JSON resource.

Parameters

path: string The relative path to the JSON resource

Returns

Promise<any> A promise that resolves to the parsed JSON object

Example

// my-data.json
{
  "coolThings": [
    "rocks"
  ]
}
// in JavaScript
const myData = await ctx.loadData('my-data.json');
console.log(myData.coolThings); // ['rocks']

Lifecycle Hooks

onModsLoaded(callback: (ctx: ModContext) => void | Promise<void>): void

Execute code after all mods have been loaded (character select screen).

Parameters

callback: (ctx: ModContext) => void | Promise<void> A callback function that receives the mod's context object as a parameter. Can be synchronous or asynchronous.

Example

ctx.onModsLoaded(async (ctx) => {
  // ...
});

onCharacterSelectionLoaded(callback: (ctx: ModContext) => void | Promise<void>): void

Execute code after the the character selection screen has fully loaded.

Parameters

callback: (ctx: ModContext) => void | Promise<void> A callback function that receives the mod's context object as a parameter. Can be synchronous or asynchronous.

Example

ctx.onCharacterSelectionLoaded(async (ctx) => {
  // ...
});

onCharacterLoaded(callback: (ctx: ModContext) => void | Promise<void>): void

Execute code after the player's chosen character has loaded and all game objects are created, but before offline progress calculations.

Parameters

callback: (ctx: ModContext) => void | Promise<void> A callback function that receives the mod's context object as a parameter. Can be synchronous or asynchronous.

Example

ctx.onCharacterLoaded(async (ctx) => {
  // ...
});

onInterfaceReady(callback: (ctx: ModContext) => void | Promise<void>): void

Execute code after offline progress has been calculated and all in-game user interface elements have been created.

Parameters

callback: (ctx: ModContext) => void | Promise<void> A callback function that receives the mod's context object as a parameter. Can be synchronous or asynchronous.

Example

ctx.onInterfaceReady(async (ctx) => {
  // ...
});

Adding and Modifying Game Data

✔️ Not documented yet, but it is available ✔️

Mod Settings

The mod settings API can be accessed through the settings property on the root context object.

section(name: string): Section

Gets or creates a settings section. The order that sections are created are the order they will display in a mod's settings window.

Parameters

name: string The name of the section. This will be displayed as a header of the section in the settings window.

Returns

Section The section's object, used to perform add, set, or get settings.

Example

ctx.settings.section('General');
ctx.settings.section('Other');
// Sections will be displayed in the settings window in this order
// 1. General
// 2. Other

Section.add(config: SettingConfig | SettingConfig[]): void

Adds a setting to the section. The order that settings are added to a section are the order they will display in a mod's settings window.

Parameters

config: SettingConfig | SettingConfig[] The setting's configuration object or an array of configuration objects to add multiple settings at once. See Settings Types section below for setting configuration options.

Example

ctx.settings.section('General').add({
  type: 'switch',
  name: 'awesomeness-detection',
  label: 'Awesomeness Detection',
  hint: 'Determines if you are awesome or not.',
  default: false
});

ctx.settings.section('Other').add([{
    type: 'label',
    label: 'I am just a label though my story seldom told...'
  }, {
    type: 'number',
    name: 'pick-a-number',
    label: 'Pick a Number',
    hint: '1 through 10'
}]);

Section.get(name: string): any

Gets the current value of a setting by its name property.

Parameters

name: string The name of the setting to get the value of

Returns

any The current value of the setting

Example

// Assuming the player has typed "1" into the setting
ctx.settings.section('Other').get('pick-a-number'); // 1

Section.set(name: string, value: any): void

Programmatically sets the value of a setting by its name property.

Parameters

name: string The name of the setting to set the value of

value: any The value to set the setting to

Example

ctx.settings.section('Other').set('pick-a-number', 5);

type(name: string, config: SettingTypeConfig): void

Registers a setting type that can then be used by by any mod when adding a setting.

Parameters

name: string The name of the setting type. This is what should be used for the type property of a setting configuration when adding a new setting. Other mods have to prepend the name with your mod's namespace.

config: SettingTypeConfig An object defining the setting type's behavior. See definition below.

Example

// manifest.json
{
  "namespace": "my_mod",
  // ...
}
ctx.settings.type('customText', {
  // See example config in SettingTypeConfig section below
});

ctx.settings.section('Genera').add({
  type: 'customText',
  // ...
});

Other mods will have to add your namespace to use your custom type:

ctx.settings.section('Other').add({
  type: 'my_mod:customText',
  // ...
});

SettingTypeConfig

All functions are required.

render(name: string, onChange: () => void, config: SettingConfig): HTMLElement

The render function is responsible for using any properties passed into the config to render HTML for the setting.

The name parameter should be used as a form of id in the setting's HTML, if needed. The common use case for this is setting an <input>'s name and id attributes to this value, and then setting a <label>'s for attribute to this value as well.

The onChange parameter should be called when this setting's value is changed. The common use case for this is adding this as an event listener to an <input> element's change event.

The config parameter holds all values passed in the config object when this setting is being added. For example, the label, hint, default, etc. properties.

Individual settings can opt to return validation errors in their onChange method. You can give a place to display this validation error in an element with a class of validation-message.

// The render function for a simple text box
function render(name, onChange, config) {
  const input = document.createElement('input');
  input.id = name;
  input.type = 'text';
  input.name = name;

  const label = document.createElement('label');
  label.for = name;
  label.textContent = config.label;

  if (config.hint) {
    const hint = document.createElement('small');
    hint.textContent = config.hint;
    label.appendChile(hint);
  }

  const validation = document.createElement('small');
  validation.classList.add('text-danger', 'validation-message');

  const root = document.createElement('div');
  root.appendChild(input);
  root.appendChild(label);
  root.appendChild(validation);

  return root;
}
get(root: HTMLElement): any

The get function is responsible for retrieving the current value of the setting. It receives just one parameter, the root HTML element returned from the render function, which can be useful for getting the current value.

// get function for simple text input defined by above render
function get(root) {
  return root.querySelector('input').value;
}
set(root: HTMLElement, value: any): void

The set function is responsible to keeping the HTML up-to-date with the current value (if updated programmatically). It receives the root HTML element from the render function and the value being set as the two parameters.

// set function for simple text setting defined above
function set(root, value) {
  root.querySelector('input').value = value;
}

Example

// Use functions defined in above examples as reference
ctx.settings.type('simpleText', {
  render: render,
  get: get,
  set: set
});

Built-In Types

Base Setting Configuration

All individual settings inherit this base setting config object.

interface SettingConfig {
  type: string; // Type of the setting
  name: string; // Name of the setting
  label: string | HTMLElement; // Display label for the setting
  hint: string | HTMLElement; // Small help text to display alongside the setting
  default: any; // Default value for the setting
  onChange(value: any, previousValue: any): void | boolean | string // See notes
}

The onChange option is a callback function that receives the new value being set and the previous value of the setting. This function can optionally return a value to serve as a validator:

  • No return value / undefined / true / truth-y (non-string) value: Validates successfully and allows the value to be changed
  • false / false-y value: Validation fails and setting value is restored to previous
  • string value: Validation fails, setting value is restored to previous, and the string contents are displayed in a .validation-message element, if available (see custom render above)

Text

A simple textbox that accepts any character by default. Value is of type string.

interface TextConfig implements SettingConfig {
  type: 'text';
  maxLength: number; // Max length attribute for the textbox
}

Number

A simple textbox that only accepts numbers. Value is of type number.

interface NumberConfig implements SettingConfig {
  type: 'number';
  min: number; // Minimum value to be entered
  max: number; // Maximum value to be entered
}

Switch

An on/off toggle switch. Value is of type boolean.

interface SwitchConfig implements SettingConfig {
  type: 'switch'
}

Dropdown

A dropdown button. Example: "Default Page on Load" game setting. Value is of type any.

DropdownConfig implements SettingConfig {
  type: 'dropdown';
  color: string; // see Button config
  options: DropdownOption[]; // see note
}

The options option defines the dropdown options available to be selected. Dropdown option schema is:

interface DropdownOption {
  value: any; // value that is used by the setting
  display: string | HTMLElement; // display text or element on the option
}

Button

A button. Value is undefined.

interface ButtonConfig implements SettingConfig {
  type: 'button';
  display: string | HTMLElement; // displayed text or element inside the button
  color: string; // see note
  onClick(): void; // triggered on click of the button
}

The color option is appended to a CSS class starting with btn- and defaults to primary (btn-primary) if not defined. Default colors available:

  • primary: blue
  • secondary: grey
  • success: green
  • info: light blue
  • warning: yellow
  • danger: red
  • dark: dark grey

Checkbox Group

A group of checkboxes. Value is of type any[].

interface CheckboxGroupConfig implements SettingConfig {
  type: 'checkbox-group';
  options: CheckboxOption[]; // see note
}

The options option defines the checkboxes that are available to be selected. Checkbox option schema is:

interface CheckboxOption {
  value: any; // value to be added to array that is set as setting value
  label: string | HTMLElement;
  hint: string | HTMLElement;
}

Radio Group

A group of radio buttons. Value is of type any.

interface RadioGroupConfig implements SettingConfig {
  type: 'radio-group';
  options: CheckboxOption[]; // see checkbox group's options schema
}

Label

A simple label. Value is undefined.

interface LabelConfig implements SettingConfig {
  type: 'label';
}

Custom

A custom-rendered setting. See SettingTypeConfig section above. This is different from registering a custom setting type as this is a one-off and will not register the type for reuse. Value is of type any.

interface CustomConfig implements SettingConfig, SettingTypeConfig {
  type: 'custom';
}

Character Data Storage

The character storage API can be accessed through the characterStorage property on the root context object.

Limitations

The character storage can only be used once a character has been loaded (after lifecycle hook onCharacterLoaded).

Each character can store up to 8,192 bytes (8kb) of data per mod, including keys. Only JSON-serializable data can be stored. This includes primitive types (string, number, boolean) and objects and arrays that contain only primitive types or other objects or arrays that fit this description. This serialization/deserialization is handled automatically.

setItem(key: string, data: any): void

Sets a key/value pair in character storage.

Parameters

key: string The key to identify the data being stored. Used in calls to getItem and removeItem.

data: any The data to be stored. See limitations above.

Example

ctx.characterStorage.setItem('coolThings', ['rocks']);

getItem(key: string): any

Gets a value by its key from character storage.

Parameters

key: string The key of the data to retrieve

Returns

any The data retrieved. Returns undefined if no such key is stored.

Example

ctx.characterStorage.getItem('coolThings'); // returns ['rocks']

removeItem(key: string): void

Removes a key/value pair by key from character storage.

Parameters

key: string The key of the key/value pair to remove

Example

ctx.characterStorage.removeItem('coolThings');
ctx.characterStorage.getItem('coolThings'); // returns undefined

clear(): void

Removes all key/value pairs from character storage.

Example

ctx.characterStorage.clear();

Account Data Storage

The account storage API can be accessed through the accountStorage property on the root context object.

Limitations

Due to the cloud-based nature of how account data is stored and potential network issues the player may experience, data integrity is not 100% guaranteed in the account storage. Account storage is advised to be used sparingly.

An account can store up to 8,192 bytes (8kb) of data per mod, including keys. Only JSON-serializable data can be stored. This includes primitive types (string, number, boolean) and objects and arrays that contain only primitive types or other objects or arrays that fit this description. This serialization/deserialization is handled automatically.

setItem(key: string, data: any): void

Sets a key/value pair in account storage.

Parameters

key: string The key to identify the data being stored. Used in calls to getItem and removeItem.

data: any The data to be stored. See limitations above.

Example

ctx.accountStorage.setItem('coolThings', ['rocks']);

getItem(key: string): any

Gets a value by its key from account storage.

Parameters

key: string The key of the data to retrieve

Returns

any The data retrieved. Returns undefined if no such key is stored.

Example

ctx.accountStorage.getItem('coolThings'); // returns ['rocks']

removeItem(key: string): void

Removes a key/value pair by key from account storage.

Parameters

key: string The key of the key/value pair to remove

Example

ctx.accountStorage.removeItem('coolThings');
ctx.accountStorage.getItem('coolThings'); // returns undefined

clear(): void

Removes all key/value pairs from account storage.

Example

ctx.accountStorage.clear();