@hackbuild/ai-views 0.0.0-stage → 0.1.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.
@@ -0,0 +1,177 @@
1
+ /**
2
+ * ChatPane and Composer in the DOM, after the earlier chat tools: the
3
+ * thread as hackbuild-ui messages, the reasoning in a fold that is open
4
+ * while it streams, the memory a reply used in a fold under it, copy and
5
+ * redo on the last reply only, and a composer whose send is the one pink
6
+ * action and turns into stop while a reply streams.
7
+ */
8
+ import { composerKey, coarsePointer, autosize, pinned, contextUse, listMeta } from "@virgilvox/hackbuild-ui/vanilla";
9
+ import { contextSegments } from "./chat.js";
10
+ import { ICON, esc, listeners, scroller } from "./dom.js";
11
+ const paras = (t) => t
12
+ .split(/\n{2,}/)
13
+ .map((p) => p.trim())
14
+ .filter(Boolean)
15
+ .map((p) => `<div class="hb-msg-text">${esc(p).replace(/\n/g, "<br>")}</div>`)
16
+ .join("");
17
+ export function turnHtml(t, o) {
18
+ if (t.role === "user") {
19
+ return `<div class="hb-msg is-user" data-turn="${t.id}"><span class="hb-msg-who"><span class="hb-msg-name">you</span></span><div class="hb-msg-parts">${paras(t.text)}</div></div>`;
20
+ }
21
+ const live = !t.done;
22
+ const think = t.think
23
+ ? `<details class="hb-think is-think"${live && !t.text ? " open" : ""}><summary>${live && !t.text ? "thinking" : `reasoning (${t.think.length} chars)`}</summary><pre aria-live="off">${esc(t.think)}</pre></details>`
24
+ : "";
25
+ const body = t.text ? paras(t.text) : live && !t.think ? `<div class="hb-msg-pending">thinking</div>` : "";
26
+ const mem = t.mem?.length
27
+ ? `<details class="hb-msg-used"><summary>memory used (${t.mem.length})</summary><ul>${t.mem.map((m) => `<li><span class="hb-msg-used-item">${esc(m.label)}</span>${m.score !== undefined ? `<span class="hb-msg-used-score">${m.score.toFixed(2)}</span>` : ""}</li>`).join("")}</ul></details>`
28
+ : "";
29
+ const acts = t.done && t.text && o.last && !o.busy
30
+ ? `<div class="hb-msg-acts" role="group" aria-label="reply actions"><button type="button" class="hb-msg-act" data-copy="${t.id}">${ICON.copy}copy</button><button type="button" class="hb-msg-act" data-redo>${ICON.redoMsg}redo</button></div>`
31
+ : "";
32
+ return (`<div class="hb-msg" data-turn="${t.id}"><span class="hb-msg-who"><span class="hb-msg-name">${esc(o.name)}</span>${t.stats ? `<span class="hb-msg-stats" title="${esc(t.stats)}">${esc(t.stats.replace(/ \((measured|inferred|vendor|unknown)\)$/, ""))}</span>` : ""}</span>` +
33
+ `${think}<div class="hb-msg-parts">${body}</div>${t.note ? `<span class="hb-msg-note">${esc(t.note)}</span>` : ""}${mem}${acts}</div>`);
34
+ }
35
+ /** The thread over a host, with the empty state inside it. */
36
+ export function mountChatPane(host, thread, o = {}) {
37
+ const name = o.name ?? "reply";
38
+ const l = listeners();
39
+ const draw = (s) => {
40
+ const sc = scroller(host);
41
+ const stick = pinned(sc);
42
+ if (!s.turns.length) {
43
+ host.innerHTML = `<div class="hb-lay-convempty"><h2 class="hb-lay-convempty-name">${esc(o.emptyName ?? "what are we working on?")}</h2>${o.emptyNote ? `<p class="hb-lay-convempty-note">${esc(o.emptyNote)}</p>` : ""}</div>`;
44
+ return;
45
+ }
46
+ // keep folds a person opened open across redraws
47
+ const open = new Set([...host.querySelectorAll("details[open]")].map((d) => `${d.closest("[data-turn]")?.dataset.turn}:${d.className}`));
48
+ const last = s.turns[s.turns.length - 1];
49
+ host.innerHTML = s.turns.map((t) => turnHtml(t, { name, last: t === last, busy: s.busy })).join("");
50
+ for (const d of host.querySelectorAll("details")) {
51
+ if (open.has(`${d.closest("[data-turn]")?.dataset.turn}:${d.className}`))
52
+ d.open = true;
53
+ }
54
+ if (stick)
55
+ sc.scrollTop = sc.scrollHeight;
56
+ };
57
+ l.on(host, "click", (e) => {
58
+ const t = e.target;
59
+ const copy = t.closest("[data-copy]");
60
+ if (copy) {
61
+ const turn = thread.snapshot().turns.find((x) => String(x.id) === copy.dataset.copy);
62
+ if (turn)
63
+ void navigator.clipboard?.writeText(turn.text).then(() => (copy.lastChild.textContent = "copied")).catch(() => (copy.lastChild.textContent = "copy blocked"));
64
+ return;
65
+ }
66
+ if (t.closest("[data-redo]"))
67
+ void thread.regenerate();
68
+ });
69
+ l.add(thread.subscribe(draw));
70
+ return { dispose: () => l.off() };
71
+ }
72
+ /** The composer: Enter sends (Shift Enter adds a line, Escape stops), send is the one pink, stop replaces it while a reply streams. */
73
+ export function mountComposer(host, thread, o = {}) {
74
+ host.innerHTML = `<form class="hb-convbox"><textarea rows="1" aria-label="${esc(o.label ?? "message")}" placeholder="${esc(o.placeholder ?? "say something")}"></textarea><span data-act></span></form>`;
75
+ const form = host.querySelector("form");
76
+ const area = host.querySelector("textarea");
77
+ const act = host.querySelector("[data-act]");
78
+ let busy = false;
79
+ const drawAct = () => {
80
+ act.innerHTML = busy ? `<button type="button" class="hb-btn" data-stop>stop</button>` : `<button type="submit" class="hb-btn hb-btn-go">send</button>`;
81
+ };
82
+ const send = () => {
83
+ const text = area.value.trim();
84
+ if (!text || busy)
85
+ return;
86
+ area.value = "";
87
+ autosize(area);
88
+ void thread.send(text);
89
+ };
90
+ const l = listeners();
91
+ l.on(form, "submit", (e) => {
92
+ e.preventDefault();
93
+ send();
94
+ });
95
+ l.on(act, "click", (e) => {
96
+ if (e.target.closest("[data-stop]"))
97
+ thread.stop();
98
+ });
99
+ l.on(area, "input", () => autosize(area));
100
+ l.on(area, "keydown", (e) => {
101
+ const k = composerKey(e, { busy, empty: !area.value, coarse: coarsePointer() });
102
+ if (k === "send") {
103
+ e.preventDefault();
104
+ send();
105
+ }
106
+ else if (k === "stop")
107
+ thread.stop();
108
+ });
109
+ l.add(thread.subscribe((s) => {
110
+ if (s.busy === busy && act.firstChild)
111
+ return;
112
+ busy = s.busy;
113
+ drawAct();
114
+ }));
115
+ return { dispose: () => l.off() };
116
+ }
117
+ /** The chat list rail (hackbuild-ui HbConversationList markup): new, open, rename, delete with a second press. */
118
+ export function mountChatList(host, list, o = {}) {
119
+ const l = listeners();
120
+ let armed = "";
121
+ let renaming = "";
122
+ const head = o.label ?? "chats";
123
+ const draw = (s) => {
124
+ host.innerHTML =
125
+ `<nav class="hb-convs" aria-label="${esc(head)}"><div class="hb-convs-hd"><span>${esc(head)}</span><button type="button" class="hb-convs-new" data-new aria-label="new chat">${ICON.plus}</button></div><ul class="hb-convs-list">` +
126
+ s.items
127
+ .map((c) => renaming === c.id
128
+ ? `<li class="hb-convs-item"><form class="hb-convs-rename" data-rename="${esc(c.id)}"><input class="hb-input" aria-label="chat name" value="${esc(c.title)}"></form></li>`
129
+ : `<li class="hb-convs-item"${c.id === s.current ? ' aria-current="true"' : ""}><button type="button" class="hb-convs-open" data-open="${esc(c.id)}"><span class="hb-convs-title">${esc(c.title)}</span><span class="hb-convs-meta">${esc(listMeta({ updated: c.updated, count: c.count }))}</span></button><span class="hb-convs-acts"><button type="button" class="hb-convs-act" data-ren="${esc(c.id)}" aria-label="rename ${esc(c.title)}" title="rename">${ICON.pen}</button><button type="button" class="hb-convs-act is-del${armed === c.id ? " is-armed" : ""}" data-del="${esc(c.id)}" aria-label="${armed === c.id ? `press again to delete ${esc(c.title)}` : `delete ${esc(c.title)}`}">${armed === c.id ? "delete?" : ICON.trash}</button></span></li>`)
130
+ .join("") +
131
+ `</ul></nav>`;
132
+ host.querySelector(".hb-convs-rename input")?.focus();
133
+ };
134
+ const redraw = () => draw(list.snapshot());
135
+ l.on(host, "click", (e) => {
136
+ const t = e.target;
137
+ if (t.closest("[data-new]"))
138
+ return void list.create();
139
+ const open = t.closest("[data-open]")?.dataset.open;
140
+ if (open)
141
+ return list.open(open);
142
+ const ren = t.closest("[data-ren]")?.dataset.ren;
143
+ if (ren)
144
+ return ((renaming = ren), redraw());
145
+ const del = t.closest("[data-del]")?.dataset.del;
146
+ if (del) {
147
+ if (armed === del)
148
+ return ((armed = ""), list.remove(del));
149
+ armed = del;
150
+ redraw();
151
+ }
152
+ });
153
+ l.on(host, "submit", (e) => {
154
+ e.preventDefault();
155
+ const f = e.target.closest("[data-rename]");
156
+ if (f)
157
+ list.rename(f.dataset.rename, f.querySelector("input").value);
158
+ renaming = "";
159
+ redraw();
160
+ });
161
+ l.add(list.subscribe(draw));
162
+ return { dispose: () => l.off() };
163
+ }
164
+ /** The context meter (hackbuild-ui `.hb-ctxmeter`): what the next request carries against the model's context. */
165
+ export function mountContextMeter(host, thread, o = {}) {
166
+ const l = listeners();
167
+ const val = (v, d) => (typeof v === "function" ? v() : (v ?? d));
168
+ const draw = (s) => {
169
+ const use = contextUse(contextSegments(s, val(o.system, "")), val(o.budget, 4096));
170
+ host.innerHTML =
171
+ `<div class="hb-ctxmeter is-${use.tone}"><div class="hb-ctxmeter-hd"><span class="hb-ctxmeter-label">context</span><span class="hb-ctxmeter-words">${esc(use.words)}</span></div>` +
172
+ `<div class="hb-ctxmeter-bar" role="meter" aria-label="context used" aria-valuemin="0" aria-valuemax="${use.budget}" aria-valuenow="${use.used}" aria-valuetext="${esc(use.words)}">${use.rows.map((r, n) => `<i class="hb-ctxmeter-p${n % 6}" style="width:${Math.min(100, r.fraction * 100)}%"></i>`).join("")}</div>` +
173
+ `<ul class="hb-ctxmeter-legend">${use.rows.map((r, n) => `<li><i class="hb-ctxmeter-p${n % 6}" aria-hidden="true"></i>${esc(r.label)} <b>${r.tokens.toLocaleString("en-US")}</b></li>`).join("")}</ul></div>`;
174
+ };
175
+ l.add(thread.subscribe(draw));
176
+ return { dispose: () => l.off() };
177
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * FrameView and CameraFeed, after the eyes view of an earlier room: a
3
+ * frame in a hackbuild-ui camera tile with what the models found drawn
4
+ * over it (boxes with their word and score, landmark points and lines),
5
+ * a count in the corner and the caption under it. CameraFeed opens the
6
+ * camera into a tile and hands frames to the page at a set rate.
7
+ */
8
+ import { type Mounted } from "./dom.js";
9
+ import { type FrameResults } from "./frame.js";
10
+ type Source = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement;
11
+ export interface FrameView extends Mounted {
12
+ /** An image url, or a live element (a camera video); null shows the empty tile. */
13
+ setSource(src: string | Source | null): Promise<void>;
14
+ setResults(r: FrameResults): void;
15
+ setMirror(on: boolean): void;
16
+ /** Draw again, as after a resize or a new video frame. */
17
+ paint(): void;
18
+ }
19
+ export interface FrameViewOptions {
20
+ empty?: string;
21
+ mirror?: boolean;
22
+ /** Ink of the drawn boxes' word strip; default the paper token. */
23
+ palette?: readonly string[];
24
+ }
25
+ export declare function mountFrameView(host: HTMLElement, o?: FrameViewOptions): FrameView;
26
+ export interface CameraFeed extends Mounted {
27
+ start(): Promise<void>;
28
+ stop(): void;
29
+ readonly video: HTMLVideoElement;
30
+ readonly live: boolean;
31
+ subscribe(fn: (s: {
32
+ live: boolean;
33
+ error: string;
34
+ }) => void): () => void;
35
+ }
36
+ export interface CameraFeedOptions {
37
+ /** Called with the video this many times a second while live. Default 4. */
38
+ fps?: number;
39
+ onFrame?: (video: HTMLVideoElement) => void | Promise<void>;
40
+ facingMode?: "user" | "environment";
41
+ /** Draw the video in a tile of its own; off when a FrameView shows it. */
42
+ tile?: boolean;
43
+ }
44
+ export declare function mountCameraFeed(host: HTMLElement, o?: CameraFeedOptions): CameraFeed;
45
+ export {};
@@ -0,0 +1,237 @@
1
+ /**
2
+ * FrameView and CameraFeed, after the eyes view of an earlier room: a
3
+ * frame in a hackbuild-ui camera tile with what the models found drawn
4
+ * over it (boxes with their word and score, landmark points and lines),
5
+ * a count in the corner and the caption under it. CameraFeed opens the
6
+ * camera into a tile and hands frames to the page at a set rate.
7
+ */
8
+ import { INSTANCE_COLOURS, cameraFault, closeCamera, openCamera } from "@virgilvox/hackbuild-ui/vanilla";
9
+ import { esc, listeners, show } from "./dom.js";
10
+ import { boxWords, fitMap, frameTag, labelColour, toView } from "./frame.js";
11
+ const css = (el, name, fb) => {
12
+ try {
13
+ return getComputedStyle(el).getPropertyValue(name).trim() || fb;
14
+ }
15
+ catch {
16
+ return fb;
17
+ }
18
+ };
19
+ export function mountFrameView(host, o = {}) {
20
+ host.innerHTML = `<div class="hb-frameview"><figure class="hb-camtile" aria-label="frame"><div class="hb-camtile-none" role="status">${esc(o.empty ?? "no frame yet")}</div><canvas aria-hidden="true"></canvas><span class="hb-camtile-tag is-tl" hidden></span></figure><p class="hb-frameview-cap" data-caption aria-live="polite" hidden></p></div>`;
21
+ const fig = host.querySelector("figure");
22
+ const canvas = host.querySelector("canvas");
23
+ const none = host.querySelector(".hb-camtile-none");
24
+ const tag = host.querySelector(".hb-camtile-tag");
25
+ const cap = host.querySelector("[data-caption]");
26
+ const palette = o.palette ?? INSTANCE_COLOURS;
27
+ let src = null;
28
+ let results = {};
29
+ let mirror = !!o.mirror;
30
+ const l = listeners();
31
+ const size = () => {
32
+ const s = src;
33
+ if (!s)
34
+ return { w: 0, h: 0 };
35
+ if (s instanceof HTMLVideoElement)
36
+ return { w: s.videoWidth, h: s.videoHeight };
37
+ if (s instanceof HTMLImageElement)
38
+ return { w: s.naturalWidth, h: s.naturalHeight };
39
+ return { w: s.width, h: s.height };
40
+ };
41
+ const paint = () => {
42
+ const r = fig.getBoundingClientRect();
43
+ const dpr = Math.min(2, window.devicePixelRatio || 1);
44
+ canvas.width = Math.max(1, Math.round(r.width * dpr));
45
+ canvas.height = Math.max(1, Math.round(r.height * dpr));
46
+ const g = canvas.getContext("2d");
47
+ if (!g)
48
+ return;
49
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
50
+ g.clearRect(0, 0, r.width, r.height);
51
+ const sz = size();
52
+ const m = fitMap(sz, { w: r.width, h: r.height }, "cover");
53
+ if (src instanceof HTMLImageElement || src instanceof HTMLCanvasElement) {
54
+ g.save();
55
+ if (mirror) {
56
+ g.translate(r.width, 0);
57
+ g.scale(-1, 1);
58
+ }
59
+ g.drawImage(src, m.dx, m.dy, sz.w * m.scale, sz.h * m.scale);
60
+ g.restore();
61
+ }
62
+ const ink = css(fig, "--hb-void", "#0a0a0a");
63
+ const paper = css(fig, "--hb-paper", "ivory");
64
+ const slime = css(fig, "--hb-slime", "#a6e22e");
65
+ g.font = `11px ${css(fig, "--hb-utility", "ui-monospace, monospace")}`;
66
+ g.textBaseline = "top";
67
+ for (const b of results.boxes ?? []) {
68
+ const v = toView(b, m, r.width, mirror);
69
+ const c = labelColour(b.label, palette);
70
+ g.lineWidth = 3;
71
+ g.strokeStyle = ink;
72
+ g.strokeRect(v.x, v.y, v.w, v.h);
73
+ g.lineWidth = 2;
74
+ g.strokeStyle = c;
75
+ g.strokeRect(v.x, v.y, v.w, v.h);
76
+ const words = boxWords(b);
77
+ if (words) {
78
+ const tw = g.measureText(words).width + 8;
79
+ const ty = v.y >= 16 ? v.y - 16 : v.y;
80
+ g.fillStyle = c;
81
+ g.fillRect(v.x - 1, ty, tw, 16);
82
+ g.fillStyle = ink;
83
+ g.fillText(words, v.x + 3, ty + 2);
84
+ }
85
+ }
86
+ for (const set of results.landmarks ?? []) {
87
+ const pts = set.points.map((p) => toView({ x: p.x, y: p.y, w: 0, h: 0 }, m, r.width, mirror));
88
+ g.strokeStyle = slime;
89
+ g.lineWidth = 1.5;
90
+ for (const [a, b] of set.edges ?? []) {
91
+ const pa = pts[a];
92
+ const pb = pts[b];
93
+ if (!pa || !pb)
94
+ continue;
95
+ g.beginPath();
96
+ g.moveTo(pa.x, pa.y);
97
+ g.lineTo(pb.x, pb.y);
98
+ g.stroke();
99
+ }
100
+ for (const p of pts) {
101
+ g.fillStyle = ink;
102
+ g.fillRect(p.x - 2.5, p.y - 2.5, 5, 5);
103
+ g.fillStyle = paper;
104
+ g.fillRect(p.x - 1.5, p.y - 1.5, 3, 3);
105
+ }
106
+ }
107
+ };
108
+ const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => paint()) : null;
109
+ ro?.observe(fig);
110
+ l.add(() => ro?.disconnect());
111
+ let video = null;
112
+ let raf = 0;
113
+ const loop = () => {
114
+ paint();
115
+ raf = requestAnimationFrame(loop);
116
+ };
117
+ l.add(() => cancelAnimationFrame(raf));
118
+ const view = {
119
+ async setSource(s) {
120
+ cancelAnimationFrame(raf);
121
+ video?.remove();
122
+ video = null;
123
+ if (typeof s === "string") {
124
+ const img = new Image();
125
+ img.src = s;
126
+ await img.decode();
127
+ src = img;
128
+ }
129
+ else
130
+ src = s;
131
+ if (src instanceof HTMLVideoElement) {
132
+ // the video sits under the canvas; the canvas draws only the marks
133
+ video = src;
134
+ video.classList.add("hb-camtile-video");
135
+ fig.classList.toggle("is-mirror", mirror);
136
+ fig.prepend(video);
137
+ raf = requestAnimationFrame(loop);
138
+ }
139
+ show(none, !src);
140
+ const sz = size();
141
+ if (sz.w && sz.h)
142
+ fig.style.setProperty("--hb-camtile-ar", `${sz.w} / ${sz.h}`);
143
+ paint();
144
+ },
145
+ setResults(r) {
146
+ results = r;
147
+ const t = frameTag(r);
148
+ show(tag, !!t);
149
+ tag.textContent = t;
150
+ show(cap, !!r.caption);
151
+ cap.textContent = r.caption ?? "";
152
+ paint();
153
+ },
154
+ setMirror(on) {
155
+ mirror = on;
156
+ fig.classList.toggle("is-mirror", on && !!video);
157
+ paint();
158
+ },
159
+ paint,
160
+ dispose: () => l.off(),
161
+ };
162
+ return view;
163
+ }
164
+ export function mountCameraFeed(host, o = {}) {
165
+ const video = document.createElement("video");
166
+ video.autoplay = true;
167
+ video.playsInline = true;
168
+ video.muted = true;
169
+ const tile = o.tile ?? true;
170
+ if (tile) {
171
+ host.innerHTML = `<figure class="hb-camtile is-mirror" aria-label="camera"><div class="hb-camtile-none" role="status">camera off</div></figure>`;
172
+ video.className = "hb-camtile-video";
173
+ host.querySelector("figure").prepend(video);
174
+ }
175
+ const none = host.querySelector(".hb-camtile-none");
176
+ let stream = null;
177
+ let timer = null;
178
+ let error = "";
179
+ let working = false;
180
+ const subs = new Set();
181
+ const emit = () => {
182
+ if (none) {
183
+ show(none, !stream);
184
+ none.textContent = error || "camera off";
185
+ host.querySelector("figure")?.classList.toggle("is-denied", !!error);
186
+ }
187
+ for (const fn of subs)
188
+ fn({ live: !!stream, error });
189
+ };
190
+ const feed = {
191
+ video,
192
+ get live() {
193
+ return !!stream;
194
+ },
195
+ async start() {
196
+ if (stream)
197
+ return;
198
+ error = "";
199
+ try {
200
+ stream = await openCamera({ facingMode: o.facingMode ?? "user", width: { ideal: 640 }, height: { ideal: 480 } });
201
+ video.srcObject = stream;
202
+ await video.play().catch(() => undefined);
203
+ timer = setInterval(() => {
204
+ if (working || !o.onFrame || video.readyState < 2)
205
+ return;
206
+ working = true;
207
+ void Promise.resolve(o.onFrame(video)).finally(() => (working = false));
208
+ }, 1000 / (o.fps ?? 4));
209
+ }
210
+ catch (e) {
211
+ error = cameraFault(e).text;
212
+ stream = null;
213
+ }
214
+ emit();
215
+ },
216
+ stop() {
217
+ if (timer)
218
+ clearInterval(timer);
219
+ timer = null;
220
+ closeCamera(stream);
221
+ stream = null;
222
+ video.srcObject = null;
223
+ emit();
224
+ },
225
+ subscribe(fn) {
226
+ subs.add(fn);
227
+ fn({ live: !!stream, error });
228
+ return () => subs.delete(fn);
229
+ },
230
+ dispose() {
231
+ feed.stop();
232
+ subs.clear();
233
+ },
234
+ };
235
+ emit();
236
+ return feed;
237
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * MaskStudio, after the earlier mask studio: drop an image, press a thing
3
+ * to cut it out (a click segment model such as SlimSAM), fix the mask by
4
+ * hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
5
+ * add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
6
+ * export the mask, a matte or the cutout. With a segment everything model
7
+ * (FastSAM) one press finds every object; each lands in the found list and
8
+ * a press adds it to the mask. Models are functions the page passes, so
9
+ * stubs run the studio with no weights.
10
+ */
11
+ import { type MaskMode, type MaskOutput, type MaskPixels, type MaskTool } from "@virgilvox/hackbuild-ui/vanilla";
12
+ import { type Mounted } from "./dom.js";
13
+ /** One object a segment model found: a mask in image pixels (0 or 255), its word and score. */
14
+ export interface FoundMask {
15
+ mask: Uint8Array;
16
+ label: string;
17
+ score: number;
18
+ }
19
+ export interface MaskModels {
20
+ /** Click segment: the mask under one point, in image pixels. */
21
+ segment?: (image: MaskPixels, point: {
22
+ x: number;
23
+ y: number;
24
+ }) => Promise<Uint8Array | null>;
25
+ /** Segment everything: every object at once. */
26
+ everything?: (image: MaskPixels) => Promise<FoundMask[]>;
27
+ }
28
+ export type StudioTool = "point" | MaskTool;
29
+ export interface StudioState {
30
+ ready: boolean;
31
+ tool: StudioTool;
32
+ mode: MaskMode;
33
+ size: number;
34
+ tolerance: number;
35
+ canUndo: boolean;
36
+ canRedo: boolean;
37
+ coverage: number;
38
+ zoom: number;
39
+ busy: string;
40
+ found: (FoundMask & {
41
+ on: boolean;
42
+ colour: string;
43
+ })[];
44
+ /** Masks put aside with a name and a small preview, newest first. */
45
+ saved: {
46
+ id: number;
47
+ name: string;
48
+ thumb: string;
49
+ coverage: number;
50
+ }[];
51
+ width: number;
52
+ height: number;
53
+ /** The last failure, in words. */
54
+ error: string;
55
+ }
56
+ export interface MaskStudio extends Mounted {
57
+ setImage(src: string | HTMLImageElement | HTMLCanvasElement | ImageBitmap | MaskPixels): Promise<void>;
58
+ setTool(t: StudioTool): void;
59
+ setMode(m: MaskMode): void;
60
+ setSize(px: number): void;
61
+ setTolerance(pct: number): void;
62
+ undo(): void;
63
+ redo(): void;
64
+ invert(): void;
65
+ clear(): void;
66
+ /** Grow, shrink or round off the mask, one undo step each. */
67
+ expand(px?: number): void;
68
+ shrink(px?: number): void;
69
+ smooth(r?: number): void;
70
+ /** Put the current mask aside; restore puts it back as one undo step. */
71
+ save(name?: string): void;
72
+ restore(id: number): void;
73
+ forget(id: number): void;
74
+ /** The current mask as ImageData (alpha by default), null before an image. */
75
+ mask(kind?: MaskOutput): ImageData | null;
76
+ zoom(dir: 1 | -1 | 0): void;
77
+ everything(): Promise<void>;
78
+ /** The click segment model at a point in image pixels, as a press with the point tool. */
79
+ cutAt(x: number, y: number, mode?: MaskMode): Promise<void>;
80
+ /** Add or take out one found object. */
81
+ toggleFound(index: number): void;
82
+ /** The mask, matte or cutout as a png Blob. */
83
+ exportAs(kind: MaskOutput): Promise<Blob | null>;
84
+ hasEverything: boolean;
85
+ hasSegment: boolean;
86
+ state(): StudioState;
87
+ subscribe(fn: (s: StudioState) => void): () => void;
88
+ setModels(m: MaskModels): void;
89
+ /** Open the file picker. */
90
+ pick(): void;
91
+ }
92
+ export interface MaskStudioOptions {
93
+ models?: MaskModels;
94
+ title?: string;
95
+ note?: string;
96
+ sampleLabel?: string;
97
+ onSample?: () => void;
98
+ /** Name of exported files, without extension. */
99
+ name?: string;
100
+ }
101
+ export declare function mountMaskStudio(host: HTMLElement, o?: MaskStudioOptions): MaskStudio;
102
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
103
+ export declare function mountMaskTools(host: HTMLElement, studio: MaskStudio): Mounted;
104
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
105
+ export declare function mountMaskVerbs(host: HTMLElement, studio: MaskStudio): Mounted;
106
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
107
+ export declare function mountMaskRack(host: HTMLElement, studio: MaskStudio, part: "found" | "mask" | "saved" | "export", o?: {
108
+ name?: string;
109
+ }): Mounted;