@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.
@@ -10917,31 +10917,7 @@ ${n}` : n;
10917
10917
  l.add(list.subscribe(() => draw()));
10918
10918
  return { dispose: () => l.off() };
10919
10919
  }
10920
- // packages/ai-views/src/mount-mask.ts
10921
- /**
10922
- * MaskStudio: drop an image, press a thing
10923
- * to cut it out (a click segment model such as SlimSAM), fix the mask by
10924
- * hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
10925
- * add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
10926
- * export the mask, a matte or the cutout. With a segment everything model
10927
- * (FastSAM) one press finds every object; each lands in the found list and
10928
- * a press adds it to the mask. Models are functions the page passes, so
10929
- * stubs run the studio with no weights. Three views (composite, mask,
10930
- * found objects) paint over the canvas; the pointer previews the click cut
10931
- * or lights the found object under it; two fingers or ctrl and the wheel
10932
- * zoom; a page that loads models on demand hears `onWant` when a tool needs
10933
- * one.
10934
- */
10935
- const ZOOMS = [
10936
- .5,
10937
- .75,
10938
- 1,
10939
- 1.5,
10940
- 2,
10941
- 3,
10942
- 4
10943
- ];
10944
- const clampZoom = (z) => Math.max(.25, Math.min(6, z));
10920
+ // packages/ai-views/src/mask-pixels.ts
10945
10921
  /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
10946
10922
  function tintInto(rgba, mask, rgb, alpha) {
10947
10923
  for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
@@ -10986,6 +10962,267 @@ ${n}` : n;
10986
10962
  t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
10987
10963
  return t.toDataURL("image/png");
10988
10964
  }
