@hackbuild/ai-views 0.1.13 → 0.1.14

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.
@@ -12,166 +12,11 @@
12
12
  * zoom; a page that loads models on demand hears `onWant` when a tool needs
13
13
  * one.
14
14
  */
15
- import { type MaskMode, type MaskOutput, type MaskPixels, type MaskTool } from "@virgilvox/hackbuild-ui/vanilla";
16
- import { type Mounted } from "./dom.js";
17
- /** One object a segment model found: a mask in image pixels (0 or 255), its word and score. */
18
- export interface FoundMask {
19
- mask: Uint8Array;
20
- label: string;
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;
38
- }
39
- /** The segment models a mask studio calls: a click segment for one point and a segment everything. */
40
- export interface MaskModels {
41
- /** Click segment: the mask under one point, in image pixels. */
42
- segment?: (image: MaskPixels, point: {
43
- x: number;
44
- y: number;
45
- }) => Promise<Uint8Array | null>;
46
- /** Segment everything: every object at once, with the decode settings when the model takes them. */
47
- everything?: (image: MaskPixels, o?: MaskEverythingOptions) => Promise<FoundMask[]>;
48
- }
49
- /** A mask studio tool: the click segment point or one of the hackbuild-ui mask tools. */
50
- export type StudioTool = "point" | MaskTool;
51
- /**
52
- * What a mask studio shows: tool, mode, sizes, undo state, coverage, zoom, found and saved masks,
53
- * image size and the last error.
54
- */
55
- export interface StudioState {
56
- ready: boolean;
57
- tool: StudioTool;
58
- mode: MaskMode;
59
- size: number;
60
- tolerance: number;
61
- canUndo: boolean;
62
- canRedo: boolean;
63
- coverage: number;
64
- zoom: number;
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;
71
- found: (FoundMask & {
72
- on: boolean;
73
- colour: string;
74
- hidden: boolean;
75
- })[];
76
- /** Masks put aside with a name and a small preview, newest first. */
77
- saved: {
78
- id: number;
79
- name: string;
80
- thumb: string;
81
- coverage: number;
82
- }[];
83
- width: number;
84
- height: number;
85
- /** The last failure, in words. */
86
- error: string;
87
- }
88
- /**
89
- * A mounted mask studio: image, tools, undo, grow and shrink, saved masks, found objects, export,
90
- * and a subscription to its state.
91
- */
92
- export interface MaskStudio extends Mounted {
93
- setImage(src: string | HTMLImageElement | HTMLCanvasElement | ImageBitmap | MaskPixels): Promise<void>;
94
- setTool(t: StudioTool): void;
95
- setMode(m: MaskMode): void;
96
- setSize(px: number): void;
97
- setTolerance(pct: number): void;
98
- undo(): void;
99
- redo(): void;
100
- invert(): void;
101
- clear(): void;
102
- /** Grow, shrink or round off the mask, one undo step each. */
103
- expand(px?: number): void;
104
- shrink(px?: number): void;
105
- smooth(r?: number): void;
106
- /** Put the current mask aside; restore puts it back as one undo step. */
107
- save(name?: string): void;
108
- restore(id: number): void;
109
- forget(id: number): void;
110
- /** The current mask as ImageData (alpha by default), null before an image. */
111
- mask(kind?: MaskOutput): ImageData | null;
112
- zoom(dir: 1 | -1 | 0): 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>;
131
- /** The click segment model at a point in image pixels, as a press with the point tool. */
132
- cutAt(x: number, y: number, mode?: MaskMode): Promise<void>;
133
- /** Add or take out one found object. */
134
- toggleFound(index: number): void;
135
- /** The mask, matte, cutout or inverse matte as a png Blob. */
136
- exportAs(kind: MaskOutput | "inverse"): Promise<Blob | null>;
137
- hasEverything: boolean;
138
- hasSegment: boolean;
139
- /** The page loads models on demand (`onWant`), so the model tools show before their models. */
140
- canWant: boolean;
141
- state(): StudioState;
142
- subscribe(fn: (s: StudioState) => void): () => void;
143
- setModels(m: MaskModels): void;
144
- /** Open the file picker. */
145
- pick(): void;
146
- }
147
- /**
148
- * Options for `mountMaskStudio`: the segment models, empty state words, a sample button and the
149
- * export file name.
150
- */
151
- export interface MaskStudioOptions {
152
- models?: MaskModels;
153
- title?: string;
154
- note?: string;
155
- sampleLabel?: string;
156
- onSample?: () => void;
157
- /** Name of exported files, without extension. */
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;
164
- }
15
+ export { mountMaskTools, mountMaskVerbs, mountMaskRack } from "./mask-parts.js";
16
+ import type { MaskStudio, MaskStudioOptions } from "./mask-types.js";
17
+ export type { FoundMask, StudioView, MaskEverythingOptions, MaskModels, StudioTool, StudioState, MaskStudio, MaskStudioOptions } from "./mask-types.js";
165
18
  /**
166
19
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
167
20
  * and lasso tools or a segment model.
168
21
  */
