@hackbuild/ai-views 0.1.2 → 0.1.6

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.
@@ -6,11 +6,35 @@
6
6
  * export the mask, a matte or the cutout. With a segment everything model
7
7
  * (FastSAM) one press finds every object; each lands in the found list and
8
8
  * a press adds it to the mask. Models are functions the page passes, so
9
- * stubs run the studio with no weights.
9
+ * stubs run the studio with no weights. Three views (composite, mask,
10
+ * found objects) paint over the canvas; the pointer previews the click cut
11
+ * or lights the found object under it; two fingers or ctrl and the wheel
12
+ * zoom; a page that loads models on demand hears `onWant` when a tool needs
13
+ * one.
10
14
  */
11
- import { INSTANCE_COLOURS, MASK_TOOLS, maskEditor, strokeIcon } from "@virgilvox/hackbuild-ui/vanilla";
15
+ import { INSTANCE_COLOURS, MASK_TOOLS, invertMask, maskEditor, maskRgba, parseRgb, strokeIcon } from "@virgilvox/hackbuild-ui/vanilla";
12
16
  import { ICON, download, esc, listeners, show } from "./dom.js";
13
17
  const ZOOMS = [0.5, 0.75, 1, 1.5, 2, 3, 4];
18
+ const clampZoom = (z) => Math.max(0.25, Math.min(6, z));
19
+ /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
20
+ function tintInto(rgba, mask, rgb, alpha) {
21
+ for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
22
+ if (!mask[i])
23
+ continue;
24
+ rgba[j] = rgb[0];
25
+ rgba[j + 1] = rgb[1];
26
+ rgba[j + 2] = rgb[2];
27
+ rgba[j + 3] = alpha;
28
+ }
29
+ }
30
+ /** ImageData to a png Blob. */
31
+ function pngOf(img) {
32
+ const c = document.createElement("canvas");
33
+ c.width = img.width;
34
+ c.height = img.height;
35
+ c.getContext("2d")?.putImageData(img, 0, 0);
36
+ return new Promise((ok) => c.toBlob((b) => ok(b), "image/png"));
37
+ }
14
38
  /** Pixels of a drawable, for a model. */
