# HTML templates for the built-in screens

The built-in system screens (confirmation, menu, save and load, backlog, title and so on) are written as HTML templates with attributes that name what each element does (`data-role` and so on).
A game copies a template into its own folder and edits it with only HTML and CSS. For elements with attributes, the engine adds what pressing does, keys, gamepad, focus and text-to-speech.
Only people who want to write JavaScript do so, either in a screen JS file placed next to the template ("Screen JS" below) or, as before, in a plugin's `screens.*`.

This document is the design for 0.4.0. The confirmation screen (`confirm`) was built this way first (the prototype), stage f1 rewrote the menu, controls help, ending name and choices, stage f2 rewrote save and load, backlog and title, and stage f3 rewrote the settings screen. That is the last screen rewritten in 0.4.0. Copying, the difference from the built-in template, and going back to the built-in template are in `lim screens`, the MCP tools, and the template editor of "Game screens" in Liminalia Studio ("Copying" below and [studio.md](../studio.md)). Checking a game's templates (`lim check` and the Studio check) is in "Checking templates" below.

Names: wording shown to creators and documents for creators say "template" and "attribute" (the rule against coined words in `docs/design/wording.md` in the repository, in Japanese). Comments in the code also say "型" (template) and "印" (attribute).

## Why this shape

- Today, to give a built-in screen a shape CSS can't reach, you have to write it from scratch in TypeScript (`WebPlugin.screens.*`). The code of the built-in screens (`packages/web/src/system/*.ts`) can't be copied by a game.
- Ren'Py starts from `screens.rpy` inside the game, and TyranoScript from the class names in `save.html`, so you can begin by copying a working built-in screen and editing it.
- If the built-in screens use the same format as games, a copy behaves the same as the built-in screen, and when an engine update changes the built-in screen, the difference from the original version can be shown.

## The shape of a template file

```html
<!-- Copied from the built-in confirmation screen (Liminalia 0.4.0, version 2) -->
<style>
  .lm-dialog { border-radius: 0; }
</style>
<template data-part="screen" data-version="2">
<div class="lm-dialog-backdrop">
  <div class="lm-dialog" role="alertdialog">
    <h2 class="lm-sr-only" data-text="confirm.heading"></h2>
    <p class="lm-dialog-message" data-field="message"></p>
    <div class="lm-dialog-buttons">
      <button class="lm-button" data-role="cancel" data-field="no"></button>
      <button class="lm-button lm-primary" data-role="ok" data-field="yes" data-autofocus></button>
    </div>
  </div>
</div>
</template>
```

- One screen is one HTML fragment (no `<html>` or `<body>`).
- It is a list of `<template data-part="part name" data-version="version">`. The whole screen is the part `screen`. Things that repeat, like one save row, and things a game may want to replace on their own, are separate parts.
- A part holds one element. If it holds two or more, the engine wraps them in `div.lm-template`.
- Text that is only indentation line breaks (whitespace between elements) is dropped on reading, so inline buttons don't get gaps between them (it is kept inside `pre` and `textarea`).
- Elements outside `<template>` are not used (they are dropped), except `<style>`. Comments can go anywhere.

### Where CSS goes

- The look of the built-in screens stays in `default.css`. Templates only carry class names. Reason: themes, `ui.*` values and the game's CSS keep working on the same class names and CSS variables.
- A template a game copied can have CSS in a `<style>` in the same file. It goes into the document's `<head>` the first time the screen is shown, and is put in again when the template changes. One file copies one screen, and one file shows its difference.
- CSS for the whole game goes into the separate project CSS (`ui.css` in `liminalia.json`). A template's `<style>` is only for that screen.
- Another option: putting `confirm.css` in the same folder. That makes two files to read and register, and splits the difference of a copy into two, so it is not taken for now. A `<style>` applies to the whole document, so write selectors starting from the screen's class name if it should not affect other screens.

## Attribute vocabulary

Attributes creators write are `data-*` (without `lm`), and states the engine writes are `data-lm-*`. Creators don't write `data-lm-*` (the engine overwrites them).

### What pressing does (`data-role`)

Can go on any element. For an element that isn't a `<button>`, the engine adds `role="button"` and `tabindex="0"` and makes Enter and Space press it.

