@ohmygame/plugin-ui 2.4.0 → 2.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,6 +22,13 @@ const project = await host.request("project.info");
22
22
  Pages allow no inline scripts and no other sites' scripts, so a page's own
23
23
  script is a file beside it.
24
24
 
25
+ The shared stylesheet reserves space for traditional page scrollbars with
26
+ `scrollbar-gutter: stable`; tabs and disclosures can change height without
27
+ shifting the page horizontally. Dialog content does the same within its own
28
+ scroll area. Overlay scrollbars keep the platform's normal behavior. A plugin
29
+ with its own scroll container should apply this property to that container;
30
+ avoid `100vw` for content width or JavaScript scrollbar-width compensation.
31
+
25
32
  Install the package for its types and for editor support:
26
33
 
27
34
  - `@ohmygame/plugin-ui` types the bridge, for example
package/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export type PluginUiMethod =
8
8
  | "command.run"
9
9
  | "ui.toast"
10
10
  | "ui.confirm"
11
+ | "browser.open"
11
12
  | "files.list"
12
13
  | "files.read"
13
14
  | "files.write"
@@ -16,7 +17,16 @@ export type PluginUiMethod =
16
17
  | "files.delete"
17
18
  | "history.list"
18
19
  | "usage.get"
19
- | "net.fetch";
20
+ | "net.fetch"
21
+ | "context.set"
22
+ | "models.list"
23
+ | "models.complete"
24
+ | "models.cancel"
25
+ | "panel.open"
26
+ | "library.add"
27
+ | "assistant.run"
28
+ | "assistant.history"
29
+ | "assistant.clear";
20
30
 
21
31
  /**
22
32
  * An HTTPS request made by the app, for a project panel whose `panel.json`
@@ -121,7 +131,9 @@ export interface PluginFileEntry {
121
131
  * file, an agent's instructions or Canvas documents. Each change to a file is
122
132
  * one the person can undo, so a page changes only what the project's snapshots
123
133
  * keep (not what a `.gitignore` leaves out); an empty folder isn't kept. A
124
- * change is refused while an agent works in the project.
134
+ * change is refused while an agent works in the project, except a `write` or
135
+ * `delete` under the manifest's `projectFiles`: that waits, reads back at once,
136
+ * and lands as one undoable change once the agent is done.
125
137
  */
