@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.
@@ -8639,31 +8639,7 @@ function mountCameraFeed(host, o = {}) {
8639
8639
  emit();
8640
8640
  return feed;
8641
8641
  }
8642
- // packages/ai-views/src/mount-mask.ts
8643
- /**
8644
- * MaskStudio: drop an image, press a thing
8645
- * to cut it out (a click segment model such as SlimSAM), fix the mask by
8646
- * hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
8647
- * add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
8648
- * export the mask, a matte or the cutout. With a segment everything model
8649
- * (FastSAM) one press finds every object; each lands in the found list and
8650
- * a press adds it to the mask. Models are functions the page passes, so
8651
- * stubs run the studio with no weights. Three views (composite, mask,
8652
- * found objects) paint over the canvas; the pointer previews the click cut
8653
- * or lights the found object under it; two fingers or ctrl and the wheel
8654
- * zoom; a page that loads models on demand hears `onWant` when a tool needs
8655
- * one.
8656
- */
8657
- const ZOOMS = [
8658
- .5,
8659
- .75,
8660
- 1,
8661
- 1.5,
8662
- 2,
8663
- 3,
8664
- 4
8665
- ];
8666
- const clampZoom = (z) => Math.max(.25, Math.min(6, z));
8642
+ // packages/ai-views/src/mask-pixels.ts
8667
8643
  /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
