@hackbuild/ai-views 0.1.12 → 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.
@@ -6665,18 +6665,16 @@ const IMAGEGEN_RECORDS = [{
6665
6665
  }];
6666
6666
  /**
6667
6667
  * Listed for pickers, not registered by attachImagegen, so routing by
6668
- * capability keeps SD-Turbo: SDXL-Turbo runs on `generateXl`. The
6669
- * export's input and output names and dtypes were read from the end of
6670
- * each onnx file (2026-11-29, measured); the pipeline has not run on the
6671
- * real weights. `loadImagegen(hub, { id:
6672
- * "sdxl-turbo" })` adds it and loads it.
6668
+ * capability keeps SD-Turbo: SDXL-Turbo runs on `generateXl`. Its graph
6669
+ * names and dtypes were read from the export (2026-11-29) and it made a
6670
+ * picture on the real weights (2026-11-30, measured). `loadImagegen(hub,
6671
+ * { id: "sdxl-turbo" })` adds it and loads it.
6673
6672
  */
6674
6673
  const IMAGEGEN_PICKER_RECORDS = [{
6675
6674
  id: "sdxl-turbo",
6676
6675
  label: "sdxl-turbo 512",
6677
6676
  speed: "steady",
6678
- verdict: "not run yet",
6679
- unrunnable: "not run yet. the graph names and dtypes are read from the export's files (measured); the pipeline has not run on them.",
6677
+ verdict: "best looking, run once",
6680
6678
  group: "good",
6681
6679
  provides: ["imagegen"],
6682
6680
  provider: "ort",
@@ -6703,7 +6701,8 @@ const IMAGEGEN_PICKER_RECORDS = [{
6703
6701
  notes: [
6704
6702
  "two text encoders, pooled embeddings and time ids, on generateXl",
6705
6703
  "fp16 edges and a float16 timestep; input_ids int32 for the first encoder and int64 for the second (measured from the graphs)",
6706
- "the highest quality of the three image models"
6704
+ "the highest quality of the three image models",
6705
+ "run on real weights 2026-11-30, headless chrome on an apple m1: one step at 512 px in 9,966 ms, text 4,291, unet 2,315, vae 3,346 ms (measured); a faint fine grid shows on some surfaces"
6707
6706
  ],
6708
6707
  form: {
6709
6708
  steps: {
@@ -8640,31 +8639,7 @@ function mountCameraFeed(host, o = {}) {
8640
8639
  emit();
8641
8640
  return feed;
8642
8641
  }
8643
- // packages/ai-views/src/mount-mask.ts
8644
- /**
8645
- * MaskStudio: drop an image, press a thing
8646
- * to cut it out (a click segment model such as SlimSAM), fix the mask by
8647
- * hand with the wand, brush and lasso of hackbuild-ui maskEditor (x swaps
8648
- * add and erase, [ and ] size the brush, ctrl z undoes), zoom and fit, and
8649
- * export the mask, a matte or the cutout. With a segment everything model
8650
- * (FastSAM) one press finds every object; each lands in the found list and
8651
- * a press adds it to the mask. Models are functions the page passes, so
8652
- * stubs run the studio with no weights. Three views (composite, mask,
8653
- * found objects) paint over the canvas; the pointer previews the click cut
8654
- * or lights the found object under it; two fingers or ctrl and the wheel
8655
- * zoom; a page that loads models on demand hears `onWant` when a tool needs
8656
- * one.
8657
- */
8658
- const ZOOMS = [
8659
- .5,
8660
- .75,
8661
- 1,
8662
- 1.5,
8663
- 2,
8664
- 3,
8665
- 4
8666
- ];
8667
- const clampZoom = (z) => Math.max(.25, Math.min(6, z));
8642
+ // packages/ai-views/src/mask-pixels.ts
8668
8643
  /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
8669
8644
  function tintInto(rgba, mask, rgb, alpha) {
8670
8645
  for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
@@ -8709,6 +8684,267 @@ function thumbOf(img) {
8709
8684
  t.getContext("2d")?.drawImage(c, 0, 0, t.width, t.height);
8710
8685
  return t.toDataURL("image/png");
8711
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));
8712
8948
  /**
8713
8949
  * Mounts a mask studio on a host: drop or open an image, then cut masks with the point, wand, brush
8714
8950
  * and lasso tools or a segment model.
@@ -8765,56 +9001,17 @@ function mountMaskStudio(host, o = {}) {
8765
9001
  for (const fn of subs) fn(s);
8766
9002
  paint();
8767
9003
  };
8768
- let painted = "";
8769
- let frameReq = 0;
8770
- const paint = () => {
8771
- if (frameReq) return;
8772
- frameReq = typeof requestAnimationFrame === "function" ? requestAnimationFrame(drawOver) : (drawOver(), 0);
8773
- };
8774
- const drawOver = () => {
8775
- frameReq = 0;
8776
- const w = ed?.width ?? 0;
8777
- const h = ed?.height ?? 0;
8778
- const g = over.getContext("2d");
8779
- if (!g || !w || !h || !pixels) return;
8780
- if (over.width !== w || over.height !== h) {
8781
- over.width = w;
8782
- over.height = h;
8783
- }
8784
- const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? editor.state.coverage + ":" + (ed?.canUndo ? 1 : 0) : ""}:${found.map((f) => f.hidden ? 0 : 1).join("")}`;
8785
- if (view === "composite" && hover < 0 && !preview) {
8786
- if (painted !== "clear") g.clearRect(0, 0, w, h);
8787
- painted = "clear";
8788
- return;
8789
- }
8790
- if (key === painted && view !== "mask") return;
8791
- painted = key;
8792
- if (view === "mask") {
8793
- g.putImageData(new ImageData(er(editor.mask(), "matte"), w, h), 0, 0);
8794
- return;
8795
- }
8796
- const rgba = new Uint8ClampedArray(w * h * 4);
8797
- if (view === "instances") found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, nr(f.colour), 150));
8798
- const hot = hover >= 0 ? found[hover] : void 0;
8799
- if (hot) tintInto(rgba, hot.mask, nr(hot.colour), 220);
8800
- else if (preview) tintInto(rgba, preview, [
8801
- 254,
8802
- 3,
8803
- 134
8804
- ], 110);
8805
- g.putImageData(new ImageData(rgba, w, h), 0, 0);
8806
- if (view === "instances") {
8807
- g.lineWidth = Math.max(1, w / 400);
8808
- g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
8809
- for (const f of found) {
8810
- if (f.hidden || !f.box) continue;
8811
- g.strokeStyle = f.colour;
8812
- g.fillStyle = f.colour;
8813
- g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
8814
- g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
8815
- }
8816
- }
8817
- };
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
+ }));
8818
9015
  const editor = ns(canvas, {
8819
9016
  tool: tool === "point" ? "wand" : tool,
8820
9017
  onError: (e) => (error = `the image did not load: ${e.message}`, emit())
@@ -8918,63 +9115,21 @@ function mountMaskStudio(host, o = {}) {
8918
9115
  canvas.addEventListener("pointermove", onHover);
8919
9116
  canvas.addEventListener("pointerleave", offHover);
8920
9117
  l.add(() => (canvas.removeEventListener("pointermove", onHover), canvas.removeEventListener("pointerleave", offHover)));
8921
- const touches = /* @__PURE__ */ new Map();
8922
- let pinch = null;
8923
- const spread = () => {
8924
- const [a, b] = [...touches.values()];
8925
- return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
8926
- };
8927
- l.on(well, "pointerdown", (e) => {
8928
- const pe = e;
8929
- if (pe.pointerType !== "touch") return;
8930
- touches.set(pe.pointerId, {
8931
- x: pe.clientX,
8932
- y: pe.clientY
8933
- });
8934
- if (touches.size === 2) {
8935
- editor.cancel();
8936
- pinch = {
8937
- d: spread() || 1,
8938
- z: zoom
8939
- };
8940
- }
9118
+ pinchZoom(l, well, {
9119
+ zoom: () => zoom,
9120
+ zoomTo: (z) => studioApi.zoomTo(z),
9121
+ cancel: () => editor.cancel(),
9122
+ ready: () => !!ed?.ready
8941
9123
  });
8942
- l.on(well, "pointermove", (e) => {
8943
- const pe = e;
8944
- if (!touches.has(pe.pointerId)) return;
8945
- touches.set(pe.pointerId, {
8946
- x: pe.clientX,
8947
- y: pe.clientY
8948
- });
8949
- if (pinch && touches.size === 2) studioApi.zoomTo(pinch.z * (spread() / pinch.d));
8950
- });
8951
- const lift = (e) => {
8952
- touches.delete(e.pointerId);
8953
- if (touches.size < 2) pinch = null;
8954
- };
8955
- l.on(well, "pointerup", lift);
8956
- l.on(well, "pointercancel", lift);
8957
- l.on(well, "wheel", (e) => {
8958
- const we = e;
8959
- if (!we.ctrlKey || !ed?.ready) return;
8960
- we.preventDefault();
8961
- studioApi.zoomTo(zoom * Math.exp(-we.deltaY / 200));
8962
- });
8963
- l.on(document, "keydown", (e) => {
8964
- const ke = e;
8965
- if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]")) return;
8966
- const k = ke.key.toLowerCase();
8967
- const cmd = ke.ctrlKey || ke.metaKey;
8968
- if (cmd && k === "o") return ke.preventDefault(), input.click();
8969
- if (!ed?.ready) return;
8970
- if (cmd && (k === "z" || k === "y")) return ke.preventDefault(), void (k === "y" || ke.shiftKey ? editor.redo() : editor.undo());
8971
- 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));
8972
- if (cmd && k === "i") return ke.preventDefault(), editor.invert();
8973
- if (cmd) return;
8974
- if (k === "delete") return ke.preventDefault(), editor.clear();
8975
- if (k === "+" || k === "=") return studioApi.zoom(1);
8976
- if (k === "-") return studioApi.zoom(-1);
8977
- 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)
8978
9133
  });
8979
9134
  canvas.addEventListener("pointerdown", onPoint, true);
8980
9135
  l.add(() => canvas.removeEventListener("pointerdown", onPoint, true));
@@ -9204,113 +9359,6 @@ function mountMaskStudio(host, o = {}) {
9204
9359
  emit();
9205
9360
  return studioApi;
9206
9361
  }
9207
- /** The tool rail of a studio: point (when a click model is set), wand, brush, lasso, and segment everything (when that model is set). */
9208
- function mountMaskTools(host, studio) {
9209
- const l = listeners();
9210
- const draw = (s) => {
9211
- host.innerHTML = [...studio.hasSegment || studio.canWant ? [{
9212
- id: "point",
9213
- label: "cut out a thing",
9214
- key: "a",
9215
- icon: "crosshairs"
9216
- }] : [], ...gt.map((t) => ({
9217
- id: t.id,
9218
- label: t.label,
9219
- key: t.key,
9220
- icon: t.icon
9221
- }))].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("");
9222
- };
9223
- l.on(host, "click", (e) => {
9224
- const t = e.target.closest("[data-tool]");
9225
- if (t) studio.setTool(t.dataset.tool);
9226
- });
9227
- l.on(document, "keydown", (e) => {
9228
- const ke = e;
9229
- if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
9230
- });
9231
- l.add(studio.subscribe(draw));
9232
- return { dispose: () => l.off() };
9233
- }
9234
- /** The verb row on the canvas: undo and redo once there is a change, zoom once there is an image. */
9235
- function mountMaskVerbs(host, studio) {
9236
- const l = listeners();
9237
- let last = "";
9238
- const draw = (s) => {
9239
- 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">${[
9240
- "composite",
9241
- "mask",
9242
- "instances"
9243
- ].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>` : "") : "";
9244
- if (html !== last) host.innerHTML = last = html;
9245
- host.hidden = !html;
9246
- };
9247
- l.on(host, "click", (e) => {
9248
- const view = e.target.closest("[data-view]")?.dataset.view;
9249
- if (view) return studio.setView(view);
9250
- const v = e.target.closest("[data-v]")?.dataset.v;
9251
- if (v === "undo") studio.undo();
9252
- else if (v === "redo") studio.redo();
9253
- else if (v === "in") studio.zoom(1);
9254
- else if (v === "out") studio.zoom(-1);
9255
- else if (v === "fit") studio.zoom(0);
9256
- });
9257
- l.add(studio.subscribe(draw));
9258
- return { dispose: () => l.off() };
9259
- }
9260
- /** The rack parts: what was found, the mask tools' settings, and the exports once there is a mask. */
9261
- function mountMaskRack(host, studio, part, o = {}) {
9262
- const l = listeners();
9263
- let last = "";
9264
- const draw = (s) => {
9265
- let html = "";
9266
- if (part === "found") {
9267
- 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>` : "");
9268
- 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>` : "";
9269
- } 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>` : "");
9270
- 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>`);
9271
- 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>`;
9272
- if (html !== last) host.innerHTML = last = html;
9273
- };
9274
- l.on(host, "click", (e) => {
9275
- const t = e.target;
9276
- const f = t.closest("[data-found]");
9277
- if (f) return studio.toggleFound(Number(f.dataset.found));
9278
- const m = t.closest("[data-mode]");
9279
- if (m) return studio.setMode(m.dataset.mode);
9280
- const show = t.closest("[data-show]");
9281
- if (show) return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
9282
- const drop = t.closest("[data-drop]");
9283
- if (drop) return studio.removeFound(Number(drop.dataset.drop));
9284
- const op = t.closest("[data-op]")?.dataset.op;
9285
- if (op === "merge") return studio.mergeFound();
9286
- if (op === "unfind") return studio.clearFound();
9287
- if (op === "invert") return studio.invert();
9288
- if (op === "clear") return studio.clear();
9289
- if (op === "smooth") return studio.smooth();
9290
- if (op === "expand") return studio.expand();
9291
- if (op === "shrink") return studio.shrink();
9292
- if (op === "save") return studio.save();
9293
- const restore = t.closest("[data-restore]");
9294
- if (restore) return studio.restore(Number(restore.dataset.restore));
9295
- const forget = t.closest("[data-forget]");
9296
- if (forget) return studio.forget(Number(forget.dataset.forget));
9297
- const ex = t.closest("[data-ex]");
9298
- if (ex) {
9299
- const kind = ex.dataset.ex;
9300
- studio.exportAs(kind).then((b) => b && download(`${o.name ?? "mask"}-${kind}.png`, b));
9301
- return;
9302
- }
9303
- if (t.closest("[data-all]")) studio.everything();
9304
- });
9305
- l.on(host, "input", (e) => {
9306
- const i = e.target;
9307
- if (i.dataset.size !== void 0) studio.setSize(Number(i.value));
9308
- if (i.dataset.tol !== void 0) studio.setTolerance(Number(i.value));
9309
- if (i.dataset.contig !== void 0) studio.setContiguous(i.checked);
9310
- });
9311
- l.add(studio.subscribe(draw));
9312
- return { dispose: () => l.off() };
9313
- }
9314
9362
  // packages/ai-views/src/mount-model.ts
9315
9363
  /**
9316
9364
  * ModelSelect in the DOM: the closed line (or the bar chip) with its one