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