169
22
  export declare function mountMaskStudio(host: HTMLElement, o?: MaskStudioOptions): MaskStudio;
170
- /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
171
- export declare function mountMaskTools(host: HTMLElement, studio: MaskStudio): Mounted;
172
- /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
173
- export declare function mountMaskVerbs(host: HTMLElement, studio: MaskStudio): Mounted;
174
- /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
175
- export declare function mountMaskRack(host: HTMLElement, studio: MaskStudio, part: "found" | "mask" | "saved" | "export", o?: {
176
- name?: string;
177
- }): Mounted;
@@ -12,51 +12,14 @@
12
12
  * zoom; a page that loads models on demand hears `onWant` when a tool needs
13
13
  * one.
14
14
  */
15
- import { INSTANCE_COLOURS, MASK_TOOLS, invertMask, maskEditor, maskRgba, parseRgb, strokeIcon } from "@virgilvox/hackbuild-ui/vanilla";
16
- import { ICON, download, esc, listeners, show } from "./dom.js";
15
+ import { INSTANCE_COLOURS, MASK_TOOLS, invertMask, maskEditor, maskRgba } from "@virgilvox/hackbuild-ui/vanilla";
16
+ import { download, esc, listeners, show } from "./dom.js";
17
+ import { pngOf, pixelsOf, thumbOf } from "./mask-pixels.js";
18
+ import { maskOverlay } from "./mask-overlay.js";
19
+ import { pinchZoom, studioKeys } from "./mask-input.js";
20
+ export { mountMaskTools, mountMaskVerbs, mountMaskRack } from "./mask-parts.js";
17
21
  const ZOOMS = [0.5, 0.75, 1, 1.5, 2, 3, 4];
18
22
  const clampZoom = (z) => Math.max(0.25, Math.min(6, z));