10965
+ // packages/ai-views/src/mask-overlay.ts
10966
+ /**
10967
+ * The paint over the studio's canvas: the mask alone, the found objects in
10968
+ * colour with their boxes and words, or the pointer's preview of a cut.
10969
+ * One repaint per animation frame, skipped when nothing it shows changed.
10970
+ */
10971
+ /** An overlay on a canvas; `paint` asks for a repaint on the next animation frame. */
10972
+ function maskOverlay(over, scene) {
10973
+ let painted = "";
10974
+ let req = 0;
10975
+ const draw = () => {
10976
+ req = 0;
10977
+ const s = scene();
10978
+ const { width: w, height: h, view, hover, preview, found } = s;
10979
+ const g = over.getContext("2d");
10980
+ if (!g || !w || !h || !s.hasImage) return;
10981
+ if (over.width !== w || over.height !== h) {
10982
+ over.width = w;
10983
+ over.height = h;
10984
+ }
10985
+ const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? s.maskKey : ""}:${found.map((f) => f.hidden ? 0 : 1).join("")}`;
10986
+ if (view === "composite" && hover < 0 && !preview) {
10987
+ if (painted !== "clear") g.clearRect(0, 0, w, h);
10988
+ painted = "clear";
10989
+ return;
10990
+ }
10991
+ if (key === painted && view !== "mask") return;
10992
+ painted = key;
10993
+ if (view === "mask") {
10994
+ g.putImageData(new ImageData(er(s.mask(), "matte"), w, h), 0, 0);
10995
+ return;
10996
+ }
10997
+ const rgba = new Uint8ClampedArray(w * h * 4);
10998
+ if (view === "instances") found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, nr(f.colour), 150));
10999
+ const hot = hover >= 0 ? found[hover] : void 0;
11000
+ if (hot) tintInto(rgba, hot.mask, nr(hot.colour), 220);
11001
+ else if (preview) tintInto(rgba, preview, [
11002
+ 254,
11003
+ 3,
11004
+ 134
11005
+ ], 110);
11006
+ g.putImageData(new ImageData(rgba, w, h), 0, 0);
11007
+ if (view !== "instances") return;
11008
+ g.lineWidth = Math.max(1, w / 400);
11009
+ g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
11010
+ for (const f of found) {
11011
+ if (f.hidden || !f.box) continue;
11012
+ g.strokeStyle = f.colour;
11013
+ g.fillStyle = f.colour;
11014
+ g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
11015
+ g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
11016
+ }
11017
+ };
11018
+ return { paint() {
11019
+ if (req) return;
11020
+ req = typeof requestAnimationFrame === "function" ? requestAnimationFrame(draw) : (draw(), 0);
11021
+ } };
11022
+ }
11023
+ // packages/ai-views/src/mask-input.ts
11024
+ /** Pinch and ctrl wheel zoom on the well around the canvas. */
11025
+ function pinchZoom(l, well, z) {
11026
+ const touches = /* @__PURE__ */ new Map();
11027
+ let pinch = null;
11028
+ const spread = () => {
11029
+ const [a, b] = [...touches.values()];
11030
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
11031
+ };
11032
+ l.on(well, "pointerdown", (e) => {
11033
+ const pe = e;
11034
+ if (pe.pointerType !== "touch") return;
11035
+ touches.set(pe.pointerId, {
11036
+ x: pe.clientX,
11037
+ y: pe.clientY
11038
+ });
11039
+ if (touches.size === 2) {
11040
+ z.cancel();
11041
+ pinch = {
11042
+ d: spread() || 1,
11043
+ z: z.zoom()
11044
+ };
11045
+ }
11046
+ });
11047
+ l.on(well, "pointermove", (e) => {
11048
+ const pe = e;
11049
+ if (!touches.has(pe.pointerId)) return;
11050
+ touches.set(pe.pointerId, {
11051
+ x: pe.clientX,
11052
+ y: pe.clientY
11053
+ });
11054
+ if (pinch && touches.size === 2) z.zoomTo(pinch.z * (spread() / pinch.d));
11055
+ });
11056
+ const lift = (e) => {
11057
+ touches.delete(e.pointerId);
11058
+ if (touches.size < 2) pinch = null;
11059
+ };
11060
+ l.on(well, "pointerup", lift);
11061
+ l.on(well, "pointercancel", lift);
11062
+ l.on(well, "wheel", (e) => {
11063
+ const we = e;
11064
+ if (!we.ctrlKey || !z.ready()) return;
11065
+ we.preventDefault();
11066
+ z.zoomTo(z.zoom() * Math.exp(-we.deltaY / 200));
11067
+ });
11068
+ }
11069
+ /** The page keys of a studio, on the document. */
11070
+ function studioKeys(l, k) {
11071
+ l.on(document, "keydown", (e) => {
11072
+ const ke = e;
11073
+ if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]")) return;
11074
+ const key = ke.key.toLowerCase();
11075
+ const cmd = ke.ctrlKey || ke.metaKey;
11076
+ if (cmd && key === "o") return ke.preventDefault(), k.open();
11077
+ if (!k.ready()) return;
11078
+ if (cmd && (key === "z" || key === "y")) return ke.preventDefault(), key === "y" || ke.shiftKey ? k.redo() : k.undo();
11079
+ if (cmd && key === "s") return ke.preventDefault(), k.save(ke.shiftKey ? "cutout" : "matte");
11080
+ if (cmd && key === "i") return ke.preventDefault(), k.invert();
11081
+ if (cmd) return;
11082
+ if (key === "delete") return ke.preventDefault(), k.clear();
11083
+ if (key === "+" || key === "=") return k.zoom(1);
11084
+ if (key === "-") return k.zoom(-1);
11085
+ if (key === "0") return k.zoom(0);
11086
+ });
11087
+ }
11088
+ // packages/ai-views/src/mask-parts.ts
11089
+ /**
11090
+ * The pieces around a mask studio, each mounted on its own host: the tool
11091
+ * rail, the verb row on the canvas, and the rack of found objects, the mask
11092
+ * and saved masks. Each reads the studio's state and calls its methods.
11093
+ */
11094
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
11095
+ function mountMaskTools(host, studio) {
11096
+ const l = listeners();
11097
+ const draw = (s) => {
11098
+ host.innerHTML = [...studio.hasSegment || studio.canWant ? [{
11099
+ id: "point",
11100
+ label: "cut out a thing",
11101
+ key: "a",
11102
+ icon: "crosshairs"
11103
+ }] : [], ...gt.map((t) => ({
11104
+ id: t.id,
11105
+ label: t.label,
11106
+ key: t.key,
11107
+ icon: t.icon
11108
+ }))].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}">${rn(t.icon, { size: 18 })}</button>`).join("");
11109
+ };
11110
+ l.on(host, "click", (e) => {
11111
+ const t = e.target.closest("[data-tool]");
11112
+ if (t) studio.setTool(t.dataset.tool);
11113
+ });
11114
+ l.on(document, "keydown", (e) => {
11115
+ const ke = e;
11116
+ if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
11117
+ });
11118
+ l.add(studio.subscribe(draw));
11119
+ return { dispose: () => l.off() };
11120
+ }
11121
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
11122
+ function mountMaskVerbs(host, studio) {
11123
+ const l = listeners();
11124
+ let last = "";
11125
+ const draw = (s) => {
11126
+ const html = s.ready ? `${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>` : ""}` + (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>` : "") + `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>` + (s.coverage > 0 || s.found.length ? `<div class="hb-seg is-toggle" role="group" aria-label="view">${[
11127
+ "composite",
11128
+ "mask",
11129
+ "instances"
11130
+ ].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>` : "") : "";
11131
+ if (html !== last) host.innerHTML = last = html;
11132
+ host.hidden = !html;
11133
+ };
11134
+ l.on(host, "click", (e) => {
11135
+ const view = e.target.closest("[data-view]")?.dataset.view;
11136
+ if (view) return studio.setView(view);
11137
+ const v = e.target.closest("[data-v]")?.dataset.v;
11138
+ if (v === "undo") studio.undo();
11139
+ else if (v === "redo") studio.redo();
11140
+ else if (v === "in") studio.zoom(1);
11141
+ else if (v === "out") studio.zoom(-1);
11142
+ else if (v === "fit") studio.zoom(0);
11143
+ });
11144
+ l.add(studio.subscribe(draw));
11145
+ return { dispose: () => l.off() };
11146
+ }
11147
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
11148
+ function mountMaskRack(host, studio, part, o = {}) {
11149
+ const l = listeners();
11150
+ let last = "";
11151
+ const draw = (s) => {
11152
+ let html = "";
11153
+ if (part === "found") {
11154
+ html = s.found.length ? `<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"}">${rn("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>` : `<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>` + (s.ready && (studio.hasEverything || studio.canWant) && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
11155
+ 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>` : "";
11156
+ } else if (part === "mask") html = `<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>` + (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>` : "") + (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>` : "") + (s.tool === "wand" ? `<label class="hb-check"><input type="checkbox" data-contig${s.contiguous ? " checked" : ""}><span>touching pixels only</span></label>` : "") + (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>` : "");
11157
+ else if (part === "saved") html = (s.coverage > 0 ? `<div class="hb-toolbar"><button type="button" class="hb-btn" data-op="save">save this mask</button></div>` : "") + (s.saved.length ? `<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>` : `<p class="hb-lay-empty-note">no saved masks. save one to come back to it.</p>`);
11158
+ else html = s.coverage > 0 ? `<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>` : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
11159
+ if (html !== last) host.innerHTML = last = html;
11160
+ };
11161
+ l.on(host, "click", (e) => {
11162
+ const t = e.target;
11163
+ const f = t.closest("[data-found]");
11164
+ if (f) return studio.toggleFound(Number(f.dataset.found));
11165
+ const m = t.closest("[data-mode]");
11166
+ if (m) return studio.setMode(m.dataset.mode);
11167
+ const show = t.closest("[data-show]");
11168
+ if (show) return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
11169
+ const drop = t.closest("[data-drop]");
11170
+ if (drop) return studio.removeFound(Number(drop.dataset.drop));
11171
+ const op = t.closest("[data-op]")?.dataset.op;
11172
+ if (op === "merge") return studio.mergeFound();
11173
+ if (op === "unfind") return studio.clearFound();
11174
+ if (op === "invert") return studio.invert();
11175
+ if (op === "clear") return studio.clear();
11176
+ if (op === "smooth") return studio.smooth();
11177
+ if (op === "expand") return studio.expand();
11178
+ if (op === "shrink") return studio.shrink();
11179
+ if (op === "save") return studio.save();
11180
+ const restore = t.closest("[data-restore]");
11181
+ if (restore) return studio.restore(Number(restore.dataset.restore));
11182
+ const forget = t.closest("[data-forget]");
11183
+ if (forget) return studio.forget(Number(forget.dataset.forget));
11184
+ const ex = t.closest("[data-ex]");
11185
+ if (ex) {
11186
+ const kind = ex.dataset.ex;
11187
+ studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
11188
+ return;
11189
+ }
11190
+ if (t.closest("[data-all]")) studio.everything();
11191
+ });
11192
+ l.on(host, "input", (e) => {
11193
+ const i = e.target;
11194
+ if (i.dataset.size !== void 0) studio.setSize(Number(i.value));
11195
+ if (i.dataset.tol !== void 0) studio.setTolerance(Number(i.value));
11196
+ if (i.dataset.contig !== void 0) studio.setContiguous(i.checked);
11197
+ });
11198
+ l.add(studio.subscribe(draw));
11199
+ return { dispose: () => l.off() };
11200
+ }
11201
+ // packages/ai-views/src/mount-mask.ts
11202
+ /**
11203
+ * MaskStudio: drop an image, press a thing
11204
+ * to cut it out (a click segment model such as SlimSAM), fix the mask by
11205
+ * hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
11206
+ * add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
11207
+ * export the mask, a matte or the cutout. With a segment everything model
11208
+ * (FastSAM) one press finds every object; each lands in the found list and
11209
+ * a press adds it to the mask. Models are functions the page passes, so
11210
+ * stubs run the studio with no weights. Three views (composite, mask,
11211
+ * found objects) paint over the canvas; the pointer previews the click cut
11212
+ * or lights the found object under it; two fingers or ctrl and the wheel
11213
+ * zoom; a page that loads models on demand hears `onWant` when a tool needs
11214
+ * one.
11215
+ */
11216
+ const ZOOMS = [
11217
+ .5,
11218
+ .75,
11219
+ 1,
11220
+ 1.5,
11221
+ 2,
11222
+ 3,
11223
+ 4
11224
+ ];
11225
+ const clampZoom = (z) => Math.max(.25, Math.min(6, z));
10989
11226
  /**
10990
11227
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
10991
11228
  * and lasso tools or a segment model.
@@ -10997,7 +11234,6 @@ ${n}` : n;
10997
11234
  const empty = host.querySelector("[data-empty]");
10998
11235
  const studio = host.querySelector("[data-studio]");
10999
11236
  const well = host.querySelector(".hb-mask-well");
11000
- host.querySelector(".hb-mask-frame");
11001
11237
  const canvas = host.querySelector(".hb-mask-canvas");
11002
11238
  const over = host.querySelector("[data-over]");
11003
11239
  const hint = host.querySelector(".hb-mask-hint");
@@ -11042,56 +11278,17 @@ ${n}` : n;
11042
11278
  for (const fn of subs) fn(s);
11043
11279
  paint();
11044
11280
  };
11045
- let painted = "";
11046
- let frameReq = 0;
11047
- const paint = () => {
11048
- if (frameReq) return;
11049
- frameReq = typeof requestAnimationFrame === "function" ? requestAnimationFrame(drawOver) : (drawOver(), 0);
11050
- };
11051
- const drawOver = () => {
11052
- frameReq = 0;
11053
- const w = ed?.width ?? 0;
11054
- const h = ed?.height ?? 0;
11055
- const g = over.getContext("2d");
11056
- if (!g || !w || !h || !pixels) return;
11057
- if (over.width !== w || over.height !== h) {
11058
- over.width = w;
11059
- over.height = h;
11060
- }
11061
- const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? editor.state.coverage + ":" + (ed?.canUndo ? 1 : 0) : ""}:${found.map((f) => f.hidden ? 0 : 1).join("")}`;
11062
- if (view === "composite" && hover < 0 && !preview) {
11063
- if (painted !== "clear") g.clearRect(0, 0, w, h);
11064
- painted = "clear";
11065
- return;
11066
- }
11067
- if (key === painted && view !== "mask") return;
11068
- painted = key;
11069
- if (view === "mask") {
11070
- g.putImageData(new ImageData(er(editor.mask(), "matte"), w, h), 0, 0);
11071
- return;
11072
- }
11073
- const rgba = new Uint8ClampedArray(w * h * 4);
11074
- if (view === "instances") found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, nr(f.colour), 150));
11075
- const hot = hover >= 0 ? found[hover] : void 0;
11076
- if (hot) tintInto(rgba, hot.mask, nr(hot.colour), 220);
11077
- else if (preview) tintInto(rgba, preview, [
11078
- 254,
11079
- 3,
11080
- 134
11081
- ], 110);
11082
- g.putImageData(new ImageData(rgba, w, h), 0, 0);
11083
- if (view === "instances") {
11084
- g.lineWidth = Math.max(1, w / 400);
11085
- g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
11086
- for (const f of found) {
11087
- if (f.hidden || !f.box) continue;
11088
- g.strokeStyle = f.colour;
11089
- g.fillStyle = f.colour;
11090
- g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
11091
- g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
11092
- }
11093
- }
11094
- };
11281
+ const { paint } = maskOverlay(over, () => ({
11282
+ width: ed?.width ?? 0,
11283
+ height: ed?.height ?? 0,
11284
+ hasImage: !!pixels,
11285
+ view,
11286
+ hover,
11287
+ preview,
11288
+ found,
11289
+ maskKey: `${editor.state.coverage}:${ed?.canUndo ? 1 : 0}`,
11290
+ mask: () => editor.mask()
11291
+ }));
11095
11292
  const editor = ns(canvas, {
11096
11293
  tool: tool === "point" ? "wand" : tool,
11097
11294
  onError: (e) => (error = `the image did not load: ${e.message}`, emit())
@@ -11195,63 +11392,21 @@ ${n}` : n;
11195
11392
  canvas.addEventListener("pointermove", onHover);
11196
11393
  canvas.addEventListener("pointerleave", offHover);
11197
11394
  l.add(() => (canvas.removeEventListener("pointermove", onHover), canvas.removeEventListener("pointerleave", offHover)));
11198
- const touches = /* @__PURE__ */ new Map();
11199
- let pinch = null;
11200
- const spread = () => {
11201
- const [a, b] = [...touches.values()];
11202
- return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
11203
- };
11204
- l.on(well, "pointerdown", (e) => {
11205
- const pe = e;
11206
- if (pe.pointerType !== "touch") return;
11207
- touches.set(pe.pointerId, {
11208
- x: pe.clientX,
11209
- y: pe.clientY
11210
- });
11211
- if (touches.size === 2) {
11212
- editor.cancel();
11213
- pinch = {
11214
- d: spread() || 1,
11215
- z: zoom
11216
- };
11217
- }
11395
+ pinchZoom(l, well, {
11396
+ zoom: () => zoom,
11397
+ zoomTo: (z) => studioApi.zoomTo(z),
11398
+ cancel: () => editor.cancel(),
11399
+ ready: () => !!ed?.ready
11218
11400
  });
11219
- l.on(well, "pointermove", (e) => {
11220
- const pe = e;
11221
- if (!touches.has(pe.pointerId)) return;
11222
- touches.set(pe.pointerId, {
11223
- x: pe.clientX,
11224
- y: pe.clientY
11225
- });
11226
- if (pinch && touches.size === 2) studioApi.zoomTo(pinch.z * (spread() / pinch.d));
11227
- });
11228
- const lift = (e) => {
11229
- touches.delete(e.pointerId);
11230
- if (touches.size < 2) pinch = null;
11231
- };
11232
- l.on(well, "pointerup", lift);
11233
- l.on(well, "pointercancel", lift);
11234
- l.on(well, "wheel", (e) => {
11235
- const we = e;
11236
- if (!we.ctrlKey || !ed?.ready) return;
11237
- we.preventDefault();
11238
- studioApi.zoomTo(zoom * Math.exp(-we.deltaY / 200));
11239
- });
11240
- l.on(document, "keydown", (e) => {
11241
- const ke = e;
11242
- if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]")) return;
11243
- const k = ke.key.toLowerCase();
11244
- const cmd = ke.ctrlKey || ke.metaKey;
11245
- if (cmd && k === "o") return ke.preventDefault(), input.click();
11246
- if (!ed?.ready) return;
11247
- if (cmd && (k === "z" || k === "y")) return ke.preventDefault(), void (k === "y" || ke.shiftKey ? editor.redo() : editor.undo());
11248
- if (cmd && k === "s") return ke.preventDefault(), void studioApi.exportAs(ke.shiftKey ? "cutout" : "matte").then((b) => b && download(`${o.name ?? "mask"}-${ke.shiftKey ? "cutout" : "matte"}.png`, b));
11249
- if (cmd && k === "i") return ke.preventDefault(), editor.invert();
11250
- if (cmd) return;
11251
- if (k === "delete") return ke.preventDefault(), editor.clear();
11252
- if (k === "+" || k === "=") return studioApi.zoom(1);
11253
- if (k === "-") return studioApi.zoom(-1);
11254
- if (k === "0") return studioApi.zoom(0);
11401
+ studioKeys(l, {
11402
+ ready: () => !!ed?.ready,
11403
+ open: () => input.click(),
11404
+ undo: () => void editor.undo(),
11405
+ redo: () => void editor.redo(),
11406
+ invert: () => editor.invert(),
11407
+ clear: () => editor.clear(),
11408
+ save: (kind) => void studioApi.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b)),
11409
+ zoom: (dir) => studioApi.zoom(dir)
11255
11410
  });
11256
11411
  canvas.addEventListener("pointerdown", onPoint, true);
11257
11412
  l.add(() => canvas.removeEventListener("pointerdown", onPoint, true));
@@ -11481,113 +11636,6 @@ ${n}` : n;
11481
11636
  emit();
11482
11637
  return studioApi;
11483
11638
  }
11484
- /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
11485
- function mountMaskTools(host, studio) {
11486
- const l = listeners();
11487
- const draw = (s) => {
11488
- host.innerHTML = [...studio.hasSegment || studio.canWant ? [{
11489
- id: "point",
11490
- label: "cut out a thing",
11491
- key: "a",
11492
- icon: "crosshairs"
11493
- }] : [], ...gt.map((t) => ({
11494
- id: t.id,
11495
- label: t.label,
11496
- key: t.key,
11497
- icon: t.icon
11498
- }))].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}">${rn(t.icon, { size: 18 })}</button>`).join("");
11499
- };
11500
- l.on(host, "click", (e) => {
11501
- const t = e.target.closest("[data-tool]");
11502
- if (t) studio.setTool(t.dataset.tool);
11503
- });
11504
- l.on(document, "keydown", (e) => {
11505
- const ke = e;
11506
- if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
11507
- });
11508
- l.add(studio.subscribe(draw));
11509
- return { dispose: () => l.off() };
11510
- }
11511
- /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
11512
- function mountMaskVerbs(host, studio) {
11513
- const l = listeners();
11514
- let last = "";
11515
- const draw = (s) => {
11516
- const html = s.ready ? `${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>` : ""}` + (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>` : "") + `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>` + (s.coverage > 0 || s.found.length ? `<div class="hb-seg is-toggle" role="group" aria-label="view">${[
11517
- "composite",
11518
- "mask",
11519
- "instances"
11520
- ].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>` : "") : "";
11521
- if (html !== last) host.innerHTML = last = html;
11522
- host.hidden = !html;
11523
- };
11524
- l.on(host, "click", (e) => {
11525
- const view = e.target.closest("[data-view]")?.dataset.view;
11526
- if (view) return studio.setView(view);
11527
- const v = e.target.closest("[data-v]")?.dataset.v;
11528
- if (v === "undo") studio.undo();
11529
- else if (v === "redo") studio.redo();
11530
- else if (v === "in") studio.zoom(1);
11531
- else if (v === "out") studio.zoom(-1);
11532
- else if (v === "fit") studio.zoom(0);
11533
- });
11534
- l.add(studio.subscribe(draw));
11535
- return { dispose: () => l.off() };
11536
- }
11537
- /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
11538
- function mountMaskRack(host, studio, part, o = {}) {
11539
- const l = listeners();
11540
- let last = "";
11541
- const draw = (s) => {
11542
- let html = "";
11543
- if (part === "found") {
11544
- html = s.found.length ? `<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"}">${rn("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>` : `<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>` + (s.ready && (studio.hasEverything || studio.canWant) && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
11545
- 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>` : "";
11546
- } else if (part === "mask") html = `<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>` + (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>` : "") + (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>` : "") + (s.tool === "wand" ? `<label class="hb-check"><input type="checkbox" data-contig${s.contiguous ? " checked" : ""}><span>touching pixels only</span></label>` : "") + (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>` : "");
11547
- else if (part === "saved") html = (s.coverage > 0 ? `<div class="hb-toolbar"><button type="button" class="hb-btn" data-op="save">save this mask</button></div>` : "") + (s.saved.length ? `<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>` : `<p class="hb-lay-empty-note">no saved masks. save one to come back to it.</p>`);
11548
- else html = s.coverage > 0 ? `<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>` : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
11549
- if (html !== last) host.innerHTML = last = html;
11550
- };
11551
- l.on(host, "click", (e) => {
11552
- const t = e.target;
11553
- const f = t.closest("[data-found]");
11554
- if (f) return studio.toggleFound(Number(f.dataset.found));
11555
- const m = t.closest("[data-mode]");
11556
- if (m) return studio.setMode(m.dataset.mode);
11557
- const show = t.closest("[data-show]");
11558
- if (show) return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
11559
- const drop = t.closest("[data-drop]");
11560
- if (drop) return studio.removeFound(Number(drop.dataset.drop));
11561
- const op = t.closest("[data-op]")?.dataset.op;
11562
- if (op === "merge") return studio.mergeFound();
11563
- if (op === "unfind") return studio.clearFound();
11564
- if (op === "invert") return studio.invert();
11565
- if (op === "clear") return studio.clear();
11566
- if (op === "smooth") return studio.smooth();
11567
- if (op === "expand") return studio.expand();
11568
- if (op === "shrink") return studio.shrink();
11569
- if (op === "save") return studio.save();
11570
- const restore = t.closest("[data-restore]");
11571
- if (restore) return studio.restore(Number(restore.dataset.restore));
11572
- const forget = t.closest("[data-forget]");
11573
- if (forget) return studio.forget(Number(forget.dataset.forget));
11574
- const ex = t.closest("[data-ex]");
11575
- if (ex) {
11576
- const kind = ex.dataset.ex;
11577
- studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
11578
- return;
11579
- }
11580
- if (t.closest("[data-all]")) studio.everything();
11581
- });
11582
- l.on(host, "input", (e) => {
11583
- const i = e.target;
11584
- if (i.dataset.size !== void 0) studio.setSize(Number(i.value));
11585
- if (i.dataset.tol !== void 0) studio.setTolerance(Number(i.value));
11586
- if (i.dataset.contig !== void 0) studio.setContiguous(i.checked);
11587
- });
11588
- l.add(studio.subscribe(draw));
11589
- return { dispose: () => l.off() };
11590
- }
11591
11639
  // packages/ai-views/src/memory.ts
11592
11640
  const n3 = (x) => Number.isFinite(x) ? x.toFixed(3) : "none";
11593
11641
  const rank = (r) => r >= 0 ? `#${r + 1}` : "none";