8668
8644
  function tintInto(rgba, mask, rgb, alpha) {
8669
8645
  for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
@@ -8708,6 +8684,267 @@ function thumbOf(img) {
8708
8684
  t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
8709
8685
  return t.toDataURL("image/png");
8710
8686
  }
8687
+ // packages/ai-views/src/mask-overlay.ts
8688
+ /**
8689
+ * The paint over the studio's canvas: the mask alone, the found objects in
8690
+ * colour with their boxes and words, or the pointer's preview of a cut.
8691
+ * One repaint per animation frame, skipped when nothing it shows changed.
8692
+ */
8693
+ /** An overlay on a canvas; `paint` asks for a repaint on the next animation frame. */
8694
+ function maskOverlay(over, scene) {
8695
+ let painted = "";
8696
+ let req = 0;
8697
+ const draw = () => {
8698
+ req = 0;
8699
+ const s = scene();
8700
+ const { width: w, height: h, view, hover, preview, found } = s;
8701
+ const g = over.getContext("2d");
8702
+ if (!g || !w || !h || !s.hasImage) return;
8703
+ if (over.width !== w || over.height !== h) {
8704
+ over.width = w;
8705
+ over.height = h;
8706
+ }
8707
+ const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? s.maskKey : ""}:${found.map((f) => f.hidden ? 0 : 1).join("")}`;
8708
+ if (view === "composite" && hover < 0 && !preview) {
8709
+ if (painted !== "clear") g.clearRect(0, 0, w, h);
8710
+ painted = "clear";
8711
+ return;
8712
+ }
8713
+ if (key === painted && view !== "mask") return;
8714
+ painted = key;
8715
+ if (view === "mask") {
8716
+ g.putImageData(new ImageData(er(s.mask(), "matte"), w, h), 0, 0);
8717
+ return;
8718
+ }
8719
+ const rgba = new Uint8ClampedArray(w * h * 4);
8720
+ if (view === "instances") found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, nr(f.colour), 150));
8721
+ const hot = hover >= 0 ? found[hover] : void 0;
8722
+ if (hot) tintInto(rgba, hot.mask, nr(hot.colour), 220);
8723
+ else if (preview) tintInto(rgba, preview, [
8724
+ 254,
8725
+ 3,
8726
+ 134
8727
+ ], 110);
8728
+ g.putImageData(new ImageData(rgba, w, h), 0, 0);
8729
+ if (view !== "instances") return;
8730
+ g.lineWidth = Math.max(1, w / 400);
8731
+ g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
8732
+ for (const f of found) {
8733
+ if (f.hidden || !f.box) continue;
8734
+ g.strokeStyle = f.colour;
8735
+ g.fillStyle = f.colour;
8736
+ g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
8737
+ g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
8738
+ }
8739
+ };
8740
+ return { paint() {
8741
+ if (req) return;
8742
+ req = typeof requestAnimationFrame === "function" ? requestAnimationFrame(draw) : (draw(), 0);
8743
+ } };
8744
+ }
8745
+ // packages/ai-views/src/mask-input.ts
8746
+ /** Pinch and ctrl wheel zoom on the well around the canvas. */
8747
+ function pinchZoom(l, well, z) {
8748
+ const touches = /* @__PURE__ */ new Map();
8749
+ let pinch = null;
8750
+ const spread = () => {
8751
+ const [a, b] = [...touches.values()];
8752
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
8753
+ };
8754
+ l.on(well, "pointerdown", (e) => {
8755
+ const pe = e;
8756
+ if (pe.pointerType !== "touch") return;
8757
+ touches.set(pe.pointerId, {
8758
+ x: pe.clientX,
8759
+ y: pe.clientY
8760
+ });
8761
+ if (touches.size === 2) {
8762
+ z.cancel();
8763
+ pinch = {
8764
+ d: spread() || 1,
8765
+ z: z.zoom()
8766
+ };
8767
+ }
8768
+ });
8769
+ l.on(well, "pointermove", (e) => {
8770
+ const pe = e;
8771
+ if (!touches.has(pe.pointerId)) return;
8772
+ touches.set(pe.pointerId, {
8773
+ x: pe.clientX,
8774
+ y: pe.clientY
8775
+ });
8776
+ if (pinch && touches.size === 2) z.zoomTo(pinch.z * (spread() / pinch.d));
8777
+ });
8778
+ const lift = (e) => {
8779
+ touches.delete(e.pointerId);
8780
+ if (touches.size < 2) pinch = null;
8781
+ };
8782
+ l.on(well, "pointerup", lift);
8783
+ l.on(well, "pointercancel", lift);
8784
+ l.on(well, "wheel", (e) => {
8785
+ const we = e;
8786
+ if (!we.ctrlKey || !z.ready()) return;
8787
+ we.preventDefault();
8788
+ z.zoomTo(z.zoom() * Math.exp(-we.deltaY / 200));
8789
+ });
8790
+ }
8791
+ /** The page keys of a studio, on the document. */
8792
+ function studioKeys(l, k) {
8793
+ l.on(document, "keydown", (e) => {
8794
+ const ke = e;
8795
+ if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]")) return;
8796
+ const key = ke.key.toLowerCase();
8797
+ const cmd = ke.ctrlKey || ke.metaKey;
8798
+ if (cmd && key === "o") return ke.preventDefault(), k.open();
8799
+ if (!k.ready()) return;
8800
+ if (cmd && (key === "z" || key === "y")) return ke.preventDefault(), key === "y" || ke.shiftKey ? k.redo() : k.undo();
8801
+ if (cmd && key === "s") return ke.preventDefault(), k.save(ke.shiftKey ? "cutout" : "matte");
8802
+ if (cmd && key === "i") return ke.preventDefault(), k.invert();
8803
+ if (cmd) return;
8804
+ if (key === "delete") return ke.preventDefault(), k.clear();
8805
+ if (key === "+" || key === "=") return k.zoom(1);
8806
+ if (key === "-") return k.zoom(-1);
8807
+ if (key === "0") return k.zoom(0);
8808
+ });
8809
+ }
8810
+ // packages/ai-views/src/mask-parts.ts
8811
+ /**
8812
+ * The pieces around a mask studio, each mounted on its own host: the tool
8813
+ * rail, the verb row on the canvas, and the rack of found objects, the mask
8814
+ * and saved masks. Each reads the studio's state and calls its methods.
8815
+ */
8816
+ /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
8817
+ function mountMaskTools(host, studio) {
8818
+ const l = listeners();
8819
+ const draw = (s) => {
8820
+ host.innerHTML = [...studio.hasSegment || studio.canWant ? [{
8821
+ id: "point",
8822
+ label: "cut out a thing",
8823
+ key: "a",
8824
+ icon: "crosshairs"
8825
+ }] : [], ...gt.map((t) => ({
8826
+ id: t.id,
8827
+ label: t.label,
8828
+ key: t.key,
8829
+ icon: t.icon
8830
+ }))].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("");
8831
+ };
8832
+ l.on(host, "click", (e) => {
8833
+ const t = e.target.closest("[data-tool]");
8834
+ if (t) studio.setTool(t.dataset.tool);
8835
+ });
8836
+ l.on(document, "keydown", (e) => {
8837
+ const ke = e;
8838
+ if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
8839
+ });
8840
+ l.add(studio.subscribe(draw));
8841
+ return { dispose: () => l.off() };
8842
+ }
8843
+ /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
8844
+ function mountMaskVerbs(host, studio) {
8845
+ const l = listeners();
8846
+ let last = "";
8847
+ const draw = (s) => {
8848
+ 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">${[
8849
+ "composite",
8850
+ "mask",
8851
+ "instances"
8852
+ ].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>` : "") : "";
8853
+ if (html !== last) host.innerHTML = last = html;
8854
+ host.hidden = !html;
8855
+ };
8856
+ l.on(host, "click", (e) => {
8857
+ const view = e.target.closest("[data-view]")?.dataset.view;
8858
+ if (view) return studio.setView(view);
8859
+ const v = e.target.closest("[data-v]")?.dataset.v;
8860
+ if (v === "undo") studio.undo();
8861
+ else if (v === "redo") studio.redo();
8862
+ else if (v === "in") studio.zoom(1);
8863
+ else if (v === "out") studio.zoom(-1);
8864
+ else if (v === "fit") studio.zoom(0);
8865
+ });
8866
+ l.add(studio.subscribe(draw));
8867
+ return { dispose: () => l.off() };
8868
+ }
8869
+ /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
8870
+ function mountMaskRack(host, studio, part, o = {}) {
8871
+ const l = listeners();
8872
+ let last = "";
8873
+ const draw = (s) => {
8874
+ let html = "";
8875
+ if (part === "found") {
8876
+ 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>` : "");
8877
+ 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>` : "";
8878
+ } 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>` : "");
8879
+ 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>`);
8880
+ 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>`;
8881
+ if (html !== last) host.innerHTML = last = html;
8882
+ };
8883
+ l.on(host, "click", (e) => {
8884
+ const t = e.target;
8885
+ const f = t.closest("[data-found]");
8886
+ if (f) return studio.toggleFound(Number(f.dataset.found));
8887
+ const m = t.closest("[data-mode]");
8888
+ if (m) return studio.setMode(m.dataset.mode);
8889
+ const show = t.closest("[data-show]");
8890
+ if (show) return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
8891
+ const drop = t.closest("[data-drop]");
8892
+ if (drop) return studio.removeFound(Number(drop.dataset.drop));
8893
+ const op = t.closest("[data-op]")?.dataset.op;
8894
+ if (op === "merge") return studio.mergeFound();
8895
+ if (op === "unfind") return studio.clearFound();
8896
+ if (op === "invert") return studio.invert();
8897
+ if (op === "clear") return studio.clear();
8898
+ if (op === "smooth") return studio.smooth();
8899
+ if (op === "expand") return studio.expand();
8900
+ if (op === "shrink") return studio.shrink();
8901
+ if (op === "save") return studio.save();
8902
+ const restore = t.closest("[data-restore]");
8903
+ if (restore) return studio.restore(Number(restore.dataset.restore));
8904
+ const forget = t.closest("[data-forget]");
8905
+ if (forget) return studio.forget(Number(forget.dataset.forget));
8906
+ const ex = t.closest("[data-ex]");
8907
+ if (ex) {
8908
+ const kind = ex.dataset.ex;
8909
+ studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
8910
+ return;
8911
+ }
8912
+ if (t.closest("[data-all]")) studio.everything();
8913
+ });
8914
+ l.on(host, "input", (e) => {
8915
+ const i = e.target;
8916
+ if (i.dataset.size !== void 0) studio.setSize(Number(i.value));
8917
+ if (i.dataset.tol !== void 0) studio.setTolerance(Number(i.value));
8918
+ if (i.dataset.contig !== void 0) studio.setContiguous(i.checked);
8919
+ });
8920
+ l.add(studio.subscribe(draw));
8921
+ return { dispose: () => l.off() };
8922
+ }
8923
+ // packages/ai-views/src/mount-mask.ts
8924
+ /**
8925
+ * MaskStudio: drop an image, press a thing
8926
+ * to cut it out (a click segment model such as SlimSAM), fix the mask by
8927
+ * hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
8928
+ * add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
8929
+ * export the mask, a matte or the cutout. With a segment everything model
8930
+ * (FastSAM) one press finds every object; each lands in the found list and
8931
+ * a press adds it to the mask. Models are functions the page passes, so
8932
+ * stubs run the studio with no weights. Three views (composite, mask,
8933
+ * found objects) paint over the canvas; the pointer previews the click cut
8934
+ * or lights the found object under it; two fingers or ctrl and the wheel
8935
+ * zoom; a page that loads models on demand hears `onWant` when a tool needs
8936
+ * one.
8937
+ */
8938
+ const ZOOMS = [
8939
+ .5,
8940
+ .75,
8941
+ 1,
8942
+ 1.5,
8943
+ 2,
8944
+ 3,
8945
+ 4
8946
+ ];
8947
+ const clampZoom = (z) => Math.max(.25, Math.min(6, z));
8711
8948
  /**
8712
8949
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
8713
8950
  * and lasso tools or a segment model.
@@ -8764,56 +9001,17 @@ function mountMaskStudio(host, o = {}) {
8764
9001
  for (const fn of subs) fn(s);
8765
9002
  paint();
8766
9003
  };
8767
- let painted = "";
8768
- let frameReq = 0;
8769
- const paint = () => {
8770
- if (frameReq) return;
8771
- frameReq = typeof requestAnimationFrame === "function" ? requestAnimationFrame(drawOver) : (drawOver(), 0);
8772
- };
8773
- const drawOver = () => {
8774
- frameReq = 0;
8775
- const w = ed?.width ?? 0;
8776
- const h = ed?.height ?? 0;
8777
- const g = over.getContext("2d");
8778
- if (!g || !w || !h || !pixels) return;
8779
- if (over.width !== w || over.height !== h) {
8780
- over.width = w;
8781
- over.height = h;
8782
- }
8783
- const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? editor.state.coverage + ":" + (ed?.canUndo ? 1 : 0) : ""}:${found.map((f) => f.hidden ? 0 : 1).join("")}`;
8784
- if (view === "composite" && hover < 0 && !preview) {
8785
- if (painted !== "clear") g.clearRect(0, 0, w, h);
8786
- painted = "clear";
8787
- return;
8788
- }
8789
- if (key === painted && view !== "mask") return;
8790
- painted = key;
8791
- if (view === "mask") {
8792
- g.putImageData(new ImageData(er(editor.mask(), "matte"), w, h), 0, 0);
8793
- return;
8794
- }
8795
- const rgba = new Uint8ClampedArray(w * h * 4);
8796
- if (view === "instances") found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, nr(f.colour), 150));
8797
- const hot = hover >= 0 ? found[hover] : void 0;
8798
- if (hot) tintInto(rgba, hot.mask, nr(hot.colour), 220);
8799
- else if (preview) tintInto(rgba, preview, [
8800
- 254,
8801
- 3,
8802
- 134
8803
- ], 110);
8804
- g.putImageData(new ImageData(rgba, w, h), 0, 0);
8805
- if (view === "instances") {
8806
- g.lineWidth = Math.max(1, w / 400);
8807
- g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
8808
- for (const f of found) {
8809
- if (f.hidden || !f.box) continue;
8810
- g.strokeStyle = f.colour;
8811
- g.fillStyle = f.colour;
8812
- g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
8813
- g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
8814
- }
8815
- }
8816
- };
9004
+ const { paint } = maskOverlay(over, () => ({
9005
+ width: ed?.width ?? 0,
9006
+ height: ed?.height ?? 0,
9007
+ hasImage: !!pixels,
9008
+ view,
9009
+ hover,
9010
+ preview,
9011
+ found,
9012
+ maskKey: `${editor.state.coverage}:${ed?.canUndo ? 1 : 0}`,
9013
+ mask: () => editor.mask()
9014
+ }));
8817
9015
  const editor = ns(canvas, {
8818
9016
  tool: tool === "point" ? "wand" : tool,
8819
9017
  onError: (e) => (error = `the image did not load: ${e.message}`, emit())
@@ -8917,63 +9115,21 @@ function mountMaskStudio(host, o = {}) {
8917
9115
  canvas.addEventListener("pointermove", onHover);
8918
9116
  canvas.addEventListener("pointerleave", offHover);
8919
9117
  l.add(() => (canvas.removeEventListener("pointermove", onHover), canvas.removeEventListener("pointerleave", offHover)));
8920
- const touches = /* @__PURE__ */ new Map();
8921
- let pinch = null;
8922
- const spread = () => {
8923
- const [a, b] = [...touches.values()];
8924
- return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
8925
- };
8926
- l.on(well, "pointerdown", (e) => {
8927
- const pe = e;
8928
- if (pe.pointerType !== "touch") return;
8929
- touches.set(pe.pointerId, {
8930
- x: pe.clientX,
8931
- y: pe.clientY
8932
- });
8933
- if (touches.size === 2) {
8934
- editor.cancel();
8935
- pinch = {
8936
- d: spread() || 1,
8937
- z: zoom
8938
- };
8939
- }
9118
+ pinchZoom(l, well, {
9119
+ zoom: () => zoom,
9120
+ zoomTo: (z) => studioApi.zoomTo(z),
9121
+ cancel: () => editor.cancel(),
9122
+ ready: () => !!ed?.ready
8940
9123
  });
8941
- l.on(well, "pointermove", (e) => {
8942
- const pe = e;
8943
- if (!touches.has(pe.pointerId)) return;
8944
- touches.set(pe.pointerId, {
8945
- x: pe.clientX,
8946
- y: pe.clientY
8947
- });
8948
- if (pinch && touches.size === 2) studioApi.zoomTo(pinch.z * (spread() / pinch.d));
8949
- });
8950
- const lift = (e) => {
8951
- touches.delete(e.pointerId);
8952
- if (touches.size < 2) pinch = null;
8953
- };
8954
- l.on(well, "pointerup", lift);
8955
- l.on(well, "pointercancel", lift);
8956
- l.on(well, "wheel", (e) => {
8957
- const we = e;
8958
- if (!we.ctrlKey || !ed?.ready) return;
8959
- we.preventDefault();
8960
- studioApi.zoomTo(zoom * Math.exp(-we.deltaY / 200));
8961
- });
8962
- l.on(document, "keydown", (e) => {
8963
- const ke = e;
8964
- if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]")) return;
8965
- const k = ke.key.toLowerCase();
8966
- const cmd = ke.ctrlKey || ke.metaKey;
8967
- if (cmd && k === "o") return ke.preventDefault(), input.click();
8968
- if (!ed?.ready) return;
8969
- if (cmd && (k === "z" || k === "y")) return ke.preventDefault(), void (k === "y" || ke.shiftKey ? editor.redo() : editor.undo());
8970
- 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));
8971
- if (cmd && k === "i") return ke.preventDefault(), editor.invert();
8972
- if (cmd) return;
8973
- if (k === "delete") return ke.preventDefault(), editor.clear();
8974
- if (k === "+" || k === "=") return studioApi.zoom(1);
8975
- if (k === "-") return studioApi.zoom(-1);
8976
- if (k === "0") return studioApi.zoom(0);
9124
+ studioKeys(l, {
9125
+ ready: () => !!ed?.ready,
9126
+ open: () => input.click(),
9127
+ undo: () => void editor.undo(),
9128
+ redo: () => void editor.redo(),
9129
+ invert: () => editor.invert(),
9130
+ clear: () => editor.clear(),
9131
+ save: (kind) => void studioApi.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b)),
9132
+ zoom: (dir) => studioApi.zoom(dir)
8977
9133
  });
8978
9134
  canvas.addEventListener("pointerdown", onPoint, true);
8979
9135
  l.add(() => canvas.removeEventListener("pointerdown", onPoint, true));
@@ -9203,113 +9359,6 @@ function mountMaskStudio(host, o = {}) {
9203
9359
  emit();
9204
9360
  return studioApi;
9205
9361
  }
9206
- /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
9207
- function mountMaskTools(host, studio) {
9208
- const l = listeners();
9209
- const draw = (s) => {
9210
- host.innerHTML = [...studio.hasSegment || studio.canWant ? [{
9211
- id: "point",
9212
- label: "cut out a thing",
9213
- key: "a",
9214
- icon: "crosshairs"
9215
- }] : [], ...gt.map((t) => ({
9216
- id: t.id,
9217
- label: t.label,
9218
- key: t.key,
9219
- icon: t.icon
9220
- }))].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("");
9221
- };
9222
- l.on(host, "click", (e) => {
9223
- const t = e.target.closest("[data-tool]");
9224
- if (t) studio.setTool(t.dataset.tool);
9225
- });
9226
- l.on(document, "keydown", (e) => {
9227
- const ke = e;
9228
- if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
9229
- });
9230
- l.add(studio.subscribe(draw));
9231
- return { dispose: () => l.off() };
9232
- }
9233
- /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
9234
- function mountMaskVerbs(host, studio) {
9235
- const l = listeners();
9236
- let last = "";
9237
- const draw = (s) => {
9238
- 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">${[
9239
- "composite",
9240
- "mask",
9241
- "instances"
9242
- ].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>` : "") : "";
9243
- if (html !== last) host.innerHTML = last = html;
9244
- host.hidden = !html;
9245
- };
9246
- l.on(host, "click", (e) => {
9247
- const view = e.target.closest("[data-view]")?.dataset.view;
9248
- if (view) return studio.setView(view);
9249
- const v = e.target.closest("[data-v]")?.dataset.v;
9250
- if (v === "undo") studio.undo();
9251
- else if (v === "redo") studio.redo();
9252
- else if (v === "in") studio.zoom(1);
9253
- else if (v === "out") studio.zoom(-1);
9254
- else if (v === "fit") studio.zoom(0);
9255
- });
9256
- l.add(studio.subscribe(draw));
9257
- return { dispose: () => l.off() };
9258
- }
9259
- /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
9260
- function mountMaskRack(host, studio, part, o = {}) {
9261
- const l = listeners();
9262
- let last = "";
9263
- const draw = (s) => {
9264
- let html = "";
9265
- if (part === "found") {
9266
- 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>` : "");
9267
- 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>` : "";
9268
- } 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>` : "");
9269
- 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>`);
9270
- 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>`;
9271
- if (html !== last) host.innerHTML = last = html;
9272
- };
9273
- l.on(host, "click", (e) => {
9274
- const t = e.target;
9275
- const f = t.closest("[data-found]");
9276
- if (f) return studio.toggleFound(Number(f.dataset.found));
9277
- const m = t.closest("[data-mode]");
9278
- if (m) return studio.setMode(m.dataset.mode);
9279
- const show = t.closest("[data-show]");
9280
- if (show) return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
9281
- const drop = t.closest("[data-drop]");
9282
- if (drop) return studio.removeFound(Number(drop.dataset.drop));
9283
- const op = t.closest("[data-op]")?.dataset.op;
9284
- if (op === "merge") return studio.mergeFound();
9285
- if (op === "unfind") return studio.clearFound();
9286
- if (op === "invert") return studio.invert();
9287
- if (op === "clear") return studio.clear();
9288
- if (op === "smooth") return studio.smooth();
9289
- if (op === "expand") return studio.expand();
9290
- if (op === "shrink") return studio.shrink();
9291
- if (op === "save") return studio.save();
9292
- const restore = t.closest("[data-restore]");
9293
- if (restore) return studio.restore(Number(restore.dataset.restore));
9294
- const forget = t.closest("[data-forget]");
9295
- if (forget) return studio.forget(Number(forget.dataset.forget));
9296
- const ex = t.closest("[data-ex]");
9297
- if (ex) {
9298
- const kind = ex.dataset.ex;
9299
- studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
9300
- return;
9301
- }
9302
- if (t.closest("[data-all]")) studio.everything();
9303
- });
9304
- l.on(host, "input", (e) => {
9305
- const i = e.target;
9306
- if (i.dataset.size !== void 0) studio.setSize(Number(i.value));
9307
- if (i.dataset.tol !== void 0) studio.setTolerance(Number(i.value));
9308
- if (i.dataset.contig !== void 0) studio.setContiguous(i.checked);
9309
- });
9310
- l.add(studio.subscribe(draw));
9311
- return { dispose: () => l.off() };
9312
- }
9313
9362
  // packages/ai-views/src/mount-model.ts
9314
9363
  /**
9315
9364
  * ModelSelect in the DOM: the closed line (or the bar chip) with its one