19
- /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
20
- function tintInto(rgba, mask, rgb, alpha) {
21
- for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
22
- if (!mask[i])
23
- continue;
24
- rgba[j] = rgb[0];
25
- rgba[j + 1] = rgb[1];
26
- rgba[j + 2] = rgb[2];
27
- rgba[j + 3] = alpha;
28
- }
29
- }
30
- /** ImageData to a png Blob. */
31
- function pngOf(img) {
32
- const c = document.createElement("canvas");
33
- c.width = img.width;
34
- c.height = img.height;
35
- c.getContext("2d")?.putImageData(img, 0, 0);
36
- return new Promise((ok) => c.toBlob((b) => ok(b), "image/png"));
37
- }
38
- /** Pixels of a drawable, for a model. */
39
- function pixelsOf(src) {
40
- const c = document.createElement("canvas");
41
- c.width = src.width;
42
- c.height = src.height;
43
- const g = c.getContext("2d");
44
- g.drawImage(src, 0, 0);
45
- const d = g.getImageData(0, 0, c.width, c.height);
46
- return { width: d.width, height: d.height, data: d.data };
47
- }
48
- /** A 48 px wide preview of a matte, as a data url. */
49
- function thumbOf(img) {
50
- const c = document.createElement("canvas");
51
- c.width = img.width;
52
- c.height = img.height;
53
- c.getContext("2d")?.putImageData(img, 0, 0);
54
- const t = document.createElement("canvas");
55
- t.width = 48;
56
- t.height = Math.max(1, Math.round((48 * img.height) / Math.max(1, img.width)));
57
- t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
58
- return t.toDataURL("image/png");
59
- }
60
23
  /**
61
24
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
62
25
  * and lasso tools or a segment model.
@@ -118,60 +81,17 @@ export function mountMaskStudio(host, o = {}) {
118
81
  paint();
119
82
  };
120
83
  // the paint over the canvas: the mask alone, the found objects in colour, or the pointer's preview
121
- let painted = "";
122
- let frameReq = 0;
123
- const paint = () => {
124
- if (frameReq)
125
- return;
126
- frameReq = typeof requestAnimationFrame === "function" ? requestAnimationFrame(drawOver) : (drawOver(), 0);
127
- };
128
- const drawOver = () => {
129
- frameReq = 0;
130
- const w = ed?.width ?? 0;
131
- const h = ed?.height ?? 0;
132
- const g = over.getContext("2d");
133
- if (!g || !w || !h || !pixels)
134
- return;
135
- if (over.width !== w || over.height !== h) {
136
- over.width = w;
137
- over.height = h;
138
- }
139
- const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? editor.state.coverage + ":" + (ed?.canUndo ? 1 : 0) : ""}:${found.map((f) => (f.hidden ? 0 : 1)).join("")}`;
140
- if (view === "composite" && hover < 0 && !preview) {
141
- if (painted !== "clear")
142
- g.clearRect(0, 0, w, h);
143
- painted = "clear";
144
- return;
145
- }
146
- if (key === painted && view !== "mask")
147
- return;
148
- painted = key;
149
- if (view === "mask") {
150
- g.putImageData(new ImageData(maskRgba(editor.mask(), "matte"), w, h), 0, 0);
151
- return;
152
- }
153
- const rgba = new Uint8ClampedArray(w * h * 4);
154
- if (view === "instances")
155
- found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, parseRgb(f.colour), 150));
156
- const hot = hover >= 0 ? found[hover] : undefined;
157
- if (hot)
158
- tintInto(rgba, hot.mask, parseRgb(hot.colour), 220);
159
- else if (preview)
160
- tintInto(rgba, preview, [254, 3, 134], 110);
161
- g.putImageData(new ImageData(rgba, w, h), 0, 0);
162
- if (view === "instances") {
163
- g.lineWidth = Math.max(1, w / 400);
164
- g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
165
- for (const f of found) {
166
- if (f.hidden || !f.box)
167
- continue;
168
- g.strokeStyle = f.colour;
169
- g.fillStyle = f.colour;
170
- g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
171
- g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
172
- }
173
- }
174
- };
84
+ const { paint } = maskOverlay(over, () => ({
85
+ width: ed?.width ?? 0,
86
+ height: ed?.height ?? 0,
87
+ hasImage: !!pixels,
88
+ view,
89
+ hover,
90
+ preview,
91
+ found,
92
+ maskKey: `${editor.state.coverage}:${ed?.canUndo ? 1 : 0}`,
93
+ mask: () => editor.mask(),
94
+ }));
175
95
  const editor = maskEditor(canvas, { tool: tool === "point" ? "wand" : tool, onError: (e) => ((error = `the image did not load: ${e.message}`), emit()) });
176
96
  l.add(editor.subscribe((s) => ((ed = s), emit())));
177
97
  // 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
@@ -289,73 +209,16 @@ export function mountMaskStudio(host, o = {}) {
289
209
  canvas.addEventListener("pointermove", onHover);
290
210
  canvas.addEventListener("pointerleave", offHover);
291
211
  l.add(() => (canvas.removeEventListener("pointermove", onHover), canvas.removeEventListener("pointerleave", offHover)));
292
- // two fingers pinch the zoom; ctrl and the wheel (a trackpad pinch) do the same
293
- const touches = new Map();
294
- let pinch = null;
295
- const spread = () => {
296
- const [a, b] = [...touches.values()];
297
- return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
298
- };
299
- l.on(well, "pointerdown", (e) => {
300
- const pe = e;
301
- if (pe.pointerType !== "touch")
302
- return;
303
- touches.set(pe.pointerId, { x: pe.clientX, y: pe.clientY });
304
- if (touches.size === 2) {
305
- editor.cancel();
306
- pinch = { d: spread() || 1, z: zoom };
307
- }
308
- });
309
- l.on(well, "pointermove", (e) => {
310
- const pe = e;
311
- if (!touches.has(pe.pointerId))
312
- return;
313
- touches.set(pe.pointerId, { x: pe.clientX, y: pe.clientY });
314
- if (pinch && touches.size === 2)
315
- studioApi.zoomTo(pinch.z * (spread() / pinch.d));
316
- });
317
- const lift = (e) => {
318
- touches.delete(e.pointerId);
319
- if (touches.size < 2)
320
- pinch = null;
321
- };
322
- l.on(well, "pointerup", lift);
323
- l.on(well, "pointercancel", lift);
324
- l.on(well, "wheel", (e) => {
325
- const we = e;
326
- if (!we.ctrlKey || !ed?.ready)
327
- return;
328
- we.preventDefault();
329
- studioApi.zoomTo(zoom * Math.exp(-we.deltaY / 200));
330
- });
331
- // the page keys: open, export, undo, invert, clear, zoom; on the document, so they come before a page's window keys
332
- l.on(document, "keydown", (e) => {
333
- const ke = e;
334
- if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]"))
335
- return;
336
- const k = ke.key.toLowerCase();
337
- const cmd = ke.ctrlKey || ke.metaKey;
338
- if (cmd && k === "o")
339
- return ke.preventDefault(), input.click();
340
- if (!ed?.ready)
341
- return;
342
- // the canvas takes undo itself while focused; anywhere else on the page it lands here
343
- if (cmd && (k === "z" || k === "y"))
344
- return ke.preventDefault(), void (k === "y" || ke.shiftKey ? editor.redo() : editor.undo());
345
- if (cmd && k === "s")
346
- return ke.preventDefault(), void studioApi.exportAs(ke.shiftKey ? "cutout" : "matte").then((b) => b && download(`${o.name ?? "mask"}-${ke.shiftKey ? "cutout" : "matte"}.png`, b));
347
- if (cmd && k === "i")
348
- return ke.preventDefault(), editor.invert();
349
- if (cmd)
350
- return;
351
- if (k === "delete")
352
- return ke.preventDefault(), editor.clear();
353
- if (k === "+" || k === "=")
354
- return studioApi.zoom(1);
355
- if (k === "-")
356
- return studioApi.zoom(-1);
357
- if (k === "0")
358
- return studioApi.zoom(0);
212
+ pinchZoom(l, well, { zoom: () => zoom, zoomTo: (z) => studioApi.zoomTo(z), cancel: () => editor.cancel(), ready: () => !!ed?.ready });
213
+ studioKeys(l, {
214
+ ready: () => !!ed?.ready,
215
+ open: () => input.click(),
216
+ undo: () => void editor.undo(),
217
+ redo: () => void editor.redo(),
218
+ invert: () => editor.invert(),
219
+ clear: () => editor.clear(),
220
+ save: (kind) => void studioApi.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b)),
221
+ zoom: (dir) => studioApi.zoom(dir),
359
222
  });
360
223
  // capture, so it runs before the editor's own handler on the canvas
361
224
  canvas.addEventListener("pointerdown", onPoint, true);
@@ -592,157 +455,3 @@ export function mountMaskStudio(host, o = {}) {
592
455
  emit();
593
456
  return studioApi;
594
457
  }
595
- /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
596
- export function mountMaskTools(host, studio) {
597
- const l = listeners();
598
- const draw = (s) => {
599
- const tools = [
600
- ...(studio.hasSegment || studio.canWant ? [{ id: "point", label: "cut out a thing", key: "a", icon: "crosshairs" }] : []),
601
- ...MASK_TOOLS.map((t) => ({ id: t.id, label: t.label, key: t.key, icon: t.icon })),
602
- ];
603
- 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("");
604
- };
605
- l.on(host, "click", (e) => {
606
- const t = e.target.closest("[data-tool]");
607
- if (t)
608
- studio.setTool(t.dataset.tool);
609
- });
610
- l.on(document, "keydown", (e) => {
611
- const ke = e;
612
- if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]"))
613
- studio.setTool("point");
614
- });
615
- l.add(studio.subscribe(draw));
616
- return { dispose: () => l.off() };
617
- }
618
- /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
619
- export function mountMaskVerbs(host, studio) {
620
- const l = listeners();
621
- let last = "";
622
- const draw = (s) => {
623
- const html = s.ready
624
- ? `${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>` : ""}` +
625
- // zoom out and fit show once zoomed in, so the row stays short
626
- (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>` : "") +
627
- `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>` +
628
- (s.coverage > 0 || s.found.length
629
- ? `<div class="hb-seg is-toggle" role="group" aria-label="view">${["composite", "mask", "instances"].filter((v) => v !== "instances" || s.found.length).map((v) => `<button type="button" data-view="${v}" class="${s.view === v ? "is-on" : ""}" aria-pressed="${s.view === v}">${v === "instances" ? "objects" : v === "composite" ? "picture" : "mask"}</button>`).join("")}</div>`
630
- : "")
631
- : "";
632
- if (html !== last)
633
- host.innerHTML = last = html;
634
- host.hidden = !html;
635
- };
636
- l.on(host, "click", (e) => {
637
- const view = e.target.closest("[data-view]")?.dataset.view;
638
- if (view)
639
- return studio.setView(view);
640
- const v = e.target.closest("[data-v]")?.dataset.v;
641
- if (v === "undo")
642
- studio.undo();
643
- else if (v === "redo")
644
- studio.redo();
645
- else if (v === "in")
646
- studio.zoom(1);
647
- else if (v === "out")
648
- studio.zoom(-1);
649
- else if (v === "fit")
650
- studio.zoom(0);
651
- });
652
- l.add(studio.subscribe(draw));
653
- return { dispose: () => l.off() };
654
- }
655
- /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
656
- export function mountMaskRack(host, studio, part, o = {}) {
657
- const l = listeners();
658
- let last = "";
659
- const draw = (s) => {
660
- let html = "";
661
- if (part === "found") {
662
- html = s.found.length
663
- ? `<div class="hb-inst"><p class="hb-inst-empty">${s.found.length} found, ${s.found.filter((f) => f.on).length} in the mask</p><div class="hb-toolbar hb-inst-foot"><button type="button" class="hb-btn hb-btn-go" data-op="merge">merge all</button><button type="button" class="hb-btn" data-op="unfind">clear all</button></div><ul class="hb-inst-list">${s.found.map((f, i) => `<li class="hb-inst-row${f.on || s.hover === i ? " is-on" : ""}${f.hidden ? " is-hidden" : ""}" 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.min(100, Math.round(f.score * 100))}%</span></button><button type="button" class="hb-inst-act" data-show="${i}" aria-pressed="${!f.hidden}" aria-label="${f.hidden ? "show" : "hide"} ${esc(f.label)}" title="${f.hidden ? "show" : "hide"}">${strokeIcon("eye", { size: 14 })}</button><button type="button" class="hb-inst-act" data-drop="${i}" aria-label="delete ${esc(f.label)}" title="delete">${ICON.trash}</button></li>`).join("")}</ul></div>`
664
- : `<p class="hb-lay-empty-note">${s.ready ? (studio.hasEverything || studio.canWant ? "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>` +
665
- (s.ready && (studio.hasEverything || studio.canWant) && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
666
- 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>` : "";
667
- }
668
- else if (part === "mask") {
669
- html =
670
- `<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>` +
671
- (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>` : "") +
672
- (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>` : "") +
673
- (s.tool === "wand" ? `<label class="hb-check"><input type="checkbox" data-contig${s.contiguous ? " checked" : ""}><span>touching pixels only</span></label>` : "") +
674
- (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>` : "");
675
- }
676
- else if (part === "saved") {
677
- html =
678
- (s.coverage > 0 ? `<div class="hb-toolbar"><button type="button" class="hb-btn" data-op="save">save this mask</button></div>` : "") +
679
- (s.saved.length
680
- ? `<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>`
681
- : `<p class="hb-lay-empty-note">no saved masks. save one to come back to it.</p>`);
682
- }
683
- else {
684
- html =
685
- s.coverage > 0
686
- ? `<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><button type="button" class="hb-btn" data-ex="inverse">inverse png</button></div>`
687
- : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
688
- }
689
- if (html !== last)
690
- host.innerHTML = last = html;
691
- };
692
- l.on(host, "click", (e) => {
693
- const t = e.target;
694
- const f = t.closest("[data-found]");
695
- if (f)
696
- return studio.toggleFound(Number(f.dataset.found));
697
- const m = t.closest("[data-mode]");
698
- if (m)
699
- return studio.setMode(m.dataset.mode);
700
- const show = t.closest("[data-show]");
701
- if (show)
702
- return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
703
- const drop = t.closest("[data-drop]");
704
- if (drop)
705
- return studio.removeFound(Number(drop.dataset.drop));
706
- const op = t.closest("[data-op]")?.dataset.op;
707
- if (op === "merge")
708
- return studio.mergeFound();
709
- if (op === "unfind")
710
- return studio.clearFound();
711
- if (op === "invert")
712
- return studio.invert();
713
- if (op === "clear")
714
- return studio.clear();
715
- if (op === "smooth")
716
- return studio.smooth();
717
- if (op === "expand")
718
- return studio.expand();
719
- if (op === "shrink")
720
- return studio.shrink();
721
- if (op === "save")
722
- return studio.save();
723
- const restore = t.closest("[data-restore]");
724
- if (restore)
725
- return studio.restore(Number(restore.dataset.restore));
726
- const forget = t.closest("[data-forget]");
727
- if (forget)
728
- return studio.forget(Number(forget.dataset.forget));
729
- const ex = t.closest("[data-ex]");
730
- if (ex) {
731
- const kind = ex.dataset.ex;
732
- return void studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
733
- }
734
- if (t.closest("[data-all]"))
735
- void studio.everything();
736
- });
737
- l.on(host, "input", (e) => {
738
- const i = e.target;
739
- if (i.dataset.size !== undefined)
740
- studio.setSize(Number(i.value));
741
- if (i.dataset.tol !== undefined)
742
- studio.setTolerance(Number(i.value));
743
- if (i.dataset.contig !== undefined)
744
- studio.setContiguous(i.checked);
745
- });
746
- l.add(studio.subscribe(draw));
747
- return { dispose: () => l.off() };
748
- }