| Value | Does | Sound |
|---|---|---|
| `ok` | Decide (the confirmation's "Yes") | select |
| `cancel` | Cancel (the confirmation's "No") | cancel |
| `close` | Close the screen. Same as Esc, right click and gamepad B | cancel |
| `back` | Go back one step (a step inside the screen; same as close if there is none) | cancel |
| `prev-page`, `next-page`, `page` | Change pages and tabs | page |
| System action names (`save`, `load`, `backlog`, `config`, `title`, `exit` and so on; `SYSTEM_ACTIONS`) | Do that action (menu, title, quick menu) | select |
| Actions on a list row (`pick`, `delete`, `protect`, `jump` and so on) | Act on that row. Decided per screen | select |

- Each screen decides which values work, listed in a table in the screen document ([screens.md](../screens.md)). An unknown value looks pressable and does nothing. The dev server prints it to the console, and `lim check` and the Studio check report it (`template-unknown-value`).
- Confirmation: `ok` (yes), `cancel` and `close` (no). Other screens are in "Parts and attributes of four screens", "Parts and attributes of three screens" and "Parts and attributes of the settings screen".
- The sound on press can be changed with `data-sound="select|cancel|page|choice|none"` (`none` plays nothing, and also no hover sound). The built-in menu's "Return to game" is `close` but plays select as before, and the ending name's proceed button plays nothing as before.
- Actions the screen can't do right now (quitting in the browser version and so on) remove the element entirely (the engine passes the action as null). Actions that can't be pressed (a locked choice) get `data-lm-disabled` and `aria-disabled`, and `disabled` on a `<button>`.

### Putting in text (`data-field`, `data-text`)

- `data-field="name"`: puts in the text of a screen value. The engine replaces the contents. Each screen decides the names. The confirmation has `message`, `yes`, `no` and `kind`.
- `data-text="key"`: puts in built-in wording (a key of `TEXT` in `strings.ts`, such as `confirm.no`). It becomes the wording a game replaced with `WebPlugin.texts`, in the language the player chose.
- Without either, the written text is shown as is (for words only the game uses).
- `data-attr-<attribute>="name"`: writes a screen value into that attribute (`data-attr-aria-label="spoken"`, `data-attr-src="image"`, `data-attr-aria-pressed="auto"`, `data-attr-data-kind="kind"` and so on). If the value is missing or empty, the attribute is removed. Attributes starting with `on`, `srcdoc`, `target`, `action` and `formaction` are not written. Attributes that take a URL never get `javascript:` and the like.
- `data-if="name"`: if that value (a screen value, or a per-screen show flag) is empty (missing, `""`, `0`, false), the element is removed entirely, and attributes inside it don't work. Used for the tabs of the controls help (not shown without pages), the time bar of choices, and the kind text of the ending name.

### Lists (`data-list`, `data-item`)

```html
<ol class="lm-slot-list" data-list="slots" data-item="slot"></ol>
<template data-part="slot" data-version="1"><li class="lm-slot">…</li></template>
```

- The contents of a `data-list="list name"` element are replaced with one `data-item` part per item. A row is a part, so a game can replace just the row.
- `data-field` and `data-role` inside a row are the row's values and actions (not the outer screen's). Lists can nest.
- Writing `<template data-list="name" data-item="part">` places rows right there without a wrapping element (rows become children of the outer element). Used where older CSS assumes children, like `.choices > button` of choices. A marker comment stays where it was placed (used when rebuilding; it doesn't affect CSS).
- One list can mix different parts (the engine picks a part per row: image buttons of choices, the table and pages of the controls help). `data-item` is the default part.

### Tying to settings (`data-setting`)

Works only on the settings screen (added in stage f3; "Parts and attributes of the settings screen" below).

```html
<div class="lm-config-row" data-setting="bgm">
  <span class="lm-config-label" data-text="config.bgm"></span>
  <input class="lm-range">
  <output data-field="bgm"></output>
</div>
<div class="lm-config-row" data-setting="skipUnread">
  <button class="lm-toggle" data-value="false" data-text="config.skipRead"></button>
  <button class="lm-toggle" data-value="true" data-text="config.skipAll"></button>
</div>
```

- `data-setting="setting name"`: goes on an item's row. The name is a player setting (`Settings` in `settings.ts`). A game's own setting is `custom.name`. Removing a row removes the item, and reordering rows reorders items.
- Controls inside the row: an `<input>` is a slider (the engine makes it `type="range"` and takes the range and step from the setting), an element with `data-value="value"` is one choice (pressing sets that value, and the pressed one gets `aria-pressed="true"`), and an element with `data-toggle` is a switch (on and off; `role="switch"`, `aria-checked`, `data-lm-on`). One row may have both a slider and choices.
- The text of `data-value` is read in the shape of the setting's value (`true` and `false` for a true/false setting, a number for a number setting).
- For a slider of a game's own setting, write `min`, `max` and `step` on the `<input>` (without them, 0 to 100 in steps of 1).
- Items that can't be used right now (the screen mode where fullscreen isn't available, desktop-only items, items the game doesn't use) are removed with their row by the engine even if written.
- An unknown name does nothing (the dev server prints it to the console, and `lim check` and the Studio check report `template-unknown-value`).

Another option: putting `data-setting` on the control itself (the `<input>` or the row of choices). The unit of showing, hiding and reordering is the row, so without it on the row, only the name of an unusable item would remain. On the row, one attribute reads as "this row is this setting".

### States (`data-lm-*`)

The engine writes these on elements, and CSS targets them. Valueless markers are present only while in that state.

| Attribute | Meaning | On |
|---|---|---|
| `data-lm-hover`, `data-lm-focus`, `data-lm-pressed` | The mouse is over it, it's selected by keys, it's being pressed | `data-role` elements (same as today's UI parts) |
| `data-lm-disabled` | Can't be pressed (with `aria-disabled`) | `data-role` elements, list rows |
| `data-lm-selected` | Selected by the first touch of a finger | `data-role` elements |
| `data-lm-read` | Already read (backlog, choices, extras) | List rows |
| `data-lm-protected` | A protected save | List rows |
| `data-lm-empty` | An empty slot | List rows |
| `data-lm-current="page"` and so on | The current page, tab or value | List rows, tabs |
| `data-lm-new` | Newly unlocked | List rows |
| `data-lm-locked` | Not unlocked yet (extras) | List rows |
| `data-lm-on` | A switch turned on (`data-toggle` on the settings screen) | The switch element |

- Each screen decides which states it writes, listed in a table in the screen document. Names not in the table can be written too (the mechanism doesn't limit names).

### Others

- `data-autofocus`: the element that gets focus on opening. Without it, the screen's outer frame gets focus (same as today's screens).

## What the engine adds to elements with attributes

In two steps.

1. When a part is built (`renderPart` in `template.ts`): a `data-role` element becomes a UI-part button (`button` in `ui-parts.ts`): `role="button"` and `tabindex`, Enter and Space, not passing the click on to the stage, sound, and states such as `data-lm-hover`. A `<button>` without `type` gets `type="button"`.
2. When the screen opens (`openStandard` and `pushScreen` in `default.ts`, same as plugin screens):
   - Clicks and wheel inside are not passed on to the stage.
   - `role="dialog"` (or an `alertdialog` or `dialog` inside, if there is one) and `aria-modal`. With a heading (`.lm-screen-title`, `h1`, `h2`), `aria-labelledby`.
   - `tabindex="-1"` on the outer frame; focus moves inside on opening and back to the element from before on closing.
   - Tab and Shift+Tab cycle inside the screen. Arrow keys and the gamepad's d-pad move to the nearest visible, selectable element in that direction. Gamepad A is Enter and B is Esc.
   - Esc, right click and gamepad B close the screen ("No" on the confirmation).
   - With text-to-speech on, the text of a button selected by keys is read.
- If the confirmation template has neither `dialog` nor `alertdialog` as a `role`, the outer frame becomes `alertdialog` (so it's read as a confirmation even if the game forgot it).

## The interface of a screen built from a template (code side)

What `renderPart` and `ScreenTemplates.render` return (`TemplateView`). Used by the code that builds screens (the built-in screens, and later an interface opened to plugins).

- `el`: the outermost element of the part. `autofocus`: the `data-autofocus` element.
- `items(list)`: the current rows of a list (the outermost element of each built part). Used to write `data-action` on the menu row of a game screen, and to tell recordings which elements of choices are pressable.
- `list(list, row values)`: rebuilds a list while open (the interface for "screens whose contents change while open", found in the prototype). If focus is in the list, it stays on the row with the same index after rebuilding (or the last row if that one is gone). Changing the tab of the controls help rebuilds the tabs and the body. Paging and saving in save and load (stage f2) and backlog search also rebuild with this.
- `update(values)`: rewrites only the values of a part (added in stage f2: the text of `data-field` and the attributes of `data-attr-*`; only the given names change, list rows are not touched, and elements removed by `data-if` are not brought back). Used for the backlog search count. The value text of the settings screen's sliders doesn't use `update` and is written directly into its `data-field` element (`update` rewrites every `data-field` element of the part, which would wipe the preview text the engine puts in).
- A `data-role` action receives the pressed element (added in stage f3, so a tab button on the settings screen can tell which `data-page` it is; `api.press` in screen JS doesn't pass it).
- Initial focus that attributes can't express is decided by the code that builds the screen. Choices focus "the first pressable choice" (as before; `data-autofocus` on the row part would put it on every row). A saved position and the previously chosen slot (save and load, title) are decided by each screen's code (stage f2's save and load decides the page to open in code, and focus stays on the outer frame as before).

## When the built-in templates are loaded

- The confirmation template and the template machinery (`template.ts`) are in the bundle loaded before play starts (`core`). The confirmation must show right away even when bundles can't be fetched (the connection dropped, an exported file is missing) or when asking about an update. It is small.
- The templates of the menu, controls help, ending name, choices, save and load, backlog, title and settings screens are a separate bundle in exports (`engine/lazy-screens-<key>.js`, entry `system/lazy-screens.ts`), loaded the first time one of them opens (`loadScreenTemplates` in `system/standard-templates.ts`). Once loaded, the remaining built-in templates are added to the store (`ScreenTemplates.addStandard`).
- The code that builds screens from templates (`menu-panel.ts`, `help.ts`, `ending.ts`, `choice-view.ts`, `saveload.ts`, `backlog-view.ts`, `title-view.ts`, `config.ts`) is in the first bundle. Splitting it into another bundle made the total 0.14 KB larger (tried), because each bundle is minified separately. The first-bundle budget has room, but the total budget doesn't.
  - The menu, controls help, save and load, backlog and settings open once loading finishes (opening the same screen again while loading happens only once). The ending name, choices and title wait for loading before showing. Only the first opening in an export is delayed, and only while loading. The title music plays without waiting.
  - If loading fails: the menu, controls help, save and load, backlog and settings don't open (they try again next time). The ending name is skipped and the game goes on to the title. Choices and the title can't move on, so they retry every second (choices until the script stops them, the title while on the title).
  - Choices are read aloud after they are laid out (checking every 80 ms, up to two seconds).
- The dev server (and Studio's previews) load them up front (when `import.meta.hot`; scripts are edited and reopened, so no waiting). Studio Mobile also loads them up front (`studio-mobile/scripts/build.ts` calls `loadScreenTemplates`).
- Exports remove the indentation and line breaks between elements of the built-in templates (`squeezeScreenTemplates` in `packages/cli/src/strip-docs.ts`). The player drops whitespace-only text containing line breaks on reading, so the screens built are the same.
- Size (the template game, gzip; `packages/cli/test/engine-bundle.test.ts`): before stage f1, what's loaded before play was 225.0 KB, and the total 256.8 KB. After stage f1 (after taking in the screen JS interface), 226.9 KB and 259.6 KB (budgets 240 KB and 260 KB). The template text (about 1 KB) left the first bundle but counts in the total. Only 0.4 KB was left under the total budget, so exports remove template indentation, strip text only the dev server reads (template error messages, screen JS error messages), and remove `ScreenTemplates.stale`, which the player doesn't use. Before rewriting the remaining screens (save and load, backlog, title, settings), the total budget had to be revisited or other things made smaller (splitting into another bundle doesn't lower the total).
- Before stage f2, the user decided to raise the total budget to 270 KB (the 240 KB budget for what loads before play stays). Before stage f2 it was 226.9 KB and 259.7 KB, after it 227.4 KB and 260.9 KB. The three templates went into the separate bundle. The first bundle grew by 0.5 KB because the code building the three screens from templates and `view.update` are slightly larger than the previous screen code.
- After stage f3 (settings), 226.7 KB and 261.6 KB. The first bundle shrank by 0.7 KB (building each item and looking up its wording moved into the template, and the code building from the template is smaller than the previous code). The total grew by 0.7 KB (the text of the settings template).

## How the engine holds the built-in templates

- The template text is an `export const` in `packages/screens/src/<screen>.ts`, listed in `STANDARD_TEMPLATES` in `packages/screens/src/index.ts`. `ScreenTemplates` in `template.ts` reads them (laying the game's over the built-in ones, and remembering each part once read).
- Reading `.html` with `?raw` is not used, so other packages that read the source of `@liminalia/web` (Studio, Studio Mobile, tests) can type-check without Vite's types. Copying imports the same text and writes it into the game.
- Export size (`packages/cli/test/engine-bundle.test.ts`, the template game, gzip): before the prototype, what loads before play was 222.8 KB and the total 254.6 KB. After the prototype, 224.7 KB and 256.5 KB (budgets 240 KB and 260 KB). After stage f1, see "When the built-in templates are loaded" above.
- Each screen's rules (working `data-role` values, value names, required `data-role` values, the plugin hooks that replace it) are written in that screen's file as `<screen>_SCREEN` (`StandardScreen`) and listed in `STANDARD_SCREENS` in `packages/screens/src/rules.ts` (read by template checks, copying and the table in `docs/screens.md`; not in the player's bundle). See "Checking templates" below.

## How a game's templates are registered and read

```json
{ "ui": { "templates": { "confirm": "ui/screens/confirm/confirm.html" } } }
```

- In `ui.templates` of `liminalia.json`, write the screen name (`id` in `screen-catalog.ts`) → the template file (a path from the game folder, where `liminalia.json` is). The usual place is `ui/screens/<screen>/<screen>.html` (copying puts it there). Other places work too.
- The `lang` type (`UiConfig.templates`), its check (`checkUi`; `.html`, a path inside the game folder) and the JSON Schema were updated together.
- The dev server and exports read the file contents into the game information (`project.templates` of `virtual:liminalia/project`; `liveConfig` in `player-info.ts`). The player doesn't fetch the game's files. Reasons: no 404 for missing files, export CSP and offline behave the same, and the confirmation can show right away without waiting.
- The dev server watches the registered files and passes the contents with `liminalia:live-config` on change. It takes effect from the next screen opened (an open screen is not rebuilt). The same applies when `ui.templates` changes.
- Files that can't be read are not used (the dev server prints to the console). Missing files and unknown screen names are reported by `lim check` and the Studio check (`template-missing`, `template-unknown-screen`).

## Keeping the original built-in version in a copied file

- Every built-in part has `data-version="version"`. When a built-in part changes, its version goes up by one (even for only added class names or attributes; anything games that copied it should know about).
- Copying copies the part as is (including `data-version`). The copied part's `data-version` records "which built-in version it was copied from". Creators don't change `data-version` when editing.
- If a game's part is older than the built-in one, the part is reported (part name, copied version, current version). The player doesn't report it (`staleParts` in `template.ts` stays for tests but isn't in the export bundle). `lim check` and the Studio check report `template-outdated` and point to `lim screens diff <screen>`.
- Showing the difference needs the original built-in text that was copied. Copying also writes the original text of each copied part into Studio's store (`.liminalia/screens/<screen>/<part>.<version>.html`). Comparing it with the current built-in template shows what changed in the built-in template, without mixing in the game's edits (a three-way comparison). Without the store (copied elsewhere and so on), only the version numbers are reported.
- The store is per part because versions go up per part. Keeping the whole screen's text under one version can't decide which original a game copied when it copied only one part, or copied parts at different times. A part's `data-version` becomes the store's file name as is.
- The comment at the top of the file (which engine version it was copied from) is for people; the engine doesn't read it.

## Replacing just one part

```html
<template data-part="slot" data-version="1">
<li class="lm-slot my-slot">…</li>
</template>
```

- Only the parts written in a game's template replace the built-in parts (merged per part name; `mergeTemplates`). Without `screen`, the whole screen stays built-in and only the row inside is the game's.
- `<style>` is added to the built-in one.
- Part names are treated as part of the interface. The built-in templates may add parts, but renaming or removing one breaks games that copied it, and is written in the CHANGELOG as action required.

## Relation to today's `screens.*` (the TypeScript interface)

`screens.*` stays, for people who want to build screens in the game's JavaScript and for existing games and plugins.

### Which wins

For one screen, the upper one wins.

1. The plugin's `WebPlugin.screens.<screen>` (`WebPlugin.title` for the title). With a theme chosen, the theme's `screens.*` laid over the plugin's (same as today).
2. The game's template (`ui.templates.<screen>`), laid over the built-in template part by part.
3. The built-in template.

Reasons:

- Existing games replace five screens with `screens.*`: confirmation, menu, save and load, backlog and title. If a template is registered later (pressing copy, or an engine update turning a built-in screen into a template), a screen running from code must not silently become something else. The order leans toward not changing the game's current screen.
- `screens.*` receives `api` and can do things HTML can't. A creator writing code for the screen is read as a stronger intent than a template.
- The reverse order (the template wins) was also considered. What's written in the game folder is the game's intent, so it seems natural for it to win. But in a game using a theme or plugin screen, copying copies the built-in template, so just pressing copy would put the theme's look back to the built-in look. It's clearer to report "the template isn't used" when both exist.

When both exist:

- The dev server reads the template but doesn't use it. `lim check` reports "`ui.templates.confirm` is not used; the plugin (name)'s `screens.confirm` comes first" (`template-overridden`).
- Copying in Studio shows when the screen is replaced by `screens.*`, and confirms before copying.
- To move to the template, remove `screens.<screen>` from the plugin (or theme).

### A theme's `screens.*` and a game's template

- A theme's `screens.*` is code, so it sits at the same level as a plugin's `screens.*` and wins over a game's template (1 above). Within a theme, as today, the theme's `screens.*` wins over the plugin's `screens.*`.
- If themes can carry templates later (`PluginTheme.templates`), they go between the game's template and the built-in one: merged per part in the order game, theme, built-in. Copying a theme's look becomes possible only in that shape.
- Changing the theme currently reloads (`main.ts`). Templates are read again at the same time, so nothing special is needed.

### A one-part template and `screens.*`

- If `screens.<screen>` replaces that screen, the whole screen is code, so the part's template isn't used (reported as when both exist).
- If `screens.*`'s `api` later gets a way to build template parts (something like `api.render("slot", values)`), rows a game replaced are used even in a screen built by code. It's also a path for JavaScript authors to borrow built-in parts and make only part of a screen code. It raises the interface version, so it is decided together with rewriting the remaining screens.

## Handling a game's HTML safely

Templates are written by creators, but things they don't notice can get in by copying distributed assets or pasting someone else's work. The player does the following.

- On reading, contents go into a `<template>` (an inert document fragment), are processed there, then copied for use. They are never put into the live document directly with `innerHTML`.
- Removed elements: `script`, `iframe`, `frame`, `frameset`, `object`, `embed`, `applet`, `link`, `meta`, `base`, `portal`, `noscript`. SVG `animate` and `set` that rewrite `href`.
- Removed attributes: those starting with `on`, `srcdoc`, `target`, `formtarget`, `action`, `formaction`. On `<a>`, `href` is kept only within the page (starting with `#`), so the game page isn't left.
- Attributes taking URLs (`href`, `src`, `srcset`, `action`, `formaction`, `poster`, `data` and so on) keep only relative paths, `#`, `data:` images (except SVG) and `blob:`. `javascript:`, outside URLs such as `http:`, and those starting with `//` are removed with the attribute.
- In `style` attributes and `<style>` (including inside parts), `@import` is removed and `url()` pointing outside becomes `none`.
- Exported games already block scripts and outside loads with CSP (`packages/cli/src/csp.ts`). The processing above is also for the dev server, which has no CSP, and for games that removed `build.csp`.
- Asset images used from a template are written as paths relative to the exported page (`assets/image/…`), the same way as the project CSS (`ui.css`) (to be aligned in a later stage).
- JavaScript goes in screen JS ("Screen JS" below) or a plugin's `screens.*`. `<script>` and `on*` attributes inside templates stay removed (they don't run inside templates).

## Copying

Used by `lim screens` and the MCP tools (`copy_screen`, `read_screen_files`, `write_screen_file`, `diff_screen`; [mcp.md](../mcp.md)). The implementation is `@liminalia/project/screen-copy`.

```text
lim screens [project] copy <screen> [--part part,…] [--js] [--force] [--json]
lim screens [project] diff <screen> [--json]
lim screens [project] reset <screen>
lim screens [project] js <screen> [--force]
```

- Every screen in the list of built-in screens (`STANDARD_SCREENS` in `packages/screens/src/rules.ts`) can be copied. The built-in template text is read from there, so a screen rewritten as a template and added to the list can be copied without changing the copying code.
- `copy`: copies the built-in template to `ui/screens/<screen>/<screen>.html` (or the place registered in `ui.templates`), and registers it in `ui.templates` if not registered. A comment with the engine version it came from and an empty `<style>` go at the top. The original text of each copied part is kept in `.liminalia/screens/<screen>/<part>.<version>.html`.
  - `--part` copies only parts. Without the file, a file with only that part is made (the other parts stay built-in). With the file, the part is added at the end.
  - An existing file (with `--part`, an existing part) isn't written without `--force`. With `--force` it's rewritten (for a part, only that part's `<template>` is replaced).
  - `--js` also places a screen JS template.
  - If a plugin's `screens.*` replaces the same screen, that is shown after copying (the same text as `template-overridden`).
- `diff`: per part, a unified diff of (1) the current built-in part to the game's part, and (2) what changed in the built-in template since the copied version (only version numbers without the original text). `--json` gives a machine-readable shape.
- `reset`: removes the screen from `ui.templates` to go back to the built-in screen. The template and screen JS are not deleted but renamed to `<name>.reset-<time>.html` (`.js`) (what the author wrote isn't silently deleted). An emptied `ui.templates` is removed.
- `js`: places a screen JS template next to the template (works without copying the template; it then applies to the built-in template's screen).
- `liminalia.json` is rewritten with `JSON.stringify(…, null, 2)` (other entries and their order stay).

## Screen JS

A way for a game to add behaviour attributes can't express (adding elements depending on values, adding its own keys, adding animation and so on) in JavaScript. It sits next to the template without making a plugin.

### Where it goes

- A `.js` with the same name in the same place as the screen's template (if `ui.templates.confirm` is `ui/screens/confirm/confirm.html`, then `ui/screens/confirm/confirm.js`). Without a registered template, `ui/screens/<screen>/<screen>.js` (it applies to the built-in template's screen).
- No registration entry is added. Reason: with the template and JS in the same folder under the same name, authors can find a screen's files easily, and `lim screens reset` can put both back together. The rule for the place is the single `screenScriptFile` in `@liminalia/lang`, used by checks, the player and copying alike.
- Only screens that can be built from templates (`STANDARD_SCREENS`) read it. Anything pointing outside the game folder is not read.

### Shape

```js
// ui/screens/confirm/confirm.js
export default function (screen, api) {
  screen.dataset.kind = String(api.values.kind);
  const key = (e) => { if (e.key === "y") api.press("ok"); };
  document.addEventListener("keydown", key);
  return () => document.removeEventListener("keydown", key); // called on closing
}
```

- Write a function as `export default`. Its arguments are the element of the screen built from the template (the part `screen`) and the screen's `api`.
- It's called right after the screen's element is built and put into the document (in the microtask right after building, before the focus on opening). The attribute behaviours (`data-role` buttons, keys, gamepad, focus, text-to-speech, Esc) are attached just as without JS.
- If it returns a function, that is called once when the screen closes (to remove listeners it added and so on).
- Errors inside the JS don't stop the screen (they go to the console, and the template's screen keeps working).

`api` (interface version 1; `ScreenScriptApi` in `@liminalia/web`):

| Name | Contents |
|---|---|
| `version` | Interface version (1) |
| `screen` | Screen name (`confirm` and so on) |
| `values` | The screen's values (what goes into `data-field`; the confirmation has `message`, `yes`, `no`, `kind`) |
| `press(action)` | Calls a `data-role` action (values that work on that screen; the confirmation has `ok`, `cancel`, `close`). `false` if there is no such action |
| `close()` | Closes the screen (same as `close`, or `cancel` or `back` if absent) |
| `result(value)` | Returns the screen's result and closes (on the confirmation, `true` is "Yes" and anything else "No") |
| `render(part, values)` | Builds a part of that screen's template (the game's part laid over the built-in one, with attribute behaviours). The values are `{ fields, roles, state }`. Placing it is up to the JS |
| `text(key)` | Built-in wording (a key of `TEXT` in `strings.ts`; replaced by `WebPlugin.texts`, in the player's language) |

- The names are also listed in `SCREEN_SCRIPT_API` in `@liminalia/lang`, used by checks. When adding one, change `ScreenScriptApi`, `SCREEN_SCRIPT_API` and this table together (a browser test checks that the `api` passed matches `SCREEN_SCRIPT_API`).
- The earlier idea of `api.render` (building template parts from the `api` of `screens.*`) went in first as `render` of screen JS. Adding it to the `api` of a plugin's `screens.*` raises the interface version, so it is decided together with rewriting the remaining screens.

### Safety line

- The line is drawn at "inside the game folder or not". JS placed inside the game folder is treated like the game's own plugin (`plugins: ["."]`). Both are code the author placed in their own folder, and both go into exports.
- `lim build --restricted` (the export stops), `lim dev` and `lim studio` with `--restricted`, and `LIMINALIA_RESTRICTED=1` don't read it, same as plugins (the template's screen keeps working).
- The rule removing `<script>` and `on*` attributes in template HTML stays. Templates can get things the author doesn't notice by copying distributed assets or pasting others' work, so running code is kept in a separate file, and only what the author placed as `.js` runs.

### Loading

- The dev server and exports import each screen's JS through the virtual module `virtual:liminalia/screen-scripts` (`packages/web/screen-scripts-module.ts`). In exports it goes into the bundle (the game's `ui/` folder isn't copied).
- In the dev server, saving a JS file makes this virtual module receive the replacement and pass it to the player (no reload). The new JS takes effect from the next screen opened (an open screen isn't rebuilt, same as templates). Adding or removing JS, or changing `ui.templates`, also rebuilds and passes it.
- Studio Mobile (`@liminalia/studio-mobile`) doesn't bundle the repository's code with Vite, so it doesn't read screen JS for now (the template's screen as is).
- On the player side, `system/screen-script.ts` holds the loaded JS, and `ScreenTemplates.screen(name, values)` builds the whole screen and calls the JS. Template-built screens are built with `screen()` instead of `render(name, "screen", …)` and call the returned `dispose()` on closing (the confirmation is `system/confirm.ts`). The remaining screens do the same when rewritten.
- The four screens of stage f1 are also built with `screen()` and call `dispose()` on closing (the menu, controls help and ending name when the screen closes, choices when choosing is done). `api.values` are that screen's values ("Parts and attributes of four screens"), and `api.press` is that screen's `data-role` actions. `api.result` goes on to the title on the ending name, and picks the choice with that number (from 0) on choices.
- The element choices' JS receives is not the built element but the choice layer (`.choices`). The built element's contents move into the layer ("Choices" in "Parts and attributes of four screens"), so the third argument of `screen(name, values, element)` passes the layer.

### Checks

`lim check`, the Studio check, VS Code and MCP look at them together with template checks ("Screen templates" in [format.md](format.md)).

| Reports | code | Severity |
|---|---|---|
| No `export default` (reading it does nothing) | `template-script-export` | Warning |
| A name not in `api` (`api.answer` and so on), or an `api.press` value that doesn't work on that screen | `template-script-unknown` | Warning |

- The JS text is read without running it. Names are checked only when the argument is received as `api` (not inside comments).

## Keeping the class names of parts

- The built-in templates carry all class names of `classes` and `parts` in the parts list (`screen-catalog.ts`). Rewriting doesn't change them, so the game's CSS, theme values, and Studio's part picking in "Game screens" keep working on copied screens.
- `packages/web/test/screen-templates.test.ts` checks, for each built-in template, that no class name from the list is missing and that parts have names and versions.

## The prototype (the confirmation)

- `packages/web/src/system/template.ts`: reads templates, makes them safe, merges parts, builds parts and attaches behaviours to attributes, finds outdated parts.
- `packages/screens/src/confirm.ts`: the built-in confirmation template.
- `packages/web/src/system/confirm.ts`: builds the confirmation from the template (replacing the earlier `confirmDialog` in `ui.ts`).
- `ask` in `default.ts`: the plugin's `screens.confirm` if present, otherwise the template.
- Tests: `test/e2e/confirm-template.test.ts` (today's behaviour; replacing with a game's template; editing during development; `screens.confirm` first), `test/e2e/screen-template-binder.test.ts` (lists, replacing one part, states, outdated parts, safety, the attributes and list rebuilding added in stage f1), `test/screen-templates.test.ts` (class names and versions, the `ui.templates` check), `test/e2e/screen-templates-author.test.ts` (replacing the four screens of stage f1 with a game's templates), `test/e2e/screen-templates-author-saves.test.ts` (the three screens of stage f2: a save row, one backlog page, the title's items), `test/e2e/screen-templates-author-config.test.ts` (the settings screen of stage f3: tabs and item order, unusable items, a switch, a game's own setting, one key binding row).
- The fix to the confirmation in stage f1: an invisible heading (`confirm.heading`) became the name (`aria-labelledby`), and the question became the description (`aria-describedby`) (version 2). With a game template without the heading, the question becomes the name.

## Parts and attributes of four screens (stage f1)

The built-in templates are `packages/screens/src/<screen>.ts`. The building code is `menu-panel.ts`, `help.ts`, `ending.ts` and `choice-view.ts` (all in `packages/web/src/system/`).
The DOM shape (class names, order, `type`, `role`, `aria-pressed`, `data-action`, `data-kind`) was kept as before the rewrite, confirmed by the fixed tests (`test/e2e/screens-behavior-*.test.ts`) passing unchanged.

### Menu (`menu`)

| Part | Contents |
|---|---|
| `screen` | `.lm-menu-panel` inside `.lm-screen.lm-menu` (heading `.lm-screen-title`, items `.lm-menu-list`, "Return to game" `.lm-menu-resume`) |
| `screen-button` | A row opening a game screen (`menu` of `defineScreen`) |

- What pressing does: items have a system action name in `data-role` (`SYSTEM_ACTIONS`: `save`, `backlog`, `title` and so on). Pressing closes the menu and then does that action. `close` closes it (Esc, right click, pad START and B too). `open` of `screen-button` opens the game screen.
- Order, shown and hidden: as written in the template. Even written actions that can't be used now (quitting in the browser version, replaying a voice on a page without one, saving and loading during a replay, unused flowchart and items, reading-forward actions over a screen waiting for the player; `menuAllows` in `menu.ts`) are removed. Actions not in the built-in order (`fullscreen`, `rollback`, `rollforward`) work if written.
- Game screen rows go where `<template data-list="screens" data-item="screen-button">` is (before "Title" in the built-in template).
- Values: `auto`, `skip` (`"true"` or `"false"`; the built-in writes them with `data-attr-aria-pressed`), and `label` of `screen-button`.
- What the engine writes: `data-action` on items (the action name, for older CSS and tests). Items with empty contents get the action's built-in wording (`menu.save` and so on, as replaced by `WebPlugin.texts`) (the built-in template's items are empty, for export size). Written text is shown as is. Pressing the outermost element itself (the dark area outside the frame) closes.
- Initial focus: `data-autofocus` ("Return to game" in the built-in).

### Controls help (`help`)

| Part | Contents |
|---|---|
| `screen` | A heading bar (heading, tabs `.lm-tabs`, close button) and the body `.lm-help-body` inside `.lm-screen.lm-help` |
| `tab` | One tab (`.lm-tab`) |
| `controls` | The table of controls (`.lm-help-table`). Rows are the `rows` list |
| `row` | One row of the controls table |
| `page` | A page the game added (`ui.help.pages`; image and text in `.lm-help-page`) |

- What pressing does: `close` (close), `page` of `tab` (show that tab).
- Values: `screen` has `tabs` (whether the game has pages; `data-if`), `tab` has `label` and `current` (`"true"` or `"false"`), `row` has `label`, `keyboard`, `touch`, `pad` ("—" for missing controls), and `page` has `title`, `image` (image URL) and `text`.
- States: `data-lm-current` on the current tab row.
- Pressing a tab rebuilds the tabs (`tabs`) and the body (`body`: `controls` for the first tab, `page` for others) with `view.list`. Focus stays on the pressed tab.
- Initial focus: the screen's outer frame (as before).

### Ending name (`ending`)

| Part | Contents |
|---|---|
| `screen` | A screen-covering proceed button `.lm-ending-go` inside `.lm-screen.lm-ending` (kind `.lm-ending-kind`, name `.lm-ending-name`, rule `.lm-ending-rule`, the end mark `.lm-ending-mark`) |

- What pressing does: `proceed` and `close` (go on to the title; Enter, Space and pad A press the selected button; Esc, right click and pad B also go on). The built-in proceed button plays no sound as before (`data-sound="none"`).
- Values: `name`, `kind` (the kind name, written into `data-kind` with `data-attr-data-kind`, so the older `.lm-ending[data-kind="bad"]` works), `kind-label` (the kind wording, only with `title=`), `mark`, `proceed`, `spoken` (the name read aloud).
- How the end mark is placed (`lm-ending-mark-above`, `lm-ending-mark-none`) is a class on the stage, so it isn't in the template.
- Initial focus: `data-autofocus` (the proceed button in the built-in).

### Choices (`choice`)

| Part | Contents |
|---|---|
| `screen` | The frame they're laid out in. The outermost element stands for the choice layer (`.choices`) itself. The built-in has the time bar (`.choice-timer`) and the list of choices |
| `option` | A text choice |
| `option-image` | An image choice (the script's `image=`; `.choice-image`) |
| `option-area` | An invisible pressable area (only `width=` and `height=`; `.choice-area`) |

- The choice layer is an element always on the stage (used by its placement `ui.choice.position`, the chat screen's layout, and a game's `screens.choice`), so the `screen` element doesn't replace the layer. While choices are shown, the class and attributes of `screen`'s outermost element are put on the layer and its contents moved into the layer, and removed when choosing is done.
- Each choice is laid out as a child of the layer with `<template data-list="options">` (so the older `.choices > button` CSS and placement calculation keep working). The engine picks a part per row (image, area, text).
- What pressing does: `choose` of a choice (choose; the sound is choice).
- Values: `screen` has `timer` (the time limit in ms; empty without one, so the `data-if="timer"` bar isn't shown; `--choice-time`, read by the bar, is written on the layer by the engine), and each choice has `text`, `image` (image URL) and `index` (position from the top, from 1).
- States: `data-lm-read` on choices whose destination was read, and `data-lm-disabled` on choices that can't be pressed (`locked=`, or other than the one chosen before during rollback) (`disabled` too on a `<button>`). For older CSS, the same choices also get the classes `is-read` and `is-locked` (`.is-read` was added to the classes in `screen-catalog.ts`).
- The look from the script (`hover=` image swaps, `x=`, `y=`, `width=`, `height=`, `cursor=`, `tip=`) is written on the pressable element by the engine.
- Keys (arrows, Enter, pad d-pad and A), number keys (counting pressable ones from the top), notifying recordings and text-to-speech stay with the engine as before (the pressable element is `data-role="choose"`; it doesn't have to be a `<button>`).
- Initial focus: the first pressable choice (decided in code).

## Parts and attributes of three screens (stage f2)

The built-in templates are `packages/screens/src/<screen>.ts`. The building code is `saveload.ts`, `backlog-view.ts` and `title-view.ts` (all in `packages/web/src/system/`).
The DOM shape (class names, order, `type`, `aria-pressed`, `aria-label`, `title`) was kept mostly as before the rewrite, confirmed by the fixed tests (`test/e2e/screens-behavior-*.test.ts`) passing unchanged (only where a backlog search bug was fixed was the test rewritten to the fixed behaviour).
The differences: the copy notice (`.lm-slot-banner`) isn't placed (rather than hidden with `hidden`) while no destination is being picked. The slot number text (`.lm-slot-name`) goes into an inner `span`. Backlog search removes non-matching pages from the list instead of hiding them.

### Save and load (`saveload`)

| Part | Contents |
|---|---|
| `screen` | A heading bar (heading, page tabs `.lm-tabs`, close button), the copy notice (the `banner` list) and the slot grid `.lm-slots` inside `.lm-screen.lm-saveload` |
| `page` | One page tab (`.lm-tab`) |
| `banner` | The notice while picking a destination for copy and move (`.lm-slot-banner`; text and "Cancel") |
| `slot` | One slot row (inside `.lm-slot-wrap`, the pressable `.lm-slot` (thumbnail, number, protected mark, date, chapter name and play time, start of the text, memo) and the tools `.lm-slot-tools`) |
| `memo` | The memo input (`.lm-slot-memo-input`; shown in place of the tools when the memo button is pressed) |

- Save and load share one template. The engine adds the class `lm-save` or `lm-load` to the outermost element (the screen names are `save` and `load`).
- What pressing does: `close` (close), `page` of `page` (show that page), `cancel` of `banner` (stop picking a destination; the sound is select as before), `pick` of `slot` (save, load, or pick as the destination), `memo`, `protect` (protect and unprotect), `copy`, `move`, `delete`. Slots without numbers (autosave and quick save) remove `memo`, `protect`, `copy` and `move`.
- Not pressable: empty slots when loading; while picking a destination, `pick` of the source, protected slots and unnumbered slots; `delete` of protected slots (`data-lm-disabled` and `disabled`).
- Values: `screen` has `heading`; `page` has `label`, `current` (`"true"` or `"false"`; `aria-pressed`) and `spoken` (the spoken name of the autosave page); `banner` has `message`; `slot` has `name`, `date`, `chapter`, `time`, `text`, `memo`, `thumb` (thumbnail URL), `protect` (the protect button's wording) and the show flags `sub`, `locked` and `tools`; `memo` has `memo`, `placeholder` and `label`.
- States: `data-lm-current` on tabs, and `data-lm-empty`, `data-lm-protected` and `data-lm-source` (the copy source) on rows. For older CSS, the pressable element (`pick`) also gets the classes `lm-empty`, `is-locked` and `is-source`.
- Changing pages, saving, protecting, copying and deleting rebuild the tabs, notice and slot list with `view.list`. If focus is in the list, it stays on the pressable element of the row with the same index.
- The page to open (for save, the slot last written; for load, the newest save) is decided in code. Initial focus is the screen's outer frame (as before).

### Backlog (`backlog`)

| Part | Contents |
|---|---|
| `screen` | A heading bar (heading, search field `.lm-log-find`, close button) and the list `.lm-log` inside `.lm-screen.lm-backlog` |
| `entry` | One page (inside `.lm-log-entry`, voice replay and speaker `.lm-log-speaker`, text `.lm-log-text`, and "Jump here" `.lm-log-jump`) |
| `empty` | The text placed in the list when nothing has been read yet (`.lm-log-empty`) |

- What pressing does: `close` (close; scrolling the wheel down at the bottom also closes), `voice` of `entry` (replay the voice; removed on pages without one) and `jump` (read again from that page, after confirming; removed on the current page and pages that can't be returned to).
- Values: `screen` has `search-label` (the search field's name and placeholder) and `count` (the number of matches; empty when not searching); `entry` has `name` (the speaker; empty for narration, "Choice" for a chosen choice), `text`, `voice-label` and `jump-title`.
- The engine puts the text with ruby, bold, color, line breaks and images, and each character's dialogue text style (`text` in cast.json), into the `data-field="text"` element. The `data-field="name"` element gets the speaker's color.
- The search field is an `<input>` with `data-input="search"`. Typing rebuilds the list (`entries`) with only pages whose speaker or text matches, and writes the count with `view.update`. Esc while typing only clears the text.
- States: `data-lm-choice` (a chosen choice), `data-lm-narration` (narration) and `data-lm-hit` (matched the search) on rows. For older CSS, also the classes `lm-log-choice`, `lm-narration` and `is-hit`.
- The list element (`data-list="entries"`) shows the bottom when opened. Initial focus is `data-autofocus` (the list in the built-in).

### Title (`title`)

| Part | Contents |
|---|---|
| `screen` | The title (`.lm-title-name`) or logo (`.lm-title-logo`) and the item list `.lm-title-menu` inside `.lm-title` |

- What pressing does: `start` (new game), `load` (continue; with `ui.title.resume`, resumes from the newest save), `extra`, `flowchart`, `config`, `help` (controls help) and `exit`. Pressing plays the voice of that action in `ui.systemVoice.actions`.
- Order, shown and hidden: as written in the template. Even written items that can't be used now (extras in a game without them, a hidden flowchart, controls help without `ui.help.title`, quitting in the browser version) are removed. `load` without saves can't be pressed (`data-lm-disabled` and `disabled`).
- Values: `name` (the game's title, translated to the language being played), `logo` (the image URL of `ui.title.logo`), `heading` (whether to show the title as text; not with a logo or when `ui.title.showName` is false).
- The background (`ui.title.background` and `ui.backgroundFocus`) and music (`ui.title.bgm`) are put on the outermost element and the stage by the engine as before. So is a title changed by `ui.title.variants`.
- The title isn't pushed onto the screen stack (`pushScreen`). On opening nothing is selected, and arrows and the pad's d-pad select items (as before). Screen JS's `dispose` is called when the title is removed (including when rebuilding).
- A plugin's `WebPlugin.title` (including a theme's `title`) comes first if present (as today).

## Parts and attributes of the settings screen (stage f3)

The built-in template is `packages/screens/src/config.ts`. The building code is `packages/web/src/system/config.ts`.
The DOM shape (class names, order, `type`, `aria-pressed`, `aria-label`, `hidden`) was kept as before the rewrite, confirmed by the fixed test (`test/e2e/screens-behavior-config.test.ts`) and the per-item tests (`settings-extra`, `settings-display`, `volume`, `controls`, `config-window`, `desktop-shell` and others) passing unchanged.
The difference: the "Change" button of key and pad bindings plays the press sound like other buttons and has `aria-pressed="false"` from the start.

| Part | Contents |
|---|---|
| `screen` | A heading bar (heading, tabs `.lm-tabs`, close button), item lists per tab `.lm-config-rows` (text, screen, sound, controls), the preview `.lm-preview` and the bottom bar `.lm-config-footer` inside `.lm-screen.lm-config` |
| `option` | One choice whose number varies (`.lm-toggle`): language (list `languages`), window size (`sizes`), system voice (`voices`) |
| `speaker` | One row of per-speaker voice volume (name, slider and value inside `.lm-config-row`). List `speakers` |
| `binding` | One row of a key or pad binding (name, the current key or button `.lm-config-keys`, "Change"). Lists `keys` (keyboard) and `buttons` (gamepad) |

- Item rows use `data-setting` ("Tying to settings" above). Names the built-in template writes: the text tab has `textSpeed`, `autoWait`, `skipUnread`, `skipSpeed`, `autoAfterChoice`, `skipAfterChoice`, `choiceTimer` and `language`. The screen tab has `windowOpacity`, `textScale`, `font`, `reduceShake`, `reduceFlash`, `readColor`, `lineSpacing`, `textEdge`, `selfVoicing`, `highContrast`, `contentFilter`, `fullscreen`, `colorVision`, `captions`, `confirm`, `hideCursor`, `analytics` and `windowScale`. The sound tab has `master`, `mute`, `bgm`, `se`, `voice`, per-speaker voice volume, `voiceStopOnPage`, `duckBgm`, `systemVoice`, `whenHidden` and `whenUnfocused`. The controls tab has `padStyle`.
- Items chosen in a shape different from the setting value: `readColor` is `on` and `off` (if the player hasn't decided, it follows whether the game sets `ui.text.readColor`), and `analytics` isn't a setting value but whether to send play statistics, remembered separately on this device. Choosing `windowScale` leaves fullscreen. The choices of `language`, `windowScale` and `systemVoice` are rows of their lists.
- Items the engine removes with their row: `language` (one language), `fullscreen` (where fullscreen isn't available), `windowScale` (not the desktop version, or only one size to choose), `analytics` (the game doesn't write `build.analytics`), `contentFilter` (the game doesn't use it, or a variant decides it), `systemVoice` (the game doesn't use it), and `whenHidden` and `whenUnfocused` (not the desktop version).
- Groups (tabs): pressing a button with `data-role="page"` and `data-page="name"` shows only the elements whose `data-page` includes that name (others get `hidden`), and puts `aria-pressed` and `data-lm-current` on the button. `data-page` can list names separated by spaces (the built-in preview has `text screen`). Without tab buttons, everything is shown. On reopening, the tab open last time (or the first) is shown. Games may choose the names (merging tabs into two, adding more, and so on).
- What pressing does: `close` (close; Esc, right click and pad B too), `page` (tabs), `reset` (reset to defaults; a game's own settings are reset only if they are in the game's defaults), `export` and `import` (exporting and importing save data; removed when unavailable), `reset-controls` (reset key and pad bindings), and `change` of `binding` (bind the next key or button pressed; pressing the waiting row again stops).
- Values: `screen` has the value text of sliders (`textSpeed`, `autoWait`, `windowOpacity`, `textScale`, `master`, `bgm`, `se`, `voice`; shown in elements with that name in `data-field`), `filter-label` (the name of the content filter item; the game's `ui.contentFilter.label`), `preview` (the preview text; the engine puts in the contents) and `controls` (whether to show key and pad bindings; `data-if`). `option` has `label` and `lang` (language only), `speaker` has `label` (also the slider's spoken name) and `volume`, and `binding` has `label`, `keys` and `waiting` (`"true"` while waiting for a press; the built-in writes it into `aria-pressed`).
- The engine gives sliders the setting's built-in name as their spoken name (`aria-label`) (one written on the `<input>` wins).
- States: `data-lm-current` on tabs, `data-lm-on` on switches, `aria-pressed` on choices.
- Starting to wait for a binding, binding, and stopping rebuild the `keys` and `buttons` lists with `view.list`. Focus stays on "Change" in the row with the same index.
- Settings changed outside the screen (muting with the M key and so on) are reflected in the controls of the open screen.
- Initial focus: the screen's outer frame (as before).

## Checking templates

`lim check`, the Studio check, the VS Code extension, and MCP's `check` and `check_text` check a game's `ui.templates` the same way (`projectDiagnostics` in `@liminalia/sdk`; the list of diagnostics is "Screen templates" in [format.md](format.md)).

| Reports | code | Severity | Where |
|---|---|---|---|
| A registered file is missing or can't be read | `template-missing` | Error | The screen's line in `ui.templates` of liminalia.json |
| A screen name that can't be built from a template | `template-unknown-screen` | Warning | Same |
| A plugin's `screens.*` replaces the same screen | `template-overridden` | Warning | Same |
| An unknown part name, a `<template>` without `data-part`, or a file with no parts and no `<style>` | `template-unknown-part` | Warning | That `<template>`'s line (line 1 for a file) |
| A `data-role`, `data-field`, `data-text` or `data-setting` that doesn't work on that screen | `template-unknown-value` | Warning | That element's line |
| A `data-role` the screen needs is missing | `template-missing-role` | Error | The line of the part `screen` |
| A `data-list` without `data-item`, or a missing `data-item` part | `template-list-item` | Error | That element's line |
| Things the player removes (the list in "Handling a game's HTML safely") | `template-unsafe` | Warning | That element's line, or the line inside `<style>` |
| The copied version is older than the built-in one, or has no version | `template-outdated` | Warning | That `<template>`'s line |

- Each screen's rules aren't written on the checking side. The owner of the built-in template (`packages/screens/src/<screen>.ts`) holds them as `StandardScreen` (`@liminalia/lang`), listed in `STANDARD_SCREENS` in `packages/screens/src/rules.ts`. The rules are the working `data-role` values (`roles`), the `data-field` names (`fields`), the required `data-role` values (`required`; per group, any one is enough), the plugin hooks that replace the screen (`replacedBy`: `screens.confirm`, `system` and so on), and the setting names tied to controls (`settings`; settings screen only; names starting with `custom.` always pass). Part names and versions are read from the built-in template text. A screen rewritten as a template gets checks just by writing and listing its rules.
- Keys that can go in `data-text` are all text keys of the built-in wording (`TEXT` in `strings.ts`).
- Required `data-role` values are checked on the whole, with the game's parts laid over the built-in ones (a template that copied only one part counts the rest from the built-in parts).
- Checks read the text without a DOM (`screen-templates.ts` in `@liminalia/lang`). The reading follows the player (the outermost `<template data-part>` is a part, and the list of removed things is the same).
- The rules live on the rendering side (`@liminalia/web/screen-rules`), and `@liminalia/lang` and `@liminalia/sdk` don't read them. `lim check` and the VS Code extension read them and pass them in, and for Studio, the side that starts the dev server (`vite.config.ts` of `web`, Studio Mobile's Service Worker, `lim mcp`) passes them with `setScreenTemplateRules` (like `setScreenTable` for the list of built-in screens).
- Screens a plugin replaces are read from the text of the plugin's `./web` (`pluginScreens` in `@liminalia/project/screen-templates`; the rendering code can't run in Node). It looks the same way as `replacedScreens` in the player (`ui-probe.ts`): the `system`, `title` and `screens` entries of an object that has only `name` and `WebPlugin` entries, plus `screens` and `title` of the theme chosen in `ui.system.preset`. Contents of `screens` held in another variable can't be read, so it leans toward not reporting.

## Things to watch when rewriting the remaining screens (learned in the prototype)

- Write the screen's rules (`StandardScreen`) in `packages/screens/src/<screen>.ts` and list them in `packages/screens/src/rules.ts` ("Checking templates" above). The `roles` of the menu and title include system action names (`SYSTEM_ACTIONS`).

- First add tests of the screen's current behaviour (shape, class names, keys, focus, text-to-speech, results, closing), and confirm they pass unchanged after the rewrite. The confirmation kept the same DOM as a template (class names, button order, `type`, `role`).
- Indentation whitespace is dropped, so templates can be indented for readability. Spaces within text (between `<b>name</b> <a>…</a>`) stay.
- Write initial focus with `data-autofocus`. What screens decide in code today (a saved position, the current page, the previously chosen slot) can't be written as attributes, so each screen's code decides it (stage f1's choices decide "the first pressable choice" in code).
- Screens whose contents change while open rebuild lists with `view.list` (added in stage f1: the controls help's tabs, save and load pages, backlog search). To rewrite only values, use `view.update(values)` (added in stage f2: the backlog search count). Take care to keep the focus and reading position.
- Learned in stage f2: where the engine builds the contents of a list row (the backlog text's ruby, color and images), code replaces the contents of the element with `data-field` (the game decides the element's place and look, and the engine puts in the contents). Template checks look at `data-field` names, so no new attribute is needed. An input (backlog search) would become a pressable button with `data-role`, so it's marked with `data-input` and the screen's code watches it.
- Learned in stage f1: a screen laid out inside an existing element (the choice layer) lays the template's outer frame over the layer. To keep CSS that assumes DOM children (`.choices > button`), use `<template data-list>`. Older attributes (`data-kind`, `data-action`, `aria-pressed`) are written the same with `data-attr-*` or in code.
- Learned in stage f3: the sliders, switches and choices of the settings screen use an attribute separate from `data-role` buttons (`data-setting`), and tying them to values calls the UI parts (`slider`, `toggle`, `choice` in `ui-parts.ts`). The unit of showing, hiding and reordering is the row, so `data-setting` goes on the row rather than the control, and the controls inside are told apart by element type (`<input>`) and attributes (`data-value`, `data-toggle`). For things whose action depends on the button pressed, like tabs, the pressed element is passed to the `data-role` action and the button's attribute (`data-page`) is read.
- If the screen's heading is `.lm-screen-title`, `h1` or `h2`, `aria-labelledby` is added (`pushScreen` looks for it).
- The sound is decided by the `data-role` value (back-type actions are cancel, pages are page, choices' choose is choice, others select). Where today's screens play a different sound, match it with `data-sound` (stage f1's menu "Return to game", the ending name).
- Measure the export size per screen ("When the built-in templates are loaded" above). Little is left under the total budget, so revisit the budget before the next screen.
- Menu and title actions work by writing a system action name in `data-role` (the same names as `SYSTEM_ACTIONS`). Conditions for showing and hiding (removed in settings, stopped in a trial version) are written by the engine with `data-lm-disabled` or `hidden`.
- When a game's template misnames a part (a part not in the built-in one), the player silently doesn't use it. `lim check` and the Studio check report it (`template-unknown-part`).

## Not built yet

- Rewriting the built-in screens that can't be built from templates (extras, flowchart, items, content warning and so on). Not rewritten in 0.4.0.
- Theme templates (`PluginTheme.templates`), and building template parts from the `api` of a plugin's `screens.*` (screen JS's `api.render` went in first).
- Reading screen JS in Studio Mobile.
