# HTML templates for the built-in screens

## 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.
