# Writing plugins

## Rendering (`./web`)

```ts
export default defineWebPlugin({
  name: "stamp",
  extensions: {
    renderers: { stamp: async (ctx, args, wait, stage) => { /* draw; if wait, wait until it's done */ } },
    restorers: [async (ctx, stage) => { /* on load, rebuild from stage alone */ }],
  },
});
```

- **renderer**: one per command name. The parameters have their defaults filled in, and `stage` is the state after the command ran.
  Decide the look from the state and parameters alone, and don't keep track of progress yourself. A value you return is received by `ctx.present()` in `run`.
- **restorer** is called on load. It plays no effects and builds the current look straight from `stage`.
  You can check that a save and load round trip gives the same screen with `lim shot --eval`, running `window.__liminalia.system.saveTo(1)` → `loadFrom(1)`.
- **Game screen size**: `ctx.screen` (`{ width, height }`, the `screen` in `liminalia.json`; in `setup(host)`, `host.screen`). It's portrait if `ctx.screen.height > ctx.screen.width`. In CSS, use the game screen class `lm-portrait` and the variables `--stage-w` and `--stage-h` (both in px).
  Game screen coordinates (px for things placed in `ctx.layers`) are in `screen` coordinates. The exception is inside the message window, choices and system screens: there, px are at the base size and scaled up or down by the `ctx.uiScale` factor (for projects at the base size, 1280×720 landscape or 720×1280 portrait, it's 1).
  A plugin used only at 1280×720 works with numbers written as they are (the engine adds nothing to the game screen of a 1280×720 project, so the look doesn't change). A plugin also used in projects of other sizes reads `ctx.screen` instead of `1280` and `720`.
- Main members of **RenderContext**:
  - Layers: `layers.background` / `sprites` / `images` (inside the camera), `fx` (outside the camera, below the message window), `hud` (above the message window and below the blackout; hidden while the screen is fully blacked out and during chapter cards), `overlay` (above the message window and the blackout)
  - For `<video>` and `<audio>` that the project plays itself, `ctx.audio.bindMedia(element, volume)` gives them the same volume as standard movies (volume × the volume of the `ui.sound.movie` group × the master volume; mute applies too,
    it follows setting changes right away, and on iOS it goes through Web Audio). The element's `muted` is left as it is
  - `asset(kind, path)`, `image(url)` (waits for loading and decoding), `spriteReady(who?)` (waits until sprites being placed with `@chara` are in place; `@chara` moves on without waiting, so a command that operates on sprite elements right after it should wait for this), `fade(el, to, ms)`, `audio`, `loadData(name)`
    (`name` is a path from the project's `data/`. `loadData("items.json")` and `loadData("items")` are the same; if `.json` is left out, it's added. The name may contain dots (`loadData("code.en")` reads `data/code.en.json`).
    It reads the file as JSON and returns it)
  - `time(ms)` returns 0 while skipping, and while drawing a command whose effect was fast-forwarded with a click. Always pass effect durations through it
  - Fast-forwarding effects: if the player clicks while an effect command (one with a time parameter that waits for its end, that is, one with `waits` or a `wait` parameter) is being drawn,
    the `Element.animate` animations in `layers` and `message` (except repeating ones) jump to their end state, and until that command finishes drawing, animations that start afterward
    also end right away. Use `delay(ms)` instead of waiting with setTimeout (it also ends on fast-forward). For effects you animate yourself with requestAnimationFrame and the like,
    register a function that finishes them with `onFastForward(finish)`, and remove it with the returned function when done. So that fast-forwarding can be turned off for each command, add `skip: t.skip()` to the command's parameters
    (effects of commands written with `skip=false` aren't fast-forwarded)
  - `waitClick()`, `cast` (the character definitions), `message` (the message window element)
  - APIs that save you from operating on internal elements directly (the engine's element structure and classes may change, so don't look for `camera.parentElement` or `.layer.mask`):
    - `world`: the layer outside the camera (the layer `@quake` shakes; it holds the background, sprites and foreground images, but not the message window). For effects that tilt, zoom or tint the whole screen,
      apply them with individual CSS properties (`translate`, `rotate`, `scale`, `filter`) so they don't clash with `@quake` and `@camera`
    - `mask.cover(color)`, `mask.uncover()`: cover or uncover the fade-to-black layer (`@mask`) without animation. This is only the look, so a command that moves on while it's covered also writes `stage.mask` itself
    - `window.hideWhile(job)`, `window.hide()`: hide the message window until job is done (for hide, until you call the returned function). They don't change the `@window` state, can overlap, and are cleared on load
    - `systemLayer`: the system screen layer (the front of the game screen, for things above notifications, such as a loading curtain). In projects that replace the system screens, it's `overlay`
    - `setBackground(image, { fade, method, folder })`: changes the background, shown the same way as `@bg`. It's only the look and doesn't change the state, so use it for temporary pictures that may go back on load
    - `toStage(clientX, clientY)`: converts page coordinates to game screen coordinates (px in `screen`), undoing the game screen's scaling and position
  - `scope({ keepOnSkip })`: cleanup for one-off effects. What you hand to `setTimeout`, `setInterval`, `requestAnimationFrame`, `frame(perFrame)`, `add(element)`, `listen(target, type, handler)` and
    `defer(cleanup)` is cleaned up by the engine on load (rebuilding) and when skipping starts (with `keepOnSkip`, not when skipping).
    `sleep(ms)` doesn't wait while skipping or during a fast-forwarded command, and ends on the spot when fast-forwarded.
    It also ends when cleaned up, so after that, check `scope.disposed` and don't continue. Call `dispose()` when the effect is over
    ```ts
    const scope = ctx.scope();
    const el = scope.add(document.createElement("div"));
    ctx.layers.fx.append(el);
    await el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: ctx.time(200) }).finished;
    await scope.sleep(800);
    scope.dispose();
    ```
  - `on(type, handler)`: events on the rendering side (the returned function removes the handler). They save you from watching the name box or sprite layers with MutationObserver
    - `page` (a page started showing; `at`, `speaker`, `label`), `speaker` (the speaker changed from the previous page; `null` for narration; `previous`)
    - `sprites` (the characters, sprite sets or variants on screen changed; `sprites`, `stage`. To operate on the elements, wait for `spriteReady(character)`)
    - `restore` (rebuilt from state, after the restorers), `load-end` (a system load finished; `from`)
    - `screen-close` (a system screen closed; `name`), `menu-close` (the menu closed)
  - `notify(text, { kind, title, time, delay, se, key, max })`: stacking notifications (the same as `@notify`; see “Notifications” below). `toast(text, ms)`: a short notice like the ones on system screens
  - `offer({ buttons } or { options, choose })`: a screen that waits for the player tells a recording (`lim shot --video`) what can be chosen (see “How recordings go on” above). The returned function withdraws it
  - `host.coverUi()`: call it while showing something that covers the in-game controls, like a full-screen movie. Meanwhile, the system doesn't show the quick menu or
    the menu button (`status.menuBar` is false too). The returned function removes the cover (`@movie` uses this during playback, but not with `menu=true`)
  - `studio` is true when running in Studio's preview. The preview rebuilds from a save every time you move to another line (calling the restorers too), so
    don't show effects that get in the way when shown on every rebuild, such as a loading curtain, when `ctx.studio` is true
  - `reduceShake` is true when the player has set screen shake to reduced, and `reduceFlash` when they've set flashing lights to reduced.
    Effects that shake the screen shouldn't shake when `reduceShake` is true, and effects that flash shouldn't flash when `reduceFlash` is true
  - `system` (`RenderSystem`): the system screen API. Use it from command rendering, restorers and project screens, without keeping the `system` from `ready`
    in a module variable. It's set after the system screens are made, and is `null` during `setup`
    - `openScreen("save")`, `openScreen("gung.map")`: open a screen by name and wait until it closes (the standard screens save, load, log, menu, config, extra,
      items, help and flowchart, or a project screen registered with `defineScreen`; `false` if it can't be opened). `openScreen(build, options)` is
      the same as `system.openScreen`: instead of stacking your own screen on the overlay, you leave blocking input, stacking, Esc and saving to the system
    - `status`, `onStatusChange(…)` (auto, skip, the open screen, whether choices are shown and so on; `SystemStatus`)
    - `perform("save")`, `perform("backlog")`, `perform("screen:gung.map")` (a standard action or a project screen; does nothing when play isn't in progress)
    - `systemVariables` (variables shared by all saves; readable and writable, and `saveSystemVariables()` stores them right away), `defineScreen(…)`, `controller` (the system screens themselves)
    - `callScene("#memo")`: calls a scene from the page being read, and shows that page again when the scene returns at @return or the next label (the same as `call=` of `@hud-button`; it can be called while a page waits for a click and while choices are shown, and the choices are shown again when it returns. It returns `true` when it calls)
    - `announce("Chapter 1 The Rainy Station")`: passes something shown outside the text (such as a chapter card's title) to screen readers and text-to-speech right away (text-to-speech only when the player has turned on Read aloud; nothing is passed while skipping)
    - `ask("There are places you haven't examined yet. Finish anyway?", "investigate-finish")`: asks yes or no (the standard confirmation box, or the game's `screens.confirm`; `true` for yes. If the player has turned confirmations off in Settings, it returns `true` without asking)
- To place your own kind of thing on the foreground layers (fg0 to fg2), push its state onto the standard image list with a `kind`,
  and register how to build it on load with `registerLayerItem(kind, build)` from `@liminalia/sdk/web` (it disappears along with its layer on `@free-image`).
- **Replacing the look**: `extensions.text` (`TextTheme`: the font, how read text is shown, the click-wait icon, how text appears),
  `extensions.sprites` (`SpriteTheme`: the time multiplier for changes of expression only).
- **One character of text** (a public interface; changes to it are announced as version changes):
  - The text becomes one `span.ch` per character (ruby is one `.ch.ruby` for the base text and its ruby, `{img}` is `.ch.lm-inline-image-unit`). Upright digits in vertical writing are `.ch.tcy`.
  - The time a character starts to appear is the element's `animation-delay` (the character's index × the time per character). Once it's fully shown (a click, skipping, or a page shown at once), `.ch.shown` is added and the animation is removed.
  - How characters appear is set by the CSS variables `--lm-reveal-animation` (the animation name; `lim-reveal` fades, `lim-reveal-rise` floats up), `--lm-reveal-time` (time for one character to appear)
    and `--lm-reveal-easing`. `ui.text.reveal` (`fade` / `none` / `rise`) and `revealTime` in `liminalia.json` write them on the stage, and the project's CSS can override them.
    For your own animation, create `@keyframes` and write its name in `--lm-reveal-animation` (end it at `opacity: 1`).
  - `TextTheme.reveal(units, perChar)` is called once right after the characters are put in the window, and `TextTheme.char(el, { index, delay, perChar })` is called for each character.
    Animations added in `char` with `el.animate(…)` (starting at `delay`) are moved to their end state by the engine when a click finishes the page,
    so you can add motion to a character without rewriting the reveal animation (lighting an ellipsis one dot at a time, and so on). `perChar` is 0 when the page is shown at once (also while skipping).

  ```ts
  text: {
    char(el, { delay, perChar }) {
      if (perChar < 100 || el.textContent !== "…") return;
      el.animate([{ clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0 0 0)" }], { duration: perChar, delay, easing: "steps(3, jump-start)", fill: "both" });
    },
  },
  ```
- **Stacking the text on another screen**: `extensions.dialogue` (`DialogueView`). In projects with `ui.chat.dialogue`, the text of each page goes into the element that `page` returns (the standard `std` uses this for chat bubbles; a later plugin replaces it). The runtime stacks finished pages in `std.chat` in `stage.extra` (`RuntimeOptions.chatDialogue`).
- **Sprites drawn instead of images** (Live2D, Spine and so on; the official `live2d` and `spine` plugins are written with this too): in `extensions.spriteParts`, put a builder (`SpritePartFactory`) for each `model.type` of a character's variants.
  It receives `{ who, variant, name, appearance, el, asset, skipping(), holdShot() }`, adds a canvas or similar inside `el` (the element that holds the sprite's position and size),
  and returns `{ update(variant, at), tick(now, mouth), dispose(), coversImage }`. `name` and `appearance` are the variant's name (`smile` for `smile+blush` in `@chara`,
  or the default variant if none is written) and the sprite set, and `update` is called when the same character's variant changes (switching expression or motion), with the new `variant` and `{ name, appearance }`.
  `variant.model` is the character's `model` with the variant's `model` of the same `type` laid over it. `tick` is called every frame, where `mouth` is how open that character's mouth is (0 to 1; from the voice's loudness or,
  without a voice, opening and closing while the text appears). `skipping()` tells whether it's skipping (finish changes without blending), and
  `holdShot()` holds screenshots (`lim shot` and the check after export) until you call the function it returns (to wait until the model is loaded and the first frame is drawn).
  With `coversImage: true`, the variant's `image` is hidden (and used as the still image that decides position and size; to hide it only after drawing, add the `sprite-covered` mark to `el` yourself).
  Showing, hiding, position, `frame` changes, speaker emphasis and tone (the CSS `filter` of `el`) work the same as engine sprites. For flipping (`flip=true` in `@chara`), the engine flips the canvases directly under `el` (including ones added after loading)
  on the same axis as the image (`flipAxis` in `frame`; write the canvas's `left` and `width` in % of the frame so a canvas larger than the frame lines up with the axis too). Outside libraries for drawing (the Cubism SDK and so on) are
  built in on the project's side, following that library's license terms. A script placed in the assets can be loaded once with `loadScript(asset("others", …))` from `@liminalia/sdk/web`
  (the CSP of exported games only allows scripts from the same place as the game, so outside URLs can't be loaded).
- To replace the **system screens** entirely, return `system: (env) => SystemController`.
  Screenshots and the check after export use `boot()`, `mode`, `screen`, `pages`, `devSkipUntil` and `startAt()`, so keep this contract.
  Studio's preview (`lim studio`) uses the optional `loadSave(save)`. It starts from save data, resolves once it starts showing the page (or choices) at that position,
  and doesn't go back to the title when it ends (built the same way as `loadFrom` in the default system screens,
  but taking a save directly instead of going through a slot). Without it, Studio's preview can't be used (the player only shows a warning).
  "Reload from Here" (⇧R) in test play uses the optional `reloadHere()`. It keeps the current state, reloads the script in a new `Runtime`, continues from the same page and returns true
  (false when play isn't in progress). Without it, the save of the current page is loaded again with `loadSave` (the history isn't carried over).
  The screen for a command line (before the text) is built by the player stopping the current play with `runtime.dispose()` and then using only the rendering side's `restore` and `restorers`,
  so there's nothing to add to the system screens (`restorers` are also called this way at times other than loading).
  Pass `env.onAssign` as is to `onAssign` of the `Runtime` you create. When play advances in Studio's preview, the "State at this line" panel uses it to show
  where values decided in the preview came from (the line that set them). It works without it, but then only "← preview" is shown, with no line.
  Projects that don't replace them use the engine's default system screens (`packages/web/src/system/`).
  "Previous choice" and "Next choice" can be built with `ChoiceHistory` and `findChoiceAhead` from `@liminalia/sdk/web`. When choices are shown
  (`setChoosing(true)`), call `history.remember(runtime, logLength)`; to go back, start a new play from `point.save` of `history.previous(choosing)`,
  and put back the kept history with `history.replace(before)`. To go forward, `findChoiceAhead({ runtime, loadSource, present })`
  gives you the point of the next choice (`save`, `temp`, `system`); start a new play from there (`present` receives what's sent to the rendering side along the way,
  so use it for things that should happen even when skipped over, such as the backlog and unlocking CGs; null if you don't need it). The runtime that runs ahead is built
  with the settings `runtime` was created with (`runtime.options`) and the current language and translation (it doesn't get `beforeStep`, which waits for the game's screens, or `afterLoad`).
  To keep it in save data, save `history.forSave(dropped)` (the number of history entries to leave out) along with it, and put it back with `replace` after loading.
  Even with replaced system screens, the player input that doesn't depend on how the screens are built (long press, swipe, gamepad, choosing
  buttons with arrow keys, the menu button on touch devices, the notice shown when a landscape game is held upright) is available with `bindPlayerInput({ stage, controls })` from
  `@liminalia/sdk/web`. In `controls`, pass whether play is in progress, the range to choose from with arrow keys, and functions for
  the menu, backlog, hiding the window, closing a screen, config, skipping while held and so on (actions you don't pass do nothing).
  A horizontal swipe calls `rollback` or `rollforward` (swiping right goes back; with `choosing` passed, also while choices are shown; `swipeSide: false` turns it off).
  On a gamepad, RT and L3 call `auto` and `skip`, R3 calls `mute`, and right and left on the D-pad during play call `quickSave` and `quickLoad`.
  During play (when there's no `navRoot`), up and down on the arrow keys and the D-pad select the visible buttons inside elements on the stage marked with `data-lm-play-nav`
  (such as the root of the standard HUD buttons); A on a gamepad presses the selected one and B stops selecting (left and right on the D-pad only move while one is selected).
  Arrow keys for which `reserved(key)` returns true aren't used for selecting (they're keys assigned to game actions). A plugin's own HUD parts can be selected the same way by putting `data-lm-play-nav` on their root.
  Parts with a `KeyboardEvent.key` name in `data-lm-key` are pressed with that key by the default system screen while playing and while choices are shown
  (upper and lower case letters are the same, and it comes before the default keys of other actions), and are listed on the Controls screen. A selected button inside `data-lm-play-nav`
  is pressed with the key that advances the text, and Esc stops selecting it.
  The right stick scrolls the scrollable elements in the open screen (`navRoot`). Gamepad buttons send `lm-pad` (`detail.button`) to what's selected (or `navRoot` if nothing is),
  and the right stick sends `lm-stick` (`detail.x`, `y`, `dt`); if the receiver calls `preventDefault()`, they aren't handled further
  (for screens that handle the gamepad themselves; viewing CGs in Extras uses this too). A gamepad without the standard mapping is reported with `onNonstandardPad(id)`.
  To match button labels to the controller model, use `padLabel(button, style)` (style is `xbox`, `playstation` or `nintendo`; `""` means from the connected gamepad).
  If you handle keys yourself, call it before your key handling. The default system screens use this too (the list of controls is in docs/player.md).
  Replaced system screens receive Android's app back button and the phone browser's back through `system.back()` (return true if handled; if not, the app goes to the background
  and the browser goes back to the previous page). When the mobile app recreates the screen's process and reloads it with `?resume=1`, call `system.resumeLeft()` (if there's nothing to resume, it starts normally).
  Device features are available from `@liminalia/sdk/web`: `keepAwake(reason, on)` (keeps the screen on; counted per reason), `vibrate([vibration, pause, …])` (an empty list stops it)
  and `openExternal(URL)` (the mobile app opens it in the device's browser)
- `setup(host)` is called once right after the rendering side is created (for loading fonts and so on).
  For fonts, use `host.fonts.add(name, url)` (registers and loads it once; true if it loaded), `host.fonts.load('500 16px "Name"')` and `host.fonts.ready(ms)`
  (waits up to ms milliseconds for the fonts in use to load; 3000 by default). None of them throw even if nothing loads (the project doesn't need to write FontFace registration and timeouts)
- **Notifications** (`@notify`, `ctx.notify`): stacked at the top right. When more are shown at once than the limit (`max`, 3 by default), the oldest are removed first, and if a notification with the same key (`key`, the text by default) is showing,
  they're merged into one and shown again (the display time is extended and `data-lm-count` goes up by one). During full-screen effects (`host.coverUi()`) they wait, and when the cover is removed they appear one after another.
  While skipping, their time is cut to 1/10, and they're cleared on load. Change the look with CSS (`.lm-notices`, `.lm-notice`, `.lm-notice--<kind>`, and `enter`, `in`, `out` in `data-lm-state`), or
  replace each notification's element with `screens.toast(api)` (`api` has `text`, `kind`, `title` and `args` (the `@notify` parameters)). For full-screen effects such as chapter title cards,
  calling `host.coverUi()` while they're shown makes notifications wait in the meantime. With `@notify when=scene-break`, the runtime holds the notification until a scene break before passing it to the rendering side (while it waits, it goes into saves)
- **Screen transition curtains** (`transitions`): with `load: { cover(ctx, { from }), reveal(ctx, { from }) }`, a load (from a slot, the backlog, the previous choice, a chapter or the flowchart) waits for `cover` to finish before discarding the current play,
  and calls `reveal` after rebuilding from state (without waiting). `screen(ctx, { name, open })` is called right after a system screen opens and right after it closes (without waiting;
  to draw above the screen, put it in `ctx.systemLayer`). If you only need the events, listen for `load-start` and `load-end` with `system.onEvent`. Works only with the standard system screens
  ```ts
  transitions: {
    load: {
      async cover(ctx) { curtain.show(ctx.systemLayer); await curtain.closed(); },
      reveal() { curtain.hide(); },
    },
  },
  ```
- **Scrollbars** (`ui.scrollbar(content, { track, thumb, back, forward, orientation, minThumb, step })`): attaches a track and thumb that the project made to scrolling content (`overflow: auto`).
  The thumb's length and position are written in px (`height` and `top` when vertical), the scrolled fraction goes to `--lm-value` (0 to 1) on the content, and whether it can scroll goes to `data-lm-scrollable` on the track. Even when the game screen is scaled,
  dragging keeps up with the thumb. The `back` and `forward` buttons get `data-lm-disabled` (`disabled` for a `<button>`) when they can't scroll
- The check after export (`lim build`) and `lim shot` wait `build.verifyWait` (2500 milliseconds by default) after the title screen appears, then take the screenshot.
  If the project decides when the screenshot may be taken, such as for a title that starts with a long fade from white, hold it with `const release = host.holdShot()`,
  and call `release()` when it may be taken (no screenshot is taken until then; after 60 seconds it gives up and takes one).
- **Calling standard actions from the project's buttons**: `ready({ host, system })` is called once right after the system screens are made, so
  keep `system` and call actions like `system.perform("auto")`. The actions are `SYSTEM_ACTIONS` (`quick-save` `quick-load` `save` `load`
  `auto` `skip` `prev-choice` `next-choice` `backlog` `config` `hide` `title` `exit` `fullscreen` and so on. They behave the same as the quick menu buttons, and `title`, `exit` and
  `prev-choice` ask for confirmation first. `fullscreen` switches between full screen and a window. It isn't in the standard menu, so to put it in the quick menu, write it in `ui.menuBar.items`).
  The selected theme (`ui.system.preset`) can be read from `system.theme` (also `RenderContext.system.theme`; `null` for the standard theme).
  When play isn't in progress (on the title screen, while a system screen is open), they do nothing. Whether auto, skip and window hiding are on can be read from
  `system.toggles` (to match the look of the project's buttons). If you don't use the standard quick menu, set `ui.menuBar.position` in liminalia.json
  to `hidden`, and if you don't need the menu button on touch devices either, set `ui.menuBar.touchButton` to `false`.
  To show and hide the quick menu partway through the scenario, use `@menu-button` (it's kept in the state, so it's the same after loading).
- **Changing the look with the project's CSS**: all of the engine's CSS is in the cascade layer `liminalia` (`@layer liminalia { … }`).
  Project CSS written outside the layer takes precedence without competing on specificity (no need to strengthen selectors like `.stage .message …`; `.nvl-page { margin: 0 }` takes effect).
  Project CSS can be loaded without a plugin by listing CSS files in `ui.css` in liminalia.json (it's loaded after the theme and plugin CSS, so at equal
  specificity it wins over plugin CSS. Files that `url()` points to are exported too; "Project CSS" in [player.md](../player.md)).
  From a plugin, add a `<style>` in `setup(host)`, or `import "./my.css"` from the plugin's `./web`.
  Change values with CSS variables where you can (set on the game screen element, they apply to everything inside):
  - Message window: `--message-left` `--message-top` `--message-right` `--message-bottom` `--message-width` `--message-height` `--message-min-height`
    (the `ui.message` game setting is also passed through these), `--message-padding` `--message-bg` `--message-image` `--message-border` `--message-radius`,
    the width of the vertical (top-to-bottom) message window `--vertical-width`, NVL padding and background `--nvl-padding` `--nvl-bg`
  - Text size setting: `--text-scale` for the text and choices, `--lm-text-scale` for the name box, backlog and standard system screens (both 1 = 100%; multiply your project screens' text by them to match).
    Above 100%, the game screen gets `lm-text-large` (the standard screens tighten their layout then)
  - Text: `--font` `--text-size` `--text-line` `--text-letter-spacing` `--text-shadow` `--text-align` `--message-fg` `--read-fg`,
    ruby (small reading aids above characters) `--ruby-size` `--ruby-gap`, paragraph spacing `--paragraph-gap`, characters per line `--line-chars`, Japanese line-breaking rules (kinsoku) `--line-break`, hanging punctuation `--hanging`
  - Name box `--name-fg` `--name-size` `--name-bg` `--name-image` `--name-border`, click-wait icon `--glyph-fg` `--glyph-size` `--glyph-gap`,
    choices `--choice-*`, speech balloons `--balloon-*`, the chat screen `--chat-*` (`--chat-bg` `--chat-head-bg` `--chat-other-bg` `--chat-me-bg` `--chat-radius` and so on; what you write in `ui.chat` is applied to the game screen through these), the standard system screens `--lm-*` (docs/player.md)
  The engine's CSS works in browsers that support `@layer` (Chrome, Edge and Android WebView 99 or later, Safari and iOS 15.4 or later, Firefox 97 or later).
- **Project screens** (investigation, maps, deduction, the original game's save screen and so on) are opened with `system.openScreen(content, options)`. The project makes the look (elements, CSS and images),
  and the system handles the rules:
  - It's placed on the same layer and in the same stacking order as the standard system screens (the one opened later is on top; `system.screen` is its name)
  - It blocks input underneath. Clicks and the wheel that advance the text (backlog, advancing) stop inside the screen, and right-click, Esc and B on a gamepad
    become this screen's "back" (with `closeOnBack: true`, it closes and the result is `null`; otherwise nothing happens). Auto and skip stop until it closes
  - `allowMenu: true` marks an in-game screen that waits for the player (investigation, maps, the codex and so on). While it's open, the player can still open the menu, save, load,
    the backlog and the settings (the shortcut keys, the menu button on phones and START on a gamepad too), and closing them returns to this screen. Right-click, Esc and B on a gamepad
    open the menu when this screen's back (`onBack`, `closeOnBack`) doesn't handle them. For a screen a scenario command opens and waits on, the save stays at that command, and the command opens it again on load.
    On touch devices the menu button appears at the top right, so keep the screen's top-right buttons clear by `var(--lm-menu-room-x, 0px)` (from the right) or `var(--lm-menu-room-y, 0px)` (from the top) in CSS (0 when the button isn't shown)
  - With `pauseScenario` (`true` by default), the scenario's next command doesn't run while it's open (for the standard screens, `ui.screen.pauseScenario`; they pause by default)
  - When it closes, `handle.result` (a Promise) resolves to the value passed to `handle.close(value)`
  - If you write `key`, the state (`handle.state`, `handle.setState(newState)`; values that can be turned into JSON) goes into saves. Reopening with the same `key`
    starts from the saved state, so a screen opened inside a command (the command calls `ctx.resumeHere()`) comes back when the command opens it again on load.
    For screens opened from outside commands (the project's buttons and so on), register how to build them with `system.defineScreen(key, build, options)`,
    and the system reopens them in the same state on load. You don't have to write a record in stage.extra and a restorer for each screen
  - Screens registered with `defineScreen` can be opened by name: `@open-screen gung.map` in the scenario (waits until it closes), `"screen:gung.map"` in
    `ui.menuBar.items` of the quick menu (also passed to the project's own quick menu through `items`), `system.perform("screen:gung.map")` and `ctx.system.openScreen("gung.map")`.
    `label` in options (text or `{ ja, en }`) becomes the button text, and with `menu: true` it's listed before "Title" in the right-click and Esc menu.
    With `extra: true` (or a function that returns true), it's also placed among the Extras tabs, and "Extras" appears on the title screen even if nothing else is unlocked (when opened from Extras, play isn't in progress, so `system.runtime` is null).
    `state` is the initial state (used when the save has no state)
  ```ts
  const h = system.openScreen((h) => buildMap(h), { key: "gung.map", state: { page: 0 }, closeOnBack: true });
  const picked = await h.result; // the value from close(value); null if backed out or discarded by a load
  ```
  ```ts
  // register in ready, and open from the quick menu ("screen:gung.notebook" in ui.menuBar.items), the menu, @open-screen gung.notebook or the project's buttons
  ready({ system }) {
    system.defineScreen?.("gung.notebook", (h) => buildNotebook(h), { label: { ja: "手帳", en: "Notebook" }, menu: true, closeOnBack: true });
  },
  // from inside command rendering (extensions.renderers)
  extensions: { renderers: { "open-notebook": async (ctx) => void (await ctx.system?.openScreen("gung.notebook")) } },
  ```
- **UI parts without a look** (`import { ui } from "@liminalia/sdk/web"`) add only behavior to elements the project made. State is exposed as attributes on the element, so
  the project's CSS decides the look (`data-lm-hover`, `data-lm-focus`, `data-lm-pressed`, `data-lm-disabled`, `data-lm-selected`, `data-lm-on`,
  `aria-pressed`, and the thumb position `--lm-value` (0 to 1)). Clicks that press them aren't passed on to advancing the text. They work outside system screens too
  - `ui.button(el, { onPress, disabled, hit, se, hoverSe, sound, tapToSelect, label })`: the pressable area `hit` is the element's rectangle (the default),
    `{ x, y, width, height }` (px from the element's top left), or `{ alpha: true, threshold }` (the non-transparent part of the image: an `img` or the background image, or another image given with `image`).
    Where buttons overlap, the topmost one whose pressable area contains the point is pressed, and transparent parts pass the press through to the button below (elements that aren't buttons don't pass it through).
    Elements other than `<button>` are made keyboard-selectable (select with Tab and the arrow keys, press with Enter and Space), and with `tapToSelect`, on touch devices
    the first tap selects and the second presses. `se` and `hoverSe` are sound effects (paths from `sound`). If you leave them out, the sounds in `ui.sound.ui` in liminalia.json are used
    (on press, the kind in `sound`: `select` by default, `"cancel"` for a close button, `"page"` for a tab, `false` for no sound; on mouseover, `hover`)
  - `ui.playSound(kind)`: plays a sound from `ui.sound.ui` (`hover`, `select`, `cancel`, `open`, `close`, `page`, `choice`; does nothing if it isn't set).
    Use it when a project screen opens or closes and so on. `open` and `close` don't play right after a press sound
  - `ui.slider(el, { min, max, step, value, onChange, onCommit, orientation, thumb, setting })`: moved by dragging (with a finger too), the arrow keys,
    Page Up/Down and Home/End, calling `onChange` on every change of value while it moves. For an `<input type="range">`, its own behavior is used
  - `ui.toggle(el, { value, onChange, setting, se })` (on and off), `ui.choice([{ el, value }, …], { value, onChange, setting })` (choose one)
  - `setting: { system, key }` binds it to a setting (`key` is `bgm` and so on, or `"custom.name"` for a project-specific value). A change is
    saved with `system.updateSettings` and applied right away, and it follows changes made elsewhere
  - `dispose()` on the returned handle removes it (it also goes away when you discard the element)
- **Replacing only the look of the standard screens**: pass functions that build the elements in `screens: { config?(api), saveload?(api), backlog?(api), menuBar?(api), menu?(api), confirm?(api), ending?(api), extra?(api), flowchart?(api), indicator?(api), codex?(api), toast?(api), choice?(api), name?(api), dialog?(api), help?(api), items?(api) }`. Opening, closing,
  blocking input and stacking work the same as the standard screens, and the function builds the contents. For config, `api` has `system` (settings can be
  bound with `setting` on `ui.slider` and the others), `languages`, `defaults` (the values for "Reset to defaults"; `ui.defaults` in liminalia.json), `reset()` (resets to defaults, keeping the language, full screen and so on), `close`, `exportSaves` and `importSaves`.
  For save and load, `mode`, `system` (`slots`, `slot`, `deleteSlot`, `autoSlots`; a slot's `chapterId` is the chapter at the saved position),
  `slotCount`, `autoSlotCount` (the number of autosave slots), `lastSlot` (the slot saved to last), `latestSlot` (the newest save, including autosaves and quick saves),
  `pageSize` (the number of slots on one page of the standard save screen), `chapterId` (the chapter being played), `inGame`, `save(slot)`, `load(slot)`, `ask(message, kind)`, `notify(message)` and `close`.
  For the backlog, `entries`, `playVoice(i)`, `jump(i)`, `color(speaker)`, `textStyle(speaker)` (`text` in cast.json), `asset(kind, path)` and `close`. For the flowchart, `flow` (scenes and connections), `title(scene)`, `reached(scene)`, `canJump(scene)`, `jump(scene)`,
  `readRate`, `endings` (for each ending scene, `scene`, `reached`, `kind` (the kind), `label` (the kind's wording), `title` (the name in `title=`) and `name` (the line in the list)), `close` and `onBack`.
  A scene's `scene.end.ending` is the kind (`bad` and so on), `scene.end.title` is the original name, and `scene.end.legacy` is the wording of the earlier way of writing in projects not yet migrated. You don't need this if you only change CSS (the standard screens are built from these parts inside too)
  - Every screen's `api` has `onClose(handler)` (when it's closed, or discarded by a load; the returned function removes it) and `leave`. In the function that builds the screen,
    put in a closing effect such as `api.leave = (el) => el.animate([{ opacity: 1 }, { opacity: 0 }], 200).finished`, and on closing it's called with that element,
    and the screen is removed after it finishes (it can't be pressed in the meantime; it's cut off after 2 seconds; there's no wait while fast-forwarding, or when screens are discarded all at once on a load or a return to the title).
    Project screens (`openScreen`, `defineScreen`) have the same `onClose` and `leave` on their `handle`, and `handle.onBack(handler)` receives back (Esc, right-click, B) first
  - Quick menu `menuBar(api)`: built once and placed by the system, and shown only when the quick menu should be shown (`status.menuBar`: play is in progress, no screen is open,
    the window isn't hidden, the message window is showing, no choices are shown, and nothing like a full-screen movie is covering it). It's also false while `hide-window` hides the window until the next text. `api` has `items` (`ui.menuBar.items` or the default list),
    `label(action)`, `perform(action)`, `status` and `onStatusChange` (to match the pressed look of auto and skip)
  - Auto and skip indicator `indicator(api)`: built once and placed by the system, and shown only during auto or skip (`hidden`; `auto` or `skip` in `data-state`,
    and the position is the class `lm-indicator-at-<position>` from `ui.indicator`). `api` has `status`, `onStatusChange` and `label("auto" | "skip")`.
    In projects that replace only the quick menu (`menuBar`), it isn't shown unless you write `ui.indicator`
  - Menu `menu(api)` (right-click, Esc, START on a gamepad; from the project's buttons, `system.perform("menu")`): `items`, `label`, `perform(action)` (runs after closing), `status`, `close`,
    `onClose(handler)` (when it's closed, or discarded by a load; you don't need to watch for the element's removal with MutationObserver)
  - Notifications `toast(api)`: see “Notifications” above
  - Confirmation `confirm(api)`: `kind` (`title`, `exit`, `end-replay`, `backlog-jump`, `prev-choice`, `import`, `delete`, `overwrite`, `load`, `investigate-finish` (finishing an investigation without examining everything),
    or the name given in `ask(message, kind)` from a project screen or `ctx.system.ask` from a renderer), `message`, `yes`, `no`, `answer(trueForYes)`. Esc and right-click mean "No"
  - Ending name `ending(api)` (shown before returning to the title when a playthrough ends with `@title-screen ending=`): `kind` (the kind of ending, such as `bad`), `label` (the kind's wording, such as BAD END;
    empty for `other` and the earlier way of writing), `title` (the name in `title=`; empty if none), `name` (the name shown large: `title`, or `label` if there's none; the written wording in the earlier way), `text` (the end mark; the Japanese mark or The End if omitted),
    `proceed` (the label of the action that moves on, for screen readers) and `close` (move on to the title). All are in the language being played. Esc and right-click also move on, and during auto the system shows it for 4 seconds and then moves on
  - Extras `extra(api)`: `extra` (extra in liminalia.json), `tab`, what's unlocked (`cgImages(cg)` for the unlocked images, `replayUnlocked`,
    `musicUnlocked`, `movieUnlocked`, `achievement`), `chapters` (chapters in liminalia.json, translated into the language being played), `asset`, `audio`, `replay(scene)`, `close`,
    `onBack(handler)` (return true if something should close first on Esc) and `onKey(handler)` (keys such as the arrows and Enter; the gamepad's D-pad, A, B, LB and RB also
    arrive with names such as `ArrowUp`, `Enter`, `Escape` and `PageUp`. Returning true skips the standard behavior, such as moving between buttons and pressing them. For paging while a CG is shown large, for example).
    A CG's `group` (a heading such as a chapter) and `description` can be used in the list
  - Codex `codex(api)` (only in projects with `data/codex.json`; opened from `@codex`, the menu or Extras): `data` (headings and categories; a category's `type` is `list`, `timeline`, `relations` or `map`,
    and for `map`, the map image), `entries` (the unlocked entries; `sections` and the relation chart's lines `links` include only unlocked ones, `fresh` marks entries not read yet, `date`, `order`, `x`, `y`),
    `entry` (the entry when opened with `@codex name`), `playing` (`false` when opened from Extras), `markSeen(key)` (marks as read; an entry's `id` and a paragraph's `key`),
    `text(ja, en)` (the text in the language being played), `asset`, `close` and `onBack`. Which entries, paragraphs and lines to unlock, and the new marks and notifications, are handled by the standard commands
  - Choices `choice(api)` (`@choice` and choice blocks; built each time): the returned element is placed in the choice layer (`.choices`) and no standard buttons are made. `api` has `options` (for each choice `index`, `text` (translated into the language being played),
    `locked` (cannot be pressed), `read` (the destination has been read before) and `look` (look parameters such as `image`, `x`, `y`, `width`, `height` and `tip`; `null` if none)), `time` (the time limit in ms; 0 if none),
    `choose(index)` (chooses; locked ones are ignored; also plays the choice sound) and `asset`. The time-limit bar (`.choice-timer`), number keys (counting the pressable `button`s in the choice layer from the top),
    telling the recorder and handing over to the chat screen are handled by the system. The placement (`ui.choice.position`) is not used, so position the element with CSS (while it is shown, the layer has `lm-choices-custom` and the standard button look does not apply)
  - Name box `name(api)` (built once): the returned element goes inside the message window's `.name` (`.name` gets `lm-name-custom`, which removes its backdrop, lines and padding), and the listener of
    `api.onChange(listener)` is called whenever the speaker changes (`speaker` (`null` for narration), `label` (the text for the name box; the translation, and both names on a page where two speak at once) and `color` (`color` in cast.json)).
    The current speaker is `api.current`. On pages with no name, `.name` gets `is-empty` and is hidden. Its position stays at `x` and `y` of `ui.name`. Not used in NVL and on the chat screen
  - Dialog and text input `dialog(api)` (`@dialog`, `@text-input`; built each time): the returned element is placed on the box's backdrop (`.lm-panel` with `lm-panel-custom`) and the standard box (`.lm-panel-box`) is not made.
    `api` has `kind` (`alert`, `confirm`, `input`, and `text` for `@text-input`), `message` (`text` of `@dialog`, `prompt` of `@text-input`), `input` (the field's `initial`, `placeholder`, `max`, `mode` and `required`; `null` without a field),
    `okLabel` and `cancelLabel` (`ok-label`, `cancel-label` or the standard wording; `null` for boxes without a cancel button), `accepts(text)` (whether `required=` and `pattern=` allow it), `ok(text)` (confirms) and `cancel()` (cancels).
    Back (Esc, right-click, B) is `cancel`. Keeping keys away from advancing the text, telling the recorder and clearing up on load are handled by the system
  - Controls help `help(api)` ("Controls" in the menu and `@open-screen help`): `rows` (each action's `label`, `keyboard`, `touch` and `pad`, made from the current bindings), `pages` (`ui.help.pages`), `asset`, `close` and `onClose`
  - Inventory `items(api)` ("Items" in the menu, `@open-screen items`, `@item-select`): `items` (`items` in liminalia.json), `held` (the counts held), `asset`, `select` (only for `@item-select`: `title` and `pick(name)`, which passes the chosen item), `close` and `onClose`
  - Which of text, theme values, CSS and replacement hooks can change each screen is in the table in [screens.md](../screens.md)
- **Screens and effects for each theme**: `themes: { <id>: { rootClass, text, title, splash, screens, texts } }`. Only when `ui.system.preset` is `<id>` are these laid over the items of the same name (other themes go back to the standard screens).
  Values (the message window, text, choice colors and so on) go in the project's `themes/<id>/theme.json` (“Themes” in [player.md](../player.md)), and screens that can't be written as values are registered here.
  `rootClass` is put on the game screen only while the theme is selected, so theme CSS scoped under it goes away with it. To override the same class names as the standard screens without changing specificity, use `:where(.class)`.
  Things that should work in every theme (rendering of the project's commands, `setup`, `ready`, `slotMeta`) go outside `themes`
- **Changing the text of the standard screens**: `texts: { "confirm.title": "Back to the title screen. Are you sure?", … }` (the keys are the nesting of
  `TEXT` in `system/strings.ts`; laid over after `ui` in the language's translation). The screens of the standard commands (codex `codex.*`, investigation `investigate.*`, map choice `mapChoice.*`, chapter end `chapter.end`) read the same table.
  To read the current language's wording from a plugin's screen, use `systemText()` from `import { systemText } from "@liminalia/sdk/web"` (its contents change with the language, so read it each time you show text)
- **Startup effect**: return `splash(ctx)` to play it once after "Click to start" and before the title (a Promise that resolves when it's done).
  To show only logos and notices, write them in `ui.splash` in liminalia.json without writing a plugin (“Startup effect” in [player.md](../player.md))
- **Ending effect**: return `endSplash(ctx)` to play something before the title every time the scenario ends and goes back to the title (for example, the startup effect again after the game is cleared). When there's nothing to play, resolve without doing anything
- **Status and events** (the `system` received in `ready`; use them for buttons the project places itself, for showing and hiding the quick menu, and for inserting the project's own effects):
  - `system.status` (`mode`, `screen`, `choosing`, `hidden` (the player hid the window), `window` (the message window is showing), `waiting`
    (waiting for a click), `auto`, `skip`, `replay`, `menuBar`, `canPrevChoice`, `canRollback`, `canRollforward`), `system.onStatusChange((s) => …)` (only when something changes)
  - `system.onEvent((e) => …)`: `start` (right after a play is created with "New Game"; to put variables into `e.runtime`, set up the game screen and so on),
    `load-start` (right before the current play is discarded for a load, a return from the backlog or the previous choice; to lower a curtain and so on), `screen-open` / `screen-close`
    (`name`, and `from` when opened), `rollback` (right before rebuilding for a rollback; `direction` is `back` or `forward`; it isn't a load, so
    don't lower a curtain), `title`, `load-end` (after rebuilding for the load from `load-start`; raise the curtain). For `start` and `load-start`, play doesn't go on until the returned Promise settles
  - `system.systemVariables` (variables shared by all saves; also readable on the title screen), `system.importData({ slots, system, read, settings })`
    (carrying data over from an earlier storage format; stores the slots, shared variables, read status and settings, and returns the number of slots that couldn't be stored)
- **The project's setting ranges and input** (ui in liminalia.json): `ui.settings` (`textSpeedMin`, `textSpeedMax`, `textSpeedStep`, `autoWaitMin`,
  `autoWaitMax`, `autoWaitStep`, `autoPerChar`; `samples` for previewing volumes, `voiceSpeakers` for which characters the per-speaker voice volumes in Settings list) sets the ranges of the settings and the auto wait time, `ui.input.rightClick: "hide"` makes right-click
  hide the window, and `ui.title.bgmVolume` changes the volume of the title BGM. During play, the game screen gets
  the class `lm-choosing` while choices are shown, and `lm-window-hidden` while the window is hidden
- **Using settings, the backlog and save slots from project screens** (the `system` received in `ready`; provided by the default system screens):
  - Settings: `system.settings` (read-only: text speed `textSpeed`, auto wait `autoWait`, master volume `master`, mute `mute`, volumes `bgm` `se` `voice`, also skip unread text
    `skipUnread`, stop the voice on the next page `voiceStopOnPage`, volume per speaker `speakerVoice`, fullscreen `fullscreen`, language `language`),
    `system.updateSettings({ bgm: 60 })` (clamps the value to its range, saves it and applies it right away; returns the settings after the change),
    `system.onSettingsChange((s) => …)` (also called for config, `@config` and toggling fullscreen; the returned function removes it).
    The numeric ranges are in `SETTING_RANGES`. Put project-specific settings in `custom` (`updateSettings({ custom: { windowAlpha: 0.8 } })`;
    merged by name and removed with `undefined`; stored in the same place, and the engine doesn't read them)
  - Backlog: `system.backlog` (oldest first: the speaker `speaker`, the name shown `label` (on a page where two people speak at once, both names joined as in the name box), the other speakers who spoke at once `with`, pieces of the text `parts` (text `text`, ruby `ruby`, bold, italic, color,
    line break `{ br: true }`), voice `voice`, position `at`, whether it can be replayed from there `canJump`, whether it's a chosen choice `choice`), `system.playBacklogVoice(i)`,
    `system.jumpToBacklog(i)` (asks first, then plays again from that entry)
  - Save slots: `system.slots({ from, to })` (numbered slots, including empty ones), `system.slot("quick")`. They have the date `date`, the start of the text `title`,
    a thumbnail `thumb` and the project's metadata `meta`. The metadata is what the plugin's `slotMeta({ runtime, host })` returns on each save
    (it's attached to saves made from the standard save screen too), with `meta` from `system.saveTo(slot, meta)` laid over it. Delete one with `system.deleteSlot(slot)`.
    They read the same way with the setting that protects save data (`saves.protect`), so don't read localStorage directly. They also hold the chapter name `chapter` and the play time `playTime` (in milliseconds)
    (save data made with earlier versions doesn't have them). If the project decides chapter names, return them from the plugin's `slotChapter({ runtime, host, label })`
    (`label` is the current file and label; return `null` for the standard way, or `""` to show nothing)
  - Autosaves: `system.autoSlots()` (newest first, with empty slots at the end; `slot` is `"auto:0"` and so on), `system.autosave(meta)` (the same as `@autosave`).
    `system.loadFrom("auto:0")`, `system.slot("auto:0")` and `system.deleteSlot("auto:0")` work too. Autosaving when quitting and when going to the background is
    `ui.autosave.leave` (projects that replaced the load screen have it off unless they write it; set it to `true` if you list autosaves).
    If the project detects switching to the background itself, call `system.leave()` (it stores what's shared by all saves and autosaves according to the setting)
  - Quick saves: `system.quickSlots()` (newest first; `slot` is `"quick"`, `"quick:1"` and so on; the number of slots is `ui.quickSave.slots`,
    and `quickSlotCount` in the api of the save and load screens). `system.perform("quick-save")` saves to an empty slot or the oldest one, and
    `system.perform("quick-load")` loads from the newest. `system.saveTo("quick")` saves to the first slot
- **Replacing only the title screen**: return `title: (api) => HTMLElement`. The returned element fills the game screen, and the other system screens
  (save, config, backlog and so on) stay standard. `api` behaves the same as the standard title buttons (`start()` New Game, `load()` Continue
  (opens the list), `loadLatest()` from the newest save, `hasSave()`, `config()`, `extra()`, `hasExtra()`, `exit()`, `canExit()`), and also has
  `project`, `host` (asset paths are `host.context.asset(kind, path)`), `ask(message, kind)` (the standard confirmation) and
  `intro` (whether this is the first title since startup; use it to decide whether to show an intro effect). It's called every time the title is shown (and rebuilt when the language changes).
  The background and BGM from `ui.title` are shown as usual. Not available in projects that replace the system screens entirely.