15
39
  function pixelsOf(src) {
16
40
  const c = document.createElement("canvas");
@@ -42,18 +66,23 @@ export function mountMaskStudio(host, o = {}) {
42
66
  const l = listeners();
43
67
  host.innerHTML =
44
68
  `<div class="hb-lay-empty" data-empty><span class="hb-lay-empty-name">${esc(o.title ?? "drop an image")}</span><p class="hb-lay-empty-note">${esc(o.note ?? "press a thing to cut it out. the picture stays on this machine.")}</p><div class="hb-lay-empty-acts"><button type="button" class="hb-btn hb-btn-go" data-pick>open an image</button>${o.sampleLabel ? `<button type="button" class="hb-btn" data-sample>${esc(o.sampleLabel)}</button>` : ""}</div></div>` +
45
- `<div class="hb-mask is-fill" data-studio hidden><div class="hb-mask-well"><div class="hb-mask-frame"><canvas class="hb-mask-canvas" tabindex="0" role="img" aria-label="image and mask"></canvas><p class="hb-mask-hint" aria-live="polite"></p></div></div></div>` +
69
+ `<div class="hb-mask is-fill" data-studio hidden><div class="hb-mask-well"><div class="hb-mask-frame"><canvas class="hb-mask-canvas" tabindex="0" role="img" aria-label="image and mask"></canvas><canvas class="hb-pc-img" data-over aria-hidden="true"></canvas><p class="hb-mask-hint" aria-live="polite"></p></div></div></div>` +
46
70
  `<input type="file" accept="image/*" hidden>`;
47
71
  const empty = host.querySelector("[data-empty]");
48
72
  const studio = host.querySelector("[data-studio]");
49
73
  const well = host.querySelector(".hb-mask-well");
50
74
  const frame = host.querySelector(".hb-mask-frame");
51
- const canvas = host.querySelector("canvas");
75
+ const canvas = host.querySelector(".hb-mask-canvas");
76
+ const over = host.querySelector("[data-over]");
52
77
  const hint = host.querySelector(".hb-mask-hint");
53
78
  const input = host.querySelector("input[type=file]");
54
79
  const subs = new Set();
55
80
  let tool = models.segment ? "point" : "wand";
56
81
  let zoom = 1;
82
+ let view = "composite";
83
+ let hover = -1;
84
+ let preview = null;
85
+ let wantAll = null;
57
86
  let busy = "";
58
87
  let error = "";
59
88
  let pixels = null;
@@ -72,6 +101,9 @@ export function mountMaskStudio(host, o = {}) {
72
101
  coverage: ed?.coverage ?? 0,
73
102
  zoom,
74
103
  busy,
104
+ contiguous: ed?.contiguous ?? true,
105
+ view,
106
+ hover,
75
107
  found,
76
108
  saved: saved.map(({ bytes: _b, ...rest }) => rest),
77
109
  width: ed?.width ?? 0,
@@ -83,6 +115,62 @@ export function mountMaskStudio(host, o = {}) {
83
115
  hint.textContent = s.busy || s.error || (tool === "point" ? "press a thing to cut it out. x takes it away instead." : (MASK_TOOLS.find((t) => t.id === tool)?.hint ?? ""));
84
116
  for (const fn of subs)
85
117
  fn(s);
118
+ paint();
119
+ };
120
+ // the paint over the canvas: the mask alone, the found objects in colour, or the pointer's preview
121
+ let painted = "";
122
+ let frameReq = 0;
123
+ const paint = () => {
124
+ if (frameReq)
125
+ return;
126
+ frameReq = typeof requestAnimationFrame === "function" ? requestAnimationFrame(drawOver) : (drawOver(), 0);
127
+ };
128
+ const drawOver = () => {
129
+ frameReq = 0;
130
+ const w = ed?.width ?? 0;
131
+ const h = ed?.height ?? 0;
132
+ const g = over.getContext("2d");
133
+ if (!g || !w || !h || !pixels)
134
+ return;
135
+ if (over.width !== w || over.height !== h) {
136
+ over.width = w;
137
+ over.height = h;
138
+ }
139
+ const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? editor.state.coverage + ":" + (ed?.canUndo ? 1 : 0) : ""}:${found.map((f) => (f.hidden ? 0 : 1)).join("")}`;
140
+ if (view === "composite" && hover < 0 && !preview) {
141
+ if (painted !== "clear")
142
+ g.clearRect(0, 0, w, h);
143
+ painted = "clear";
144
+ return;
145
+ }
146
+ if (key === painted && view !== "mask")
147
+ return;
148
+ painted = key;
149
+ if (view === "mask") {
150
+ g.putImageData(new ImageData(maskRgba(editor.mask(), "matte"), w, h), 0, 0);
151
+ return;
152
+ }
153
+ const rgba = new Uint8ClampedArray(w * h * 4);
154
+ if (view === "instances")
155
+ found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, parseRgb(f.colour), 150));
156
+ const hot = hover >= 0 ? found[hover] : undefined;
157
+ if (hot)
158
+ tintInto(rgba, hot.mask, parseRgb(hot.colour), 220);
159
+ else if (preview)
160
+ tintInto(rgba, preview, [254, 3, 134], 110);
161
+ g.putImageData(new ImageData(rgba, w, h), 0, 0);
162
+ if (view === "instances") {
163
+ g.lineWidth = Math.max(1, w / 400);
164
+ g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
165
+ for (const f of found) {
166
+ if (f.hidden || !f.box)
167
+ continue;
168
+ g.strokeStyle = f.colour;
169
+ g.fillStyle = f.colour;
170
+ g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
171
+ g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
172
+ }
173
+ }
86
174
  };
87
175
  const editor = maskEditor(canvas, { tool: tool === "point" ? "wand" : tool, onError: (e) => ((error = `the image did not load: ${e.message}`), emit()) });
88
176
  l.add(editor.subscribe((s) => ((ed = s), emit())));
@@ -94,6 +182,7 @@ export function mountMaskStudio(host, o = {}) {
94
182
  studio.style.setProperty("--hb-mask-w", `${Math.round(fitW * zoom)}px`);
95
183
  studio.classList.toggle("is-zoomed", zoom > 1);
96
184
  };
185
+ const zoomStep = (dir) => (dir > 0 ? ZOOMS.find((z) => z > zoom + 1e-3) : [...ZOOMS].reverse().find((z) => z < zoom - 1e-3)) ?? zoom;
97
186
  const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => applyZoom()) : null;
98
187
  ro?.observe(well);
99
188
  l.add(() => ro?.disconnect());
@@ -121,19 +210,153 @@ export function mountMaskStudio(host, o = {}) {
121
210
  emit();
122
211
  }
123
212
  };
213
+ const at = (pe) => {
214
+ const r = canvas.getBoundingClientRect();
215
+ const w = ed?.width ?? 0;
216
+ const h = ed?.height ?? 0;
217
+ return { x: Math.max(0, Math.min(w - 1, Math.round(((pe.clientX - r.left) / r.width) * w))), y: Math.max(0, Math.min(h - 1, Math.round(((pe.clientY - r.top) / r.height) * h))) };
218
+ };
219
+ const foundAt = (x, y) => found.findIndex((f) => !f.hidden && f.mask[y * (ed?.width ?? 0) + x]);
124
220
  const onPoint = (e) => {
125
221
  if (tool !== "point")
126
222
  return;
127
223
  e.stopImmediatePropagation();
128
224
  e.preventDefault();
129
225
  const pe = e;
130
- const r = canvas.getBoundingClientRect();
131
226
  if (!ed?.ready)
132
227
  return;
133
- const x = Math.round(((pe.clientX - r.left) / r.width) * ed.width);
134
- const y = Math.round(((pe.clientY - r.top) / r.height) * ed.height);
228
+ const { x, y } = at(pe);
229
+ // a press on a found object takes it in or out, as the segment everything page does
230
+ const i = foundAt(x, y);
231
+ if (i >= 0)
232
+ return studioApi.toggleFound(i);
233
+ if (!models.segment)
234
+ return o.onWant?.("segment");
235
+ preview = null;
135
236
  void cut(x, y, (ed.mode === "erase") !== pe.shiftKey);
136
237
  };
238
+ // the pointer lights the found object under it, or previews the click cut once the model is in
239
+ let asking = false;
240
+ let next = null;
241
+ const ask = async (p) => {
242
+ if (!pixels || !models.segment)
243
+ return;
244
+ asking = true;
245
+ try {
246
+ const m = await models.segment(pixels, p);
247
+ if (tool === "point" && next !== null)
248
+ preview = m;
249
+ }
250
+ catch {
251
+ preview = null;
252
+ }
253
+ finally {
254
+ asking = false;
255
+ }
256
+ paint();
257
+ const n = next;
258
+ if (n && (n.x !== p.x || n.y !== p.y))
259
+ void ask(n);
260
+ };
261
+ const onHover = (e) => {
262
+ const pe = e;
263
+ if (!ed?.ready || pe.buttons || pe.pointerType === "touch")
264
+ return;
265
+ const p = at(pe);
266
+ const i = found.length && (tool === "point" || view === "instances") ? foundAt(p.x, p.y) : -1;
267
+ if (i !== hover) {
268
+ hover = i;
269
+ emit();
270
+ }
271
+ if (i >= 0 || tool !== "point" || !models.segment) {
272
+ next = null;
273
+ if (preview)
274
+ (preview = null), paint();
275
+ return;
276
+ }
277
+ next = p;
278
+ if (!asking)
279
+ void ask(p);
280
+ };
281
+ const offHover = () => {
282
+ next = null;
283
+ preview = null;
284
+ if (hover >= 0)
285
+ (hover = -1), emit();
286
+ else
287
+ paint();
288
+ };
289
+ canvas.addEventListener("pointermove", onHover);
290
+ canvas.addEventListener("pointerleave", offHover);
291
+ l.add(() => (canvas.removeEventListener("pointermove", onHover), canvas.removeEventListener("pointerleave", offHover)));
292
+ // two fingers pinch the zoom; ctrl and the wheel (a trackpad pinch) do the same
293
+ const touches = new Map();
294
+ let pinch = null;
295
+ const spread = () => {
296
+ const [a, b] = [...touches.values()];
297
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
298
+ };
299
+ l.on(well, "pointerdown", (e) => {
300
+ const pe = e;
301
+ if (pe.pointerType !== "touch")
302
+ return;
303
+ touches.set(pe.pointerId, { x: pe.clientX, y: pe.clientY });
304
+ if (touches.size === 2) {
305
+ editor.cancel();
306
+ pinch = { d: spread() || 1, z: zoom };
307
+ }
308
+ });
309
+ l.on(well, "pointermove", (e) => {
310
+ const pe = e;
311
+ if (!touches.has(pe.pointerId))
312
+ return;
313
+ touches.set(pe.pointerId, { x: pe.clientX, y: pe.clientY });
314
+ if (pinch && touches.size === 2)
315
+ studioApi.zoomTo(pinch.z * (spread() / pinch.d));
316
+ });
317
+ const lift = (e) => {
318
+ touches.delete(e.pointerId);
319
+ if (touches.size < 2)
320
+ pinch = null;
321
+ };
322
+ l.on(well, "pointerup", lift);
323
+ l.on(well, "pointercancel", lift);
324
+ l.on(well, "wheel", (e) => {
325
+ const we = e;
326
+ if (!we.ctrlKey || !ed?.ready)
327
+ return;
328
+ we.preventDefault();
329
+ studioApi.zoomTo(zoom * Math.exp(-we.deltaY / 200));
330
+ });
331
+ // the page keys: open, export, undo, invert, clear, zoom; on the document, so they come before a page's window keys
332
+ l.on(document, "keydown", (e) => {
333
+ const ke = e;
334
+ if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]"))
335
+ return;
336
+ const k = ke.key.toLowerCase();
337
+ const cmd = ke.ctrlKey || ke.metaKey;
338
+ if (cmd && k === "o")
339
+ return ke.preventDefault(), input.click();
340
+ if (!ed?.ready)
341
+ return;
342
+ // the canvas takes undo itself while focused; anywhere else on the page it lands here
343
+ if (cmd && (k === "z" || k === "y"))
344
+ return ke.preventDefault(), void (k === "y" || ke.shiftKey ? editor.redo() : editor.undo());
345
+ if (cmd && k === "s")
346
+ return ke.preventDefault(), void studioApi.exportAs(ke.shiftKey ? "cutout" : "matte").then((b) => b && download(`${o.name ?? "mask"}-${ke.shiftKey ? "cutout" : "matte"}.png`, b));
347
+ if (cmd && k === "i")
348
+ return ke.preventDefault(), editor.invert();
349
+ if (cmd)
350
+ return;
351
+ if (k === "delete")
352
+ return ke.preventDefault(), editor.clear();
353
+ if (k === "+" || k === "=")
354
+ return studioApi.zoom(1);
355
+ if (k === "-")
356
+ return studioApi.zoom(-1);
357
+ if (k === "0")
358
+ return studioApi.zoom(0);
359
+ });
137
360
  // capture, so it runs before the editor's own handler on the canvas
138
361
  canvas.addEventListener("pointerdown", onPoint, true);
139
362
  l.add(() => canvas.removeEventListener("pointerdown", onPoint, true));
@@ -164,6 +387,8 @@ export function mountMaskStudio(host, o = {}) {
164
387
  error = "";
165
388
  found = [];
166
389
  saved = [];
390
+ hover = -1;
391
+ preview = null;
167
392
  let drawable = null;
168
393
  if (typeof src === "string") {
169
394
  const img = new Image();
@@ -189,9 +414,13 @@ export function mountMaskStudio(host, o = {}) {
189
414
  canvas.focus({ preventScroll: true });
190
415
  },
191
416
  setTool(t) {
192
- if (t === "point" && !models.segment)
193
- return;
417
+ if (t === "point" && !models.segment) {
418
+ if (!o.onWant)
419
+ return;
420
+ o.onWant("segment");
421
+ }
194
422
  tool = t;
423
+ preview = null;
195
424
  if (t !== "point")
196
425
  editor.setTool(t);
197
426
  canvas.dataset.tool = t;
@@ -226,24 +455,76 @@ export function mountMaskStudio(host, o = {}) {
226
455
  },
227
456
  mask: (kind = "alpha") => (ed?.ready ? editor.toImageData(kind) : null),
228
457
  zoom(dir) {
229
- if (dir === 0)
230
- zoom = 1;
231
- else {
232
- const i = ZOOMS.indexOf(zoom);
233
- zoom = ZOOMS[Math.max(0, Math.min(ZOOMS.length - 1, i + dir))];
234
- }
458
+ zoom = dir === 0 ? 1 : zoomStep(dir);
459
+ applyZoom();
460
+ emit();
461
+ },
462
+ zoomTo(z) {
463
+ zoom = clampZoom(z);
235
464
  applyZoom();
236
465
  emit();
237
466
  },
238
- async everything() {
239
- if (!models.everything || !pixels)
467
+ setView(v) {
468
+ view = v;
469
+ emit();
470
+ },
471
+ setContiguous: (on) => editor.setContiguous(on),
472
+ setMask(m) {
473
+ if (ed?.ready && m.length === ed.width * ed.height)
474
+ editor.setMask(m);
475
+ },
476
+ addFound(list) {
477
+ const n = found.length;
478
+ found = [...found, ...list.filter((f) => f.mask.length === (ed?.width ?? 0) * (ed?.height ?? 0)).map((f, i) => ({ ...f, on: false, hidden: false, colour: INSTANCE_COLOURS[(n + i) % INSTANCE_COLOURS.length] }))];
479
+ if (found.length > n && view === "composite")
480
+ view = "instances";
481
+ emit();
482
+ },
483
+ showFound(i, on) {
484
+ found = found.map((x, k) => (k === i ? { ...x, hidden: !on } : x));
485
+ emit();
486
+ },
487
+ removeFound(i) {
488
+ found = found.filter((_, k) => k !== i);
489
+ hover = -1;
490
+ emit();
491
+ },
492
+ mergeFound() {
493
+ if (!ed?.ready || !found.length)
240
494
  return;
495
+ const cur = editor.mask();
496
+ for (const f of found)
497
+ if (!f.hidden)
498
+ for (let p = 0; p < cur.length; p++)
499
+ if (f.mask[p])
500
+ cur[p] = 255;
501
+ found = found.map((x) => (x.hidden ? x : { ...x, on: true }));
502
+ editor.setMask(cur);
503
+ },
504
+ clearFound() {
505
+ found = [];
506
+ hover = -1;
507
+ if (view === "instances")
508
+ view = "composite";
509
+ emit();
510
+ },
511
+ pixels: () => pixels,
512
+ async everything(eo) {
513
+ if (!pixels)
514
+ return;
515
+ if (!models.everything) {
516
+ wantAll = eo ?? {};
517
+ return o.onWant?.("everything");
518
+ }
519
+ wantAll = null;
241
520
  busy = "finding every object";
242
521
  error = "";
243
522
  emit();
244
523
  try {
245
- const list = await models.everything(pixels);
246
- found = list.map((f, i) => ({ ...f, on: false, colour: INSTANCE_COLOURS[i % INSTANCE_COLOURS.length] }));
524
+ const list = await models.everything(pixels, eo);
525
+ found = list.map((f, i) => ({ ...f, on: false, hidden: false, colour: INSTANCE_COLOURS[i % INSTANCE_COLOURS.length] }));
526
+ if (found.length)
527
+ view = "instances";
247
528
  }
248
529
  catch (e) {
249
530
  error = `segment everything failed: ${e instanceof Error ? e.message : String(e)}`;
@@ -268,6 +549,8 @@ export function mountMaskStudio(host, o = {}) {
268
549
  async exportAs(kind) {
269
550
  if (!ed?.ready)
270
551
  return null;
552
+ if (kind === "inverse")
553
+ return pngOf(new ImageData(maskRgba(invertMask(editor.mask()), "matte"), ed.width, ed.height));
271
554
  return editor.toBlob(kind);
272
555
  },
273
556
  get hasEverything() {
@@ -276,6 +559,9 @@ export function mountMaskStudio(host, o = {}) {
276
559
  get hasSegment() {
277
560
  return !!models.segment;
278
561
  },
562
+ get canWant() {
563
+ return !!o.onWant;
564
+ },
279
565
  state,
280
566
  subscribe(fn) {
281
567
  subs.add(fn);
@@ -289,9 +575,11 @@ export function mountMaskStudio(host, o = {}) {
289
575
  tool = "point";
290
576
  canvas.dataset.tool = "point";
291
577
  }
292
- if (tool === "point" && !m.segment)
578
+ if (tool === "point" && !m.segment && !o.onWant)
293
579
  studioApi.setTool("wand");
294
580
  emit();
581
+ if (wantAll && m.everything)
582
+ void studioApi.everything(wantAll);
295
583
  },
296
584
  pick: () => input.click(),
297
585
  dispose() {
@@ -309,7 +597,7 @@ export function mountMaskTools(host, studio) {
309
597
  const l = listeners();
310
598
  const draw = (s) => {
311
599
  const tools = [
312
- ...(studio.hasSegment ? [{ id: "point", label: "cut out a thing", key: "a", icon: "crosshairs" }] : []),
600
+ ...(studio.hasSegment || studio.canWant ? [{ id: "point", label: "cut out a thing", key: "a", icon: "crosshairs" }] : []),
313
601
  ...MASK_TOOLS.map((t) => ({ id: t.id, label: t.label, key: t.key, icon: t.icon })),
314
602
  ];
315
603
  host.innerHTML = tools.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}">${strokeIcon(t.icon, { size: 18 })}</button>`).join("");
@@ -321,16 +609,7 @@ export function mountMaskTools(host, studio) {
321
609
  });
322
610
  l.on(document, "keydown", (e) => {
323
611
  const ke = e;
324
- const typing = !!ke.target.closest?.("input,textarea,[contenteditable]");
325
- if (!typing && !ke.ctrlKey && !ke.metaKey && studio.state().ready) {
326
- if (ke.key === "+" || ke.key === "=")
327
- return studio.zoom(1);
328
- if (ke.key === "-")
329
- return studio.zoom(-1);
330
- if (ke.key === "0")
331
- return studio.zoom(0);
332
- }
333
- if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && studio.hasSegment && !ke.target.closest?.("input,textarea,[contenteditable]"))
612
+ if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]"))
334
613
  studio.setTool("point");
335
614
  });
