@hackbuild/ai-views 0.1.13 → 0.1.15

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
@@ -255,7 +255,7 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
255
255
  | file | gzip (measured) | ceiling |
256
256
  |---|---|---|
257
257
  | `dist/index.js` (main entry, imports external) | 21,601 bytes | 22,681 bytes |
258
- | `dist/single/elements.iife.js` (single file build) | 100,338 bytes | 105,354 bytes |
258
+ | `dist/single/elements.iife.js` (single file build) | 100,802 bytes | 105,842 bytes |
259
259
 
260
260
  Measured 2026-11-30 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
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The studio's zoom by hand and its page keys. Two fingers pinch the zoom,
3
+ * ctrl and the wheel (a trackpad pinch) do the same. The keys open, export,
4
+ * undo, invert, clear and zoom; they listen on the document, so they come
5
+ * before a page's window keys, and typing in a field is left alone.
6
+ */
7
+ import type { listeners } from "./dom.js";
8
+ type Listeners = ReturnType<typeof listeners>;
9
+ /** Pinch and ctrl wheel zoom on the well around the canvas. */
10
+ export declare function pinchZoom(l: Listeners, well: HTMLElement, z: {
11
+ zoom(): number;
12
+ zoomTo(z: number): void;
13
+ cancel(): void;
14
+ ready(): boolean;
15
+ }): void;
16
+ /** What the page keys do. */
17
+ export interface StudioKeys {
18
+ ready(): boolean;
19
+ open(): void;
20
+ undo(): void;
21
+ redo(): void;
22
+ invert(): void;
23
+ clear(): void;
24
+ /** ctrl s saves the matte, ctrl shift s the cutout. */
25
+ save(kind: "matte" | "cutout"): void;
26
+ zoom(dir: 1 | -1 | 0): void;
27
+ }
28
+ /** The page keys of a studio, on the document. */
29
+ export declare function studioKeys(l: Listeners, k: StudioKeys): void;
30
+ export {};
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The studio's zoom by hand and its page keys. Two fingers pinch the zoom,
3
+ * ctrl and the wheel (a trackpad pinch) do the same. The keys open, export,
4
+ * undo, invert, clear and zoom; they listen on the document, so they come
5
+ * before a page's window keys, and typing in a field is left alone.
6
+ */
7
+ /** Pinch and ctrl wheel zoom on the well around the canvas. */
8
+ export function pinchZoom(l, well, z) {
9
+ const touches = new Map();
10
+ let pinch = null;
11
+ const spread = () => {
12
+ const [a, b] = [...touches.values()];
13
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
14
+ };
15
+ l.on(well, "pointerdown", (e) => {
16
+ const pe = e;
17
+ if (pe.pointerType !== "touch")
18
+ return;
19
+ touches.set(pe.pointerId, { x: pe.clientX, y: pe.clientY });
20
+ if (touches.size === 2) {
21
+ z.cancel();
22
+ pinch = { d: spread() || 1, z: z.zoom() };
23
+ }
24
+ });
25
+ l.on(well, "pointermove", (e) => {
26
+ const pe = e;
27
+ if (!touches.has(pe.pointerId))
28
+ return;
29
+ touches.set(pe.pointerId, { x: pe.clientX, y: pe.clientY });
30
+ if (pinch && touches.size === 2)
31
+ z.zoomTo(pinch.z * (spread() / pinch.d));
32
+ });
33
+ const lift = (e) => {
34
+ touches.delete(e.pointerId);
35
+ if (touches.size < 2)
36
+ pinch = null;
37
+ };
38
+ l.on(well, "pointerup", lift);
39
+ l.on(well, "pointercancel", lift);
40
+ l.on(well, "wheel", (e) => {
41
+ const we = e;
42
+ if (!we.ctrlKey || !z.ready())
43
+ return;
44
+ we.preventDefault();
45
+ z.zoomTo(z.zoom() * Math.exp(-we.deltaY / 200));
46
+ });
47
+ }
48
+ /** The page keys of a studio, on the document. */
49
+ export function studioKeys(l, k) {
50
+ l.on(document, "keydown", (e) => {
51
+ const ke = e;
52
+ if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]"))
53
+ return;
54
+ const key = ke.key.toLowerCase();
55
+ const cmd = ke.ctrlKey || ke.metaKey;
56
+ if (cmd && key === "o")
57
+ return ke.preventDefault(), k.open();
58
+ if (!k.ready())
59
+ return;
60
+ // the canvas takes undo itself while focused; anywhere else on the page it lands here
61
+ if (cmd && (key === "z" || key === "y"))
62
+ return ke.preventDefault(), key === "y" || ke.shiftKey ? k.redo() : k.undo();
63
+ if (cmd && key === "s")
64
+ return ke.preventDefault(), k.save(ke.shiftKey ? "cutout" : "matte");
65
+ if (cmd && key === "i")
66
+ return ke.preventDefault(), k.invert();
67
+ if (cmd)
68
+ return;
69
+ if (key === "delete")
70
+ return ke.preventDefault(), k.clear();
71
+ if (key === "+" || key === "=")
72
+ return k.zoom(1);
73
+ if (key === "-")
74
+ return k.zoom(-1);
75
+ if (key === "0")
76
+ return k.zoom(0);
77
+ });
78
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The paint over the studio's canvas: the mask alone, the found objects in
3
+ * colour with their boxes and words, or the pointer's preview of a cut.
4
+ * One repaint per animation frame, skipped when nothing it shows changed.
5
+ */
6
+ import type { StudioState, StudioView } from "./mask-types.js";
7
+ /** What the overlay shows, read when it repaints. */
8
+ export interface OverlayScene {
9
+ width: number;
10
+ height: number;
11
+ hasImage: boolean;
12
+ view: StudioView;
13
+ /** The found object under the pointer, or -1. */
14
+ hover: number;
15
+ /** The click cut the pointer would make, or null. */
16
+ preview: Uint8Array | null;
17
+ found: StudioState["found"];
18
+ /** Changes whenever the mask does. */
19
+ maskKey: string;
20
+ mask(): Uint8Array;
21
+ }
22
+ /** An overlay on a canvas; `paint` asks for a repaint on the next animation frame. */
23
+ export declare function maskOverlay(over: HTMLCanvasElement, scene: () => OverlayScene): {
24
+ paint(): void;
25
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The paint over the studio's canvas: the mask alone, the found objects in
3
+ * colour with their boxes and words, or the pointer's preview of a cut.
4
+ * One repaint per animation frame, skipped when nothing it shows changed.
5
+ */
6
+ import { maskRgba, parseRgb } from "@virgilvox/hackbuild-ui/vanilla";
7
+ import { tintInto } from "./mask-pixels.js";
8
+ /** An overlay on a canvas; `paint` asks for a repaint on the next animation frame. */
9
+ export function maskOverlay(over, scene) {
10
+ let painted = "";
11
+ let req = 0;
12
+ const draw = () => {
13
+ req = 0;
14
+ const s = scene();
15
+ const { width: w, height: h, view, hover, preview, found } = s;
16
+ const g = over.getContext("2d");
17
+ if (!g || !w || !h || !s.hasImage)
18
+ return;
19
+ if (over.width !== w || over.height !== h) {
20
+ over.width = w;
21
+ over.height = h;
22
+ }
23
+ const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? s.maskKey : ""}:${found.map((f) => (f.hidden ? 0 : 1)).join("")}`;
24
+ if (view === "composite" && hover < 0 && !preview) {
25
+ if (painted !== "clear")
26
+ g.clearRect(0, 0, w, h);
27
+ painted = "clear";
28
+ return;
29
+ }
30
+ if (key === painted && view !== "mask")
31
+ return;
32
+ painted = key;
33
+ if (view === "mask") {
34
+ g.putImageData(new ImageData(maskRgba(s.mask(), "matte"), w, h), 0, 0);
35
+ return;
36
+ }
37
+ const rgba = new Uint8ClampedArray(w * h * 4);
38
+ if (view === "instances")
39
+ found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, parseRgb(f.colour), 150));
40
+ const hot = hover >= 0 ? found[hover] : undefined;
41
+ if (hot)
42
+ tintInto(rgba, hot.mask, parseRgb(hot.colour), 220);
43
+ else if (preview)
44
+ tintInto(rgba, preview, [254, 3, 134], 110);
45
+ g.putImageData(new ImageData(rgba, w, h), 0, 0);
46
+ if (view !== "instances")
47
+ return;
48
+ g.lineWidth = Math.max(1, w / 400);
49
+ g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
50
+ for (const f of found) {
51
+ if (f.hidden || !f.box)
52
+ continue;
53
+ g.strokeStyle = f.colour;
54
+ g.fillStyle = f.colour;
55
+ g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
56
+ g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
57
+ }
58
+ };
59
+ return {
60
+ paint() {
61
+ if (req)
62
+ return;
63
+ req = typeof requestAnimationFrame === "function" ? requestAnimationFrame(draw) : (draw(), 0);
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The pieces around a mask studio, each mounted on its own host: the tool
3
+ * rail, the verb row on the canvas, and the rack of found objects, the mask
4
+ * and saved masks. Each reads the studio's state and calls its methods.
5
+ */
6
+ import { type Mounted } from "./dom.js";
7
+ import type { MaskStudio } from "./mask-types.js";
8
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
9
+ export declare function mountMaskTools(host: HTMLElement, studio: MaskStudio): Mounted;
10
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
11
+ export declare function mountMaskVerbs(host: HTMLElement, studio: MaskStudio): Mounted;
12
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
13
+ export declare function mountMaskRack(host: HTMLElement, studio: MaskStudio, part: "found" | "mask" | "saved" | "export", o?: {
14
+ name?: string;
15
+ }): Mounted;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The pieces around a mask studio, each mounted on its own host: the tool
3
+ * rail, the verb row on the canvas, and the rack of found objects, the mask
4
+ * and saved masks. Each reads the studio's state and calls its methods.
5
+ */
6
+ import { MASK_TOOLS, strokeIcon } from "@virgilvox/hackbuild-ui/vanilla";
7
+ import { ICON, download, esc, listeners } from "./dom.js";
8
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
9
+ export function mountMaskTools(host, studio) {
10
+ const l = listeners();
11
+ const draw = (s) => {
12
+ const tools = [
13
+ ...(studio.hasSegment || studio.canWant ? [{ id: "point", label: "cut out a thing", key: "a", icon: "crosshairs" }] : []),
14
+ ...MASK_TOOLS.map((t) => ({ id: t.id, label: t.label, key: t.key, icon: t.icon })),
15
+ ];
16
+ 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("");
17
+ };
18
+ l.on(host, "click", (e) => {
19
+ const t = e.target.closest("[data-tool]");
20
+ if (t)
21
+ studio.setTool(t.dataset.tool);
22
+ });
23
+ l.on(document, "keydown", (e) => {
24
+ const ke = e;
25
+ if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]"))
26
+ studio.setTool("point");
27
+ });
28
+ l.add(studio.subscribe(draw));
29
+ return { dispose: () => l.off() };
30
+ }
31
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
32
+ export function mountMaskVerbs(host, studio) {
33
+ const l = listeners();
34
+ let last = "";
35
+ const draw = (s) => {
36
+ const html = s.ready
37
+ ? `${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>` : ""}` +
38
+ // zoom out and fit show once zoomed in, so the row stays short
39
+ (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>` : "") +
40
+ `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>` +
41
+ (s.coverage > 0 || s.found.length
42
+ ? `<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>`
43
+ : "")
44
+ : "";
45
+ if (html !== last)
46
+ host.innerHTML = last = html;
47
+ host.hidden = !html;
48
+ };
49
+ l.on(host, "click", (e) => {
50
+ const view = e.target.closest("[data-view]")?.dataset.view;
51
+ if (view)
52
+ return studio.setView(view);
53
+ const v = e.target.closest("[data-v]")?.dataset.v;
54
+ if (v === "undo")
55
+ studio.undo();
56
+ else if (v === "redo")
57
+ studio.redo();
58
+ else if (v === "in")
59
+ studio.zoom(1);
60
+ else if (v === "out")
61
+ studio.zoom(-1);
62
+ else if (v === "fit")
63
+ studio.zoom(0);
64
+ });
65
+ l.add(studio.subscribe(draw));
66
+ return { dispose: () => l.off() };
67
+ }
68
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
69
+ export function mountMaskRack(host, studio, part, o = {}) {
70
+ const l = listeners();
71
+ let last = "";
72
+ const draw = (s) => {
73
+ let html = "";
74
+ if (part === "found") {
75
+ html = s.found.length
76
+ ? `<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>`
77
+ : `<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>` +
78
+ (s.ready && (studio.hasEverything || studio.canWant) && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
79
+ 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>` : "";
80
+ }
81
+ else if (part === "mask") {
82
+ html =
83
+ `<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>` +
84
+ (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>` : "") +
85
+ (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>` : "") +
86
+ (s.tool === "wand" ? `<label class="hb-check"><input type="checkbox" data-contig${s.contiguous ? " checked" : ""}><span>touching pixels only</span></label>` : "") +
87
+ (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>` : "");
88
+ }
89
+ else if (part === "saved") {
90
+ html =
91
+ (s.coverage > 0 ? `<div class="hb-toolbar"><button type="button" class="hb-btn" data-op="save">save this mask</button></div>` : "") +
92
+ (s.saved.length
93
+ ? `<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>`
94
+ : `<p class="hb-lay-empty-note">no saved masks. save one to come back to it.</p>`);
95
+ }
96
+ else {
97
+ html =
98
+ s.coverage > 0
99
+ ? `<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>`
100
+ : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
101
+ }
102
+ if (html !== last)
103
+ host.innerHTML = last = html;
104
+ };
105
+ l.on(host, "click", (e) => {
106
+ const t = e.target;
107
+ const f = t.closest("[data-found]");
108
+ if (f)
109
+ return studio.toggleFound(Number(f.dataset.found));
110
+ const m = t.closest("[data-mode]");
111
+ if (m)
112
+ return studio.setMode(m.dataset.mode);
113
+ const show = t.closest("[data-show]");
114
+ if (show)
115
+ return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
116
+ const drop = t.closest("[data-drop]");
117
+ if (drop)
118
+ return studio.removeFound(Number(drop.dataset.drop));
119
+ const op = t.closest("[data-op]")?.dataset.op;
120
+ if (op === "merge")
121
+ return studio.mergeFound();
122
+ if (op === "unfind")
123
+ return studio.clearFound();
124
+ if (op === "invert")
125
+ return studio.invert();
126
+ if (op === "clear")
127
+ return studio.clear();
128
+ if (op === "smooth")
129
+ return studio.smooth();
130
+ if (op === "expand")
131
+ return studio.expand();
132
+ if (op === "shrink")
133
+ return studio.shrink();
134
+ if (op === "save")
135
+ return studio.save();
136
+ const restore = t.closest("[data-restore]");
137
+ if (restore)
138
+ return studio.restore(Number(restore.dataset.restore));
139
+ const forget = t.closest("[data-forget]");
140
+ if (forget)
141
+ return studio.forget(Number(forget.dataset.forget));
142
+ const ex = t.closest("[data-ex]");
143
+ if (ex) {
144
+ const kind = ex.dataset.ex;
145
+ return void studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
146
+ }
147
+ if (t.closest("[data-all]"))
148
+ void studio.everything();
149
+ });
150
+ l.on(host, "input", (e) => {
151
+ const i = e.target;
152
+ if (i.dataset.size !== undefined)
153
+ studio.setSize(Number(i.value));
154
+ if (i.dataset.tol !== undefined)
155
+ studio.setTolerance(Number(i.value));
156
+ if (i.dataset.contig !== undefined)
157
+ studio.setContiguous(i.checked);
158
+ });
159
+ l.add(studio.subscribe(draw));
160
+ return { dispose: () => l.off() };
161
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Canvas helpers of the mask studio: tint a mask into pixels, image data to
3
+ * a png, a drawable's pixels for a model, and a small preview of a matte.
4
+ */
5
+ import type { MaskPixels } from "@virgilvox/hackbuild-ui/vanilla";
6
+ /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
7
+ export declare function tintInto(rgba: Uint8ClampedArray, mask: Uint8Array, rgb: readonly number[], alpha: number): void;
8
+ /** ImageData to a png Blob. */
9
+ export declare function pngOf(img: ImageData): Promise<Blob | null>;
10
+ /** Pixels of a drawable, for a model. */
11
+ export declare function pixelsOf(src: CanvasImageSource & {
12
+ width: number;
13
+ height: number;
14
+ }): MaskPixels;
15
+ /** A 48 px wide preview of a matte, as a data url. */
16
+ export declare function thumbOf(img: ImageData): string;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Canvas helpers of the mask studio: tint a mask into pixels, image data to
3
+ * a png, a drawable's pixels for a model, and a small preview of a matte.
4
+ */
5
+ /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
6
+ export function tintInto(rgba, mask, rgb, alpha) {
7
+ for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
8
+ if (!mask[i])
9
+ continue;
10
+ rgba[j] = rgb[0];
11
+ rgba[j + 1] = rgb[1];
12
+ rgba[j + 2] = rgb[2];
13
+ rgba[j + 3] = alpha;
14
+ }
15
+ }
16
+ /** ImageData to a png Blob. */
17
+ export function pngOf(img) {
18
+ const c = document.createElement("canvas");
19
+ c.width = img.width;
20
+ c.height = img.height;
21
+ c.getContext("2d")?.putImageData(img, 0, 0);
22
+ return new Promise((ok) => c.toBlob((b) => ok(b), "image/png"));
23
+ }
24
+ /** Pixels of a drawable, for a model. */
25
+ export function pixelsOf(src) {
26
+ const c = document.createElement("canvas");
27
+ c.width = src.width;
28
+ c.height = src.height;
29
+ const g = c.getContext("2d");
30
+ g.drawImage(src, 0, 0);
31
+ const d = g.getImageData(0, 0, c.width, c.height);
32
+ return { width: d.width, height: d.height, data: d.data };
33
+ }
34
+ /** A 48 px wide preview of a matte, as a data url. */
35
+ export function thumbOf(img) {
36
+ const c = document.createElement("canvas");
37
+ c.width = img.width;
38
+ c.height = img.height;
39
+ c.getContext("2d")?.putImageData(img, 0, 0);
40
+ const t = document.createElement("canvas");
41
+ t.width = 48;
42
+ t.height = Math.max(1, Math.round((48 * img.height) / Math.max(1, img.width)));
43
+ t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
44
+ return t.toDataURL("image/png");
45
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The mask studio's contract: what a segment model returns, the models a
3
+ * page passes, the studio's state, its methods and its options.
4
+ */
5
+ import type { Mounted } from "./dom.js";
6
+ import type { MaskMode, MaskOutput, MaskPixels, MaskTool } from "@virgilvox/hackbuild-ui/vanilla";
7
+ /** One object a segment model found: a mask in image pixels (0 or 255), its word and score. */
8
+ export interface FoundMask {
9
+ mask: Uint8Array;
10
+ label: string;
11
+ score: number;
12
+ /** The box in image pixels, drawn in the found view when present. */
13
+ box?: {
14
+ x: number;
15
+ y: number;
16
+ w: number;
17
+ h: number;
18
+ };
19
+ }
20
+ /** What the canvas shows: the picture with the mask, the mask alone, or every found object in its colour. */
21
+ export type StudioView = "composite" | "mask" | "instances";
22
+ /** Decode settings for a segment everything model (FastSAM): confidence, overlap, smallest area, sigmoid. */
23
+ export interface MaskEverythingOptions {
24
+ confidence?: number;
25
+ iou?: number;
26
+ minArea?: number;
27
+ sigmoid?: boolean;
28
+ }
29
+ /** The segment models a mask studio calls: a click segment for one point and a segment everything. */
30
+ export interface MaskModels {
31
+ /** Click segment: the mask under one point, in image pixels. */
32
+ segment?: (image: MaskPixels, point: {
33
+ x: number;
34
+ y: number;
35
+ }) => Promise<Uint8Array | null>;
36
+ /** Segment everything: every object at once, with the decode settings when the model takes them. */
37
+ everything?: (image: MaskPixels, o?: MaskEverythingOptions) => Promise<FoundMask[]>;
38
+ }
39
+ /** A mask studio tool: the click segment point or one of the hackbuild-ui mask tools. */
40
+ export type StudioTool = "point" | MaskTool;
41
+ /**
42
+ * What a mask studio shows: tool, mode, sizes, undo state, coverage, zoom, found and saved masks,
43
+ * image size and the last error.
44
+ */
45
+ export interface StudioState {
46
+ ready: boolean;
47
+ tool: StudioTool;
48
+ mode: MaskMode;
49
+ size: number;
50
+ tolerance: number;
51
+ canUndo: boolean;
52
+ canRedo: boolean;
53
+ coverage: number;
54
+ zoom: number;
55
+ busy: string;
56
+ /** The magic wand takes only touching pixels when true. */
57
+ contiguous: boolean;
58
+ view: StudioView;
59
+ /** The found object under the pointer, or -1. */
60
+ hover: number;
61
+ found: (FoundMask & {
62
+ on: boolean;
63
+ colour: string;
64
+ hidden: boolean;
65
+ })[];
66
+ /** Masks put aside with a name and a small preview, newest first. */
67
+ saved: {
68
+ id: number;
69
+ name: string;
70
+ thumb: string;
71
+ coverage: number;
72
+ }[];
73
+ width: number;
74
+ height: number;
75
+ /** The last failure, in words. */
76
+ error: string;
77
+ }
78
+ /**
79
+ * A mounted mask studio: image, tools, undo, grow and shrink, saved masks, found objects, export,
80
+ * and a subscription to its state.
81
+ */
82
+ export interface MaskStudio extends Mounted {
83
+ setImage(src: string | HTMLImageElement | HTMLCanvasElement | ImageBitmap | MaskPixels): Promise<void>;
84
+ setTool(t: StudioTool): void;
85
+ setMode(m: MaskMode): void;
86
+ setSize(px: number): void;
87
+ setTolerance(pct: number): void;
88
+ undo(): void;
89
+ redo(): void;
90
+ invert(): void;
91
+ clear(): void;
92
+ /** Grow, shrink or round off the mask, one undo step each. */
93
+ expand(px?: number): void;
94
+ shrink(px?: number): void;
95
+ smooth(r?: number): void;
96
+ /** Put the current mask aside; restore puts it back as one undo step. */
97
+ save(name?: string): void;
98
+ restore(id: number): void;
99
+ forget(id: number): void;
100
+ /** The current mask as ImageData (alpha by default), null before an image. */
101
+ mask(kind?: MaskOutput): ImageData | null;
102
+ zoom(dir: 1 | -1 | 0): void;
103
+ /** Set the zoom directly, 0.25 to 6, as a pinch does. */
104
+ zoomTo(z: number): void;
105
+ setView(v: StudioView): void;
106
+ setContiguous(on: boolean): void;
107
+ /** Replace the mask (0 or 255 per image pixel) as one undo step, as the no model modes do. */
108
+ setMask(mask: ArrayLike<number>): void;
109
+ /** Add objects to the found list (a model the page ran itself, or colour clusters). */
110
+ addFound(list: FoundMask[]): void;
111
+ /** Show or hide one found object in the found view. */
112
+ showFound(index: number, on: boolean): void;
113
+ removeFound(index: number): void;
114
+ /** Put every shown found object into the mask, one undo step. */
115
+ mergeFound(): void;
116
+ clearFound(): void;
117
+ /** The picture's pixels, null before an image. */
118
+ pixels(): MaskPixels | null;
119
+ /** Find every object with the segment everything model; asks for it through `onWant` when missing. */
120
+ everything(o?: MaskEverythingOptions): Promise<void>;
121
+ /** The click segment model at a point in image pixels, as a press with the point tool. */
122
+ cutAt(x: number, y: number, mode?: MaskMode): Promise<void>;
123
+ /** Add or take out one found object. */
124
+ toggleFound(index: number): void;
125
+ /** The mask, matte, cutout or inverse matte as a png Blob. */
126
+ exportAs(kind: MaskOutput | "inverse"): Promise<Blob | null>;
127
+ hasEverything: boolean;
128
+ hasSegment: boolean;
129
+ /** The page loads models on demand (`onWant`), so the model tools show before their models. */
130
+ canWant: boolean;
131
+ state(): StudioState;
132
+ subscribe(fn: (s: StudioState) => void): () => void;
133
+ setModels(m: MaskModels): void;
134
+ /** Open the file picker. */
135
+ pick(): void;
136
+ }
137
+ /**
138
+ * Options for `mountMaskStudio`: the segment models, empty state words, a sample button and the
139
+ * export file name.
140
+ */
141
+ export interface MaskStudioOptions {
142
+ models?: MaskModels;
143
+ title?: string;
144
+ note?: string;
145
+ sampleLabel?: string;
146
+ onSample?: () => void;
147
+ /** Name of exported files, without extension. */
148
+ name?: string;
149
+ /**
150
+ * A tool needs a model the studio does not have yet: the page loads it and calls setModels.
151
+ * With this set, the point tool shows before its model loads.
152
+ */
153
+ onWant?: (kind: "segment" | "everything") => void;
154
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The mask studio's contract: what a segment model returns, the models a
3
+ * page passes, the studio's state, its methods and its options.
4
+ */
5
+ export {};