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