Studio (./studio)
On this page
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.
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”:navStatereturns the current place within the screen as a value that can be turned into JSON, andrestoreNavgoes back to that place; the screen is already in front by then)- The
ctxAPI:readData(name),writeData(name, text, baseHash): project data (.json inpaths.data). Pass thehashyou got when reading back asbaseHash; 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 changedproject(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 currentnavStatein 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)script: the scenario being edited in the “Script” tab (The script API)
- Match the look with Studio’s CSS variables (colors
--sheet,--paper,--rule,--ink,--ink-soft,--cue,--cue-wash,--markand 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, likeleft: calc(var(--list-w) - 4px))- An example is 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. Readvalue, and when you change it withupdate(copy => …)orset(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;mergeJsonis also available). If the file changes elsewhere while nothing is waiting to be saved, it reloads.undo(),redo()andbindKeys(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’sflush),reload()(from the screen’srefresh),dispose()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 itsel). It suggests candidates from the project’s asset list, shows a preview for image folders, and marks paths that aren’t in the list withdata-missing. It reloads the candidates when the project changesaskConfirm(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(andSTUDIO_PLUGIN_API_VERSION): the plugin API version. From 2, the parts in this section andcast,speakers,assets,scriptsandparseon the dev server side are available. It’sundefinedin older versions of Studio, so plugins that use the newer API check it and branchctx.language(from 3): Studio’s display language ("ja"or"en"). Match your screens’ text to it. For the names of screens, panels and actions, writetitleEnalongsidetitle, and the English display shows that insteadsuggestAssets(request, ctx)(from 4; write it in the plugin definition alongsideviews,panesandcommands): 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,@bgmand so on).requesthas 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 asignalthat 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.
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 callsshowand collapsing callshide; otherwise, as with screens, there areflushandrefresh(navStateisn’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 itcommands: listed at the end of the “More” menu in the top bar. If you writekey(in CodeMirror notation;Modis ⌘ on Mac and Ctrl elsewhere), it can be called with that key in the “Script” tab. Ifrun(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 }.selectionis the selected range ({ from: { line, ch }, to, text }; null if nothing is selected). null if no scenario is opentext(): 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 typingapply(edits): rewrites lines of the open scenario. ⌘Z undoes them together as one change, and they’re saved automatically afterward// 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
fromtoto(both included) withtext.textmay contain line breaks; null deletes the lines. Settingtotofrom - 1adds the text before linefrom expectis 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 withctx.writeScripton 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)
- Replaces lines
- An example is the “スタンプ” (Stamp) pane and action in examples/stamp-plugin/src/studio.ts (it adds
@stampbefore 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>/…).
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.
const total = await ctx.server<{ count: number }>("/total");
for await (const s of ctx.stream<{ path: string }>("/scan", { body: { folder: "stamps" } })) show(s);
routeskeys are the method and the path aftername, like"GET /status". Return a value (turned into JSON; no body ifundefined), an async iterator (each item it yields is sent as one line) or aResponse(to return images or sounds as they are). ThrowingStudioServerError(status, message)(or anErrorwith a number from 400 to 599 instatus, for plugins outside the project that don’t import the sdk) returns that status, and the screen’sserverandstreamthrow anErrorwithstatus- Cancellation: when the screen leaves its
for await(break) or abortsinit.signal, the connection is closed and the server side’sreq.signalis aborted. If it’s in the middle of sending, the iterator is closed andfinallyruns. Stop long work (child processes) by watchingreq.signal req:method,path,query,json()(null if there’s no body),text(),signalctx(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 settingsreadScript(file),writeScript(file, text, baseHash): scenarios (without the extension). Pass thehashyou got when reading back asbaseHash; 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’sctx. Saving notifies the screen’sonDataChangedcommands(): 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 commandscheck(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 aslim check). Use it to check AI suggestions before applying themlog(message): writes to the dev server’s logapiVersion(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 likectx.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, aScriptfrom@liminalia/sdk. Passtextto 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.serverandctx.streamadd 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 (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)