336
615
  l.add(studio.subscribe(draw));
@@ -345,13 +624,19 @@ export function mountMaskVerbs(host, studio) {
345
624
  ? `${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>` : ""}` +
346
625
  // zoom out and fit show once zoomed in, so the row stays short
347
626
  (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>` : "") +
348
- `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>`
627
+ `<button type="button" class="hb-iconbtn" data-v="in" aria-label="zoom in" title="zoom in (+)">${ICON.zoomIn}</button>` +
628
+ (s.coverage > 0 || s.found.length
629
+ ? `<div class="hb-seg is-toggle" role="group" aria-label="view">${["composite", "mask", "instances"].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>`
630
+ : "")
349
631
  : "";
350
632
  if (html !== last)
351
633
  host.innerHTML = last = html;
352
634
  host.hidden = !html;
353
635
  };
354
636
  l.on(host, "click", (e) => {
637
+ const view = e.target.closest("[data-view]")?.dataset.view;
638
+ if (view)
639
+ return studio.setView(view);
355
640
  const v = e.target.closest("[data-v]")?.dataset.v;
356
641
  if (v === "undo")
357
642
  studio.undo();
@@ -375,9 +660,9 @@ export function mountMaskRack(host, studio, part, o = {}) {
375
660
  let html = "";
376
661
  if (part === "found") {
377
662
  html = s.found.length
378
- ? `<div class="hb-inst"><ul class="hb-inst-list">${s.found.map((f, i) => `<li class="hb-inst-row${f.on ? " is-on" : ""}" 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.round(f.score * 100)}%</span></button></li>`).join("")}</ul></div>`
379
- : `<p class="hb-lay-empty-note">${s.ready ? (studio.hasEverything ? "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>` +
380
- (s.ready && studio.hasEverything && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
663
+ ? `<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"}">${strokeIcon("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>`
664
+ : `<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>` +
665
+ (s.ready && (studio.hasEverything || studio.canWant) && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
381
666
  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>` : "";
382
667
  }
383
668
  else if (part === "mask") {
@@ -385,6 +670,7 @@ export function mountMaskRack(host, studio, part, o = {}) {
385
670
  `<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>` +
386
671
  (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>` : "") +
387
672
  (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>` : "") +
673
+ (s.tool === "wand" ? `<label class="hb-check"><input type="checkbox" data-contig${s.contiguous ? " checked" : ""}><span>touching pixels only</span></label>` : "") +
388
674
  (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>` : "");
389
675
  }
390
676
  else if (part === "saved") {
@@ -397,7 +683,7 @@ export function mountMaskRack(host, studio, part, o = {}) {
397
683
  else {
398
684
  html =
399
685
  s.coverage > 0
400
- ? `<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></div>`
686
+ ? `<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>`
401
687
  : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
402
688
  }
403
689
  if (html !== last)
@@ -411,7 +697,17 @@ export function mountMaskRack(host, studio, part, o = {}) {
411
697
  const m = t.closest("[data-mode]");
412
698
  if (m)
413
699
  return studio.setMode(m.dataset.mode);
700
+ const show = t.closest("[data-show]");
701
+ if (show)
702
+ return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
703
+ const drop = t.closest("[data-drop]");
704
+ if (drop)
705
+ return studio.removeFound(Number(drop.dataset.drop));
414
706
  const op = t.closest("[data-op]")?.dataset.op;
707
+ if (op === "merge")
708
+ return studio.mergeFound();
709
+ if (op === "unfind")
710
+ return studio.clearFound();
415
711
  if (op === "invert")
416
712
  return studio.invert();
417
713
  if (op === "clear")
@@ -444,6 +740,8 @@ export function mountMaskRack(host, studio, part, o = {}) {
444
740
  studio.setSize(Number(i.value));
445
741
  if (i.dataset.tol !== undefined)
446
742
  studio.setTolerance(Number(i.value));
743
+ if (i.dataset.contig !== undefined)
744
+ studio.setContiguous(i.checked);
447
745
  });
448
746
  l.add(studio.subscribe(draw));
449
747
  return { dispose: () => l.off() };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The talk views around a chat: MemoryPane (what is stored, search, sources,
3
+ * protect, forget, export, import, erase), SourcesDrop (files and folders
4
+ * into memory), PersonaRack (a persona in three parts sent in priority order
5
+ * and trimmed to a budget, with presets), VoiceRow (spoken replies) and
6
+ * SessionMenu (clear, export and import of chats). Each binds a library
7
+ * object to hackbuild-ui classes; none holds a model.
8
+ */
9
+ import { type Kind, type StoredItem, type EditPatch, type ExportData, type Recall } from "@hackbuild/memory";
10
+ import type { ChatList } from "./chat.js";
11
+ import type { PersonaRack, VoiceRow } from "./talk.js";
12
+ import type { Speaker } from "./speaker.js";
13
+ import { type Mounted } from "./dom.js";
14
+ /** What a memory pane needs from a store; a `Memory` from @hackbuild/memory fits. */
15
+ export interface MemoryLike {
16
+ all(): StoredItem[];
17
+ add(text: string, o?: {
18
+ kind?: Kind;
19
+ section?: string;
20
+ meta?: Record<string, unknown>;
21
+ }): Promise<unknown>;
22
+ remove(ids: number[]): Promise<void>;
23
+ edit(id: number, patch: EditPatch): Promise<unknown>;
24
+ recall(q: string, o?: {
25
+ k?: number;
26
+ }): Promise<Recall>;
27
+ export(): ExportData;
28
+ import(data: ExportData, o?: {
29
+ replace?: boolean;
30
+ }): Promise<number>;
31
+ }
32
+ /** A memory pane over a host: `refresh` after the store changes elsewhere, `used` to mark what the last reply used. */
33
+ export interface MemoryPaneHandle extends Mounted {
34
+ refresh(): void;
35
+ used(labels: readonly string[]): void;
36
+ }
37
+ /** True when an item is kept out of cleanup: decay never drops it. */
38
+ export declare const isProtected: (it: StoredItem) => boolean;
39
+ /** Protect an item from cleanup (it becomes lore, which never decays) or give it back its kind. */
40
+ export declare function protect(mem: Pick<MemoryLike, "edit">, it: StoredItem, on: boolean): Promise<void>;
41
+ /** Options of a memory pane. */
42
+ export interface MemoryPaneOptions {
43
+ name?: string;
44
+ onChange?: () => void;
45
+ /** The chip filter: by source (default) or by kind. */
46
+ by?: "source" | "kind";
47
+ /** Chip words for kinds, as { doc: "imported", lore: "background" }. */
48
+ kinds?: Readonly<Record<string, string>>;
49
+ /** The export button's words (default "export"). */
50
+ exportLabel?: string;
51
+ /** Extra footer actions, as consolidate; `onAct` gets the id. */
52
+ acts?: readonly {
53
+ id: string;
54
+ label: string;
55
+ }[];
56
+ onAct?: (id: string) => void;
57
+ }
58
+ /** The memory pane: counts, search, a source or kind filter, add a note, the list with protect and forget, export, import, erase. */
59
+ export declare function mountMemoryPane(host: HTMLElement, mem: MemoryLike, o?: MemoryPaneOptions): MemoryPaneHandle;
60
+ /** Options for a sources drop: what reads the files into memory, and a line per file. */
61
+ export interface SourcesDropOptions {
62
+ /** @hackbuild/memory `ingest(mem, files, o)` bound to a store. */
63
+ ingest: (files: File[], o: {
64
+ onFile: (e: {
65
+ name: string;
66
+ chunks: number;
67
+ note?: string;
68
+ }) => void;
69
+ }) => Promise<{
70
+ files: number;
71
+ chunks: number;
72
+ }>;
73
+ accept?: string;
74
+ }
75
+ /** A drop zone for sources: files or a whole folder of text, pdf, docx, zip and mail go into memory; a line per file says what came in. */
76
+ export declare function mountSourcesDrop(host: HTMLElement, o: SourcesDropOptions): Mounted;
77
+ /** The persona rack: presets one press away, name, the three parts with their cost, the template, save, and the persona as a file. */
78
+ export declare function mountPersonaRack(host: HTMLElement, rack: PersonaRack): Mounted;
79
+ /** The voice row: auto speak, voice, rate, pitch, test and stop. */
80
+ export declare function mountVoiceRow(host: HTMLElement, row: VoiceRow, o?: {
81
+ test?: string;
82
+ }): Mounted;
83
+ /** The voice clone row of a speaker: clone from an audio file, record `seconds` of mic, download the clone as wav, clear it. */
84
+ export declare function mountVoiceClone(host: HTMLElement, sp: Speaker, o?: {
85
+ seconds?: number;
86
+ can?: () => boolean;
87
+ hint?: string;
88
+ }): Mounted;
89
+ /** The session menu of a chat list: clear the open chat, export it as markdown, every chat as json, and import. */
90
+ export declare function mountSessionMenu(host: HTMLElement, list: ChatList, o?: {
91
+ onImport?: (n: number) => void;
92
+ }): Mounted;