@hackbuild/ai-views 0.0.0-stage → 0.1.1

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,127 @@
1
+ /**
2
+ * MaskStudio: 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
+ /** The segment models a mask studio calls: a click segment for one point and a segment everything. */
20
+ export interface MaskModels {
21
+ /** Click segment: the mask under one point, in image pixels. */
22
+ segment?: (image: MaskPixels, point: {
23
+ x: number;
24
+ y: number;
25
+ }) => Promise<Uint8Array | null>;
26
+ /** Segment everything: every object at once. */
27
+ everything?: (image: MaskPixels) => Promise<FoundMask[]>;
28
+ }
29
+ /** A mask studio tool: the click segment point or one of the hackbuild-ui mask tools. */
30
+ export type StudioTool = "point" | MaskTool;
31
+ /**
32
+ * What a mask studio shows: tool, mode, sizes, undo state, coverage, zoom, found and saved masks,
33
+ * image size and the last error.
34
+ */
35
+ export interface StudioState {
36
+ ready: boolean;
37
+ tool: StudioTool;
38
+ mode: MaskMode;
39
+ size: number;
40
+ tolerance: number;
41
+ canUndo: boolean;
42
+ canRedo: boolean;
43
+ coverage: number;
44
+ zoom: number;
45
+ busy: string;
46
+ found: (FoundMask & {
47
+ on: boolean;
48
+ colour: string;
49
+ })[];
50
+ /** Masks put aside with a name and a small preview, newest first. */
51
+ saved: {
52
+ id: number;
53
+ name: string;
54
+ thumb: string;
55
+ coverage: number;
56
+ }[];
57
+ width: number;
58
+ height: number;
59
+ /** The last failure, in words. */
60
+ error: string;
61
+ }
62
+ /**
63
+ * A mounted mask studio: image, tools, undo, grow and shrink, saved masks, found objects, export,
64
+ * and a subscription to its state.
65
+ */
66
+ export interface MaskStudio extends Mounted {
67
+ setImage(src: string | HTMLImageElement | HTMLCanvasElement | ImageBitmap | MaskPixels): Promise<void>;
68
+ setTool(t: StudioTool): void;
69
+ setMode(m: MaskMode): void;
70
+ setSize(px: number): void;
71
+ setTolerance(pct: number): void;
72
+ undo(): void;
73
+ redo(): void;
74
+ invert(): void;
75
+ clear(): void;
76
+ /** Grow, shrink or round off the mask, one undo step each. */
77
+ expand(px?: number): void;
78
+ shrink(px?: number): void;
79
+ smooth(r?: number): void;
80
+ /** Put the current mask aside; restore puts it back as one undo step. */
81
+ save(name?: string): void;
82
+ restore(id: number): void;
83
+ forget(id: number): void;
84
+ /** The current mask as ImageData (alpha by default), null before an image. */
85
+ mask(kind?: MaskOutput): ImageData | null;
86
+ zoom(dir: 1 | -1 | 0): void;
87
+ everything(): Promise<void>;
88
+ /** The click segment model at a point in image pixels, as a press with the point tool. */
89
+ cutAt(x: number, y: number, mode?: MaskMode): Promise<void>;
90
+ /** Add or take out one found object. */
91
+ toggleFound(index: number): void;
92
+ /** The mask, matte or cutout as a png Blob. */
93
+ exportAs(kind: MaskOutput): Promise<Blob | null>;
94
+ hasEverything: boolean;
95
+ hasSegment: boolean;
96
+ state(): StudioState;
97
+ subscribe(fn: (s: StudioState) => void): () => void;
98
+ setModels(m: MaskModels): void;
99
+ /** Open the file picker. */
100
+ pick(): void;
101
+ }
102
+ /**
103
+ * Options for `mountMaskStudio`: the segment models, empty state words, a sample button and the
104
+ * export file name.
105
+ */
106
+ export interface MaskStudioOptions {
107
+ models?: MaskModels;
108
+ title?: string;
109
+ note?: string;
110
+ sampleLabel?: string;
111
+ onSample?: () => void;
112
+ /** Name of exported files, without extension. */
113
+ name?: string;
114
+ }
115
+ /**
116
+ * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
117
+ * and lasso tools or a segment model.
118
+ */
119
+ export declare function mountMaskStudio(host: HTMLElement, o?: MaskStudioOptions): MaskStudio;
120
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
121
+ export declare function mountMaskTools(host: HTMLElement, studio: MaskStudio): Mounted;
122
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
123
+ export declare function mountMaskVerbs(host: HTMLElement, studio: MaskStudio): Mounted;
124
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
125
+ export declare function mountMaskRack(host: HTMLElement, studio: MaskStudio, part: "found" | "mask" | "saved" | "export", o?: {
126
+ name?: string;
127
+ }): Mounted;
@@ -0,0 +1,450 @@
1
+ /**
2
+ * MaskStudio: 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 { INSTANCE_COLOURS, MASK_TOOLS, maskEditor, strokeIcon } from "@virgilvox/hackbuild-ui/vanilla";
12
+ import { ICON, download, esc, listeners, show } from "./dom.js";
13
+ const ZOOMS = [0.5, 0.75, 1, 1.5, 2, 3, 4];
14
+ /** Pixels of a drawable, for a model. */
15
+ function pixelsOf(src) {
16
+ const c = document.createElement("canvas");
17
+ c.width = src.width;
18
+ c.height = src.height;
19
+ const g = c.getContext("2d");
20
+ g.drawImage(src, 0, 0);
21
+ const d = g.getImageData(0, 0, c.width, c.height);
22
+ return { width: d.width, height: d.height, data: d.data };
23
+ }
24
+ /** A 48 px wide preview of a matte, as a data url. */
25
+ function thumbOf(img) {
26
+ const c = document.createElement("canvas");
27
+ c.width = img.width;
28
+ c.height = img.height;
29
+ c.getContext("2d")?.putImageData(img, 0, 0);
30
+ const t = document.createElement("canvas");
31
+ t.width = 48;
32
+ t.height = Math.max(1, Math.round((48 * img.height) / Math.max(1, img.width)));
33
+ t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
34
+ return t.toDataURL("image/png");
35
+ }
36
+ /**
37
+ * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
38
+ * and lasso tools or a segment model.
39
+ */
40
+ export function mountMaskStudio(host, o = {}) {
41
+ let models = o.models ?? {};
42
+ const l = listeners();
43
+ host.innerHTML =
44
+ `<div class="hb-lay-empty" data-empty><span class="hb-lay-empty-name">${esc(o.title ?? "drop an image")}</span><p class="hb-lay-empty-note">${esc(o.note ?? "press a thing to cut it out. the picture stays on this machine.")}</p><div class="hb-lay-empty-acts"><button type="button" class="hb-btn hb-btn-go" data-pick>open an image</button>${o.sampleLabel ? `<button type="button" class="hb-btn" data-sample>${esc(o.sampleLabel)}</button>` : ""}</div></div>` +
45
+ `<div class="hb-mask is-fill" data-studio hidden><div class="hb-mask-well"><div class="hb-mask-frame"><canvas class="hb-mask-canvas" tabindex="0" role="img" aria-label="image and mask"></canvas><p class="hb-mask-hint" aria-live="polite"></p></div></div></div>` +
46
+ `<input type="file" accept="image/*" hidden>`;
47
+ const empty = host.querySelector("[data-empty]");
48
+ const studio = host.querySelector("[data-studio]");
49
+ const well = host.querySelector(".hb-mask-well");
50
+ const frame = host.querySelector(".hb-mask-frame");
51
+ const canvas = host.querySelector("canvas");
52
+ const hint = host.querySelector(".hb-mask-hint");
53
+ const input = host.querySelector("input[type=file]");
54
+ const subs = new Set();
55
+ let tool = models.segment ? "point" : "wand";
56
+ let zoom = 1;
57
+ let busy = "";
58
+ let error = "";
59
+ let pixels = null;
60
+ let found = [];
61
+ let saved = [];
62
+ let savedSeq = 0;
63
+ let ed = null;
64
+ const state = () => ({
65
+ ready: !!ed?.ready,
66
+ tool,
67
+ mode: ed?.mode ?? "add",
68
+ size: ed?.size ?? 24,
69
+ tolerance: ed?.tolerance ?? 6,
70
+ canUndo: !!ed?.canUndo,
71
+ canRedo: !!ed?.canRedo,
72
+ coverage: ed?.coverage ?? 0,
73
+ zoom,
74
+ busy,
75
+ found,
76
+ saved: saved.map(({ bytes: _b, ...rest }) => rest),
77
+ width: ed?.width ?? 0,
78
+ height: ed?.height ?? 0,
79
+ error,
80
+ });
81
+ const emit = () => {
82
+ const s = state();
83
+ hint.textContent = s.busy || s.error || (tool === "point" ? "press a thing to cut it out. x takes it away instead." : (MASK_TOOLS.find((t) => t.id === tool)?.hint ?? ""));
84
+ for (const fn of subs)
85
+ fn(s);
86
+ };
87
+ const editor = maskEditor(canvas, { tool: tool === "point" ? "wand" : tool, onError: (e) => ((error = `the image did not load: ${e.message}`), emit()) });
88
+ l.add(editor.subscribe((s) => ((ed = s), emit())));
89
+ // the well fills the subject (.hb-mask.is-fill); at fit the frame is as large as the well holds at the image's ratio
90
+ const applyZoom = () => {
91
+ const ratio = ed && ed.height ? ed.width / ed.height : 4 / 3;
92
+ const fitW = Math.max(1, Math.min(well.clientWidth, well.clientHeight * ratio));
93
+ studio.style.setProperty("--hb-mask-ratio", String(ratio));
94
+ studio.style.setProperty("--hb-mask-w", `${Math.round(fitW * zoom)}px`);
95
+ studio.classList.toggle("is-zoomed", zoom > 1);
96
+ };
97
+ const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => applyZoom()) : null;
98
+ ro?.observe(well);
99
+ l.add(() => ro?.disconnect());
100
+ // a press with the point tool asks the click segment model, before the editor sees it
101
+ const cut = async (x, y, erase) => {
102
+ if (!ed?.ready || !pixels || !models.segment)
103
+ return;
104
+ busy = "cutting it out";
105
+ error = "";
106
+ emit();
107
+ try {
108
+ const m = await models.segment(pixels, { x, y });
109
+ if (!m)
110
+ return;
111
+ const cur = editor.mask();
112
+ for (let i = 0; i < cur.length; i++)
113
+ cur[i] = erase ? (m[i] ? 0 : cur[i]) : m[i] || cur[i] ? 255 : 0;
114
+ editor.setMask(cur);
115
+ }
116
+ catch (err) {
117
+ error = `the cut failed: ${err instanceof Error ? err.message : String(err)}`;
118
+ }
119
+ finally {
120
+ busy = "";
121
+ emit();
122
+ }
123
+ };
124
+ const onPoint = (e) => {
125
+ if (tool !== "point")
126
+ return;
127
+ e.stopImmediatePropagation();
128
+ e.preventDefault();
129
+ const pe = e;
130
+ const r = canvas.getBoundingClientRect();
131
+ if (!ed?.ready)
132
+ return;
133
+ const x = Math.round(((pe.clientX - r.left) / r.width) * ed.width);
134
+ const y = Math.round(((pe.clientY - r.top) / r.height) * ed.height);
135
+ void cut(x, y, (ed.mode === "erase") !== pe.shiftKey);
136
+ };
137
+ // capture, so it runs before the editor's own handler on the canvas
138
+ canvas.addEventListener("pointerdown", onPoint, true);
139
+ l.add(() => canvas.removeEventListener("pointerdown", onPoint, true));
140
+ const take = (f) => {
141
+ if (!f)
142
+ return;
143
+ const url = URL.createObjectURL(f);
144
+ void studioApi.setImage(url).finally(() => URL.revokeObjectURL(url));
145
+ };
146
+ l.on(input, "change", () => {
147
+ take(input.files?.[0]);
148
+ input.value = "";
149
+ });
150
+ l.on(host, "dragover", (e) => e.preventDefault());
151
+ l.on(host, "drop", (e) => {
152
+ e.preventDefault();
153
+ take(e.dataTransfer?.files?.[0]);
154
+ });
155
+ l.on(empty, "click", (e) => {
156
+ const t = e.target;
157
+ if (t.closest("[data-pick]"))
158
+ input.click();
159
+ else if (t.closest("[data-sample]"))
160
+ o.onSample?.();
161
+ });
162
+ const studioApi = {
163
+ async setImage(src) {
164
+ error = "";
165
+ found = [];
166
+ saved = [];
167
+ let drawable = null;
168
+ if (typeof src === "string") {
169
+ const img = new Image();
170
+ img.crossOrigin = "anonymous";
171
+ img.src = src;
172
+ await img.decode();
173
+ drawable = img;
174
+ }
175
+ else if ("data" in src && !(src instanceof HTMLCanvasElement)) {
176
+ pixels = src;
177
+ }
178
+ else
179
+ drawable = src;
180
+ if (drawable)
181
+ pixels = pixelsOf(drawable);
182
+ show(empty, false);
183
+ // .hb-mask sets display, so the hidden attribute would not hide it
184
+ show(studio, true);
185
+ await editor.setImage(pixels);
186
+ zoom = 1;
187
+ applyZoom();
188
+ emit();
189
+ canvas.focus({ preventScroll: true });
190
+ },
191
+ setTool(t) {
192
+ if (t === "point" && !models.segment)
193
+ return;
194
+ tool = t;
195
+ if (t !== "point")
196
+ editor.setTool(t);
197
+ canvas.dataset.tool = t;
198
+ emit();
199
+ },
200
+ setMode: (m) => editor.setMode(m),
201
+ setSize: (px) => editor.setSize(px),
202
+ setTolerance: (p) => editor.setTolerance(p),
203
+ undo: () => void editor.undo(),
204
+ redo: () => void editor.redo(),
205
+ invert: () => editor.invert(),
206
+ clear: () => editor.clear(),
207
+ expand: (px) => editor.expand(px),
208
+ shrink: (px) => editor.shrink(px),
209
+ smooth: (r) => editor.smooth(r),
210
+ save(name) {
211
+ if (!ed?.ready || !ed.coverage)
212
+ return;
213
+ const bytes = editor.mask();
214
+ const id = ++savedSeq;
215
+ saved = [{ id, name: name ?? `mask ${id}`, thumb: thumbOf(editor.toImageData("matte")), coverage: ed.coverage, bytes }, ...saved];
216
+ emit();
217
+ },
218
+ restore(id) {
219
+ const m = saved.find((x) => x.id === id);
220
+ if (m && ed?.ready && m.bytes.length === ed.width * ed.height)
221
+ editor.setMask(m.bytes);
222
+ },
223
+ forget(id) {
224
+ saved = saved.filter((x) => x.id !== id);
225
+ emit();
226
+ },
227
+ mask: (kind = "alpha") => (ed?.ready ? editor.toImageData(kind) : null),
228
+ zoom(dir) {
229
+ if (dir === 0)
230
+ zoom = 1;
231
+ else {
232
+ const i = ZOOMS.indexOf(zoom);
233
+ zoom = ZOOMS[Math.max(0, Math.min(ZOOMS.length - 1, i + dir))];
234
+ }
235
+ applyZoom();
236
+ emit();
237
+ },
238
+ async everything() {
239
+ if (!models.everything || !pixels)
240
+ return;
241
+ busy = "finding every object";
242
+ error = "";
243
+ emit();
244
+ try {
245
+ const list = await models.everything(pixels);
246
+ found = list.map((f, i) => ({ ...f, on: false, colour: INSTANCE_COLOURS[i % INSTANCE_COLOURS.length] }));
247
+ }
248
+ catch (e) {
249
+ error = `segment everything failed: ${e instanceof Error ? e.message : String(e)}`;
250
+ }
251
+ finally {
252
+ busy = "";
253
+ emit();
254
+ }
255
+ },
256
+ cutAt: (x, y, mode) => cut(x, y, (mode ?? ed?.mode) === "erase"),
257
+ toggleFound(i) {
258
+ const f = found[i];
259
+ if (!f)
260
+ return;
261
+ found = found.map((x, k) => (k === i ? { ...x, on: !x.on } : x));
262
+ const cur = editor.mask();
263
+ for (let p = 0; p < cur.length; p++)
264
+ if (f.mask[p])
265
+ cur[p] = f.on ? 0 : 255;
266
+ editor.setMask(cur);
267
+ },
268
+ async exportAs(kind) {
269
+ if (!ed?.ready)
270
+ return null;
271
+ return editor.toBlob(kind);
272
+ },
273
+ get hasEverything() {
274
+ return !!models.everything;
275
+ },
276
+ get hasSegment() {
277
+ return !!models.segment;
278
+ },
279
+ state,
280
+ subscribe(fn) {
281
+ subs.add(fn);
282
+ fn(state());
283
+ return () => subs.delete(fn);
284
+ },
285
+ setModels(m) {
286
+ const hadSegment = !!models.segment;
287
+ models = m;
288
+ if (m.segment && !hadSegment) {
289
+ tool = "point";
290
+ canvas.dataset.tool = "point";
291
+ }
292
+ if (tool === "point" && !m.segment)
293
+ studioApi.setTool("wand");
294
+ emit();
295
+ },
296
+ pick: () => input.click(),
297
+ dispose() {
298
+ l.off();
299
+ editor.dispose();
300
+ subs.clear();
301
+ },
302
+ };
303
+ canvas.dataset.tool = tool;
304
+ emit();
305
+ return studioApi;
306
+ }
307
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
308
+ export function mountMaskTools(host, studio) {
309
+ const l = listeners();
310
+ const draw = (s) => {
311
+ const tools = [
312
+ ...(studio.hasSegment ? [{ id: "point", label: "cut out a thing", key: "a", icon: "crosshairs" }] : []),
313
+ ...MASK_TOOLS.map((t) => ({ id: t.id, label: t.label, key: t.key, icon: t.icon })),
314
+ ];
315
+ host.innerHTML = tools.map((t) => `<button type="button" class="hb-iconbtn" data-tool="${t.id}" aria-label="${esc(t.label)} (${t.key})" title="${esc(t.label)} (${t.key})" aria-pressed="${s.tool === t.id}" aria-keyshortcuts="${t.key}">${strokeIcon(t.icon, { size: 18 })}</button>`).join("");
316
+ };
317
+ l.on(host, "click", (e) => {
318
+ const t = e.target.closest("[data-tool]");
319
+ if (t)
320
+ studio.setTool(t.dataset.tool);
321
+ });
322
+ l.on(document, "keydown", (e) => {
323
+ const ke = e;
324
+ const typing = !!ke.target.closest?.("input,textarea,[contenteditable]");
325
+ if (!typing && !ke.ctrlKey && !ke.metaKey && studio.state().ready) {
326
+ if (ke.key === "+" || ke.key === "=")
327
+ return studio.zoom(1);
328
+ if (ke.key === "-")
329
+ return studio.zoom(-1);
330
+ if (ke.key === "0")
331
+ return studio.zoom(0);
332
+ }
333
+ if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && studio.hasSegment && !ke.target.closest?.("input,textarea,[contenteditable]"))
334
+ studio.setTool("point");
335
+ });
336
+ l.add(studio.subscribe(draw));
337
+ return { dispose: () => l.off() };
338
+ }
339
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
340
+ export function mountMaskVerbs(host, studio) {
341
+ const l = listeners();
342
+ let last = "";
343
+ const draw = (s) => {
344
+ const html = s.ready
345
+ ? `${s.canUndo ? `<button type="button" class="hb-iconbtn" data-v="undo" aria-label="undo" title="undo (ctrl z)">${ICON.undo}</button>` : ""}${s.canRedo ? `<button type="button" class="hb-iconbtn" data-v="redo" aria-label="redo" title="redo (ctrl shift z)">${ICON.redo}</button>` : ""}` +
346
+ // zoom out and fit show once zoomed in, so the row stays short
347
+ (s.zoom !== 1 ? `<button type="button" class="hb-iconbtn" data-v="out" aria-label="zoom out" title="zoom out (-)">${ICON.zoomOut}</button><button type="button" class="hb-iconbtn" data-v="fit" aria-label="fit, now ${Math.round(s.zoom * 100)} percent" title="fit (0)">${ICON.fit}</button>` : "") +
348
+ `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>`
349
+ : "";
350
+ if (html !== last)
351
+ host.innerHTML = last = html;
352
+ host.hidden = !html;
353
+ };
354
+ l.on(host, "click", (e) => {
355
+ const v = e.target.closest("[data-v]")?.dataset.v;
356
+ if (v === "undo")
357
+ studio.undo();
358
+ else if (v === "redo")
359
+ studio.redo();
360
+ else if (v === "in")
361
+ studio.zoom(1);
362
+ else if (v === "out")
363
+ studio.zoom(-1);
364
+ else if (v === "fit")
365
+ studio.zoom(0);
366
+ });
367
+ l.add(studio.subscribe(draw));
368
+ return { dispose: () => l.off() };
369
+ }
370
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
371
+ export function mountMaskRack(host, studio, part, o = {}) {
372
+ const l = listeners();
373
+ let last = "";
374
+ const draw = (s) => {
375
+ let html = "";
376
+ if (part === "found") {
377
+ html = s.found.length
378
+ ? `<div class="hb-inst"><ul class="hb-inst-list">${s.found.map((f, i) => `<li class="hb-inst-row${f.on ? " is-on" : ""}" style="--hb-inst-c:${f.colour}"><button type="button" class="hb-inst-pick" data-found="${i}" aria-pressed="${f.on}"><span class="hb-inst-sw"></span><span class="hb-inst-name">${esc(f.label)}</span><span class="hb-inst-score">${Math.round(f.score * 100)}%</span></button></li>`).join("")}</ul></div>`
379
+ : `<p class="hb-lay-empty-note">${s.ready ? (studio.hasEverything ? "find every object at once, or press a thing on the picture." : "press a thing to cut it out.") : "nothing yet. open an image or try the sample."}</p>` +
380
+ (s.ready && studio.hasEverything && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
381
+ html += s.ready ? `<div class="hb-kv"><span class="hb-label">mask keeps</span><span class="hb-readout">${Math.round(s.coverage * 100)}%</span></div>` : "";
382
+ }
383
+ else if (part === "mask") {
384
+ html =
385
+ `<div class="hb-seg is-toggle" role="group" aria-label="mode">${["add", "erase"].map((m) => `<button type="button" data-mode="${m}" class="${s.mode === m ? "is-on" : ""}" aria-pressed="${s.mode === m}">${m}<span class="hb-mask-key" aria-hidden="true">x</span></button>`).join("")}</div>` +
386
+ (s.tool === "brush" || s.tool === "eraser" ? `<label class="hb-field"><span class="hb-label">brush, ${s.size} px</span><input class="hb-range" type="range" min="4" max="160" step="2" value="${s.size}" data-size></label>` : "") +
387
+ (s.tool === "wand" || s.tool === "flood" ? `<label class="hb-field"><span class="hb-label">reach, ${s.tolerance}</span><input class="hb-range" type="range" min="0" max="100" step="1" value="${s.tolerance}" data-tol></label>` : "") +
388
+ (s.coverage > 0 ? `<div class="hb-toolbar"><button type="button" class="hb-btn" data-op="smooth">smooth</button><button type="button" class="hb-btn" data-op="expand">expand</button><button type="button" class="hb-btn" data-op="shrink">shrink</button><button type="button" class="hb-btn" data-op="invert">invert</button><button type="button" class="hb-btn" data-op="clear">clear</button></div>` : "");
389
+ }
390
+ else if (part === "saved") {
391
+ html =
392
+ (s.coverage > 0 ? `<div class="hb-toolbar"><button type="button" class="hb-btn" data-op="save">save this mask</button></div>` : "") +
393
+ (s.saved.length
394
+ ? `<div class="hb-inst"><ul class="hb-inst-list">${s.saved.map((m) => `<li class="hb-inst-row"><button type="button" class="hb-inst-pick" data-restore="${m.id}"><img class="hb-inst-sw" src="${m.thumb}" alt=""><span class="hb-inst-name">${esc(m.name)}</span><span class="hb-inst-score">${Math.round(m.coverage * 100)}%</span></button><button type="button" class="hb-inst-act" data-forget="${m.id}" aria-label="forget ${esc(m.name)}" title="forget">${ICON.x}</button></li>`).join("")}</ul></div>`
395
+ : `<p class="hb-lay-empty-note">no saved masks. save one to come back to it.</p>`);
396
+ }
397
+ else {
398
+ html =
399
+ s.coverage > 0
400
+ ? `<div class="hb-toolbar" role="group" aria-label="export"><button type="button" class="hb-btn" data-ex="cutout">cutout png</button><button type="button" class="hb-btn" data-ex="alpha">mask png</button><button type="button" class="hb-btn" data-ex="matte">matte png</button></div>`
401
+ : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
402
+ }
403
+ if (html !== last)
404
+ host.innerHTML = last = html;
405
+ };
406
+ l.on(host, "click", (e) => {
407
+ const t = e.target;
408
+ const f = t.closest("[data-found]");
409
+ if (f)
410
+ return studio.toggleFound(Number(f.dataset.found));
411
+ const m = t.closest("[data-mode]");
412
+ if (m)
413
+ return studio.setMode(m.dataset.mode);
414
+ const op = t.closest("[data-op]")?.dataset.op;
415
+ if (op === "invert")
416
+ return studio.invert();
417
+ if (op === "clear")
418
+ return studio.clear();
419
+ if (op === "smooth")
420
+ return studio.smooth();
421
+ if (op === "expand")
422
+ return studio.expand();
423
+ if (op === "shrink")
424
+ return studio.shrink();
425
+ if (op === "save")
426
+ return studio.save();
427
+ const restore = t.closest("[data-restore]");
428
+ if (restore)
429
+ return studio.restore(Number(restore.dataset.restore));
430
+ const forget = t.closest("[data-forget]");
431
+ if (forget)
432
+ return studio.forget(Number(forget.dataset.forget));
433
+ const ex = t.closest("[data-ex]");
434
+ if (ex) {
435
+ const kind = ex.dataset.ex;
436
+ return void studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
437
+ }
438
+ if (t.closest("[data-all]"))
439
+ void studio.everything();
440
+ });
441
+ l.on(host, "input", (e) => {
442
+ const i = e.target;
443
+ if (i.dataset.size !== undefined)
444
+ studio.setSize(Number(i.value));
445
+ if (i.dataset.tol !== undefined)
446
+ studio.setTolerance(Number(i.value));
447
+ });
448
+ l.add(studio.subscribe(draw));
449
+ return { dispose: () => l.off() };
450
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * ModelSelect in the DOM: the closed line (or the bar chip) with its one
3
+ * pink "load, <size>", and the sheet in a drawer with search, the three
4
+ * filters, grouped rows, options and the sheet's own "your own" forms. Rows come from
5
+ * useModelPick; hackbuild-ui modelSelect, modelSheet and drawer draw them.
6
+ */
7
+ import { type ModelRow } from "@virgilvox/hackbuild-ui/vanilla";
8
+ import { type Mounted } from "./dom.js";
9
+ import type { JobsPick, ModelPick } from "./pick.js";
10
+ /** The sheet of one pick, in a drawer on the body. Opens on `open()`. */
11
+ export declare function pickSheet(pick: ModelPick): Mounted & {
12
+ open(): void;
13
+ };
14
+ /** Options for `mountModelSelect`: the one line or the chip variant, and whether to draw the load button. */
15
+ export interface ModelSelectOptions {
16
+ /** "line" (default): the one line and the pink load. "chip": the one model chip of the bar. */
17
+ variant?: "line" | "chip";
18
+ /** Draw the pink load. Off on a gate, whose own button is the pink action. */
19
+ go?: boolean;
20
+ }
21
+ /** The closed picker over a host; pressing it opens the sheet. */
22
+ export declare function mountModelSelect(host: HTMLElement, pick: ModelPick, o?: ModelSelectOptions): Mounted;
23
+ /** The words of a gate's one pink button for a pick: "load, 1.7 gb", then "ready". */
24
+ export declare function gateWords(row: ModelRow | undefined): string;
25
+ /** Several jobs: one line per job, presets with totals, and one pink "load all, <total>". */
26
+ export declare function mountModelJobs(host: HTMLElement, jobs: JobsPick, o?: {
27
+ go?: boolean;
28
+ }): Mounted;