@hackbuild/ai-views 0.1.2 → 0.1.6

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  Put a model picker, a chat, a transcriber, a mask studio or a camera frame on your page, drawn with the hackbuild-ui stylesheet, as custom elements or Vue components.
4
4
 
5
- [![npm](https://img.shields.io/npm/v/@hackbuild/ai-views)](https://www.npmjs.com/package/@hackbuild/ai-views) [![licence MIT](https://img.shields.io/badge/licence-MIT-blue)](../../LICENSE) ![gzip 16.9 kB measured](https://img.shields.io/badge/gzip-16.9%20kB-blue) ![types included](https://img.shields.io/badge/types-included-blue)
5
+ [![npm](https://img.shields.io/npm/v/@hackbuild/ai-views)](https://www.npmjs.com/package/@hackbuild/ai-views) [![licence MIT](https://img.shields.io/badge/licence-MIT-blue)](../../LICENSE) ![gzip 21.5 kB measured](https://img.shields.io/badge/gzip-21.5%20kB-blue) ![types included](https://img.shields.io/badge/types-included-blue)
6
6
 
7
7
  Browser status: no model run of this package has been verified in a real browser yet.
8
8
 
@@ -254,8 +254,8 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
254
254
 
255
255
  | file | gzip (measured) | ceiling |
256
256
  |---|---|---|
257
- | `dist/index.js` (main entry, imports external) | 16,915 bytes | 17,760 bytes |
258
- | `dist/single/elements.iife.js` (single file build) | 86,306 bytes | 90,621 bytes |
257
+ | `dist/index.js` (main entry, imports external) | 21,494 bytes | 22,568 bytes |
258
+ | `dist/single/elements.iife.js` (single file build) | 100,092 bytes | 105,096 bytes |
259
259
 
260
260
  Measured 2026-11-25 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
261
261
  tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
package/dist/chat.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * with its reasoning kept apart for the think fold, the memory each reply
5
5
  * used, stop, regenerate, and a markdown export. Framework free.
6
6
  */
7
- import type { ChatEngine } from "@hackbuild/chat";
7
+ import type { ChatEngine, StreamOptions } from "@hackbuild/chat";
8
8
  /** A memory recalled for a reply, with its label and score. */
9
9
  export interface MemoryUsed {
10
10
  label: string;
@@ -40,7 +40,19 @@ export interface ThreadSnapshot {
40
40
  */
41
41
  export interface ThreadOptions {
42
42
  engine?: ChatEngine | null;
43
- system?: string;
43
+ /** The system prompt, or a function read at each reply (a persona that changes). */
44
+ system?: string | (() => string);
45
+ /**
46
+ * Builds the system prompt from the persona and the memory recalled for this reply, in place
47
+ * of the default join; a page fits both to a budget here (priority trimmed sections).
48
+ */
49
+ systemFor?: (mem: MemoryUsed[]) => string;
50
+ /** Sampling, schema and other reply options, read at each reply. */
51
+ stream?: () => Omit<StreamOptions, "signal">;
52
+ /** How many earlier turns go with each request; all when unset. */
53
+ history?: () => number;
54
+ /** Called when a reply ends with text, with the user's message: speak it, save a note. */
55
+ onReply?: (turn: Turn, said: string) => void;
44
56
  /** Memory for a message; its hits ride along in the system prompt and show under the reply. */
45
57
  recall?: (query: string) => Promise<MemoryUsed[]>;
46
58
  /** What a reply says with no engine. */
@@ -62,6 +74,8 @@ export interface ChatThread {
62
74
  setEngine(engine: ChatEngine | null): void;
63
75
  /** The thread as markdown, for an export. */
64
76
  markdown(title?: string): string;
77
+ /** Replace the turns (a restored or imported chat). */
78
+ load(turns: readonly Turn[]): void;
65
79
  }
66
80
  /** What a reply says when no chat engine is set. */
67
81
  export declare const NO_ENGINE = "this needs a model. pick one in the bar and load it.";
@@ -93,6 +107,25 @@ export interface ChatList {
93
107
  rename(id: string, title: string): void;
94
108
  remove(id: string): void;
95
109
  setEngine(engine: ChatEngine | null): void;
110
+ /** Every chat as plain data, for storage or an export. */
111
+ dump(): ChatListData;
112
+ /** Adds chats from `dump()` data (an import or a reload); `replace` drops the current ones first. */
113
+ restore(data: ChatListData, o?: {
114
+ replace?: boolean;
115
+ }): void;
116
+ }
117
+ /** A chat list as plain data: format, version, the open chat and each chat's title and turns. */
118
+ export interface ChatListData {
119
+ format: "hackbuild-chats";
120
+ version: 1;
121
+ current?: string;
122
+ chats: {
123
+ id: string;
124
+ title: string;
125
+ updated: number;
126
+ named?: boolean;
127
+ turns: Turn[];
128
+ }[];
96
129
  }
97
130
  /**
98
131
  * Creates a list of chat threads, newest first, with one open; its `thread` always speaks for the
package/dist/chat.js CHANGED
@@ -46,20 +46,27 @@ export function chatThread(o = {}) {
46
46
  mem = await o.recall(lastUser.text);
47
47
  if (mem.length)
48
48
  patch(live.id, { mem });
49
- const sys = [o.system, mem.length ? `things you remember:\n${mem.map((m) => `- ${m.label}`).join("\n")}` : ""].filter(Boolean).join("\n\n");
49
+ const base = typeof o.system === "function" ? o.system() : o.system;
50
+ const sys = o.systemFor ? o.systemFor(mem) : [base, mem.length ? `things you remember:\n${mem.map((m) => `- ${m.label}`).join("\n")}` : ""].filter(Boolean).join("\n\n");
51
+ const past = turns.filter((t) => t.id !== live.id && t.text);
52
+ const keep = o.history?.();
53
+ const sent = keep !== undefined && keep >= 0 ? past.slice(Math.max(0, past.length - 1 - keep)) : past;
50
54
  const history = [
51
55
  ...(sys ? [{ role: "system", content: sys }] : []),
52
- ...turns.filter((t) => t.id !== live.id && t.text).map((t) => ({ role: t.role, content: t.text })),
56
+ ...sent.map((t) => ({ role: t.role, content: t.text })),
53
57
  ];
54
58
  let text = "";
55
59
  let think = "";
56
- const it = engine.stream(history, { signal, ...(o.maxTokens ? { maxTokens: o.maxTokens } : {}) });
60
+ const it = engine.stream(history, { ...(o.maxTokens ? { maxTokens: o.maxTokens } : {}), ...o.stream?.(), signal });
57
61
  for (;;) {
58
62
  const step = await it.next();
59
63
  if (step.done) {
60
64
  const s = step.value?.stats;
61
65
  const stats = s ? statsText({ tokPerSec: s.tokensPerSecond, firstMs: s.firstTokenMs, tokens: s.tokens, source: s.tokensSource }) : "";
62
66
  patch(live.id, { done: true, ...(stats ? { stats } : {}) });
67
+ const fin = turns.find((t) => t.id === live.id);
68
+ if (fin?.text)
69
+ o.onReply?.(fin, lastUser?.text ?? "");
63
70
  break;
64
71
  }
65
72
  const ev = step.value;
@@ -122,6 +129,11 @@ export function chatThread(o = {}) {
122
129
  engine = e;
123
130
  emit();
124
131
  },
132
+ load(next) {
133
+ ac?.abort();
134
+ turns = next.map((t) => ({ ...t, id: ++seq, done: true }));
135
+ emit();
136
+ },
125
137
  markdown(title = "chat") {
126
138
  const lines = [`# ${title}`, ""];
127
139
  for (const t of turns)
@@ -181,6 +193,7 @@ export function chatList(o = {}) {
181
193
  clear: () => chats.get(current).t.clear(),
182
194
  setEngine: (e) => list.setEngine(e),
183
195
  markdown: (title) => chats.get(current).t.markdown(title ?? chats.get(current).title),
196
+ load: (t) => chats.get(current).t.load(t),
184
197
  },
185
198
  snapshot: snap,
186
199
  subscribe(fn) {
@@ -227,6 +240,37 @@ export function chatList(o = {}) {
227
240
  for (const c of chats.values())
228
241
  c.t.setEngine(e);
229
242
  },
243
+ dump() {
244
+ return {
245
+ format: "hackbuild-chats",
246
+ version: 1,
247
+ current,
248
+ chats: [...chats].map(([id, c]) => ({ id, title: c.title, updated: c.updated, named: c.named, turns: c.t.snapshot().turns.filter((t) => t.done).map((t) => ({ ...t })) })),
249
+ };
250
+ },
251
+ restore(data, ro = {}) {
252
+ if (data?.format !== "hackbuild-chats" || data.version !== 1 || !Array.isArray(data.chats))
253
+ throw new Error("not a hackbuild-chats version 1 file.");
254
+ const empty = [...chats.values()].every((c) => !c.t.snapshot().turns.length);
255
+ if (ro.replace || empty) {
256
+ for (const c of chats.values())
257
+ c.t.stop();
258
+ chats.clear();
259
+ }
260
+ let open = "";
261
+ for (const c of data.chats) {
262
+ const id = `chat-${++seq}`;
263
+ const t = chatThread({ ...o, engine });
264
+ t.load((c.turns ?? []).filter((x) => (x.role === "user" || x.role === "assistant") && typeof x.text === "string").map((x) => ({ ...x, think: x.think ?? "" })));
265
+ chats.set(id, { t, title: String(c.title || "chat"), updated: +c.updated || now(), named: !!c.named });
266
+ if (c.id === data.current)
267
+ open = id;
268
+ }
269
+ if (!chats.size)
270
+ return void list.create();
271
+ current = open || (chats.has(current) ? current : snap().items[0].id);
272
+ follow();
273
+ },
230
274
  };
231
275
  list.create();
232
276
  return list;
@@ -16,8 +16,10 @@ import type { ModelRecord } from "@hackbuild/models";
16
16
  import { type Loader, type ModelPick } from "./pick.js";
17
17
  export { mountModelSelect, mountModelJobs, pickSheet, gateWords, chipWords, shortName, type ModelSelectOptions } from "./mount-model.js";
18
18
  export { mountChatPane, mountComposer, mountChatList, mountContextMeter, turnHtml, type ChatPaneOptions, type ComposerOptions } from "./mount-chat.js";
19
+ export { mountExportMenu, isMedia, droppedFiles } from "./mount-transcribe.js";
20
+ export { mountMemoryPane, mountSourcesDrop, mountPersonaRack, mountVoiceRow, mountVoiceClone, mountSessionMenu, protect, isProtected, type MemoryLike, type MemoryPaneHandle, type MemoryPaneOptions, type SourcesDropOptions } from "./mount-talk.js";
19
21
  export { mountTranscribeDrop, mountTranscriptView, mountTranscribeQueue, mountTranscriptExports, transcriptHtml, type TranscribeDropOptions, type TranscribeDropHandle, type TranscriptViewOptions } from "./mount-transcribe.js";
20
- export { mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMaskRack, type MaskStudio, type MaskModels, type MaskStudioOptions, type FoundMask, type StudioState, type StudioTool } from "./mount-mask.js";
22
+ export { mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMaskRack, type MaskStudio, type MaskModels, type MaskStudioOptions, type FoundMask, type MaskEverythingOptions, type StudioState, type StudioTool, type StudioView } from "./mount-mask.js";
21
23
  export { mountFrameView, mountCameraFeed, type FrameView, type FrameViewOptions, type CameraFeed, type CameraFeedOptions } from "./mount-frame.js";
22
24
  export { mountMemoryInspector, type MemoryInspector } from "./memory.js";
23
25
  type Base = new () => HTMLElement;
package/dist/elements.js CHANGED
@@ -23,6 +23,8 @@ import { transcribeQueue } from "./transcribe.js";
23
23
  import { mountMemoryInspector } from "./memory.js";
24
24
  export { mountModelSelect, mountModelJobs, pickSheet, gateWords, chipWords, shortName } from "./mount-model.js";
25
25
  export { mountChatPane, mountComposer, mountChatList, mountContextMeter, turnHtml } from "./mount-chat.js";
26
+ export { mountExportMenu, isMedia, droppedFiles } from "./mount-transcribe.js";
27
+ export { mountMemoryPane, mountSourcesDrop, mountPersonaRack, mountVoiceRow, mountVoiceClone, mountSessionMenu, protect, isProtected } from "./mount-talk.js";
26
28
  export { mountTranscribeDrop, mountTranscriptView, mountTranscribeQueue, mountTranscriptExports, transcriptHtml } from "./mount-transcribe.js";
27
29
  export { mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMaskRack } from "./mount-mask.js";
28
30
  export { mountFrameView, mountCameraFeed } from "./mount-frame.js";
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export { JOBS, JOB_NAMES, ALL_RECORDS, FACE_API_BASE, jobRecords, isJob, type Job, type JobDef } from "./jobs.js";
2
2
  export { rowOf, groupOf, backendOf, sizeWords, detailOf, optionsOf, isNoDownload, isUncensored, type RowContext } from "./rows.js";
3
- export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, defaultPick, ownRecord, type ModelPick, type PickOptions, type PickSnapshot, type Loader, type LoadContext, type JobsPick, type JobLine, type PickPreset, } from "./pick.js";
4
- export { chatThread, chatList, contextSegments, NO_ENGINE, type ChatList, type ChatListItem, type ChatListSnapshot, type ChatThread, type ThreadOptions, type ThreadSnapshot, type Turn, type MemoryUsed } from "./chat.js";
5
- export { transcribeQueue, type TranscribeQueue, type Transcriber, type RunResult, type RunContext, type Channel, type ExportKind, type QueueSnapshot } from "./transcribe.js";
3
+ export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, storedIds, verifyRepo, type RepoCheck, defaultPick, ownRecord, type ModelPick, type PickOptions, type PickSnapshot, type Loader, type LoadContext, type JobsPick, type JobLine, type PickPreset, } from "./pick.js";
4
+ export { chatThread, chatList, contextSegments, NO_ENGINE, type ChatList, type ChatListData, type ChatListItem, type ChatListSnapshot, type ChatThread, type ThreadOptions, type ThreadSnapshot, type Turn, type MemoryUsed } from "./chat.js";
5
+ export { transcribeQueue, type TranscribeQueue, type Transcriber, type RunResult, type RunContext, type TranscribeRunOptions, type Channel, type ExportKind, type QueueSnapshot } from "./transcribe.js";
6
6
  export { fitMap, toView, boxWords, frameTag, labelColour, type FrameBox, type FrameLandmarks, type FrameResults } from "./frame.js";
7
7
  export { traceRows, inspectorHtml, type TraceRow, type RecallLike } from "./memory.js";
8
8
  export { jobLoader, asImage, RUNTIME_URLS, type JobLoaderOptions, type JobValues, type RuntimeModules, type DetectFn, type DepthFn, type AskFn, type ImageJob } from "./loaders.js";
9
+ export { speaker, canClone, type Speaker, type SpeakerOptions, type SpokenLine } from "./speaker.js";
10
+ export { personaRack, voiceRow, type Persona, type PersonaPresetX, type PersonaRack, type VoiceRow } from "./talk.js";
package/dist/index.js CHANGED
@@ -3,9 +3,11 @@
3
3
  // "@hackbuild/ai-views/elements"; the Vue components in "@hackbuild/ai-views/vue".
4
4
  export { JOBS, JOB_NAMES, ALL_RECORDS, FACE_API_BASE, jobRecords, isJob } from "./jobs.js";
5
5
  export { rowOf, groupOf, backendOf, sizeWords, detailOf, optionsOf, isNoDownload, isUncensored } from "./rows.js";
6
- export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, defaultPick, ownRecord, } from "./pick.js";
6
+ export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, storedIds, verifyRepo, defaultPick, ownRecord, } from "./pick.js";
7
7
  export { chatThread, chatList, contextSegments, NO_ENGINE } from "./chat.js";
8
8
  export { transcribeQueue } from "./transcribe.js";
9
9
  export { fitMap, toView, boxWords, frameTag, labelColour } from "./frame.js";
10
10
  export { traceRows, inspectorHtml } from "./memory.js";
11
11
  export { jobLoader, asImage, RUNTIME_URLS } from "./loaders.js";
12
+ export { speaker, canClone } from "./speaker.js";
13
+ export { personaRack, voiceRow } from "./talk.js";
package/dist/loaders.js CHANGED
@@ -144,17 +144,33 @@ export function asImage(img) {
144
144
  c.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(p.data), p.width, p.height), 0, 0);
145
145
  return c;
146
146
  }
147
- /** A file as 16 kHz mono samples, decoded by the browser. */
147
+ /** A file as 16 kHz samples per channel (at most two), decoded by the browser. */
148
148
  async function pcm16k(file) {
149
149
  const bytes = await file.arrayBuffer();
150
150
  const probeCtx = new OfflineAudioContext(1, 1, 16000);
151
151
  const buf = await probeCtx.decodeAudioData(bytes);
152
- const off = new OfflineAudioContext(1, Math.max(1, Math.ceil(buf.duration * 16000)), 16000);
152
+ const ch = Math.min(2, buf.numberOfChannels);
153
+ const off = new OfflineAudioContext(ch, Math.max(1, Math.ceil(buf.duration * 16000)), 16000);
153
154
  const src = off.createBufferSource();
154
155
  src.buffer = buf;
155
156
  src.connect(off.destination);
156
157
  src.start();
157
- return (await off.startRendering()).getChannelData(0);
158
+ const out = await off.startRendering();
159
+ return Array.from({ length: ch }, (_, i) => out.getChannelData(i));
160
+ }
161
+ /** A level rail folded to at most `bins` bins: loudest frame and whether the gate kept most of it. */
162
+ function railOf(rail, bins = 400) {
163
+ const n = Math.max(1, Math.min(bins, rail.db.length));
164
+ const db = new Array(n).fill(-90);
165
+ const kept = new Array(n).fill(0);
166
+ const count = new Array(n).fill(0);
167
+ for (let i = 0; i < rail.db.length; i++) {
168
+ const b = Math.min(n - 1, Math.floor((i * n) / rail.db.length));
169
+ db[b] = Math.max(db[b], rail.db[i]);
170
+ kept[b] += rail.open[i];
171
+ count[b]++;
172
+ }
173
+ return { db: db.map((x) => Math.round(x * 10) / 10), kept: kept.map((k, b) => (count[b] && k / count[b] >= 0.5 ? 1 : 0)) };
158
174
  }
159
175
  async function dspOf(rt) {
160
176
  rt.dsp ??= rt.modules.dsp
@@ -185,15 +201,17 @@ async function adapt(job, rec, value, rt, ctx) {
185
201
  case "transcribe": {
186
202
  const t = await import("@hackbuild/transcribe");
187
203
  const run = async (file, c) => {
188
- const [dsp, pcm] = await Promise.all([dspOf(rt), pcm16k(file)]);
189
- const lang = ctx.options.language;
190
- const out = await t.transcribe(hub, dsp, pcm, {
204
+ const [dsp, chans] = await Promise.all([dspOf(rt), pcm16k(file)]);
205
+ const { channel, ...run } = c.options ?? {};
206
+ const lang = run.language ?? ctx.options.language;
207
+ const out = await t.transcribe(hub, dsp, t.toMono(chans, channel ?? "auto"), {
208
+ ...run,
191
209
  model: rec.id,
192
210
  signal: c.signal,
193
211
  ...(lang ? { language: lang } : {}),
194
212
  onProgress: (p) => c.onProgress(p.total ? p.done / p.total : 0),
195
213
  });
196
- return { segments: out.segments, dropped: out.dropped, duration: out.stats.dur, language: out.language, model: rec.label ?? rec.id };
214
+ return { segments: out.segments, dropped: out.dropped, duration: out.stats.dur, language: out.language, model: rec.label ?? rec.id, stats: out.stats, rail: railOf(out.rail) };
197
215
  };
198
216
  return run;
199
217
  }
@@ -218,6 +236,21 @@ async function adapt(job, rec, value, rt, ctx) {
218
236
  const keys = new WeakMap();
219
237
  const keyOf = (img) => keys.get(img) ?? (keys.set(img, `img-${++key}`), `img-${key}`);
220
238
  const first = async (image, x, y) => (await v.segment(hub, asImage(image), { points: [{ x, y, label: 1 }] }, { model: rec.id, key: keyOf(image) }))[0];
239
+ if (rec.provides?.includes("segment.everything")) {
240
+ // FastSAM: one pass finds every object; a press picks the one under it from that pass
241
+ let last = null;
242
+ const all = async (image, o = {}) => {
243
+ const key = JSON.stringify(o);
244
+ if (last?.img !== image || last.key !== key)
245
+ last = { img: image, key, list: await v.segmentEverything(hub, asImage(image), { ...o, model: rec.id }) };
246
+ return last.list;
247
+ };
248
+ const fast = {
249
+ segment: async (image, p) => v.instanceAt(await all(image), p.x, p.y)?.mask.data ?? null,
250
+ everything: async (image, o) => (await all(image, o)).map((i, k) => ({ mask: i.mask.data, label: i.label ?? `object ${k + 1}`, score: i.score, box: i.box })),
251
+ };
252
+ return fast;
253
+ }
221
254
  const models = {
222
255
  segment: async (image, p) => (await first(image, p.x, p.y))?.data ?? null,
223
256
  everything: async (image) => {
@@ -6,7 +6,11 @@
6
6
  * export the mask, a matte or the cutout. With a segment everything model
7
7
  * (FastSAM) one press finds every object; each lands in the found list and
8
8
  * a press adds it to the mask. Models are functions the page passes, so
9
- * stubs run the studio with no weights.
9
+ * stubs run the studio with no weights. Three views (composite, mask,
10
+ * found objects) paint over the canvas; the pointer previews the click cut
11
+ * or lights the found object under it; two fingers or ctrl and the wheel
12
+ * zoom; a page that loads models on demand hears `onWant` when a tool needs
13
+ * one.
10
14
  */
11
15
  import { type MaskMode, type MaskOutput, type MaskPixels, type MaskTool } from "@virgilvox/hackbuild-ui/vanilla";
12
16
  import { type Mounted } from "./dom.js";
@@ -15,6 +19,22 @@ export interface FoundMask {
15
19
  mask: Uint8Array;
16
20
  label: string;
17
21
  score: number;
22
+ /** The box in image pixels, drawn in the found view when present. */
23
+ box?: {
24
+ x: number;
25
+ y: number;
26
+ w: number;
27
+ h: number;
28
+ };
29
+ }
30
+ /** What the canvas shows: the picture with the mask, the mask alone, or every found object in its colour. */
31
+ export type StudioView = "composite" | "mask" | "instances";
32
+ /** Decode settings for a segment everything model (FastSAM): confidence, overlap, smallest area, sigmoid. */
33
+ export interface MaskEverythingOptions {
34
+ confidence?: number;
35
+ iou?: number;
36
+ minArea?: number;
37
+ sigmoid?: boolean;
18
38
  }
19
39
  /** The segment models a mask studio calls: a click segment for one point and a segment everything. */
20
40
  export interface MaskModels {
@@ -23,8 +43,8 @@ export interface MaskModels {
23
43
  x: number;
24
44
  y: number;
25
45
  }) => Promise<Uint8Array | null>;
26
- /** Segment everything: every object at once. */
27
- everything?: (image: MaskPixels) => Promise<FoundMask[]>;
46
+ /** Segment everything: every object at once, with the decode settings when the model takes them. */
47
+ everything?: (image: MaskPixels, o?: MaskEverythingOptions) => Promise<FoundMask[]>;
28
48
  }
29
49
  /** A mask studio tool: the click segment point or one of the hackbuild-ui mask tools. */
30
50
  export type StudioTool = "point" | MaskTool;
@@ -43,9 +63,15 @@ export interface StudioState {
43
63
  coverage: number;
44
64
  zoom: number;
45
65
  busy: string;
66
+ /** The magic wand takes only touching pixels when true. */
67
+ contiguous: boolean;
68
+ view: StudioView;
69
+ /** The found object under the pointer, or -1. */
70
+ hover: number;
46
71
  found: (FoundMask & {
47
72
  on: boolean;
48
73
  colour: string;
74
+ hidden: boolean;
49
75
  })[];
50
76
  /** Masks put aside with a name and a small preview, newest first. */
51
77
  saved: {
@@ -84,15 +110,34 @@ export interface MaskStudio extends Mounted {
84
110
  /** The current mask as ImageData (alpha by default), null before an image. */
85
111
  mask(kind?: MaskOutput): ImageData | null;
86
112
  zoom(dir: 1 | -1 | 0): void;
87
- everything(): Promise<void>;
113
+ /** Set the zoom directly, 0.25 to 6, as a pinch does. */
114
+ zoomTo(z: number): void;
115
+ setView(v: StudioView): void;
116
+ setContiguous(on: boolean): void;
117
+ /** Replace the mask (0 or 255 per image pixel) as one undo step, as the no model modes do. */
118
+ setMask(mask: ArrayLike<number>): void;
119
+ /** Add objects to the found list (a model the page ran itself, or colour clusters). */
120
+ addFound(list: FoundMask[]): void;
121
+ /** Show or hide one found object in the found view. */
122
+ showFound(index: number, on: boolean): void;
123
+ removeFound(index: number): void;
124
+ /** Put every shown found object into the mask, one undo step. */
125
+ mergeFound(): void;
126
+ clearFound(): void;
127
+ /** The picture's pixels, null before an image. */
128
+ pixels(): MaskPixels | null;
129
+ /** Find every object with the segment everything model; asks for it through `onWant` when missing. */
130
+ everything(o?: MaskEverythingOptions): Promise<void>;
88
131
  /** The click segment model at a point in image pixels, as a press with the point tool. */
89
132
  cutAt(x: number, y: number, mode?: MaskMode): Promise<void>;
90
133
  /** Add or take out one found object. */
91
134
  toggleFound(index: number): void;
92
- /** The mask, matte or cutout as a png Blob. */
93
- exportAs(kind: MaskOutput): Promise<Blob | null>;
135
+ /** The mask, matte, cutout or inverse matte as a png Blob. */
136
+ exportAs(kind: MaskOutput | "inverse"): Promise<Blob | null>;
94
137
  hasEverything: boolean;
95
138
  hasSegment: boolean;
139
+ /** The page loads models on demand (`onWant`), so the model tools show before their models. */
140
+ canWant: boolean;
96
141
  state(): StudioState;
97
142
  subscribe(fn: (s: StudioState) => void): () => void;
98
143
  setModels(m: MaskModels): void;
@@ -111,6 +156,11 @@ export interface MaskStudioOptions {
111
156
  onSample?: () => void;
112
157
  /** Name of exported files, without extension. */
113
158
  name?: string;
159
+ /**
160
+ * A tool needs a model the studio does not have yet: the page loads it and calls setModels.
161
+ * With this set, the point tool shows before its model loads.
162
+ */
163
+ onWant?: (kind: "segment" | "everything") => void;
114
164
  }
115
165
  /**
116
166
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush