# Writing plugins

## Studio (`./studio`)

Adds project-specific management screens (settings tables, data editing and so on) to the "Plugins" tab of Studio. Only Studio (the dev server) reads it, and
it isn't included in the exported game. In the tab's left panel, the screens are grouped by plugin name (`name`) and listed in the order of `views`.
You can start a new plugin from a template with a working example, with "Create new" in the "Plugins" tab.

```ts
import { defineStudioPlugin } from "@liminalia/sdk/studio";

export default defineStudioPlugin({
  name: "stamp",
  views: [{ id: "stamp-book", title: "Stamp book", mount: (el, ctx) => { /* build inside el */ return { flush, refresh }; } }],
});
```

- `mount(el, ctx)` is called only once, the first time the tab is opened. What it returns (optional): `show`, `hide` (entering and leaving the tab), `flush` (saves anything waiting to be saved right away;
  called before the window closes, on ⌘S and before "Refresh"; if it can't save, it refuses with a string giving the reason), `refresh` (when "Refresh" reloads the project),
  `navState`, `restoreNav` (for "Back" and "Forward": `navState` returns the current place within the screen as a value that can be turned into JSON, and `restoreNav` goes back to that place; the screen is already in front by then)
- The `ctx` API:
  - `readData(name)`, `writeData(name, text, baseHash)`: project data (.json in `paths.data`). Pass the `hash` you got when reading back as `baseHash`;
    if the file was rewritten elsewhere, nothing is saved and you get `{ ok: false, current }` (the screen decides what to do, such as laying its changes over the current contents and saving again).
    The change history is kept in `.liminalia/history/@data/`
  - `onDataChanged(listener)`: data changed elsewhere (in another editor, by AI, through git). `onProjectChanged(listener)`: the list of files, characters or assets changed
  - `project` (the title, the screen size, and the lists of files, characters and assets), `assetUrl(kind, path)`, `uploadAsset(kind, path, file, overwrite)` (images, sounds, videos and fonts only)
  - `openScript(file, line)` (opens that line of the scenario in the "Script" tab), `notify(text)` (a notice shown at the bottom of the screen)
  - `remember()`: call it before moving within the screen (before changing the open page or the selected item) to keep the current `navState` in the back history. It does nothing while moving with "Back" and "Forward"
  - `server(path, init)`, `stream(path, init)`: call the dev server side API of the same plugin ([The dev server side](../plugins.md#開発サーバー側の口studio-server))
  - `script`: the scenario being edited in the "Script" tab ([The script API](../plugins.md#台本の口ctxscript))
- Match the look with Studio's CSS variables (colors `--sheet`, `--paper`, `--rule`, `--ink`, `--ink-soft`, `--cue`, `--cue-wash`, `--mark` and so on;
  text `--fs-s` (12px), `--fs-m` (14px), `--fs-l` (20px, headings), `--fs-xl` (36px); lines `--line`; corner radii `--r-s`, `--r-m`, `--r-l`.
  They all point to Radix Colors steps and work with the dark color scheme too. Grays are mauve, and actions and the current position are violet. No shadows).
  Buttons, input fields and select fields get Studio's default look as they are (`button.primary`, `button.ghost`)
- `Splitter`, a handle for changing a panel's width by dragging its border, is also available from `@liminalia/sdk/studio` (it records the width in px in a CSS variable on the container:
  ``new Splitter({ host, side: "left", variable: () => "--list-w", min: 200, max: (w) => w - 480, storageKey: (v) => `project.screen${v}` })``).
  The handle's look is `.splitter` (`position: absolute`; decide where it goes in the screen's CSS, like `left: calc(var(--list-w) - 4px)`)
- An example is [examples/stamp-plugin/src/studio.ts](../../examples/stamp-plugin/src/studio.ts) (it saves a memo for each image asset in `data/stamps.json`)

### UI parts (`@liminalia/sdk/studio`)

- `dataDocument(ctx, name, { fallback, delay, indent, history })`: holds project data as a single document. Read `value`, and when you change it with `update(copy => …)` or `set(value)`,
  it's saved automatically after a short wait (`delay`, 800 milliseconds by default). If the file was rewritten elsewhere (in another editor, by AI, through git), it merges three ways, based on the contents when it was read, and saves again
  (items changed by only one side take that side's value; if both changed an item, this side's value is used; `mergeJson` is also available). If the file changes elsewhere while nothing is waiting to be saved, it reloads.
  `undo()`, `redo()` and `bindKeys(element)` give you ⌘Z and ⇧⌘Z within the element (undoing text inside input fields is left to the browser). `onChange((value, reason) => …)`
  (`local`, `remote`, `undo`, `redo`, `load`), `flush()` (can be returned as is from the screen's `flush`), `reload()` (from the screen's `refresh`), `dispose()`
  ```ts
  const memos = dataDocument<Record<string, string>>(ctx, "stamps.json", { fallback: {} });
  memos.update((m) => void (m[path] = text));
  return { flush: () => memos.flush(), refresh: () => memos.reload() };
  ```
- `assetField(ctx, { kind, value, onChange, placeholder, allowEmpty, preview, label })`: a field for choosing an asset (place its `el`). It suggests candidates from the project's asset list, shows a preview for image folders,
  and marks paths that aren't in the list with `data-missing`. It reloads the candidates when the project changes
- `askConfirm(text, { ok })`, `askText(label, { ok, placeholder, value })`: dialogs that look the same as Studio's own ("Yes" and "Cancel" in the screen's language)
- `ctx.apiVersion` (and `STUDIO_PLUGIN_API_VERSION`): the plugin API version. From 2, the parts in this section and `cast`, `speakers`, `assets`, `scripts` and `parse` on the dev server side are available.
  It's `undefined` in older versions of Studio, so plugins that use the newer API check it and branch
- `ctx.language` (from 3): Studio's display language (`"ja"` or `"en"`). Match your screens' text to it. For the names of screens, panels and actions,
  write `titleEn` alongside `title`, and the English display shows that instead
- `suggestAssets(request, ctx)` (from 4; write it in the plugin definition alongside `views`, `panes` and `commands`): adds assets that fit the scene being written to the script's completion.
  It's called where you type the value of an asset-type parameter (`@bg`, `@se`, `@bgm` and so on). `request` has the command and parameter names, the asset folder and the candidates (`candidates`),
  the three lines of dialogue and narration before that line (`before`) and the two after it (`after`), and a `signal` that aborts when typing continues. Return a list of `{ path }`, and up to five of them, in order of fit,
  are listed at the top of the suggestions with a "Fits the scene" mark (the usual suggestions appear below them as they are, without waiting for the answer; if it fails, nothing is added)

### Right panel and actions (`panes`, `commands`)

Things you use while writing (AI consultation, dictionaries and so on) go in the right panel of the "Script" tab, not in a tab.

```ts
export default defineStudioPlugin({
  name: "stamp",
  panes: [{ id: "stamp-pane", title: "Stamp", mount: (el, ctx) => { /* build inside el */ } }],
  commands: [{ id: "stamp-first", title: "Add a line that presses the first stamp", key: "Mod-Alt-s", run: (ctx) => { /* … */ } }],
});
```

- **`panes`**: listed in the right panel as collapsible sections, like the timeline (below the comments section). They start collapsed, and the first time one is opened,
  `mount(el, ctx)` is called once. Opening calls `show` and collapsing calls `hide`; otherwise, as with screens, there are `flush` and `refresh` (`navState` isn't used).
  The whole right panel scrolls vertically, so something that grows tall, like a conversation pane, should set its own height and scroll inside it
- **`commands`**: listed at the end of the "More" menu in the top bar. If you write `key` (in CodeMirror notation; `Mod` is ⌘ on Mac and Ctrl elsewhere),
  it can be called with that key in the "Script" tab. If `run(ctx)` throws, the error is shown as a notice

### The script API (`ctx.script`)

Reading and writing the scenario open in the "Script" tab and its text. Lines are counted from 1, and positions within a line from 0.

- `current()`: `{ file, line, selection, readOnly }`. `selection` is the selected range (`{ from: { line, ch }, to, text }`; null if nothing is selected).
  null if no scenario is open
- `text()`: the open scenario's text, including what hasn't been saved yet. `read(file)`: reads a scenario (for the open scenario, the text being edited)
- `onChange(listener)`: the scenario was reopened, the cursor moved, or the selection changed. Not called while you're typing
- `apply(edits)`: rewrites lines of the open scenario. ⌘Z undoes them together as one change, and they're saved automatically afterward
  ```ts
  // rewrite lines 3–4 and add a line before line 10
  ctx.script.apply([
    { file, from: 3, to: 4, expect: "line 3 before the rewrite\nline 4 before the rewrite", text: "a new line" },
    { file, from: 10, to: 9, expect: "", text: "@stamp stamps/ok.png" },
  ]);
  ```
  - Replaces lines `from` to `to` (both included) with `text`. `text` may contain line breaks; null deletes the lines. Setting `to` to `from - 1` adds the text before line `from`
  - `expect` is those lines before the rewrite (joined with line breaks). The writer keeps typing while AI is drafting a suggestion, so instead of the whole file,
    it checks only that the lines being rewritten are unchanged. If they differ, nothing is rewritten and `{ ok: false, reason: "changed", index }` is returned
  - Other reasons: `not-open` (the scenario isn't open; save it with `ctx.writeScript` on the dev server side), `readonly` (a scenario in an imported project that hasn't been opened up for editing yet),
    `invalid` (a line range is out of bounds or overlaps another)
- An example is the “スタンプ” (Stamp) pane and action in [examples/stamp-plugin/src/studio.ts](../../examples/stamp-plugin/src/studio.ts) (it adds `@stamp` before the cursor line)

### The dev server side (`./studio-server`)

For things the browser screen alone can't do, such as starting child processes (AI CLIs and so on) or reading files outside the project, add APIs on the dev server (Node) side and
call them from the screen. Only the dev server (`lim studio`, `lim dev`, the desktop version) reads it, and it isn't included in the exported game.
Make `name` the same as `name` in the same plugin's `./studio` (the endpoint paths become `STUDIO_API/plugin/<name>/…`).

```ts
import { defineStudioServerPlugin, StudioServerError } from "@liminalia/sdk/studio-server";

export default defineStudioServerPlugin({
  name: "stamp",
  routes: {
    "GET /total": (req, ctx) => ({ count: 3 }),            // return a value → JSON
    "POST /scan": async function* (req, ctx) {             // async iterator → sent one at a time
      const { folder } = await req.json<{ folder: string }>();
      if (!folder) throw new StudioServerError(400, "Send a folder");
      for (const f of list(folder)) {
        if (req.signal.aborted) return;                    // the screen stopped it
        yield { path: f };
      }
    },
  },
  dispose() { /* when the dev server closes; stop the child processes you started */ },
});
```

On the screen side, `ctx.server` receives a value, and `ctx.stream` receives what's sent, one item at a time.

```ts
const total = await ctx.server<{ count: number }>("/total");
for await (const s of ctx.stream<{ path: string }>("/scan", { body: { folder: "stamps" } })) show(s);
```

- **`routes`** keys are the method and the path after `name`, like `"GET /status"`. Return
  a value (turned into JSON; no body if `undefined`), an async iterator (each item it yields is sent as one line) or a `Response` (to return images or sounds as they are).
  Throwing `StudioServerError(status, message)` (or an `Error` with a number from 400 to 599 in `status`, for plugins outside the project that don't import the sdk)
  returns that status, and the screen's `server` and `stream` throw an `Error` with `status`
- **Cancellation**: when the screen leaves its `for await` (`break`) or aborts `init.signal`, the connection is closed and the server side's `req.signal` is aborted.
  If it's in the middle of sending, the iterator is closed and `finally` runs. Stop long work (child processes) by watching `req.signal`
- **`req`**: `method`, `path`, `query`, `json()` (null if there's no body), `text()`, `signal`
- **`ctx` (server side)**:
  - `root`, `paths` (the project folder, and where the scenarios, assets and data are)
  - `stateDir()`: a folder this plugin can use freely (`.liminalia/plugins/<name>/`; created if it doesn't exist). Use it for Studio-only data such as conversation history and settings
  - `readScript(file)`, `writeScript(file, text, baseHash)`: scenarios (without the extension). Pass the `hash` you got when reading back as `baseHash`; if the file was rewritten elsewhere,
    nothing is saved and you get `{ ok: false, current }`. Saving keeps the previous contents in the change history and tells Studio about an outside change (if the scenario is open, Studio merges it with the text being edited)
  - `readData(name)`, `writeData(name, text, baseHash)`: the same project data as the screen's `ctx`. Saving notifies the screen's `onDataChanged`
  - `commands()`: the specs of the commands available in the project (built-in, standard and plugin). Built-in commands include words for what you want to do (`keywords`; `command-meta.ts`).
    Use them as guidance when you let AI choose commands
  - `check(file, text)`: checks a scenario's contents without saving and returns that file's diagnostics (taking other files' labels, characters and assets into account, with the same rules as `lim check`).
    Use it to check AI suggestions before applying them
  - `log(message)`: writes to the dev server's log
  - `apiVersion` (from 2), and APIs that save you from reading the project's contents yourself (all from 2; older versions of Studio don't have them, so call them like `ctx.parse?.(…)`):
    `cast()` (cast in cast.json), `speakers()` (speakers in cast.json and the characters' speaker), `assets()` (folder → list of paths), `scripts()` (the list of scenario names),
    `parse(file, text?)` (the parsed scenario, a `Script` from `@liminalia/sdk`. Pass `text` to parse a draft before it's saved. null for a file that doesn't exist)
- **Loading**: loaded only once, the first time the API is called. After you change it, Studio's "Refresh" asks for a restart. A plugin that can't be loaded is
  reported in the dev server's log, and calling its API returns the reason
- **Protection**: the API accepts only requests from the same origin as Studio that carry the header `x-liminalia-studio: 1` (`ctx.server` and `ctx.stream` add it).
  This keeps other pages from calling the API (including the parts that start child processes)
- An example is [examples/stamp-plugin/src/studio-server.ts](../../examples/stamp-plugin/src/studio-server.ts) (an API that measures the stamp images' sizes on the Node side and returns the total, and an API that sends them one at a time)