126
138
  export interface PluginFiles {
127
139
  /** A folder's entries, the project's root without a path; `recursive` skips generated folders such as `node_modules`. `truncated` means it stopped at 10,000. */
@@ -140,12 +152,193 @@ export interface PluginFiles {
140
152
  delete(path: string): Promise<null>;
141
153
  }
142
154
 
155
+ /** What a tool's handler gets besides its input. */
156
+ export interface PluginToolCall {
157
+ /** Aborted when the caller gives up, such as when the person stops the agent. */
158
+ signal: AbortSignal;
159
+ /** Shows how the call is going; at most 2,000 characters each. */
160
+ progress(message: string): void;
161
+ }
162
+
163
+ /**
164
+ * The tools the manifest says this panel answers (`contributes.tools[].panel`,
165
+ * API 2.35.0). The agent and the plugin's commands call them; the app shows
166
+ * the panel and hands its page the call, with input its schema checked.
167
+ */
168
+ export interface PluginTools {
169
+ /**
170
+ * Answers one tool; what the handler returns, as JSON, is its result, and
171
+ * what it throws is the tool's error. A call that comes before the page
172
+ * handles it waits up to 10 seconds. Returns a function that stops.
173
+ */
174
+ handle(name: string, handler: (input: any, call: PluginToolCall) => unknown | Promise<unknown>): () => void;
175
+ }
176
+
177
+ /**
178
+ * What the person is looking at in the panel, for a plugin with the
179
+ * `composer` capability (API 2.35.0): it shows in the composer, and the next
180
+ * message carries it while the panel shows, unless the person removes it.
181
+ */
182
+ export interface PluginContext {
183
+ /** `label` is at most 120 characters, `text` at most 8,000; a new one replaces the last. */
184
+ set(value: { label: string; text: string }): Promise<null>;
185
+ clear(): Promise<null>;
186
+ }
187
+
188
+ /** A model the person set up, from `host.models.list()`. */
189
+ export interface PluginModel {
190
+ provider: string;
191
+ id: string;
192
+ name: string;
193
+ /** Whether it reads images. */
194
+ images: boolean;
195
+ /** The one a request without `model` uses. */
196
+ default?: true;
197
+ }
198
+
199
+ export interface PluginModelMessage {
200
+ role: "user" | "assistant";
201
+ text: string;
202
+ /**
203
+ * In a user's message, for a model whose `images` is true: PNG, JPEG, WebP
204
+ * or GIF, at most 8 in a request and 5 MB each. Send Blobs: base64 text
205
+ * needs its `type`, and counts toward the request's 2 MB as JSON.
206
+ */
207
+ images?: Array<{ data: Blob; type?: string } | { data: string; type: string }>;
208
+ }
209
+
210
+ /**
211
+ * One request to a model (API 2.35.0). Text is at most 200,000 characters in
212
+ * all, over at most 40 messages, the last of them the user's.
213
+ */
214
+ export interface PluginModelRequest {
215
+ system?: string;
216
+ messages: PluginModelMessage[];
217
+ /** Asks for JSON and reads the answer as `json`; the request fails if it isn't JSON. */
218
+ json?: boolean;
219
+ /** 1 to 8,192; 2,048 when left out. */
220
+ maxTokens?: number;
221
+ /** One of `list()`; the default model when left out. */
222
+ model?: { provider: string; id: string };
223
+ }
224
+
225
+ export interface PluginModelResult {
226
+ text: string;
227
+ json?: unknown;
228
+ model: { provider: string; id: string };
229
+ /** Tokens read and written, which count toward the person's usage. */
230
+ usage: { input: number; output: number };
231
+ stopReason: "stop" | "length";
232
+ }
233
+
234
+ /**
235
+ * The person's language models, for a plugin with the `models` capability
236
+ * (API 2.35.0). Each request counts toward their usage and is written in the
237
+ * plugin's log. A request starts only while the panel shows; hiding it
238
+ * doesn't stop one that runs. A plugin has at most 3 running at once and 30
239
+ * a minute, and each has 2 minutes.
240
+ */
241
+ export interface PluginModels {
242
+ list(): Promise<PluginModel[]>;
243
+ /** `signal` stops it; so does the page closing or reloading. */
244
+ complete(request: PluginModelRequest, options?: { signal?: AbortSignal }): Promise<PluginModelResult>;
245
+ }
246
+
247
+ /** One of the plugin's tools the assistant used, and what it answered. */
248
+ export interface PluginAssistantToolUse {
249
+ id: string;
250
+ name: string;
251
+ input: unknown;
252
+ result: string;
253
+ error?: true;
254
+ }
255
+
256
+ /** A panel's assistant conversation: the person's messages, and each of the assistant's steps. */
257
+ export type PluginAssistantEntry =
258
+ | { role: "user"; text: string; /** How many images came with it; they aren't kept. */ images?: number; at: string }
259
+ | { role: "assistant"; text: string; tools?: PluginAssistantToolUse[]; at: string };
260
+
261
+ /** How a run is going: the assistant's text in a step, then each tool it uses and its answer. */
262
+ export type PluginAssistantEvent =
263
+ | { type: "text"; text: string }
264
+ | { type: "tool"; id: string; name: string; input: unknown }
265
+ | { type: "tool.result"; id: string; name: string; result: string; error?: true };
266
+
267
+ export interface PluginAssistant {
268
+ /**
269
+ * Says `text` to the assistant, with images for a model that reads them,
270
+ * and resolves with its last text once it is done. It uses the plugin's
271
+ * tools by their manifest names, at most 8 steps a run; each tool call is
272
+ * a change the person can undo, refused while the project's agent works.
273
+ * It starts only while the page shows, and one run goes at a time in a panel.
274
+ */
275
+ run(
276
+ request: { text: string; images?: Array<{ data: Blob | string; type?: string }>; system?: string; model?: { provider: string; id: string }; maxTokens?: number },
277
+ options?: { signal?: AbortSignal; onEvent?: (event: PluginAssistantEvent) => void },
278
+ ): Promise<{ text: string; model: { provider: string; id: string }; usage: { input: number; output: number }; steps: number; stopped?: "steps" | "length" }>;
279
+ /** The conversation so far, oldest first. */
280
+ history(): Promise<PluginAssistantEntry[]>;
281
+ /** Forgets the conversation, to start over. */
282
+ clear(): Promise<null>;
283
+ }
284
+
143
285
  export interface PluginUiHost {
144
286
  plugin: { id: string; version: string; panel: string };
145
287
  locale: "en" | "zh-CN";
146
288
  files: PluginFiles;
289
+ tools: PluginTools;
290
+ context: PluginContext;
291
+ models: PluginModels;
292
+ /**
293
+ * The panel's assistant, with `capabilities.models` (API 2.35.0): the
294
+ * person's model, run by the app in a loop with this plugin's own tools,
295
+ * its conversation kept for this panel in this project apart from the
296
+ * project's chats. The page draws it; each step counts toward the
297
+ * plugin's model limits. Only an installed plugin's panel has one.
298
+ */
299
+ assistant: PluginAssistant;
300
+ /**
301
+ * Imports a `.js` or `.mjs` module of the project, such as
302
+ * `pixelfx/effects/ricochet.js`, from a folder the manifest's
303
+ * `ui.projectModules` names (API 2.35.0). Once a `.js` or `.mjs` file of
304
+ * the project changes, the next import loads it, and what it imports, as
305
+ * they are now.
306
+ */
307
+ modules: { import<T = any>(path: string): Promise<T> };
308
+ /**
309
+ * The state this panel was opened with before the page loaded (API 2.35.0),
310
+ * such as where to go; undefined when it wasn't given one. Later openings
311
+ * come as the `open` event.
312
+ */
313
+ opened: unknown;
314
+ panels: {
315
+ /**
316
+ * Shows one of the plugin's own panels, this one included, while this
317
+ * page shows (API 2.35.0). With `state`, JSON of at most 16,000
318
+ * characters, its page hears it: as `opened` when it loads, or the `open`
319
+ * event when it already has.
320
+ */
321
+ open(panel: string, options?: { state?: unknown }): Promise<null>;
322
+ };
323
+ /**
324
+ * The person's Library, with `capabilities.library` (API 2.35.0), where a
325
+ * page puts what it makes instead of a download. Each file is listed as
326
+ * added by the plugin, and the person sees a toast as it comes.
327
+ */
328
+ library: {
329
+ /**
330
+ * Adds a PNG, JPEG or WebP image, sound, video or 3D model of at most
331
+ * 200 MB, named with its type, such as `ricochet.png`: a File keeps its
332
+ * own name unless given one. `prompt`, at most 1,000 characters, says
333
+ * what it was made from. Only while the page shows; a plugin adds at
334
+ * most 2 at once and 20 a minute.
335
+ */
336
+ add(file: Blob | File, options?: { name?: string; prompt?: string }): Promise<{ id: string; name: string; mediaType: "image" | "video" | "audio" | "model" }>;
337
+ };
147
338
  request(method: "ui.toast", params: PluginUiToast): Promise<null>;
148
339
  request(method: "ui.confirm", params: PluginUiConfirm): Promise<boolean>;
340
+ /** Opens an HTTP(S) address in a new Browser tab and reveals the panel. Desktop project pages only; visible pages may ask at most 5 times in 10 seconds. No page access is granted. */
341
+ request(method: "browser.open", params: { url: string }): Promise<null>;
149
342
  request(method: "composer.fill", params: PluginUiComposerFill): Promise<null>;
150
343
  /** The project's latest turns that changed files, newest first; `limit` is 1 to 100, 20 when left out. */
151
344
  request(method: "history.list", params?: { limit?: number }): Promise<{ turns: PluginHistoryTurn[] }>;
@@ -165,6 +358,8 @@ export interface PluginUiHost {
165
358
  on(event: "progress", listener: (value: { command: string; message: string }) => void): () => void;
166
359
  /** A command the person ran from the panel's toolbar finished; it has `error` if it failed. */
167
360
  on(event: "command", listener: (value: { command: string; result?: unknown; error?: string }) => void): () => void;
361
+ /** The panel was opened again with a state while the page was loaded, by a command, a page or the plugin's native code. */
362
+ on(event: "open", listener: (value: { state: unknown }) => void): () => void;
168
363
  }
169
364
 
170
365
  export function connect(): Promise<PluginUiHost>;
package/index.js CHANGED
@@ -15,6 +15,11 @@
15
15
  // one end of a MessageChannel once it loads; everything goes through it.
16
16
 
17
17
  const HANDSHAKE = "ohmygame-plugin-ui";
18
+ // How long a call to one of the page's tools waits for the page to handle it.
19
+ const TOOL_HANDLER_WAIT_MS = 10_000;
20
+ // What lets the page import its project's modules, as the app put it in the
21
+ // page's address; read as this file loads, before the page can change it.
22
+ const modulesToken = /^[A-Za-z0-9_-]{16,64}$/.exec(new URL(location.href).searchParams.get("modules") ?? "")?.[0];
18
23
 
19
24
  let connecting;
20
25
 
@@ -34,9 +39,69 @@ export function connect() {
34
39
  function bridge(port, hello) {
35
40
  let next = 0;
36
41
  const pending = new Map();
42
+ // A page's own part of its project modules' addresses: new for each load, and after each change of files.
43
+ const sessionRevision = Date.now().toString(36);
44
+ let moduleRevision = 0;
37
45
  const listeners = new Map();
38
46
  const emit = (name, value) => listeners.get(name)?.forEach((listener) => listener(value));
47
+ // Tools the page answers for its panel, as the manifest's `tools[].panel` names them.
48
+ const handlers = new Map();
49
+ const handlerWaits = new Map();
50
+ const toolCalls = new Map();
51
+ const answerTool = (toolCall, message) => {
52
+ try {
53
+ port.postMessage({ toolCall, ...message });
54
+ } catch (error) {
55
+ // A result that can't be copied, such as one holding a function or an
56
+ // element, is the tool's error; a closed port has nowhere to send either.
57
+ try {
58
+ port.postMessage({ toolCall, error: `The tool's answer can't be sent: ${String(error?.message ?? error).slice(0, 500)}. Return JSON.` });
59
+ } catch {
60
+ // Closed.
61
+ }
62
+ }
63
+ };
64
+ const handlerFor = (name) => {
65
+ const handler = handlers.get(name);
66
+ if (handler) return Promise.resolve(handler);
67
+ // A page may start handling its tools only once it has loaded what they need.
68
+ return new Promise((resolve) => {
69
+ const waiting = { resolve, timer: setTimeout(() => {
70
+ handlerWaits.get(name)?.delete(waiting);
71
+ resolve(undefined);
72
+ }, TOOL_HANDLER_WAIT_MS) };
73
+ if (!handlerWaits.has(name)) handlerWaits.set(name, new Set());
74
+ handlerWaits.get(name).add(waiting);
75
+ });
76
+ };
77
+ const runTool = async (toolCall, name, input) => {
78
+ const controller = new AbortController();
79
+ toolCalls.set(toolCall, controller);
80
+ try {
81
+ const handler = await handlerFor(name);
82
+ if (controller.signal.aborted) return;
83
+ if (!handler) {
84
+ answerTool(toolCall, { error: `This page doesn't handle the tool ${name}. Call host.tools.handle("${name}", …) when it loads.` });
85
+ return;
86
+ }
87
+ answerTool(toolCall, { accepted: true });
88
+ const progress = (message) => {
89
+ if (!controller.signal.aborted) answerTool(toolCall, { progress: String(message).slice(0, 2000) });
90
+ };
91
+ const result = await handler(input, { signal: controller.signal, progress });
92
+ if (!controller.signal.aborted) answerTool(toolCall, { result: result === undefined ? null : result });
93
+ } catch (error) {
94
+ if (!controller.signal.aborted) answerTool(toolCall, { error: String(error?.message ?? error).slice(0, 4000) || "The tool failed" });
95
+ } finally {
96
+ toolCalls.delete(toolCall);
97
+ }
98
+ };
39
99
  port.onmessage = ({ data }) => {
100
+ if (data && Number.isSafeInteger(data.toolCall)) {
101
+ if (data.cancel === true) toolCalls.get(data.toolCall)?.abort();
102
+ else if (typeof data.name === "string") void runTool(data.toolCall, data.name, data.input);
103
+ return;
104
+ }
40
105
  if (data && typeof data.event === "string") {
41
106
  // The app checks the page still answers; a page stuck in a loop can't, so it is offered a reload.
42
107
  if (data.event === "ping") {
@@ -44,6 +109,10 @@ function bridge(port, hello) {
44
109
  return;
45
110
  }
46
111
  if (data.event === "theme") applyTheme(data);
112
+ // When a module may have changed, the project's modules are imported again from here on;
113
+ // only then, as each import of a new address keeps another copy of them in the page.
114
+ if (data.event === "files" && (!Array.isArray(data.paths) || data.truncated || data.paths.some((path) => /\.m?js$/i.test(path))))
115
+ moduleRevision += 1;
47
116
  emit(data.event, data);
48
117
  return;
49
118
  }
@@ -71,6 +140,22 @@ function bridge(port, hello) {
71
140
  /** Which plugin and project the page is for. */
72
141
  plugin: hello.plugin,
73
142
  locale: hello.locale,
143
+ /** The state the panel was opened with before the page loaded; later ones come as the `open` event. */
144
+ opened: hello.opened ? hello.opened.state : undefined,
145
+ /** Shows one of the plugin's own panels; its page hears `state`. */
146
+ panels: {
147
+ open(panel, options = {}) {
148
+ return api.request("panel.open", { panel, ...(options.state !== undefined ? { state: options.state } : {}) });
149
+ },
150
+ },
151
+ /** The person's Library, with the `library` capability. */
152
+ library: {
153
+ /** Adds a file the page made, named with its type (`ricochet.png`); a File keeps its own name unless given one. */
154
+ add(file, options = {}) {
155
+ const name = options.name ?? file?.name;
156
+ return api.request("library.add", { data: file, name, ...(options.prompt ? { prompt: options.prompt } : {}) });
157
+ },
158
+ },
74
159
  /** Calls the app; rejects with the app's reason when it refuses. */
75
160
  request(method, params) {
76
161
  const id = next++;
@@ -79,6 +164,117 @@ function bridge(port, hello) {
79
164
  port.postMessage(params === undefined ? { id, method } : { id, method, params });
80
165
  });
81
166
  },
167
+ /**
168
+ * Answers the tools the manifest says this panel answers
169
+ * (`contributes.tools[].panel`), which the agent and commands call. The
170
+ * handler gets the input the tool's schema checked, and `{ signal,
171
+ * progress }`; what it returns, as JSON, is the tool's result. Returns a
172
+ * function that stops handling it.
173
+ */
174
+ tools: {
175
+ handle(name, handler) {
176
+ if (typeof handler !== "function") throw new TypeError("A tool's handler is a function");
177
+ handlers.set(name, handler);
178
+ for (const waiting of handlerWaits.get(name) ?? []) {
179
+ clearTimeout(waiting.timer);
180
+ waiting.resolve(handler);
181
+ }
182
+ handlerWaits.delete(name);
183
+ return () => {
184
+ if (handlers.get(name) === handler) handlers.delete(name);
185
+ };
186
+ },
187
+ },
188
+ /**
189
+ * What the person is looking at in this panel, for a plugin with the
190
+ * `composer` capability. The app shows it in the composer and the next
191
+ * message carries it, while the panel shows; `clear` takes it back.
192
+ */
193
+ context: {
194
+ set(value) {
195
+ return api.request("context.set", { label: value?.label, text: value?.text });
196
+ },
197
+ clear() {
198
+ return api.request("context.set", {});
199
+ },
200
+ },
201
+ /**
202
+ * The language models the person set up, for a plugin with the `models`
203
+ * capability. Each request runs on their providers and counts toward
204
+ * their usage, so ask only for what the person asked for, while the panel
205
+ * shows.
206
+ */
207
+ models: {
208
+ list() {
209
+ return api.request("models.list");
210
+ },
211
+ async complete(request, { signal } = {}) {
212
+ signal?.throwIfAborted();
213
+ const call = `call-${next}-${Math.random().toString(36).slice(2, 10)}`;
214
+ const stop = () => void api.request("models.cancel", { call }).catch(() => {});
215
+ signal?.addEventListener("abort", stop, { once: true });
216
+ try {
217
+ return await api.request("models.complete", { ...request, call });
218
+ } catch (error) {
219
+ // Stopped by the page, it fails as an abort does, not with the app's message.
220
+ if (signal?.aborted) throw signal.reason;
221
+ throw error;
222
+ } finally {
223
+ signal?.removeEventListener("abort", stop);
224
+ }
225
+ },
226
+ },
227
+ /**
228
+ * The panel's assistant, with the `models` capability: the person's
229
+ * model, run by the app with the plugin's own tools, its conversation
230
+ * kept for this panel in this project. The page draws it.
231
+ */
232
+ assistant: {
233
+ async run(request, { signal, onEvent } = {}) {
234
+ signal?.throwIfAborted();
235
+ const call = `assistant-${next}-${Math.random().toString(36).slice(2, 10)}`;
236
+ const stop = () => void api.request("models.cancel", { call }).catch(() => {});
237
+ const heard = (data) => {
238
+ if (data.call !== call || !onEvent) return;
239
+ const { event: _event, call: _call, ...event } = data;
240
+ onEvent(event);
241
+ };
242
+ if (!listeners.has("assistant")) listeners.set("assistant", new Set());
243
+ listeners.get("assistant").add(heard);
244
+ signal?.addEventListener("abort", stop, { once: true });
245
+ try {
246
+ return await api.request("assistant.run", { ...request, call });
247
+ } catch (error) {
248
+ // Stopped by the page, it fails as an abort does, not with the app's message.
249
+ if (signal?.aborted) throw signal.reason;
250
+ throw error;
251
+ } finally {
252
+ signal?.removeEventListener("abort", stop);
253
+ listeners.get("assistant")?.delete(heard);
254
+ }
255
+ },
256
+ history() {
257
+ return api.request("assistant.history");
258
+ },
259
+ clear() {
260
+ return api.request("assistant.clear");
261
+ },
262
+ },
263
+ /**
264
+ * Imports a module of the project from a folder the manifest's
265
+ * `ui.projectModules` names, such as `pixelfx/effects/ricochet.js`.
266
+ * After a module of the project changes, the next import loads it, and
267
+ * what it imports, as they are now.
268
+ */
269
+ modules: {
270
+ import(path) {
271
+ if (!modulesToken) return Promise.reject(new Error("This page imports no project modules; list their folders in ui.projectModules"));
272
+ if (typeof path !== "string" || !/^[^/\\.][^\\]*\.m?js$/i.test(path) || path.split("/").some((part) => !part || part.startsWith(".")))
273
+ return Promise.reject(new TypeError("A module is a .js or .mjs path in the project, such as fx/burst.js"));
274
+ const base = `/_modules/${modulesToken}/${sessionRevision}-${moduleRevision}/`;
275
+ return import(new URL(base + path.split("/").map(encodeURIComponent).join("/"), location.href).href);
276
+ },
277
+ },
82
278
  /** `theme`, `visibility`, `progress`, `command` and `files` events; returns a function that stops listening. */
83
279
  on(name, listener) {
84
280
  if (!listeners.has(name)) listeners.set(name, new Set());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ohmygame/plugin-ui",
3
- "version": "2.4.0",
3
+ "version": "2.35.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
package/plugin-ui.css CHANGED
@@ -108,8 +108,13 @@
108
108
  --shadow-float: 0 8px 28px rgb(0 0 0 / 9%), 0 0 0 1px rgb(0 0 0 / 7%);
109
109
  color-scheme: light;
110
110
  }
111
+ /* Keep page width stable when tabs or disclosures change its scroll height. */
112
+ html { scrollbar-gutter: stable; }
111
113
  * { box-sizing: border-box; }
112
114
  body { margin: 0; padding: var(--space-4); }
115
+ @media (min-width: 720px) {
116
+ body { padding: var(--space-6); }
117
+ }
113
118
  :focus-visible { outline: 2px solid var(--color-focus); outline-offset: 2px; }
114
119
 
115
120
  .omg-row { display: flex; align-items: center; gap: var(--space-2); min-height: 32px; }
package/ui/1/base.js CHANGED
@@ -105,3 +105,20 @@ export function filled(slot) {
105
105
  export function define(name, component) {
106
106
  if (!customElements.get(name)) customElements.define(name, component);
107
107
  }
108
+
109
+ // Follow focus across the components' open shadow roots.
110
+ export function activeElement(root = document) {
111
+ let active = root.activeElement;
112
+ while (active?.shadowRoot?.activeElement)
113
+ active = active.shadowRoot.activeElement;
114
+ return active;
115
+ }
116
+
117
+ export function containsFocus(host) {
118
+ let node = activeElement(host.ownerDocument);
119
+ while (node) {
120
+ if (node === host) return true;
121
+ node = node.parentNode || node.host;
122
+ }
123
+ return false;
124
+ }
package/ui/1/controls.js CHANGED
@@ -1,5 +1,4 @@
1
- // Controls: buttons, a button bound to one of the plugin's commands, and a
2
- // select.
1
+ // Controls: buttons, command buttons, and collapsible content.
3
2
  import { connect } from "../../plugin-ui.js";
4
3
  import { OmgElement, css, define, text } from "./base.js";
5
4
 
@@ -96,6 +95,89 @@ class OmgButton extends OmgElement {
96
95
  }
97
96
  }
98
97
 
98
+ /**
99
+ * `<omg-disclosure heading open disabled>`: a plain title row with a leading
100
+ * arrow that shows or hides content. Closing keeps the content mounted and
101
+ * returns focus to the button when focus was inside. Enter and Space use the
102
+ * button's native activation.
103
+ *
104
+ * @attr {string} heading - The button's label.
105
+ * @attr {boolean} open - Shows the content; closed by default.
106
+ * @attr {boolean} disabled - Disables the button, without changing the content's state.
107
+ * @prop {boolean} open - The `open` attribute; setting it does not emit an event.
108
+ * @prop {boolean} disabled - The `disabled` attribute.
109
+ * @fires {{ open: boolean }} omg-toggle - The person opened or closed the content; bubbles across shadow roots.
110
+ * @slot - The content, retained while closed.
111
+ * @part button - The toggle button.
112
+ * @part heading - The button's label.
113
+ * @part icon - The expansion arrow.
114
+ * @part body - The content, hidden while closed.
115
+ */
116
+ class OmgDisclosure extends OmgElement {
117
+ static observedAttributes = ["heading", "open", "disabled"];
118
+ static delegatesFocus = true;
119
+ static styles = [
120
+ css(`
121
+ :host { display: block; min-width: 0; }
122
+ button {
123
+ display: grid; grid-template-columns: var(--space-2) minmax(0, 1fr); align-items: center; gap: var(--space-2); width: 100%; min-height: 30px;
124
+ padding: var(--space-1) 0; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--color-text);
125
+ font: inherit; font-weight: var(--weight-medium); text-align: start; cursor: pointer;
126
+ transition: background var(--duration-fast);
127
+ }
128
+ button:not(:disabled):hover { background: color-mix(in srgb, var(--color-hover) 60%, transparent); }
129
+ button:disabled { opacity: 0.4; cursor: default; }
130
+ .heading { min-width: 0; overflow-wrap: anywhere; }
131
+ /* Centre the SVG's visible strokes in an 8px track, matching the status dot. */
132
+ .icon { width: 14px; height: 14px; justify-self: center; color: var(--color-text-secondary); transform: rotate(-90deg); transition: transform var(--duration-fast); }
133
+ :host([open]) .icon { transform: rotate(0deg); }
134
+ .body { display: flex; flex-direction: column; gap: var(--space-4); min-width: 0; padding-top: var(--space-2); padding-inline-start: var(--space-4); }
135
+ `),
136
+ ];
137
+ static template = `
138
+ <button part="button" type="button" aria-expanded="false" aria-controls="body">
139
+ <svg class="icon" part="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m4 6 4 4 4-4" /></svg>
140
+ <span class="heading" part="heading"></span>
141
+ </button>
142
+ <div id="body" class="body" part="body" hidden><slot></slot></div>`;
143
+
144
+ constructor() {
145
+ super();
146
+ this.part("button").addEventListener("click", () => {
147
+ if (this.disabled) return;
148
+ this.open = !this.open;
149
+ this.dispatchEvent(new CustomEvent("omg-toggle", { bubbles: true, composed: true, detail: { open: this.open } }));
150
+ });
151
+ }
152
+
153
+ get open() {
154
+ return this.hasAttribute("open");
155
+ }
156
+
157
+ set open(value) {
158
+ this.toggleAttribute("open", Boolean(value));
159
+ }
160
+
161
+ get disabled() {
162
+ return this.hasAttribute("disabled");
163
+ }
164
+
165
+ set disabled(value) {
166
+ this.toggleAttribute("disabled", Boolean(value));
167
+ }
168
+
169
+ update() {
170
+ const button = this.part("button");
171
+ const body = this.part("body");
172
+ const active = this.getRootNode().activeElement;
173
+ if (!this.open && !body.hidden && active !== this && this.contains(active)) button.focus();
174
+ text(this.part("heading"), this.getAttribute("heading"));
175
+ button.disabled = this.disabled;
176
+ button.setAttribute("aria-expanded", String(this.open));
177
+ body.hidden = !this.open;
178
+ }
179
+ }
180
+
99
181
  /** Commands running now from command buttons that wait for one another. */
100
182
  const running = new Set();
101
183
  const changes = new EventTarget();
@@ -228,4 +310,5 @@ class OmgCommandButton extends OmgButton {
228
310
  }
229
311
 
230
312
  define("omg-button", OmgButton);
313
+ define("omg-disclosure", OmgDisclosure);
231
314
  define("omg-command-button", OmgCommandButton);