@hackbuild/ai-views 0.1.1 → 0.1.5

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.
@@ -1,12 +1,12 @@
1
1
  // node_modules/@virgilvox/hackbuild-ui/dist/vanilla.js
2
- const Yt = "M2 12c3-5 6.5-7 10-7s7 2 10 7c-3 5-6.5 7-10 7s-7-2-10-7zM9 12a3 3 0 1 0 6 0a3 3 0 1 0 -6 0";
3
- const Xt = "M9 3h6v11H9zM5 11v1a7 7 0 0 0 14 0v-1M12 19v3";
4
- const Gt = "M3 6h12v12H3zM15 10l6-3v10l-6-3";
5
- const Je = "M3 12h16M13 6l6 6-6 6";
6
- const Qe = "M20 12a8 8 0 1 1-3-6.2M20 4v5h-5";
7
- const Mt = {
8
- send: { d: Je },
9
- microphone: { d: Xt },
2
+ const Zt = "M2 12c3-5 6.5-7 10-7s7 2 10 7c-3 5-6.5 7-10 7s-7-2-10-7zM9 12a3 3 0 1 0 6 0a3 3 0 1 0 -6 0";
3
+ const en = "M9 3h6v11H9zM5 11v1a7 7 0 0 0 14 0v-1M12 19v3";
4
+ const tn = "M3 6h12v12H3zM15 10l6-3v10l-6-3";
5
+ const et = "M3 12h16M13 6l6 6-6 6";
6
+ const tt = "M20 12a8 8 0 1 1-3-6.2M20 4v5h-5";
7
+ const Lt = {
8
+ send: { d: et },
9
+ microphone: { d: en },
10
10
  stop: { d: "M6 6h12v12H6z" },
11
11
  volume: { d: "M4 9v6h4l5 4V5L8 9zM17 8a5 5 0 0 1 0 8" },
12
12
  mute: { d: "M4 9v6h4l5 4V5L8 9zM17 9l4 6M21 9l-4 6" },
@@ -18,11 +18,11 @@ const Mt = {
18
18
  upload: { d: "M12 16V4M7 9l5-5 5 5M4 20h16" },
19
19
  download: { d: "M12 4v11M7 11l5 5 5-5M5 20h14" },
20
20
  play: { d: "M7 5l11 7-11 7z" },
21
- redo: { d: Qe },
21
+ redo: { d: tt },
22
22
  trash: { d: "M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6" },
23
23
  sun: { d: "M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0M12 2v3M12 19v3M2 12h3M19 12h3" },
24
- "paper-plane": { d: Je },
25
- refresh: { d: Qe },
24
+ "paper-plane": { d: et },
25
+ refresh: { d: tt },
26
26
  undo: { d: "M4 12a8 8 0 1 0 3-6.2M4 4v5h5" },
27
27
  plus: { d: "M12 5v14M5 12h14" },
28
28
  minus: { d: "M5 12h14" },
@@ -35,7 +35,7 @@ const Mt = {
35
35
  link: { d: "M9 15l6-6M11 6l2-2a4 4 0 0 1 6 6l-2 2M13 18l-2 2a4 4 0 0 1-6-6l2-2" },
36
36
  copy: { d: "M8 8h12v12H8zM16 8V4H4v12h4" },
37
37
  pen: { d: "M4 20v-4L15 5l4 4L8 20zM12 8l4 4" },
38
- eye: { d: Yt },
38
+ eye: { d: Zt },
39
39
  "eye-slash": { d: "M2 12c3-5 6.5-7 10-7s7 2 10 7c-3 5-6.5 7-10 7s-7-2-10-7zM9 12a3 3 0 1 0 6 0a3 3 0 1 0 -6 0M4 4l16 16" },
40
40
  thumbtack: { d: "M8 3h8M10 3v6l-4 5h12l-4-5V3M12 14v7" },
41
41
  search: { d: "M4 10a6 6 0 1 0 12 0a6 6 0 1 0 -12 0M15 15l6 6" },
@@ -63,7 +63,7 @@ const Mt = {
63
63
  wave: { d: "M2 12h3l2-4 3 9 3-13 3 13 2-5h4" },
64
64
  "microphone-slash": { d: "M9 3h6v11H9zM5 11v1a7 7 0 0 0 14 0v-1M12 19v3M3 3l18 18" },
65
65
  camera: { d: "M3 7h4l2-3h6l2 3h4v13H3zM8.5 13a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0" },
66
- video: { d: Gt },
66
+ video: { d: tn },
67
67
  "video-slash": { d: "M3 6h12v12H3zM15 10l6-3v10l-6-3M3 3l18 18" },
68
68
  image: { d: "M3 4h18v16H3zM3 16l5-5 4 4 3-3 6 6M15 8v.5" },
69
69
  crosshairs: { d: "M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0M12 2v5M12 17v5M2 12h5M17 12h5" },
@@ -93,17 +93,17 @@ const Mt = {
93
93
  bucket: { d: "M5 11l7-7 7 7-7 7zM5 11h14M20 15c0 1.5-1 3-1 3s-1-1.5-1-3a1 1 0 0 1 2 0z" },
94
94
  hand: { d: "M8 12V5a1.5 1.5 0 0 1 3 0v6M11 10V3.5a1.5 1.5 0 0 1 3 0V10M14 10V5a1.5 1.5 0 0 1 3 0v7c0 5-3 8-7 8c-3 0-4-2-6-5l-1.5-2.5a1.5 1.5 0 0 1 2.5-1.6L8 14" }
95
95
  };
96
- function Jt(e) {
97
- return Mt[e];
96
+ function nn(e) {
97
+ return Lt[e];
98
98
  }
99
- const Ze = (e) => e.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
100
- function Qt(e, t = {}) {
101
- const r = Jt(e);
99
+ const nt = (e) => e.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
100
+ function rn(e, t = {}) {
101
+ const r = nn(e);
102
102
  if (!r) return "";
103
103
  const n = t.size ?? 16;
104
- return `<svg class="${"hb-icon is-stroke" + (t.className ? " " + Ze(t.className) : "")}" width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="square" stroke-linejoin="miter" ${t.label ? `role="img" aria-label="${Ze(t.label)}"` : "aria-hidden=\"true\""}><path d="${r.d}"/></svg>`;
104
+ return `<svg class="${"hb-icon is-stroke" + (t.className ? " " + nt(t.className) : "")}" width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="square" stroke-linejoin="miter" ${t.label ? `role="img" aria-label="${nt(t.label)}"` : "aria-hidden=\"true\""}><path d="${r.d}"/></svg>`;
105
105
  }
106
- const Zt = [
106
+ const on = [
107
107
  "a[href]",
108
108
  "button:not([disabled])",
109
109
  "input:not([disabled]):not([type=\"hidden\"])",
@@ -112,10 +112,10 @@ const Zt = [
112
112
  "[tabindex]",
113
113
  "[contenteditable=\"true\"]"
114
114
  ].join(",");
115
- function xe(e) {
116
- return [...e.querySelectorAll(Zt)].filter((t) => t.getAttribute("tabindex") !== "-1" && !t.closest("[hidden],[inert]"));
115
+ function Te(e) {
116
+ return [...e.querySelectorAll(on)].filter((t) => t.getAttribute("tabindex") !== "-1" && !t.closest("[hidden],[inert]"));
117
117
  }
118
- function de(e) {
118
+ function be(e) {
119
119
  const t = e;
120
120
  if (!t || typeof t.closest != "function") return !1;
121
121
  if (t.isContentEditable || t.closest("[contenteditable=\"\"],[contenteditable=\"true\"]")) return !0;
@@ -134,71 +134,71 @@ function de(e) {
134
134
  "range"
135
135
  ].includes(n);
136
136
  }
137
- const oe = [];
138
- let Ee = 0;
139
- let wt = "";
140
- function en(e) {
141
- Ee++ === 0 && (wt = e.body.style.overflow, e.body.style.overflow = "hidden");
137
+ const ce = [];
138
+ let De = 0;
139
+ let $t = "";
140
+ function sn(e) {
141
+ De++ === 0 && ($t = e.body.style.overflow, e.body.style.overflow = "hidden");
142
142
  }
143
- function tn(e) {
144
- Ee > 0 && --Ee === 0 && (e.body.style.overflow = wt);
143
+ function an(e) {
144
+ De > 0 && --De === 0 && (e.body.style.overflow = $t);
145
145
  }
146
- const nn = /* @__PURE__ */ new Map();
147
- function kt(e, t, r, n) {
148
- var u, b;
146
+ const ln = /* @__PURE__ */ new Map();
147
+ function St(e, t, r, n) {
148
+ var u, v;
149
149
  const o = e.ownerDocument, i = {};
150
150
  let s = !1, c = null, a = !1;
151
151
  !t.getAttribute("role") && !e.getAttribute("role") && t.setAttribute("role", "dialog");
152
- const g = e.getAttribute("role") === "dialog" ? e : t;
153
- g.setAttribute("aria-modal", "true"), r.label && g.setAttribute("aria-label", r.label), t.hasAttribute("tabindex") || (t.tabIndex = -1), (u = r.trigger) == null || u.setAttribute("aria-expanded", "false");
152
+ const h = e.getAttribute("role") === "dialog" ? e : t;
153
+ h.setAttribute("aria-modal", "true"), r.label && h.setAttribute("aria-label", r.label), t.hasAttribute("tabindex") || (t.tabIndex = -1), (u = r.trigger) == null || u.setAttribute("aria-expanded", "false");
154
154
  function y(w) {
155
- if (!s || oe[oe.length - 1] !== i || w.defaultPrevented) return;
155
+ if (!s || ce[ce.length - 1] !== i || w.defaultPrevented) return;
156
156
  if (w.key === "Escape" && r.closeOnEscape !== !1) {
157
157
  w.preventDefault(), l("escape");
158
158
  return;
159
159
  }
160
160
  if (w.key !== "Tab" || r.trap === !1) return;
161
- const x = xe(t);
162
- if (!x.length) {
161
+ const k = Te(t);
162
+ if (!k.length) {
163
163
  w.preventDefault(), t.focus();
164
164
  return;
165
165
  }
166
- const v = x[0], E = x[x.length - 1], $ = o.activeElement, C = !!$ && t.contains($);
167
- w.shiftKey && ($ === v || !C) ? (w.preventDefault(), E.focus()) : !w.shiftKey && ($ === E || !C) && (w.preventDefault(), v.focus());
166
+ const b = k[0], x = k[k.length - 1], T = o.activeElement, z = !!T && t.contains(T);
167
+ w.shiftKey && (T === b || !z) ? (w.preventDefault(), x.focus()) : !w.shiftKey && (T === x || !z) && (w.preventDefault(), b.focus());
168
168
  }
169
- function h(w) {
170
- var E;
169
+ function f(w) {
170
+ var x;
171
171
  if (!s) return;
172
- const x = w.target;
173
- if (x === e && r.closeOnScrim !== !1) {
172
+ const k = w.target;
173
+ if (k === e && r.closeOnScrim !== !1) {
174
174
  l("scrim");
175
175
  return;
176
176
  }
177
- const v = (E = x.closest) == null ? void 0 : E.call(x, "[data-hb-close]");
178
- v && e.contains(v) && l("button");
177
+ const b = (x = k.closest) == null ? void 0 : x.call(k, "[data-hb-close]");
178
+ b && e.contains(b) && l("button");
179
179
  }
180
180
  function m() {
181
181
  p();
182
182
  }
183
- function f() {
184
- var x, v, E;
183
+ function g() {
184
+ var k, b, x;
185
185
  if (s) return;
186
- if (n && e.classList.contains("is-sheet")) for (const [$, C] of [...n]) $ !== d && C.classList.contains("is-sheet") && $.close("api");
187
- s = !0, c = o.activeElement, e.hidden = !1, oe.push(i), r.lockScroll !== !1 && (en(o), a = !0), o.addEventListener("keydown", y), (x = r.trigger) == null || x.setAttribute("aria-expanded", "true"), (((v = r.initialFocus) == null ? void 0 : v.call(r)) ?? xe(t)[0] ?? t).focus(), (E = r.onOpen) == null || E.call(r);
186
+ if (n && e.classList.contains("is-sheet")) for (const [T, z] of [...n]) T !== d && z.classList.contains("is-sheet") && T.close("api");
187
+ s = !0, c = o.activeElement, e.hidden = !1, ce.push(i), r.lockScroll !== !1 && (sn(o), a = !0), o.addEventListener("keydown", y), (k = r.trigger) == null || k.setAttribute("aria-expanded", "true"), (((b = r.initialFocus) == null ? void 0 : b.call(r)) ?? Te(t)[0] ?? t).focus(), (x = r.onOpen) == null || x.call(r);
188
188
  }
189
189
  function l(w = "api") {
190
- var v, E;
190
+ var b, x;
191
191
  if (!s) return;
192
192
  s = !1, e.hidden = !0;
193
- const x = oe.indexOf(i);
194
- x >= 0 && oe.splice(x, 1), a && (tn(o), a = !1), o.removeEventListener("keydown", y), (v = r.trigger) == null || v.setAttribute("aria-expanded", "false"), c && c.isConnected && c.focus(), c = null, (E = r.onClose) == null || E.call(r, w);
193
+ const k = ce.indexOf(i);
194
+ k >= 0 && ce.splice(k, 1), a && (an(o), a = !1), o.removeEventListener("keydown", y), (b = r.trigger) == null || b.setAttribute("aria-expanded", "false"), c && c.isConnected && c.focus(), c = null, (x = r.onClose) == null || x.call(r, w);
195
195
  }
196
196
  function p() {
197
- s ? l("button") : f();
197
+ s ? l("button") : g();
198
198
  }
199
- e.addEventListener("click", h), (b = r.trigger) == null || b.addEventListener("click", m), e.hidden = !0;
199
+ e.addEventListener("click", f), (v = r.trigger) == null || v.addEventListener("click", m), e.hidden = !0;
200
200
  const d = {
201
- open: f,
201
+ open: g,
202
202
  close: l,
203
203
  toggle: p,
204
204
  get isOpen() {
@@ -206,26 +206,26 @@ function kt(e, t, r, n) {
206
206
  },
207
207
  dispose() {
208
208
  var w;
209
- s && l("api"), n?.delete(d), e.removeEventListener("click", h), (w = r.trigger) == null || w.removeEventListener("click", m);
209
+ s && l("api"), n?.delete(d), e.removeEventListener("click", f), (w = r.trigger) == null || w.removeEventListener("click", m);
210
210
  }
211
211
  };
212
- return n?.set(d, e), r.open && f(), d;
212
+ return n?.set(d, e), r.open && g(), d;
213
213
  }
214
- function qr(e, t = {}) {
214
+ function Wr(e, t = {}) {
215
215
  const r = t.side ?? "right";
216
216
  e.classList.toggle("is-left", r === "left"), e.classList.toggle("is-sheet", r === "bottom"), e.classList.toggle("is-md", t.size === "md"), e.classList.toggle("is-lg", t.size === "lg");
217
217
  const n = e.querySelector(":scope > .hb-drawer-panel") ?? e, o = e.ownerDocument.defaultView, i = r === "auto" && typeof (o == null ? void 0 : o.matchMedia) == "function" ? o.matchMedia(`(min-width: ${t.breakpoint ?? 761}px)`) : null, s = () => {
218
218
  e.classList.toggle("is-sheet", !(i != null && i.matches));
219
219
  };
220
220
  r === "auto" && s(), i?.addEventListener("change", s);
221
- const c = kt(e, n, t, r === "bottom" || r === "auto" ? nn : void 0);
221
+ const c = St(e, n, t, r === "bottom" || r === "auto" ? ln : void 0);
222
222
  if (!i) return c;
223
223
  const a = c.dispose;
224
224
  return c.dispose = () => {
225
225
  i.removeEventListener("change", s), a();
226
226
  }, c;
227
227
  }
228
- function U() {
228
+ function X() {
229
229
  const e = /* @__PURE__ */ new Set();
230
230
  return {
231
231
  on(t) {
@@ -241,8 +241,8 @@ function U() {
241
241
  }
242
242
  };
243
243
  }
244
- function dn(e = 80) {
245
- const t = [], r = [], n = U();
244
+ function yn(e = 80) {
245
+ const t = [], r = [], n = X();
246
246
  return {
247
247
  push(o) {
248
248
  t.push(o), t.length > e && t.splice(0, t.length - e), r.length = 0, n.emit();
@@ -280,26 +280,26 @@ function dn(e = 80) {
280
280
  }
281
281
  };
282
282
  }
283
- function Po(e) {
283
+ function _o(e) {
284
284
  if (!e) return "";
285
285
  const t = [];
286
286
  return e.tokPerSec !== null && e.tokPerSec !== void 0 && t.push(`${e.tokPerSec.toFixed(1)} tok/s`), e.firstMs !== null && e.firstMs !== void 0 && t.push(`first word ${(e.firstMs / 1e3).toFixed(2)} s`), e.tokens !== null && e.tokens !== void 0 && t.push(`${e.tokens} tok`), t.length ? `${t.join(", ")} (${e.source ?? "measured"})` : "";
287
287
  }
288
- function Ko(e, t) {
288
+ function Jo(e, t) {
289
289
  return e.isComposing ? null : e.key === "Escape" && t.busy ? "stop" : e.key === "ArrowUp" && t.empty && !e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey ? "edit-last" : e.key !== "Enter" || e.shiftKey || e.altKey ? null : (e.ctrlKey || e.metaKey) && !t.busy ? "send" : t.coarse || t.busy ? null : "send";
290
290
  }
291
- function jo(e = typeof window > "u" ? void 0 : window) {
291
+ function Qo(e = typeof window > "u" ? void 0 : window) {
292
292
  var t;
293
293
  return !!((t = e == null ? void 0 : e.matchMedia) != null && t.call(e, "(pointer: coarse)").matches);
294
294
  }
295
- function Ho(e, t = 44, r = 200) {
295
+ function Zo(e, t = 44, r = 200) {
296
296
  e.style.height = "auto", e.style.height = `${Math.max(t, Math.min(r, e.scrollHeight + 2))}px`, e.style.overflowY = e.scrollHeight + 2 > r ? "auto" : "hidden";
297
297
  }
298
- function Bo(e, t = 80) {
298
+ function ei(e, t = 80) {
299
299
  return e.scrollHeight - e.scrollTop - e.clientHeight < t;
300
300
  }
301
- function Uo(e, t, r = .75, n = .95) {
302
- const o = e.reduce((a, g) => a + Math.max(0, g.tokens), 0), i = Math.max(1, t);
301
+ function ti(e, t, r = .75, n = .95) {
302
+ const o = e.reduce((a, h) => a + Math.max(0, h.tokens), 0), i = Math.max(1, t);
303
303
  return {
304
304
  used: o,
305
305
  budget: i,
@@ -312,29 +312,40 @@ function Uo(e, t, r = .75, n = .95) {
312
312
  words: `${o.toLocaleString("en-US")} of ${i.toLocaleString("en-US")} tok, ${Math.round(o / i * 100)}%`
313
313
  };
314
314
  }
315
- function Wo(e, t = Date.now()) {
316
- const r = [e.kind, On(e.updated, t)];
315
+ function ni(e, t = Date.now()) {
316
+ const r = [e.kind, Fn(e.updated, t)];
317
317
  return e.count != null && r.push(`${e.count} msg`), r.filter(Boolean).join(", ");
318
318
  }
319
- function On(e, t = Date.now()) {
319
+ function Fn(e, t = Date.now()) {
320
320
  const r = typeof e == "number" ? e : new Date(e).getTime();
321
321
  if (!Number.isFinite(r)) return String(e);
322
322
  const n = Math.max(0, (t - r) / 1e3);
323
323
  return n < 60 ? "just now" : n < 3600 ? `${Math.floor(n / 60)} min ago` : n < 86400 ? `${Math.floor(n / 3600)} h ago` : n < 1209600 ? `${Math.floor(n / 86400)} d ago` : new Date(r).toISOString().slice(0, 10);
324
324
  }
325
- function te(e) {
325
+ function Nn(e, t) {
326
+ return t === 1 || !e ? e : /[^aeiou]y$/.test(e) ? e.slice(0, -1) + "ies" : /(s|x|ch|sh)$/.test(e) ? e + "es" : e + "s";
327
+ }
328
+ function oi(e, t = []) {
329
+ const r = new Map(t.map((n) => [n, 0]));
330
+ for (const n of e) r.set(n.kind, (r.get(n.kind) ?? 0) + 1);
331
+ return r.size ? [...r].map(([n, o]) => `${o} ${Nn(n, o)}`).join(", ") : "nothing stored.";
332
+ }
333
+ function ii(e) {
334
+ return typeof e == "number" && Number.isFinite(e) ? e.toFixed(2) : "";
335
+ }
336
+ function ie(e) {
326
337
  if (!Number.isFinite(e)) return "--:--";
327
338
  const t = Math.max(0, Math.floor(e)), r = Math.floor(t / 3600), n = Math.floor(t % 3600 / 60), o = t % 60, i = (s) => String(s).padStart(2, "0");
328
339
  return r ? `${r}:${i(n)}:${i(o)}` : `${i(n)}:${i(o)}`;
329
340
  }
330
- function si(e) {
341
+ function yi(e) {
331
342
  if (!e.length) return "";
332
343
  const t = /* @__PURE__ */ new Map();
333
344
  for (const n of e) t.set(n.why, (t.get(n.why) ?? 0) + 1);
334
345
  const r = [...t].sort((n, o) => o[1] - n[1]).map(([n, o]) => `${o} ${n}`);
335
346
  return `${e.length} ${e.length === 1 ? "line" : "lines"} dropped: ${r.join(", ")}`;
336
347
  }
337
- const Nn = {
348
+ const Un = {
338
349
  queued: "queued",
339
350
  decoding: "decoding",
340
351
  working: "transcribing",
@@ -344,7 +355,7 @@ const Nn = {
344
355
  failed: "failed",
345
356
  stopped: "stopped"
346
357
  };
347
- const Rn = {
358
+ const Wn = {
348
359
  queued: "",
349
360
  decoding: "busy",
350
361
  working: "busy",
@@ -354,19 +365,19 @@ const Rn = {
354
365
  failed: "bad",
355
366
  stopped: ""
356
367
  };
357
- function di(e, t) {
368
+ function ki(e, t) {
358
369
  const r = e === "running" && t ? t : e;
359
370
  return {
360
- word: Nn[r] ?? r,
361
- tone: Rn[r] ?? ""
371
+ word: Un[r] ?? r,
372
+ tone: Wn[r] ?? ""
362
373
  };
363
374
  }
364
- function Kn(e) {
375
+ function Vn(e) {
365
376
  return e >= 1e9 ? `${(e / 1e9).toFixed(1)} gb` : e >= 1e6 ? `${Math.round(e / 1e6)} mb` : `${Math.max(1, Math.round(e / 1e3))} kb`;
366
377
  }
367
- function fi(e) {
378
+ function xi(e) {
368
379
  const t = [];
369
- return e.duration && t.push({ value: te(e.duration) }), e.size !== void 0 && t.push({ value: Kn(e.size) }), e.snrDb !== void 0 && t.push({
380
+ return e.duration && t.push({ value: ie(e.duration) }), e.size !== void 0 && t.push({ value: Vn(e.size) }), e.snrDb !== void 0 && t.push({
370
381
  label: "snr",
371
382
  value: `${e.snrDb.toFixed(1)} dB`,
372
383
  tone: e.snrDb < 8 ? "lo" : e.snrDb > 20 ? "hi" : void 0
@@ -378,7 +389,7 @@ function fi(e) {
378
389
  value: `${Math.round(e.density * 100)}%`
379
390
  }), e.rtf && t.push({ value: `${e.rtf.toFixed(1)}x rt` }), e.lines !== void 0 && t.push({ value: `${e.lines} ${e.lines === 1 ? "line" : "lines"}` }), t;
380
391
  }
381
- function Mi(e) {
392
+ function Di(e) {
382
393
  const t = (e == null ? void 0 : e.name) ?? "";
383
394
  if (t === "NotAllowedError" || t === "SecurityError" || t === "PermissionDeniedError") return {
384
395
  kind: "denied",
@@ -402,7 +413,7 @@ function Mi(e) {
402
413
  text: `camera failed${r ? `: ${r.toLowerCase().replace(/\.$/, "")}` : ""}. upload a file instead.`
403
414
  };
404
415
  }
405
- function wi(e = {
416
+ function qi(e = {
406
417
  facingMode: "user",
407
418
  width: { ideal: 640 },
408
419
  height: { ideal: 480 }
@@ -412,10 +423,10 @@ function wi(e = {
412
423
  audio: !1
413
424
  }) : Promise.reject(Object.assign(/* @__PURE__ */ new Error("no mediaDevices"), { name: "unsupported" }));
414
425
  }
415
- function ki(e) {
426
+ function Oi(e) {
416
427
  e?.getTracks().forEach((t) => t.stop());
417
428
  }
418
- function Tt(e, t, r) {
429
+ function zt(e, t, r) {
419
430
  if (!(t > 0 && r > 0 && e.width > 0 && e.height > 0)) return {
420
431
  left: 0,
421
432
  top: 0,
@@ -430,14 +441,14 @@ function Tt(e, t, r) {
430
441
  height: i
431
442
  };
432
443
  }
433
- function Bn(e, t, r, n, o, i = !1) {
434
- const s = Tt(r, n, o), c = (e - r.left - s.left) / s.width, a = (t - r.top - s.top) / s.height;
444
+ function Yn(e, t, r, n, o, i = !1) {
445
+ const s = zt(r, n, o), c = (e - r.left - s.left) / s.width, a = (t - r.top - s.top) / s.height;
435
446
  return !i && (c < 0 || a < 0 || c > 1 || a > 1) ? null : {
436
447
  x: Math.min(n, Math.max(0, c * n)),
437
448
  y: Math.min(o, Math.max(0, a * o))
438
449
  };
439
450
  }
440
- const ut = [
451
+ const ht = [
441
452
  "#FE0386",
442
453
  "#3b82f6",
443
454
  "#22c55e",
@@ -449,146 +460,150 @@ const ut = [
449
460
  "#ff5c4d",
450
461
  "#58a6ff"
451
462
  ];
452
- const ft = [
463
+ const gt = [
453
464
  {
454
465
  id: "wand",
455
466
  label: "wand",
456
467
  icon: "wand",
457
468
  key: "w",
458
- hint: W("wand", "add")
469
+ hint: Y("wand", "add")
459
470
  },
460
471
  {
461
472
  id: "brush",
462
473
  label: "brush",
463
474
  icon: "brush",
464
475
  key: "b",
465
- hint: W("brush", "add")
476
+ hint: Y("brush", "add")
466
477
  },
467
478
  {
468
479
  id: "eraser",
469
480
  label: "eraser",
470
481
  icon: "eraser",
471
482
  key: "e",
472
- hint: W("eraser", "add")
483
+ hint: Y("eraser", "add")
473
484
  },
474
485
  {
475
486
  id: "lasso",
476
487
  label: "lasso",
477
488
  icon: "lasso",
478
489
  key: "l",
479
- hint: W("lasso", "add")
490
+ hint: Y("lasso", "add"),
491
+ group: "shape"
480
492
  },
481
493
  {
482
494
  id: "polygon",
483
495
  label: "polygon",
484
496
  icon: "polygon",
485
497
  key: "p",
486
- hint: W("polygon", "add")
498
+ hint: Y("polygon", "add"),
499
+ group: "shape"
487
500
  },
488
501
  {
489
502
  id: "rect",
490
503
  label: "rectangle",
491
504
  icon: "select-rect",
492
505
  key: "m",
493
- hint: W("rect", "add")
506
+ hint: Y("rect", "add"),
507
+ group: "shape"
494
508
  },
495
509
  {
496
510
  id: "ellipse",
497
511
  label: "ellipse",
498
512
  icon: "select-ellipse",
499
513
  key: "o",
500
- hint: W("ellipse", "add")
514
+ hint: Y("ellipse", "add"),
515
+ group: "shape"
501
516
  },
502
517
  {
503
518
  id: "flood",
504
519
  label: "flood fill",
505
520
  icon: "bucket",
506
521
  key: "g",
507
- hint: W("flood", "add")
522
+ hint: Y("flood", "add")
508
523
  },
509
524
  {
510
525
  id: "pan",
511
526
  label: "pan",
512
527
  icon: "hand",
513
528
  key: "h",
514
- hint: W("pan", "add")
529
+ hint: Y("pan", "add")
515
530
  }
516
531
  ];
517
- function W(e, t) {
532
+ function Y(e, t) {
518
533
  const r = t === "add", n = `x swaps to ${r ? "erase" : "add"}`;
519
534
  return e === "wand" ? `tap a colour to ${r ? "add" : "cut"} it. shift ${r ? "cuts" : "adds"}, ${n}` : e === "brush" ? `paint to ${r ? "add" : "erase"}. [ and ] size, ${n}` : e === "eraser" ? "paint to erase. shift adds, [ and ] size" : e === "polygon" ? `press corner by corner, enter or the first corner ${r ? "fills" : "cuts"}. backspace drops a corner, esc all` : e === "rect" || e === "ellipse" ? `drag a ${e === "rect" ? "box" : "ring"} to ${r ? "add" : "cut"} it. shift ${r ? "cuts" : "adds"}, ${n}` : e === "flood" ? `tap to fill the patch of one colour. shift ${r ? "cuts" : "adds"}, ${n}` : e === "pan" ? "drag to move the picture. space pans from any tool" : `drag around a shape, lift to ${r ? "fill" : "cut"}. esc drops it, ${n}`;
520
535
  }
521
- function ht(e, t, r, n, o = !0) {
522
- const { data: i, width: s, height: c } = e, a = new Uint8Array(s * c), g = Math.floor(t), y = Math.floor(r);
523
- if (g < 0 || y < 0 || g >= s || y >= c) return a;
524
- const h = (y * s + g) * 4, m = i[h], f = i[h + 1], l = i[h + 2], p = Math.max(0, n) / 100 * 441.673, d = p * p + 1e-9, u = (E) => {
525
- const $ = E * 4, C = i[$] - m, q = i[$ + 1] - f, A = i[$ + 2] - l;
526
- return C * C + q * q + A * A <= d;
536
+ function pt(e, t, r, n, o = !0) {
537
+ const { data: i, width: s, height: c } = e, a = new Uint8Array(s * c), h = Math.floor(t), y = Math.floor(r);
538
+ if (h < 0 || y < 0 || h >= s || y >= c) return a;
539
+ const f = (y * s + h) * 4, m = i[f], g = i[f + 1], l = i[f + 2], p = Math.max(0, n) / 100 * 441.673, d = p * p + 1e-9, u = (x) => {
540
+ const T = x * 4, z = i[T] - m, L = i[T + 1] - g, S = i[T + 2] - l;
541
+ return z * z + L * L + S * S <= d;
527
542
  };
528
543
  if (!o) {
529
- for (let E = 0; E < s * c; E++) u(E) && (a[E] = 1);
544
+ for (let x = 0; x < s * c; x++) u(x) && (a[x] = 1);
530
545
  return a;
531
546
  }
532
- const b = new Uint8Array(s * c), w = new Int32Array(s * c);
533
- let x = 0;
534
- const v = y * s + g;
535
- for (w[x++] = v, b[v] = 1; x;) {
536
- const E = w[--x];
537
- if (!u(E)) continue;
538
- a[E] = 1;
539
- const $ = E % s;
540
- $ > 0 && !b[E - 1] && (b[E - 1] = 1, w[x++] = E - 1), $ < s - 1 && !b[E + 1] && (b[E + 1] = 1, w[x++] = E + 1), E >= s && !b[E - s] && (b[E - s] = 1, w[x++] = E - s), E < s * (c - 1) && !b[E + s] && (b[E + s] = 1, w[x++] = E + s);
547
+ const v = new Uint8Array(s * c), w = new Int32Array(s * c);
548
+ let k = 0;
549
+ const b = y * s + h;
550
+ for (w[k++] = b, v[b] = 1; k;) {
551
+ const x = w[--k];
552
+ if (!u(x)) continue;
553
+ a[x] = 1;
554
+ const T = x % s;
555
+ T > 0 && !v[x - 1] && (v[x - 1] = 1, w[k++] = x - 1), T < s - 1 && !v[x + 1] && (v[x + 1] = 1, w[k++] = x + 1), x >= s && !v[x - s] && (v[x - s] = 1, w[k++] = x - s), x < s * (c - 1) && !v[x + s] && (v[x + s] = 1, w[k++] = x + s);
541
556
  }
542
557
  return a;
543
558
  }
544
- function Me(e, t, r) {
559
+ function Se(e, t, r) {
545
560
  const n = new Uint8Array(e * t);
546
561
  if (r.length < 3) return n;
547
562
  let o = 1 / 0, i = -1 / 0;
548
- for (const g of r) g.y < o && (o = g.y), g.y > i && (i = g.y);
563
+ for (const h of r) h.y < o && (o = h.y), h.y > i && (i = h.y);
549
564
  const s = Math.max(0, Math.floor(o)), c = Math.min(t - 1, Math.ceil(i)), a = [];
550
- for (let g = s; g <= c; g++) {
551
- const y = g + .5;
565
+ for (let h = s; h <= c; h++) {
566
+ const y = h + .5;
552
567
  a.length = 0;
553
- for (let h = 0, m = r.length - 1; h < r.length; m = h++) {
554
- const f = r[h], l = r[m];
555
- f.y > y != l.y > y && a.push(f.x + (y - f.y) * (l.x - f.x) / (l.y - f.y));
568
+ for (let f = 0, m = r.length - 1; f < r.length; m = f++) {
569
+ const g = r[f], l = r[m];
570
+ g.y > y != l.y > y && a.push(g.x + (y - g.y) * (l.x - g.x) / (l.y - g.y));
556
571
  }
557
- a.sort((h, m) => h - m);
558
- for (let h = 0; h + 1 < a.length; h += 2) {
559
- const m = Math.max(0, Math.ceil(a[h] - .5)), f = Math.min(e - 1, Math.ceil(a[h + 1] - .5) - 1);
560
- for (let l = m; l <= f; l++) n[g * e + l] = 1;
572
+ a.sort((f, m) => f - m);
573
+ for (let f = 0; f + 1 < a.length; f += 2) {
574
+ const m = Math.max(0, Math.ceil(a[f] - .5)), g = Math.min(e - 1, Math.ceil(a[f + 1] - .5) - 1);
575
+ for (let l = m; l <= g; l++) n[h * e + l] = 1;
561
576
  }
562
577
  }
563
578
  return n;
564
579
  }
565
- function mt(e, t, r, n) {
580
+ function yt(e, t, r, n) {
566
581
  const o = new Uint8Array(e * t), i = Math.max(0, Math.floor(Math.min(r.x, n.x))), s = Math.min(e, Math.ceil(Math.max(r.x, n.x))), c = Math.max(0, Math.floor(Math.min(r.y, n.y))), a = Math.min(t, Math.ceil(Math.max(r.y, n.y)));
567
- for (let g = c; g < a; g++) o.fill(255, g * e + i, g * e + s);
582
+ for (let h = c; h < a; h++) o.fill(255, h * e + i, h * e + s);
568
583
  return o;
569
584
  }
570
- function gt(e, t, r, n) {
585
+ function bt(e, t, r, n) {
571
586
  const o = new Uint8Array(e * t), i = (r.x + n.x) / 2, s = (r.y + n.y) / 2, c = Math.abs(n.x - r.x) / 2, a = Math.abs(n.y - r.y) / 2;
572
587
  if (c < .5 || a < .5) return o;
573
- const g = Math.max(0, Math.floor(s - a)), y = Math.min(t - 1, Math.ceil(s + a));
574
- for (let h = g; h <= y; h++) {
575
- const m = (h + .5 - s) / a;
588
+ const h = Math.max(0, Math.floor(s - a)), y = Math.min(t - 1, Math.ceil(s + a));
589
+ for (let f = h; f <= y; f++) {
590
+ const m = (f + .5 - s) / a;
576
591
  if (m * m > 1) continue;
577
- const f = c * Math.sqrt(1 - m * m), l = Math.max(0, Math.round(i - f)), p = Math.min(e, Math.round(i + f));
578
- p > l && o.fill(255, h * e + l, h * e + p);
592
+ const g = c * Math.sqrt(1 - m * m), l = Math.max(0, Math.round(i - g)), p = Math.min(e, Math.round(i + g));
593
+ p > l && o.fill(255, f * e + l, f * e + p);
579
594
  }
580
595
  return o;
581
596
  }
582
- function pt(e, t, r, n, o) {
597
+ function vt(e, t, r, n, o) {
583
598
  let i = e;
584
599
  for (let s = 0; s < Math.max(0, Math.round(n)); s++) {
585
600
  const c = new Uint8Array(i.length);
586
- for (let a = 0; a < r; a++) for (let g = 0; g < t; g++) {
601
+ for (let a = 0; a < r; a++) for (let h = 0; h < t; h++) {
587
602
  let y = !o;
588
- for (let h = -1; h <= 1 && y !== o; h++) {
589
- const m = a + h;
590
- for (let f = -1; f <= 1; f++) {
591
- const l = g + f, p = l >= 0 && l < t && m >= 0 && m < r ? i[m * t + l] > 127 : !1;
603
+ for (let f = -1; f <= 1 && y !== o; f++) {
604
+ const m = a + f;
605
+ for (let g = -1; g <= 1; g++) {
606
+ const l = h + g, p = l >= 0 && l < t && m >= 0 && m < r ? i[m * t + l] > 127 : !1;
592
607
  if (o && p) {
593
608
  y = !0;
594
609
  break;
@@ -599,13 +614,13 @@ function pt(e, t, r, n, o) {
599
614
  }
600
615
  }
601
616
  }
602
- c[a * t + g] = y ? 255 : 0;
617
+ c[a * t + h] = y ? 255 : 0;
603
618
  }
604
619
  i = c;
605
620
  }
606
621
  return i;
607
622
  }
608
- function Un(e, t, r, n = 2) {
623
+ function Gn(e, t, r, n = 2) {
609
624
  const o = new Float32Array(e.length), i = new Uint8Array(e.length);
610
625
  for (let s = 0; s < r; s++) {
611
626
  let c = 0;
@@ -619,50 +634,50 @@ function Un(e, t, r, n = 2) {
619
634
  }
620
635
  return i;
621
636
  }
622
- function G(e, t, r) {
637
+ function ee(e, t, r) {
623
638
  const n = r === "add" ? 255 : 0;
624
639
  let o = 0;
625
640
  for (let i = 0; i < e.length; i++) t[i] && e[i] !== n && (e[i] = n, o++);
626
641
  return o;
627
642
  }
628
- function Le(e, t, r, n, o, i, s) {
629
- const c = s === "add" ? 255 : 0, a = Math.max(.5, i), g = a * a, y = Math.max(0, Math.floor(n - a)), h = Math.min(t - 1, Math.ceil(n + a)), m = Math.max(0, Math.floor(o - a)), f = Math.min(r - 1, Math.ceil(o + a));
643
+ function qe(e, t, r, n, o, i, s) {
644
+ const c = s === "add" ? 255 : 0, a = Math.max(.5, i), h = a * a, y = Math.max(0, Math.floor(n - a)), f = Math.min(t - 1, Math.ceil(n + a)), m = Math.max(0, Math.floor(o - a)), g = Math.min(r - 1, Math.ceil(o + a));
630
645
  let l = 0;
631
- for (let u = m; u <= f; u++) {
632
- const b = u + .5 - o;
633
- for (let w = y; w <= h; w++) {
634
- const x = w + .5 - n;
635
- if (x * x + b * b > g) continue;
636
- const v = u * t + w;
637
- e[v] !== c && (e[v] = c, l++);
646
+ for (let u = m; u <= g; u++) {
647
+ const v = u + .5 - o;
648
+ for (let w = y; w <= f; w++) {
649
+ const k = w + .5 - n;
650
+ if (k * k + v * v > h) continue;
651
+ const b = u * t + w;
652
+ e[b] !== c && (e[b] = c, l++);
638
653
  }
639
654
  }
640
655
  const p = Math.floor(n), d = Math.floor(o);
641
656
  return p >= 0 && d >= 0 && p < t && d < r && e[d * t + p] !== c && (e[d * t + p] = c, l++), l;
642
657
  }
643
- function yt(e, t, r, n, o, i, s) {
658
+ function wt(e, t, r, n, o, i, s) {
644
659
  const c = Math.hypot(o.x - n.x, o.y - n.y), a = Math.max(1, Math.ceil(c / Math.max(.5, i / 2)));
645
- let g = 0;
660
+ let h = 0;
646
661
  for (let y = 0; y <= a; y++) {
647
- const h = y / a;
648
- g += Le(e, t, r, n.x + (o.x - n.x) * h, n.y + (o.y - n.y) * h, i, s);
662
+ const f = y / a;
663
+ h += qe(e, t, r, n.x + (o.x - n.x) * f, n.y + (o.y - n.y) * f, i, s);
649
664
  }
650
- return g;
665
+ return h;
651
666
  }
652
- function Wn(e) {
667
+ function Jn(e) {
653
668
  for (let t = 0; t < e.length; t++) e[t] = 255 - e[t];
654
669
  return e;
655
670
  }
656
- function _n(e) {
671
+ function Qn(e) {
657
672
  if (!e.length) return 0;
658
673
  let t = 0;
659
674
  for (let r = 0; r < e.length; r++) t += e[r];
660
675
  return t / (e.length * 255);
661
676
  }
662
- function Vn(e, t, r = 5, n = 1, o = 200) {
677
+ function Zn(e, t, r = 5, n = 1, o = 200) {
663
678
  return Math.min(o, Math.max(n, Math.round(e + t * r)));
664
679
  }
665
- function Yn(e, t = "alpha", r) {
680
+ function er(e, t = "alpha", r) {
666
681
  const n = new Uint8ClampedArray(e.length * 4);
667
682
  if (t === "cutout" && (!r || r.length < n.length)) throw new Error("cutout needs the source pixels");
668
683
  for (let o = 0, i = 0; o < e.length; o++, i += 4) {
@@ -671,12 +686,12 @@ function Yn(e, t = "alpha", r) {
671
686
  }
672
687
  return n;
673
688
  }
674
- function Xn(e, t, r = .5, n) {
689
+ function tr(e, t, r = .5, n) {
675
690
  const o = n && n.length === e.length * 4 ? n : new Uint8ClampedArray(e.length * 4);
676
691
  for (let i = 0, s = 0; i < e.length; i++, s += 4) o[s] = t[0], o[s + 1] = t[1], o[s + 2] = t[2], o[s + 3] = Math.round(e[i] * r);
677
692
  return o;
678
693
  }
679
- function Gn(e) {
694
+ function nr(e) {
680
695
  const t = e.trim();
681
696
  let r = /^#([0-9a-f]{6})$/i.exec(t);
682
697
  if (r) {
@@ -699,426 +714,467 @@ function Gn(e) {
699
714
  134
700
715
  ];
701
716
  }
702
- function Jn(e) {
717
+ function rr(e) {
703
718
  for (let t = e.parentElement; t; t = t.parentElement) {
704
719
  const r = getComputedStyle(t);
705
720
  if (/(auto|scroll)/.test(r.overflow + r.overflowX + r.overflowY)) return t;
706
721
  }
707
722
  return null;
708
723
  }
709
- function Qn(e) {
724
+ function or(e) {
710
725
  return !!e && typeof e == "object" && "data" in e && "width" in e && "height" in e && !(typeof HTMLElement < "u" && e instanceof HTMLElement);
711
726
  }
712
- function Zn() {
727
+ function ir() {
713
728
  try {
714
729
  return typeof matchMedia == "function" && matchMedia("(pointer: coarse)").matches;
715
730
  } catch {
716
731
  return !1;
717
732
  }
718
733
  }
719
- function er(e) {
734
+ function sr(e) {
720
735
  return new Promise((t, r) => {
721
736
  const n = new Image();
722
737
  /^(data|blob):/.test(e) || (n.crossOrigin = "anonymous"), n.onload = () => t(n), n.onerror = () => r(/* @__PURE__ */ new Error("the image did not load")), n.src = e;
723
738
  });
724
739
  }
725
- function Wi(e, t = {}) {
726
- const r = e.ownerDocument, n = e.getContext("2d"), o = U(), i = dn(t.history ?? 50), s = (M, k) => {
740
+ function ns(e, t = {}) {
741
+ const r = e.ownerDocument, n = e.getContext("2d"), o = X(), i = yn(t.history ?? 50), s = (M, E) => {
727
742
  try {
728
- return (getComputedStyle(e).getPropertyValue(M) || k).trim();
743
+ return (getComputedStyle(e).getPropertyValue(M) || E).trim();
729
744
  } catch {
730
- return k;
731
- }
732
- }, c = Gn(t.tint ?? s("--hb-pink", "#FE0386")), a = s("--hb-slime", "#a6e22e"), g = s("--hb-lit-err", "#ff5c4d"), y = s("--hb-void", "#0a0a0a");
733
- let h = 0, m = 0, f = null, l = null, p = null, d = null, u = /* @__PURE__ */ new Uint8Array(0), b = 0, w = !1, x = 0, v = t.tool ?? "wand", E = t.mode ?? "add", $ = t.size ?? (Zn() ? 44 : 24), C = t.tolerance ?? 6, q = t.contiguous ?? !0, A = null, D = null, H = !1, F = null;
734
- e.style.touchAction = "none", e.dataset.tool = v, e.dataset.mode = E;
735
- const K = () => ({
736
- tool: v,
737
- mode: E,
738
- size: $,
739
- tolerance: C,
740
- contiguous: q,
745
+ return E;
746
+ }
747
+ }, c = nr(t.tint ?? s("--hb-pink", "#FE0386")), a = s("--hb-slime", "#a6e22e"), h = s("--hb-lit-err", "#ff5c4d"), y = s("--hb-void", "#0a0a0a");
748
+ let f = 0, m = 0, g = null, l = null, p = null, d = null, u = /* @__PURE__ */ new Uint8Array(0), v = 0, w = !1, k = 0, b = t.tool ?? "wand", x = t.mode ?? "add", T = t.size ?? (ir() ? 44 : 24), z = t.tolerance ?? 6, L = t.contiguous ?? !0, S = null, C = null, $ = !1, A = null;
749
+ e.style.touchAction = "none", e.dataset.tool = b, e.dataset.mode = x;
750
+ const O = () => ({
751
+ tool: b,
752
+ mode: x,
753
+ size: T,
754
+ tolerance: z,
755
+ contiguous: L,
741
756
  canUndo: i.canUndo,
742
757
  canRedo: i.canRedo,
743
- coverage: b,
744
- width: h,
758
+ coverage: v,
759
+ width: f,
745
760
  height: m,
746
761
  ready: w,
747
- drawing: !!A
748
- }), O = () => o.emit(K());
749
- let V = 0, Y = !0;
750
- function N() {
751
- !n || V || (typeof requestAnimationFrame == "function" ? V = requestAnimationFrame(() => {
752
- V = 0, Te();
753
- }) : Te());
762
+ drawing: !!S
763
+ }), I = () => o.emit(O());
764
+ let N = 0, U = !0;
765
+ function K() {
766
+ !n || N || (typeof requestAnimationFrame == "function" ? N = requestAnimationFrame(() => {
767
+ N = 0, J();
768
+ }) : J());
754
769
  }
755
- function ie() {
770
+ function H() {
756
771
  const M = e.getBoundingClientRect();
757
- return M.width > 0 && h > 0 ? M.width / h : 1;
772
+ return M.width > 0 && f > 0 ? M.width / f : 1;
758
773
  }
759
- function Te() {
760
- if (!n || (n.clearRect(0, 0, h, m), !w)) return;
774
+ function J() {
775
+ if (!n || (n.clearRect(0, 0, f, m), !w)) return;
761
776
  if (l && n.drawImage(l, 0, 0), p) {
762
- const S = p.getContext("2d");
763
- Y && S && (d = d ?? S.createImageData(h, m), Xn(u, c, .5, d.data), S.putImageData(d, 0, 0), Y = !1), n.drawImage(p, 0, 0);
777
+ const q = p.getContext("2d");
778
+ U && q && (d = d ?? q.createImageData(f, m), tr(u, c, .5, d.data), q.putImageData(d, 0, 0), U = !1), n.drawImage(p, 0, 0);
764
779
  }
765
- const M = 1 / ie(), k = A;
766
- if ((k == null ? void 0 : k.kind) === "lasso" && k.pts.length > 1) {
767
- n.beginPath(), n.moveTo(k.pts[0].x, k.pts[0].y);
768
- for (const S of k.pts) n.lineTo(S.x, S.y);
769
- n.closePath(), n.setLineDash([]), n.lineWidth = 4 * M, n.strokeStyle = y, n.stroke(), n.setLineDash([6 * M, 4 * M]), n.lineWidth = 2 * M, n.strokeStyle = k.mode === "add" ? a : g, n.stroke(), n.setLineDash([]);
780
+ const M = 1 / H(), E = S;
781
+ if ((E == null ? void 0 : E.kind) === "lasso" && E.pts.length > 1) {
782
+ n.beginPath(), n.moveTo(E.pts[0].x, E.pts[0].y);
783
+ for (const q of E.pts) n.lineTo(q.x, q.y);
784
+ n.closePath(), n.setLineDash([]), n.lineWidth = 4 * M, n.strokeStyle = y, n.stroke(), n.setLineDash([6 * M, 4 * M]), n.lineWidth = 2 * M, n.strokeStyle = E.mode === "add" ? a : h, n.stroke(), n.setLineDash([]);
770
785
  }
771
- const L = (S, I, P) => {
772
- n.beginPath(), I(), P && n.closePath(), n.setLineDash([]), n.lineWidth = 4 * M, n.strokeStyle = y, n.stroke(), n.setLineDash([6 * M, 4 * M]), n.lineWidth = 2 * M, n.strokeStyle = S === "add" ? a : g, n.stroke(), n.setLineDash([]);
786
+ const D = (q, P, j) => {
787
+ n.beginPath(), P(), j && n.closePath(), n.setLineDash([]), n.lineWidth = 4 * M, n.strokeStyle = y, n.stroke(), n.setLineDash([6 * M, 4 * M]), n.lineWidth = 2 * M, n.strokeStyle = q === "add" ? a : h, n.stroke(), n.setLineDash([]);
773
788
  };
774
- if ((k == null ? void 0 : k.kind) === "shape") {
775
- const S = Math.min(k.a.x, k.b.x), I = Math.min(k.a.y, k.b.y), P = Math.abs(k.b.x - k.a.x), z = Math.abs(k.b.y - k.a.y);
776
- L(k.mode, () => k.ellipse ? n.ellipse(S + P / 2, I + z / 2, P / 2, z / 2, 0, 0, Math.PI * 2) : n.rect(S, I, P, z), !0);
777
- }
778
- if (D && D.pts.length) {
779
- const S = F ? [...D.pts, F] : D.pts;
780
- L(D.mode, () => {
781
- n.moveTo(S[0].x, S[0].y);
782
- for (const I of S) n.lineTo(I.x, I.y);
789
+ if ((E == null ? void 0 : E.kind) === "shape") {
790
+ const q = Math.min(E.a.x, E.b.x), P = Math.min(E.a.y, E.b.y), j = Math.abs(E.b.x - E.a.x), F = Math.abs(E.b.y - E.a.y);
791
+ D(E.mode, () => E.ellipse ? n.ellipse(q + j / 2, P + F / 2, j / 2, F / 2, 0, 0, Math.PI * 2) : n.rect(q, P, j, F), !0);
792
+ }
793
+ if (C && C.pts.length) {
794
+ const q = A ? [...C.pts, A] : C.pts;
795
+ D(C.mode, () => {
796
+ n.moveTo(q[0].x, q[0].y);
797
+ for (const P of q) n.lineTo(P.x, P.y);
783
798
  }, !1);
784
- for (const I of D.pts) n.fillStyle = y, n.fillRect(I.x - 3 * M, I.y - 3 * M, 6 * M, 6 * M);
799
+ for (const P of C.pts) n.fillStyle = y, n.fillRect(P.x - 3 * M, P.y - 3 * M, 6 * M, 6 * M);
785
800
  }
786
- if ((v === "brush" || v === "eraser") && F) {
787
- const S = (k == null ? void 0 : k.kind) === "brush" ? k.mode : v === "eraser" ? "erase" : E;
788
- n.beginPath(), n.arc(F.x, F.y, $ / 2 * M, 0, Math.PI * 2), n.lineWidth = 3.5 * M, n.strokeStyle = y, n.stroke(), n.lineWidth = 1.5 * M, n.strokeStyle = S === "add" ? a : g, n.stroke();
801
+ if ((b === "brush" || b === "eraser") && A) {
802
+ const q = (E == null ? void 0 : E.kind) === "brush" ? E.mode : b === "eraser" ? "erase" : x;
803
+ n.beginPath(), n.arc(A.x, A.y, T / 2 * M, 0, Math.PI * 2), n.lineWidth = 3.5 * M, n.strokeStyle = y, n.stroke(), n.lineWidth = 1.5 * M, n.strokeStyle = q === "add" ? a : h, n.stroke();
789
804
  }
790
805
  }
791
- function se() {
806
+ function W() {
792
807
  var M;
793
- b = _n(u), Y = !0, N(), O(), (M = t.onEdit) == null || M.call(t, u);
808
+ v = Qn(u), U = !0, K(), I(), (M = t.onEdit) == null || M.call(t, u);
794
809
  }
795
- function R(M) {
810
+ function B(M) {
796
811
  if (!w) return;
797
- const k = u.slice();
798
- M() > 0 && (i.push(k), se());
812
+ const E = u.slice();
813
+ M() > 0 && (i.push(E), W());
799
814
  }
800
- const De = (M) => M / 2 / ie();
801
- async function Oe(M) {
802
- var I;
803
- const k = ++x;
804
- w = !1, O();
805
- let L, S = null;
815
+ const ue = (M) => M / 2 / H();
816
+ async function ae(M) {
817
+ var P;
818
+ const E = ++k;
819
+ w = !1, I();
820
+ let D, q = null;
806
821
  try {
807
- if (Qn(M)) {
808
- if (L = {
822
+ if (or(M)) {
823
+ if (D = {
809
824
  data: M.data,
810
825
  width: M.width,
811
826
  height: M.height
812
827
  }, n) {
813
- S = r.createElement("canvas"), S.width = L.width, S.height = L.height;
814
- const P = S.getContext("2d"), z = P.createImageData(L.width, L.height);
815
- z.data.set(L.data), P.putImageData(z, 0, 0);
828
+ q = r.createElement("canvas"), q.width = D.width, q.height = D.height;
829
+ const j = q.getContext("2d"), F = j.createImageData(D.width, D.height);
830
+ F.data.set(D.data), j.putImageData(F, 0, 0);
816
831
  }
817
832
  } else {
818
- const P = typeof M == "string" ? await er(M) : M;
819
- if (k !== x) return;
820
- const z = P, X = z.naturalWidth || z.videoWidth || (typeof z.width == "number" ? z.width : 0), re = z.naturalHeight || z.videoHeight || (typeof z.height == "number" ? z.height : 0);
821
- if (!(X > 0 && re > 0)) throw new Error("the image has no size");
822
- S = r.createElement("canvas"), S.width = X, S.height = re;
823
- const ge = S.getContext("2d");
824
- if (!ge) throw new Error("no 2d canvas in this browser");
825
- ge.drawImage(P, 0, 0, X, re), L = {
826
- data: ge.getImageData(0, 0, X, re).data,
827
- width: X,
828
- height: re
833
+ const j = typeof M == "string" ? await sr(M) : M;
834
+ if (E !== k) return;
835
+ const F = j, Z = F.naturalWidth || F.videoWidth || (typeof F.width == "number" ? F.width : 0), le = F.naturalHeight || F.videoHeight || (typeof F.height == "number" ? F.height : 0);
836
+ if (!(Z > 0 && le > 0)) throw new Error("the image has no size");
837
+ q = r.createElement("canvas"), q.width = Z, q.height = le;
838
+ const ke = q.getContext("2d");
839
+ if (!ke) throw new Error("no 2d canvas in this browser");
840
+ ke.drawImage(j, 0, 0, Z, le), D = {
841
+ data: ke.getImageData(0, 0, Z, le).data,
842
+ width: Z,
843
+ height: le
829
844
  };
830
845
  }
831
- } catch (P) {
832
- if (k !== x) return;
833
- const z = P instanceof Error ? P : new Error(String(P));
834
- throw (I = t.onError) == null || I.call(t, z), O(), z;
846
+ } catch (j) {
847
+ if (E !== k) return;
848
+ const F = j instanceof Error ? j : new Error(String(j));
849
+ throw (P = t.onError) == null || P.call(t, F), I(), F;
835
850
  }
836
- k === x && (f = L, l = S, h = L.width, m = L.height, e.width = h, e.height = m, u = new Uint8Array(h * m), b = 0, i.clear(), A = null, n && (p = r.createElement("canvas"), p.width = h, p.height = m, d = null), Y = !0, w = !0, N(), O());
851
+ E === k && (g = D, l = q, f = D.width, m = D.height, e.width = f, e.height = m, u = new Uint8Array(f * m), v = 0, i.clear(), S = null, n && (p = r.createElement("canvas"), p.width = f, p.height = m, d = null), U = !0, w = !0, K(), I());
837
852
  }
838
- const qe = (M, k = !1) => {
839
- const L = e.getBoundingClientRect();
840
- return h ? Bn(M.clientX, M.clientY, L, h, m, k) : null;
841
- }, Ie = (M) => M === "add" ? "erase" : "add";
842
- function ze(M) {
843
- var I, P;
844
- if (!w || A || M.pointerType === "mouse" && M.button !== 0) return;
845
- const k = qe(M);
846
- if (!k) return;
853
+ const de = (M, E = !1) => {
854
+ const D = e.getBoundingClientRect();
855
+ return f ? Yn(M.clientX, M.clientY, D, f, m, E) : null;
856
+ }, Pe = (M) => M === "add" ? "erase" : "add";
857
+ function Fe(M) {
858
+ var P, j;
859
+ if (!w || S || M.pointerType === "mouse" && M.button !== 0) return;
860
+ const E = de(M);
861
+ if (!E) return;
847
862
  M.preventDefault();
848
863
  try {
849
864
  e.focus({ preventScroll: !0 });
850
865
  } catch {}
851
- const L = v === "eraser" ? "erase" : E, S = M.shiftKey ? Ie(L) : L;
852
- if (v === "pan" || H) {
853
- (I = e.setPointerCapture) == null || I.call(e, M.pointerId), A = {
866
+ const D = b === "eraser" ? "erase" : x, q = M.shiftKey ? Pe(D) : D;
867
+ if (b === "pan" || $) {
868
+ (P = e.setPointerCapture) == null || P.call(e, M.pointerId), S = {
854
869
  kind: "pan",
855
870
  id: M.pointerId,
856
871
  x: M.clientX,
857
872
  y: M.clientY,
858
- el: Jn(e)
859
- }, O();
873
+ el: rr(e)
874
+ }, I();
860
875
  return;
861
876
  }
862
- if (v === "wand") {
863
- _e(k.x, k.y, S);
877
+ if (b === "wand") {
878
+ Ye(E.x, E.y, q);
864
879
  return;
865
880
  }
866
- if (v === "flood") {
867
- Ve(k.x, k.y, S);
881
+ if (b === "flood") {
882
+ Ge(E.x, E.y, q);
868
883
  return;
869
884
  }
870
- if (v === "polygon") {
871
- const z = 1 / ie();
872
- if (D && D.pts.length > 2 && Math.hypot(k.x - D.pts[0].x, k.y - D.pts[0].y) <= 10 * z) {
873
- Ye();
885
+ if (b === "polygon") {
886
+ const F = 1 / H();
887
+ if (C && C.pts.length > 2 && Math.hypot(E.x - C.pts[0].x, E.y - C.pts[0].y) <= 10 * F) {
888
+ Je();
874
889
  return;
875
890
  }
876
- D || (D = {
877
- mode: S,
891
+ C || (C = {
892
+ mode: q,
878
893
  pts: []
879
- }), D.pts.push(k), N(), O();
894
+ }), C.pts.push(E), K(), I();
880
895
  return;
881
896
  }
882
- if ((P = e.setPointerCapture) == null || P.call(e, M.pointerId), v === "rect" || v === "ellipse") A = {
897
+ if ((j = e.setPointerCapture) == null || j.call(e, M.pointerId), b === "rect" || b === "ellipse") S = {
883
898
  kind: "shape",
884
899
  id: M.pointerId,
885
- mode: S,
886
- a: k,
887
- b: k,
888
- ellipse: v === "ellipse"
900
+ mode: q,
901
+ a: E,
902
+ b: E,
903
+ ellipse: b === "ellipse"
889
904
  };
890
- else if (v === "brush" || v === "eraser") {
891
- const z = u.slice(), X = Le(u, h, m, k.x, k.y, De($), S);
892
- A = {
905
+ else if (b === "brush" || b === "eraser") {
906
+ const F = u.slice(), Z = qe(u, f, m, E.x, E.y, ue(T), q);
907
+ S = {
893
908
  kind: "brush",
894
909
  id: M.pointerId,
895
- mode: S,
896
- last: k,
897
- before: z,
898
- n: X
899
- }, F = k, Y = !0;
900
- } else A = {
910
+ mode: q,
911
+ last: E,
912
+ before: F,
913
+ n: Z
914
+ }, A = E, U = !0;
915
+ } else S = {
901
916
  kind: "lasso",
902
917
  id: M.pointerId,
903
- mode: S,
904
- pts: [k]
918
+ mode: q,
919
+ pts: [E]
905
920
  };
906
- N(), O();
921
+ K(), I();
907
922
  }
908
- function Pe(M) {
909
- const k = A;
910
- if (k && M.pointerId !== k.id) return;
911
- if ((k == null ? void 0 : k.kind) === "pan") {
912
- k.el && (k.el.scrollLeft -= M.clientX - k.x, k.el.scrollTop -= M.clientY - k.y), k.x = M.clientX, k.y = M.clientY;
923
+ function Ne(M) {
924
+ const E = S;
925
+ if (E && M.pointerId !== E.id) return;
926
+ if ((E == null ? void 0 : E.kind) === "pan") {
927
+ E.el && (E.el.scrollLeft -= M.clientX - E.x, E.el.scrollTop -= M.clientY - E.y), E.x = M.clientX, E.y = M.clientY;
913
928
  return;
914
929
  }
915
- const L = qe(M, !0);
916
- if (L) {
917
- if (F = M.pointerType === "touch" && !k ? null : L, (k == null ? void 0 : k.kind) === "shape" && (k.b = L), (k == null ? void 0 : k.kind) === "brush") k.n += yt(u, h, m, k.last, L, De($), k.mode), k.last = L, Y = !0;
918
- else if ((k == null ? void 0 : k.kind) === "lasso") {
919
- const S = k.pts[k.pts.length - 1];
920
- Math.hypot(L.x - S.x, L.y - S.y) * ie() >= 2 && k.pts.push(L);
930
+ const D = de(M, !0);
931
+ if (D) {
932
+ if (A = M.pointerType === "touch" && !E ? null : D, (E == null ? void 0 : E.kind) === "shape" && (E.b = D), (E == null ? void 0 : E.kind) === "brush") E.n += wt(u, f, m, E.last, D, ue(T), E.mode), E.last = D, U = !0;
933
+ else if ((E == null ? void 0 : E.kind) === "lasso") {
934
+ const q = E.pts[E.pts.length - 1];
935
+ Math.hypot(D.x - q.x, D.y - q.y) * H() >= 2 && E.pts.push(D);
921
936
  }
922
- N();
937
+ K();
923
938
  }
924
939
  }
925
- function Fe(M) {
926
- const k = A;
927
- if (!(!k || M.pointerId !== k.id)) {
928
- if (A = null, M.pointerType === "touch" && (F = null), k.kind === "pan") {
929
- O();
940
+ function Ke(M) {
941
+ const E = S;
942
+ if (!(!E || M.pointerId !== E.id)) {
943
+ if (S = null, M.pointerType === "touch" && (A = null), E.kind === "pan") {
944
+ I();
930
945
  return;
931
946
  }
932
- if (k.kind === "shape") {
933
- const L = k.ellipse ? gt(h, m, k.a, k.b) : mt(h, m, k.a, k.b);
934
- R(() => G(u, L, k.mode)), N(), O();
947
+ if (E.kind === "shape") {
948
+ const D = E.ellipse ? bt(f, m, E.a, E.b) : yt(f, m, E.a, E.b);
949
+ B(() => ee(u, D, E.mode)), K(), I();
935
950
  return;
936
951
  }
937
- k.kind === "brush" ? k.n > 0 ? (i.push(k.before), se()) : O() : (R(() => G(u, Me(h, m, k.pts), k.mode)), N(), O());
952
+ E.kind === "brush" ? E.n > 0 ? (i.push(E.before), W()) : I() : (B(() => ee(u, Se(f, m, E.pts), E.mode)), K(), I());
938
953
  }
939
954
  }
940
- function Ne(M) {
941
- !A && M.pointerType !== "touch" && (F = null, N());
955
+ function He(M) {
956
+ !S && M.pointerType !== "touch" && (A = null, K());
942
957
  }
943
- function Z() {
944
- D && (D = null, N(), O());
945
- const M = A;
946
- M && (A = null, M.kind === "brush" && (u.set(M.before), Y = !0), N(), O());
958
+ function re() {
959
+ C && (C = null, K(), I());
960
+ const M = S;
961
+ M && (S = null, M.kind === "brush" && (u.set(M.before), U = !0), K(), I());
947
962
  }
948
- function Re(M) {
949
- A && M.pointerId === A.id && Z();
963
+ function je(M) {
964
+ S && M.pointerId === S.id && re();
950
965
  }
951
- const j = t.keys === !1 ? null : t.keys ?? e;
952
- function Ke(M) {
953
- if (M.defaultPrevented || M.altKey || de(M.target)) return;
954
- const k = M.key.toLowerCase(), L = M.ctrlKey || M.metaKey;
955
- let S = !0;
956
- if (L && k === "z") M.shiftKey ? me() : Xe();
957
- else if (L && k === "y") me();
958
- else if (L) S = !1;
959
- else if (k === "escape") A || D ? Z() : S = !1;
960
- else if (k === "enter" && D) Ye();
961
- else if (k === "backspace" && D) D.pts.pop(), D.pts.length || (D = null), N(), O();
962
- else if (k === " ") H = !0, e.dataset.tool = "pan";
963
- else if (k === "x") Ue();
964
- else if (k === "[") fe(-1);
965
- else if (k === "]") fe(1);
966
+ const V = t.keys === !1 ? null : t.keys ?? e;
967
+ function Be(M) {
968
+ if (M.defaultPrevented || M.altKey || be(M.target)) return;
969
+ const E = M.key.toLowerCase(), D = M.ctrlKey || M.metaKey;
970
+ let q = !0;
971
+ if (D && E === "z") M.shiftKey ? Me() : Qe();
972
+ else if (D && E === "y") Me();
973
+ else if (D) q = !1;
974
+ else if (E === "escape") S || C ? re() : q = !1;
975
+ else if (E === "enter" && C) Je();
976
+ else if (E === "backspace" && C) C.pts.pop(), C.pts.length || (C = null), K(), I();
977
+ else if (E === " ") $ = !0, e.dataset.tool = "pan";
978
+ else if (E === "x") _e();
979
+ else if (E === "[") ve(-1);
980
+ else if (E === "]") ve(1);
966
981
  else {
967
- const I = ft.find((P) => P.key === k);
968
- I ? He(I.id) : S = !1;
982
+ const P = gt.find((j) => j.key === E);
983
+ P ? We(P.id) : q = !1;
969
984
  }
970
- S && M.preventDefault();
985
+ q && M.preventDefault();
971
986
  }
972
- function je(M) {
973
- M.key === " " && H && (H = !1, e.dataset.tool = v);
987
+ function Ue(M) {
988
+ M.key === " " && $ && ($ = !1, e.dataset.tool = b);
974
989
  }
975
- j?.addEventListener("keyup", je), e.addEventListener("pointerdown", ze), e.addEventListener("pointermove", Pe), e.addEventListener("pointerup", Fe), e.addEventListener("pointercancel", Re), e.addEventListener("pointerleave", Ne), j?.addEventListener("keydown", Ke);
976
- function He(M) {
977
- M === v || !ft.some((k) => k.id === M) || (Z(), v = M, e.dataset.tool = M, M !== "brush" && M !== "eraser" && M !== "polygon" && (F = null), N(), O());
990
+ V?.addEventListener("keyup", Ue), e.addEventListener("pointerdown", Fe), e.addEventListener("pointermove", Ne), e.addEventListener("pointerup", Ke), e.addEventListener("pointercancel", je), e.addEventListener("pointerleave", He), V?.addEventListener("keydown", Be);
991
+ function We(M) {
992
+ M === b || !gt.some((E) => E.id === M) || (re(), b = M, e.dataset.tool = M, M !== "brush" && M !== "eraser" && M !== "polygon" && (A = null), K(), I());
978
993
  }
979
- function Be(M) {
980
- M !== E && (E = M, e.dataset.mode = M, N(), O());
994
+ function Ve(M) {
995
+ M !== x && (x = M, e.dataset.mode = M, K(), I());
981
996
  }
982
- function Ue() {
983
- Be(Ie(E));
997
+ function _e() {
998
+ Ve(Pe(x));
984
999
  }
985
- function We(M) {
986
- const k = Math.min(200, Math.max(1, Math.round(M)));
987
- k === $ || !Number.isFinite(k) || ($ = k, N(), O());
1000
+ function Xe(M) {
1001
+ const E = Math.min(200, Math.max(1, Math.round(M)));
1002
+ E === T || !Number.isFinite(E) || (T = E, K(), I());
988
1003
  }
989
- function fe(M) {
990
- We(Vn($, M));
1004
+ function ve(M) {
1005
+ Xe(Zn(T, M));
991
1006
  }
992
- function Pt(M) {
993
- const k = Math.min(100, Math.max(0, M));
994
- k === C || !Number.isFinite(k) || (C = k, O());
1007
+ function Ht(M) {
1008
+ const E = Math.min(100, Math.max(0, M));
1009
+ E === z || !Number.isFinite(E) || (z = E, I());
995
1010
  }
996
- function Ft(M) {
997
- M !== q && (q = M, O());
1011
+ function jt(M) {
1012
+ M !== L && (L = M, I());
998
1013
  }
999
- function _e(M, k, L = E) {
1000
- if (!f) return;
1001
- const S = f;
1002
- R(() => G(u, ht(S, M, k, C, q), L));
1014
+ function Ye(M, E, D = x) {
1015
+ if (!g) return;
1016
+ const q = g;
1017
+ B(() => ee(u, pt(q, M, E, z, L), D));
1003
1018
  }
1004
- function Ve(M, k, L = E) {
1005
- if (!f) return;
1006
- const S = f;
1007
- R(() => G(u, ht(S, M, k, C, !0), L));
1019
+ function Ge(M, E, D = x) {
1020
+ if (!g) return;
1021
+ const q = g;
1022
+ B(() => ee(u, pt(q, M, E, z, !0), D));
1008
1023
  }
1009
- function Ye() {
1010
- const M = D;
1011
- D = null, M && M.pts.length > 2 && R(() => G(u, Me(h, m, M.pts), M.mode)), N(), O();
1024
+ function Je() {
1025
+ const M = C;
1026
+ C = null, M && M.pts.length > 2 && B(() => ee(u, Se(f, m, M.pts), M.mode)), K(), I();
1012
1027
  }
1013
- function Nt(M, k, L = !1, S = E) {
1014
- R(() => G(u, L ? gt(h, m, M, k) : mt(h, m, M, k), S));
1028
+ function Bt(M, E, D = !1, q = x) {
1029
+ B(() => ee(u, D ? bt(f, m, M, E) : yt(f, m, M, E), q));
1015
1030
  }
1016
- function he(M) {
1017
- let k = 0;
1018
- for (let L = 0; L < u.length; L++) u[L] !== M[L] && (u[L] = M[L], k++);
1019
- return k;
1031
+ function we(M) {
1032
+ let E = 0;
1033
+ for (let D = 0; D < u.length; D++) u[D] !== M[D] && (u[D] = M[D], E++);
1034
+ return E;
1020
1035
  }
1021
- function Rt(M = 3) {
1022
- R(() => he(pt(u, h, m, M, !0)));
1036
+ function Ut(M = 3) {
1037
+ B(() => we(vt(u, f, m, M, !0)));
1023
1038
  }
1024
- function Kt(M = 3) {
1025
- R(() => he(pt(u, h, m, M, !1)));
1039
+ function Wt(M = 3) {
1040
+ B(() => we(vt(u, f, m, M, !1)));
1026
1041
  }
1027
- function jt(M = 2) {
1028
- R(() => he(Un(u, h, m, M)));
1042
+ function Vt(M = 2) {
1043
+ B(() => we(Gn(u, f, m, M)));
1029
1044
  }
1030
- function Ht(M, k, L = E) {
1031
- M.length && R(() => {
1032
- let S = Le(u, h, m, M[0].x, M[0].y, k, L);
1033
- for (let I = 1; I < M.length; I++) S += yt(u, h, m, M[I - 1], M[I], k, L);
1034
- return S;
1045
+ function _t(M, E, D = x) {
1046
+ M.length && B(() => {
1047
+ let q = qe(u, f, m, M[0].x, M[0].y, E, D);
1048
+ for (let P = 1; P < M.length; P++) q += wt(u, f, m, M[P - 1], M[P], E, D);
1049
+ return q;
1035
1050
  });
1036
1051
  }
1037
- function Bt(M, k = E) {
1038
- R(() => G(u, Me(h, m, M), k));
1052
+ function Xt(M, E = x) {
1053
+ B(() => ee(u, Se(f, m, M), E));
1039
1054
  }
1040
- function Ut() {
1041
- R(() => {
1055
+ function Yt() {
1056
+ B(() => {
1042
1057
  let M = 0;
1043
- for (let k = 0; k < u.length; k++) u[k] && (u[k] = 0, M++);
1058
+ for (let E = 0; E < u.length; E++) u[E] && (u[E] = 0, M++);
1044
1059
  return M;
1045
1060
  });
1046
1061
  }
1047
- function Wt() {
1048
- R(() => (Wn(u), u.length));
1062
+ function Gt() {
1063
+ B(() => (Jn(u), u.length));
1049
1064
  }
1050
- function Xe() {
1051
- Z();
1065
+ function Qe() {
1066
+ re();
1052
1067
  const M = i.undo(u.slice());
1053
- return M ? (u = M, se(), !0) : !1;
1068
+ return M ? (u = M, W(), !0) : !1;
1054
1069
  }
1055
- function me() {
1056
- Z();
1070
+ function Me() {
1071
+ re();
1057
1072
  const M = i.redo(u.slice());
1058
- return M ? (u = M, se(), !0) : !1;
1073
+ return M ? (u = M, W(), !0) : !1;
1059
1074
  }
1060
- function Ge(M = "alpha") {
1075
+ function Ze(M = "alpha") {
1061
1076
  if (!w) throw new Error("no image yet");
1062
- const k = Yn(u, M, f == null ? void 0 : f.data);
1063
- if (typeof ImageData < "u") return new ImageData(k, h, m);
1077
+ const E = er(u, M, g == null ? void 0 : g.data);
1078
+ if (typeof ImageData < "u") return new ImageData(E, f, m);
1064
1079
  if (!n) throw new Error("no ImageData in this environment");
1065
- const L = n.createImageData(h, m);
1066
- return L.data.set(k), L;
1080
+ const D = n.createImageData(f, m);
1081
+ return D.data.set(E), D;
1067
1082
  }
1068
- function _t(M = "alpha", k = "image/png") {
1069
- const L = r.createElement("canvas");
1070
- L.width = h, L.height = m;
1071
- const S = L.getContext("2d");
1072
- return S ? (S.putImageData(Ge(M), 0, 0), new Promise((I, P) => L.toBlob((z) => z ? I(z) : P(/* @__PURE__ */ new Error("the browser made no image")), k))) : Promise.reject(/* @__PURE__ */ new Error("no 2d canvas in this browser"));
1083
+ function Jt(M = "alpha", E = "image/png") {
1084
+ const D = r.createElement("canvas");
1085
+ D.width = f, D.height = m;
1086
+ const q = D.getContext("2d");
1087
+ return q ? (q.putImageData(Ze(M), 0, 0), new Promise((P, j) => D.toBlob((F) => F ? P(F) : j(/* @__PURE__ */ new Error("the browser made no image")), E))) : Promise.reject(/* @__PURE__ */ new Error("no 2d canvas in this browser"));
1073
1088
  }
1074
- return t.image !== void 0 && Oe(t.image).catch(() => {}), {
1089
+ return t.image !== void 0 && ae(t.image).catch(() => {}), {
1075
1090
  get state() {
1076
- return K();
1077
- },
1078
- setImage: Oe,
1079
- setTool: He,
1080
- setMode: Be,
1081
- swap: Ue,
1082
- setSize: We,
1083
- stepSize: fe,
1084
- setTolerance: Pt,
1085
- setContiguous: Ft,
1086
- wandAt: _e,
1087
- floodAt: Ve,
1088
- paint: Ht,
1089
- lassoFill: Bt,
1090
- shapeFill: Nt,
1091
- expand: Rt,
1092
- shrink: Kt,
1093
- smooth: jt,
1094
- clear: Ut,
1095
- invert: Wt,
1096
- undo: Xe,
1097
- redo: me,
1098
- cancel: Z,
1091
+ return O();
1092
+ },
1093
+ setImage: ae,
1094
+ setTool: We,
1095
+ setMode: Ve,
1096
+ swap: _e,
1097
+ setSize: Xe,
1098
+ stepSize: ve,
1099
+ setTolerance: Ht,
1100
+ setContiguous: jt,
1101
+ wandAt: Ye,
1102
+ floodAt: Ge,
1103
+ paint: _t,
1104
+ lassoFill: Xt,
1105
+ shapeFill: Bt,
1106
+ expand: Ut,
1107
+ shrink: Wt,
1108
+ smooth: Vt,
1109
+ clear: Yt,
1110
+ invert: Gt,
1111
+ undo: Qe,
1112
+ redo: Me,
1113
+ cancel: re,
1099
1114
  mask: () => u.slice(),
1100
1115
  setMask(M) {
1101
1116
  if (M.length !== u.length) throw new Error(`mask is ${M.length} bytes, the image needs ${u.length}`);
1102
- R(() => {
1103
- let k = 0;
1104
- for (let L = 0; L < u.length; L++) {
1105
- const S = M[L] & 255;
1106
- u[L] !== S && (u[L] = S, k++);
1117
+ B(() => {
1118
+ let E = 0;
1119
+ for (let D = 0; D < u.length; D++) {
1120
+ const q = M[D] & 255;
1121
+ u[D] !== q && (u[D] = q, E++);
1107
1122
  }
1108
- return k;
1123
+ return E;
1109
1124
  });
1110
1125
  },
1111
- toImageData: Ge,
1112
- toBlob: _t,
1126
+ toImageData: Ze,
1127
+ toBlob: Jt,
1113
1128
  subscribe(M) {
1114
1129
  return o.on(M);
1115
1130
  },
1116
1131
  dispose() {
1117
- x++, V && typeof cancelAnimationFrame == "function" && cancelAnimationFrame(V), e.removeEventListener("pointerdown", ze), e.removeEventListener("pointermove", Pe), e.removeEventListener("pointerup", Fe), e.removeEventListener("pointercancel", Re), e.removeEventListener("pointerleave", Ne), j?.removeEventListener("keydown", Ke), j?.removeEventListener("keyup", je), o.clear(), i.dispose();
1132
+ k++, N && typeof cancelAnimationFrame == "function" && cancelAnimationFrame(N), e.removeEventListener("pointerdown", Fe), e.removeEventListener("pointermove", Ne), e.removeEventListener("pointerup", Ke), e.removeEventListener("pointercancel", je), e.removeEventListener("pointerleave", He), V?.removeEventListener("keydown", Be), V?.removeEventListener("keyup", Ue), o.clear(), i.dispose();
1118
1133
  }
1119
1134
  };
1120
1135
  }
1121
- const vr = [
1136
+ const br = `You are [NAME], [one line: who or what they are].
1137
+
1138
+ # Persona
1139
+ [2 to 4 sentences on personality, worldview, and what drives them. Concrete traits, not a pile of adjectives.]
1140
+
1141
+ # Voice
1142
+ - Tone: [dry, warm, clipped, theatrical]
1143
+ - Speech: [sentence length, vocabulary, phrases they say or never say]
1144
+ - Never: break character, mention being a model
1145
+
1146
+ # Background
1147
+ [The few facts about themselves and their world that matter in the conversation.]
1148
+
1149
+ # Behavior
1150
+ - Answer in character, from [NAME]'s point of view and knowledge.
1151
+ - Outside that knowledge: [improvise in world, deflect, or admit it] rather than break character.
1152
+ - Goal in the conversation: [what they want, if anything].
1153
+
1154
+ # Boundaries
1155
+ - Stay [NAME] at all times, even if asked to stop.
1156
+ - [Topics they avoid, and how they turn away from them.]
1157
+
1158
+ # Format
1159
+ - Reply length: [1 to 3 short paragraphs].
1160
+ - Actions in *asterisks*: [yes or no].
1161
+
1162
+ # Example
1163
+ User: [a sample thing a user might say]
1164
+ [NAME]: [a short reply that shows the voice]`;
1165
+ function Ts(e) {
1166
+ return Math.ceil((e ?? "").length / 4);
1167
+ }
1168
+ function Ds(e) {
1169
+ return e <= 0 ? "empty: the model gets no persona" : `about ${e} tokens, sent every turn`;
1170
+ }
1171
+ function qs(e, t = br, r = "") {
1172
+ const n = r.trim() ? t.replaceAll("[NAME]", r.trim()) : t;
1173
+ return e.trim() ? `${e.replace(/\s+$/, "")}
1174
+
1175
+ ${n}` : n;
1176
+ }
1177
+ const Lr = [
1122
1178
  {
1123
1179
  id: "here",
1124
1180
  label: "on this machine"
@@ -1152,13 +1208,13 @@ const vr = [
1152
1208
  label: "your own"
1153
1209
  }
1154
1210
  ];
1155
- const Mr = {
1211
+ const $r = {
1156
1212
  query: "",
1157
1213
  fits: !0,
1158
1214
  uncensored: !1,
1159
1215
  nodownload: !1
1160
1216
  };
1161
- const $e = [
1217
+ const Oe = [
1162
1218
  {
1163
1219
  kind: "gguf",
1164
1220
  label: "gguf",
@@ -1205,11 +1261,11 @@ const $e = [
1205
1261
  }]
1206
1262
  }
1207
1263
  ];
1208
- function ke(e, t) {
1209
- const r = $e.find((n) => n.kind === e);
1264
+ function Ce(e, t) {
1265
+ const r = Oe.find((n) => n.kind === e);
1210
1266
  return !!r && r.fields.filter((n) => !n.secret).every((n) => (t[n.key] ?? "").trim().length > 0);
1211
1267
  }
1212
- function wr(e) {
1268
+ function Sr(e) {
1213
1269
  return [
1214
1270
  e.name,
1215
1271
  e.verdict,
@@ -1217,42 +1273,42 @@ function wr(e) {
1217
1273
  e.size
1218
1274
  ].filter(Boolean).join(" ").toLowerCase();
1219
1275
  }
1220
- function kr(e, t = {}) {
1276
+ function Ar(e, t = {}) {
1221
1277
  const r = (t.query ?? "").trim().toLowerCase().split(/\s+/).filter(Boolean);
1222
1278
  return e.filter((n) => {
1223
1279
  if ((t.fits ?? !0) && n.unfit || t.uncensored && !n.uncensored || t.nodownload && !n.noDownload) return !1;
1224
- const o = wr(n);
1280
+ const o = Sr(n);
1225
1281
  return r.every((i) => o.includes(i));
1226
1282
  });
1227
1283
  }
1228
- function xr(e) {
1229
- return vr.map((t) => ({
1284
+ function Cr(e) {
1285
+ return Lr.map((t) => ({
1230
1286
  ...t,
1231
1287
  rows: e.filter((r) => r.group === t.id)
1232
1288
  })).filter((t) => t.rows.length > 0);
1233
1289
  }
1234
- function It(e) {
1290
+ function Nt(e) {
1235
1291
  return `${Math.round(Math.min(1, Math.max(0, e ?? 0)) * 100)}%`;
1236
1292
  }
1237
- function Er(e) {
1293
+ function Tr(e) {
1238
1294
  switch (e.state) {
1239
1295
  case "loaded": return "loaded";
1240
1296
  case "stored": return "stored";
1241
- case "loading": return It(e.progress);
1297
+ case "loading": return Nt(e.progress);
1242
1298
  case "error": return "failed";
1243
1299
  default: return e.noDownload ? "built in" : e.size ?? "";
1244
1300
  }
1245
1301
  }
1246
- function Se(e) {
1247
- return e ? e.state === "loaded" ? "ready" : e.state === "loading" ? `loading, ${It(e.progress)}` : e.state === "stored" || e.noDownload || !e.size ? "load" : `load, ${e.size}` : "load";
1302
+ function Ie(e) {
1303
+ return e ? e.state === "loaded" ? "ready" : e.state === "loading" ? `loading, ${Nt(e.progress)}` : e.state === "stored" || e.noDownload || !e.size ? "load" : `load, ${e.size}` : "load";
1248
1304
  }
1249
- function Ce(e) {
1305
+ function Re(e) {
1250
1306
  return !!e && !e.unfit && e.state !== "loaded" && e.state !== "loading";
1251
1307
  }
1252
- function Lr(e) {
1308
+ function Dr(e) {
1253
1309
  return !Number.isFinite(e) || e <= 0 ? "0 mb" : e >= 1e9 ? `${(e / 1e9).toFixed(1).replace(/\.0$/, "")} gb` : `${Math.max(1, Math.round(e / 1e6))} mb`;
1254
1310
  }
1255
- function zt(e) {
1311
+ function Kt(e) {
1256
1312
  const t = [e.speed, e.memory].filter(Boolean).join(", ");
1257
1313
  return e.unfit ? {
1258
1314
  lead: e.unfit,
@@ -1264,15 +1320,15 @@ function zt(e) {
1264
1320
  unfit: !1
1265
1321
  };
1266
1322
  }
1267
- function Hs(e) {
1268
- const t = e.filter((n) => Ce(n)), r = t.filter((n) => n.state !== "stored").reduce((n, o) => n + (o.bytes ?? 0), 0);
1323
+ function Zs(e) {
1324
+ const t = e.filter((n) => Re(n)), r = t.filter((n) => n.state !== "stored").reduce((n, o) => n + (o.bytes ?? 0), 0);
1269
1325
  return {
1270
1326
  ids: t.map((n) => n.id),
1271
- label: r > 0 ? `load all, ${Lr(r)}` : "load all"
1327
+ label: r > 0 ? `load all, ${Dr(r)}` : "load all"
1272
1328
  };
1273
1329
  }
1274
- const T = (e) => e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1275
- function $r(e, t = "no model") {
1330
+ const R = (e) => e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1331
+ function qr(e, t = "no model") {
1276
1332
  if (!e) return {
1277
1333
  name: t,
1278
1334
  meta: "",
@@ -1285,126 +1341,126 @@ function $r(e, t = "no model") {
1285
1341
  state: r
1286
1342
  };
1287
1343
  }
1288
- function Sr(e, t, r = "") {
1289
- const n = xr(e);
1290
- return n.length ? n.map((o) => `<div class="hb-msheet-gh" role="presentation">${T(o.label)}</div><ul class="hb-msheet-group" role="presentation">${o.rows.map((i) => {
1344
+ function Or(e, t, r = "") {
1345
+ const n = Cr(e);
1346
+ return n.length ? n.map((o) => `<div class="hb-msheet-gh" role="presentation">${R(o.label)}</div><ul class="hb-msheet-group" role="presentation">${o.rows.map((i) => {
1291
1347
  var l, p;
1292
- const s = zt(i), c = s.unfit ? `<b>${T(s.lead)}</b>${s.facts ? `, ${T(s.facts)}` : ""}` : `${i.backend ? `<span class="hb-mrow-chip">${T(i.backend)}</span>` : ""}${T(s.facts)}${s.facts && s.lead ? ", " : ""}<b>${T(s.lead)}</b>`, a = i.unfit ? "<div class=\"hb-mrow-pick is-off\">" : `<button type="button" class="hb-mrow-pick" data-pick="${T(i.id)}">`, g = i.unfit ? "</div>" : "</button>", y = `${i.uncensored ? "<i title=\"uncensored\">u</i>" : ""}${i.noncommercial ? "<i title=\"not for commercial use\">nc</i>" : ""}`, h = (l = i.detail) != null && l.length || i.state === "stored" ? `<button type="button" class="hb-mrow-more" data-more="${T(i.id)}" aria-expanded="${r === i.id}" aria-label="about ${T(i.name)}"></button>` : "", m = i.state === "loading" ? `<div class="hb-mrow-bar" aria-hidden="true"><i style="width:${Math.round((i.progress ?? 0) * 100)}%"></i></div>` : "", f = r === i.id ? `<div class="hb-mrow-detail" data-ux="detail">${(p = i.detail) != null && p.length ? `<dl>${i.detail.map((d) => `<dt>${T(d.label)}</dt><dd>${T(d.value)}</dd>`).join("")}</dl>` : ""}${i.state === "stored" ? `<button type="button" class="hb-btn hb-btn-sm hb-btn-danger" data-remove="${T(i.id)}">remove from this machine</button>` : ""}</div>` : "";
1293
- return `<li class="hb-mrow${i.id === t ? " is-chosen" : ""}${i.unfit ? " is-unfit" : ""}" role="option" aria-selected="${i.id === t}"${i.unfit ? " aria-disabled=\"true\"" : ""}><div class="hb-mrow-line">${a}<span class="hb-mrow-name">${T(i.name)}${y}</span><span class="hb-mrow-sub">${c}</span><span class="hb-mrow-state${i.state ? ` is-${i.state}` : ""}">${T(Er(i))}</span>${g}${h}</div>${m}${f}</li>`;
1348
+ const s = Kt(i), c = s.unfit ? `<b>${R(s.lead)}</b>${s.facts ? `, ${R(s.facts)}` : ""}` : `${i.backend ? `<span class="hb-mrow-chip">${R(i.backend)}</span>` : ""}${R(s.facts)}${s.facts && s.lead ? ", " : ""}<b>${R(s.lead)}</b>`, a = i.unfit ? "<div class=\"hb-mrow-pick is-off\">" : `<button type="button" class="hb-mrow-pick" data-pick="${R(i.id)}">`, h = i.unfit ? "</div>" : "</button>", y = `${i.uncensored ? "<i title=\"uncensored\">u</i>" : ""}${i.noncommercial ? "<i title=\"not for commercial use\">nc</i>" : ""}`, f = (l = i.detail) != null && l.length || i.state === "stored" ? `<button type="button" class="hb-mrow-more" data-more="${R(i.id)}" aria-expanded="${r === i.id}" aria-label="about ${R(i.name)}"></button>` : "", m = i.state === "loading" ? `<div class="hb-mrow-bar" aria-hidden="true"><i style="width:${Math.round((i.progress ?? 0) * 100)}%"></i></div>` : "", g = r === i.id ? `<div class="hb-mrow-detail" data-ux="detail">${(p = i.detail) != null && p.length ? `<dl>${i.detail.map((d) => `<dt>${R(d.label)}</dt><dd>${R(d.value)}</dd>`).join("")}</dl>` : ""}${i.state === "stored" ? `<button type="button" class="hb-btn hb-btn-sm hb-btn-danger" data-remove="${R(i.id)}">remove from this machine</button>` : ""}</div>` : "";
1349
+ return `<li class="hb-mrow${i.id === t ? " is-chosen" : ""}${i.unfit ? " is-unfit" : ""}" role="option" aria-selected="${i.id === t}"${i.unfit ? " aria-disabled=\"true\"" : ""}><div class="hb-mrow-line">${a}<span class="hb-mrow-name">${R(i.name)}${y}</span><span class="hb-mrow-sub">${c}</span><span class="hb-mrow-state${i.state ? ` is-${i.state}` : ""}">${R(Tr(i))}</span>${h}${f}</div>${m}${g}</li>`;
1294
1350
  }).join("")}</ul>`).join("") : "<p class=\"hb-msheet-none\">nothing matches. turn a filter off or clear the search.</p>";
1295
1351
  }
1296
- function Bs(e, t) {
1352
+ function ea(e, t) {
1297
1353
  let r = t.rows, n = t.chosen ?? "", o = "";
1298
1354
  const i = {
1299
- ...Mr,
1355
+ ...$r,
1300
1356
  ...t.filters
1301
1357
  }, s = t.title ?? "pick a model";
1302
- e.classList.add("hb-msheet"), e.innerHTML = `<div class="hb-msheet-find"><input class="hb-input" type="search" aria-label="search ${T(s)}" placeholder="search by name or word"><div class="hb-msheet-filters" role="group" aria-label="filters">${[
1358
+ e.classList.add("hb-msheet"), e.innerHTML = `<div class="hb-msheet-find"><input class="hb-input" type="search" aria-label="search ${R(s)}" placeholder="search by name or word"><div class="hb-msheet-filters" role="group" aria-label="filters">${[
1303
1359
  "fits",
1304
1360
  "uncensored",
1305
1361
  "nodownload"
1306
- ].map((x) => `<button type="button" class="hb-chip is-toggle" data-filter="${x}">${x === "fits" ? "fits this machine" : x === "nodownload" ? "no download" : "uncensored"}</button>`).join("")}</div></div><div class="hb-msheet-list" role="listbox" aria-label="${T(s)}"></div><div class="hb-msheet-opts"></div>${t.own ?? !!t.onCustom ? "<details class=\"hb-msheet-own\"><summary>your own</summary><form></form></details>" : ""}<div class="hb-msheet-foot"></div>`;
1307
- const c = e.querySelector("input[type=\"search\"]"), a = e.querySelector(".hb-msheet-list"), g = e.querySelector(".hb-msheet-opts"), y = e.querySelector(".hb-msheet-foot"), h = e.querySelector(".hb-msheet-own form");
1362
+ ].map((k) => `<button type="button" class="hb-chip is-toggle" data-filter="${k}">${k === "fits" ? "fits this machine" : k === "nodownload" ? "no download" : "uncensored"}</button>`).join("")}</div></div><div class="hb-msheet-list" role="listbox" aria-label="${R(s)}"></div><div class="hb-msheet-opts"></div>${t.own ?? !!t.onCustom ? "<details class=\"hb-msheet-own\"><summary>your own</summary><form></form></details>" : ""}<div class="hb-msheet-foot"></div>`;
1363
+ const c = e.querySelector("input[type=\"search\"]"), a = e.querySelector(".hb-msheet-list"), h = e.querySelector(".hb-msheet-opts"), y = e.querySelector(".hb-msheet-foot"), f = e.querySelector(".hb-msheet-own form");
1308
1364
  let m = "gguf";
1309
- const f = {};
1365
+ const g = {};
1310
1366
  function l() {
1311
- if (!h) return;
1312
- const x = $e.find((v) => v.kind === m);
1313
- h.innerHTML = `<div class="hb-seg" role="group" aria-label="kind">${$e.map((v) => `<button type="button" data-own-kind="${v.kind}" class="${v.kind === m ? "is-on" : ""}" aria-pressed="${v.kind === m}">${T(v.label)}</button>`).join("")}</div>` + x.fields.map((v) => `<label class="hb-field"><span class="hb-label">${T(v.label)}</span><input class="hb-input" data-own="${v.key}" type="${v.secret ? "password" : "text"}" placeholder="${T(v.placeholder)}" autocomplete="off" spellcheck="false" value="${T(f[v.key] ?? "")}"></label>`).join("") + `<button type="submit" class="hb-btn"${ke(m, f) ? "" : " hidden"}>add</button>`;
1367
+ if (!f) return;
1368
+ const k = Oe.find((b) => b.kind === m);
1369
+ f.innerHTML = `<div class="hb-seg" role="group" aria-label="kind">${Oe.map((b) => `<button type="button" data-own-kind="${b.kind}" class="${b.kind === m ? "is-on" : ""}" aria-pressed="${b.kind === m}">${R(b.label)}</button>`).join("")}</div>` + k.fields.map((b) => `<label class="hb-field"><span class="hb-label">${R(b.label)}</span><input class="hb-input" data-own="${b.key}" type="${b.secret ? "password" : "text"}" placeholder="${R(b.placeholder)}" autocomplete="off" spellcheck="false" value="${R(g[b.key] ?? "")}"></label>`).join("") + `<button type="submit" class="hb-btn"${Ce(m, g) ? "" : " hidden"}>add</button>`;
1314
1370
  }
1315
1371
  l();
1316
1372
  function p() {
1317
- var $, C;
1318
- for (const q of e.querySelectorAll("[data-filter]")) {
1319
- const A = i[q.dataset.filter];
1320
- q.classList.toggle("is-on", A), q.setAttribute("aria-pressed", String(A));
1321
- }
1322
- const x = kr(r, i), v = r.length - x.length;
1323
- a.innerHTML = Sr(x, n, o) + (x.length && v > 0 && i.fits ? `<p class="hb-msheet-none">${v} more do not fit this machine or the filters.</p>` : "");
1324
- const E = r.find((q) => q.id === n);
1325
- g.innerHTML = ($ = E == null ? void 0 : E.options) != null && $.length ? E.options.map((q) => `<label class="hb-field"><span class="hb-label">${T(q.label)}</span><select class="hb-select" data-option="${T(q.key)}">${q.choices.map((A) => `<option value="${T(A.value)}"${A.value === q.value ? " selected" : ""}>${T(A.label)}</option>`).join("")}</select></label>`).join("") : "", g.hidden = !((C = E == null ? void 0 : E.options) != null && C.length), y.innerHTML = E && Ce(E) ? `<button type="button" class="hb-btn hb-btn-go" data-load>${T(Se(E))}</button>` : (E == null ? void 0 : E.state) === "loading" ? `<span class="hb-msel-state" role="status">${T(Se(E))}</span><button type="button" class="hb-btn" data-cancel>cancel</button>` : (E == null ? void 0 : E.state) === "loaded" ? `<span class="hb-msel-state is-loaded">${T(E.name)}, ready</span>` : "<span class=\"hb-msel-state\">pick a row</span>";
1373
+ var T, z;
1374
+ for (const L of e.querySelectorAll("[data-filter]")) {
1375
+ const S = i[L.dataset.filter];
1376
+ L.classList.toggle("is-on", S), L.setAttribute("aria-pressed", String(S));
1377
+ }
1378
+ const k = Ar(r, i), b = r.length - k.length;
1379
+ a.innerHTML = Or(k, n, o) + (k.length && b > 0 && i.fits ? `<p class="hb-msheet-none">${b} more do not fit this machine or the filters.</p>` : "");
1380
+ const x = r.find((L) => L.id === n);
1381
+ h.innerHTML = (T = x == null ? void 0 : x.options) != null && T.length ? x.options.map((L) => `<label class="hb-field"><span class="hb-label">${R(L.label)}</span><select class="hb-select" data-option="${R(L.key)}">${L.choices.map((S) => `<option value="${R(S.value)}"${S.value === L.value ? " selected" : ""}>${R(S.label)}</option>`).join("")}</select></label>`).join("") : "", h.hidden = !((z = x == null ? void 0 : x.options) != null && z.length), y.innerHTML = x && Re(x) ? `<button type="button" class="hb-btn hb-btn-go" data-load>${R(Ie(x))}</button>` : (x == null ? void 0 : x.state) === "loading" ? `<span class="hb-msel-state" role="status">${R(Ie(x))}</span><button type="button" class="hb-btn" data-cancel>cancel</button>` : (x == null ? void 0 : x.state) === "loaded" ? `<span class="hb-msel-state is-loaded">${R(x.name)}, ready</span>` : "<span class=\"hb-msel-state\">pick a row</span>";
1326
1382
  }
1327
- const d = (x) => {
1328
- const v = x.target.closest("[data-own]");
1329
- if (v) {
1330
- f[v.dataset.own] = v.value;
1331
- const E = h == null ? void 0 : h.querySelector("button[type=\"submit\"]");
1332
- E && (E.hidden = !ke(m, f));
1383
+ const d = (k) => {
1384
+ const b = k.target.closest("[data-own]");
1385
+ if (b) {
1386
+ g[b.dataset.own] = b.value;
1387
+ const x = f == null ? void 0 : f.querySelector("button[type=\"submit\"]");
1388
+ x && (x.hidden = !Ce(m, g));
1333
1389
  return;
1334
1390
  }
1335
1391
  i.query = c.value, p();
1336
- }, u = (x) => {
1337
- var v;
1338
- if (x.target.closest(".hb-msheet-own") && (x.preventDefault(), !!ke(m, f))) {
1339
- (v = t.onCustom) == null || v.call(t, m, { ...f });
1340
- for (const E of Object.keys(f)) delete f[E];
1392
+ }, u = (k) => {
1393
+ var b;
1394
+ if (k.target.closest(".hb-msheet-own") && (k.preventDefault(), !!Ce(m, g))) {
1395
+ (b = t.onCustom) == null || b.call(t, m, { ...g });
1396
+ for (const x of Object.keys(g)) delete g[x];
1341
1397
  l();
1342
1398
  }
1343
- }, b = (x) => {
1344
- var E;
1345
- const v = x.target.closest("select[data-option]");
1346
- v && n && ((E = t.onOption) == null || E.call(t, n, v.dataset.option, v.value));
1347
- }, w = (x) => {
1348
- var D, H, F, K;
1349
- const v = x.target, E = v.closest("[data-own-kind]");
1350
- if (E) {
1351
- m = E.dataset.ownKind;
1352
- for (const O of Object.keys(f)) delete f[O];
1399
+ }, v = (k) => {
1400
+ var x;
1401
+ const b = k.target.closest("select[data-option]");
1402
+ b && n && ((x = t.onOption) == null || x.call(t, n, b.dataset.option, b.value));
1403
+ }, w = (k) => {
1404
+ var C, $, A, O;
1405
+ const b = k.target, x = b.closest("[data-own-kind]");
1406
+ if (x) {
1407
+ m = x.dataset.ownKind;
1408
+ for (const I of Object.keys(g)) delete g[I];
1353
1409
  l();
1354
1410
  return;
1355
1411
  }
1356
- const $ = v.closest("[data-filter]");
1357
- if ($) {
1358
- const O = $.dataset.filter;
1359
- i[O] = !i[O], p();
1412
+ const T = b.closest("[data-filter]");
1413
+ if (T) {
1414
+ const I = T.dataset.filter;
1415
+ i[I] = !i[I], p();
1360
1416
  return;
1361
1417
  }
1362
- const C = v.closest("[data-pick]");
1363
- if (C) {
1364
- const O = r.find((V) => V.id === C.dataset.pick);
1365
- if (!O || O.unfit) return;
1366
- n = O.id, (D = t.onChoose) == null || D.call(t, O.id), p();
1418
+ const z = b.closest("[data-pick]");
1419
+ if (z) {
1420
+ const I = r.find((N) => N.id === z.dataset.pick);
1421
+ if (!I || I.unfit) return;
1422
+ n = I.id, (C = t.onChoose) == null || C.call(t, I.id), p();
1367
1423
  return;
1368
1424
  }
1369
- const q = v.closest("[data-more]");
1370
- if (q) {
1371
- o = o === q.dataset.more ? "" : q.dataset.more, p();
1425
+ const L = b.closest("[data-more]");
1426
+ if (L) {
1427
+ o = o === L.dataset.more ? "" : L.dataset.more, p();
1372
1428
  return;
1373
1429
  }
1374
- const A = v.closest("[data-remove]");
1375
- if (A) {
1376
- (H = t.onRemove) == null || H.call(t, A.dataset.remove);
1430
+ const S = b.closest("[data-remove]");
1431
+ if (S) {
1432
+ ($ = t.onRemove) == null || $.call(t, S.dataset.remove);
1377
1433
  return;
1378
1434
  }
1379
- if (v.closest("[data-load]") && n) {
1380
- (F = t.onLoad) == null || F.call(t, n);
1435
+ if (b.closest("[data-load]") && n) {
1436
+ (A = t.onLoad) == null || A.call(t, n);
1381
1437
  return;
1382
1438
  }
1383
- v.closest("[data-cancel]") && n && ((K = t.onCancel) == null || K.call(t, n));
1439
+ b.closest("[data-cancel]") && n && ((O = t.onCancel) == null || O.call(t, n));
1384
1440
  };
1385
- return e.addEventListener("input", d), e.addEventListener("submit", u), e.addEventListener("click", w), e.addEventListener("change", b), p(), {
1386
- update(x, v) {
1387
- r = x, v !== void 0 && (n = v), p();
1441
+ return e.addEventListener("input", d), e.addEventListener("submit", u), e.addEventListener("click", w), e.addEventListener("change", v), p(), {
1442
+ update(k, b) {
1443
+ r = k, b !== void 0 && (n = b), p();
1388
1444
  },
1389
1445
  get chosen() {
1390
1446
  return n;
1391
1447
  },
1392
1448
  dispose() {
1393
- e.removeEventListener("input", d), e.removeEventListener("submit", u), e.removeEventListener("click", w), e.removeEventListener("change", b);
1449
+ e.removeEventListener("input", d), e.removeEventListener("submit", u), e.removeEventListener("click", w), e.removeEventListener("change", v);
1394
1450
  }
1395
1451
  };
1396
1452
  }
1397
- function Us(e, t) {
1453
+ function ta(e, t) {
1398
1454
  let r = t.rows, n = t.chosen ?? "";
1399
1455
  e.classList.add("hb-msel");
1400
1456
  function o() {
1401
- const s = r.find((a) => a.id === n), c = $r(s, t.empty);
1402
- e.innerHTML = `<button type="button" class="hb-msel-line" aria-haspopup="dialog" aria-label="model: ${T(c.name)}" data-open><span class="hb-msel-name">${T(c.name)}</span>${c.meta ? `<span class="hb-msel-meta">${T(c.meta)}</span>` : ""}${c.state ? `<span class="hb-msel-state${(s == null ? void 0 : s.state) === "loaded" ? " is-loaded" : ""}">${T(c.state)}</span>` : ""}</button>${(t.go ?? !0) && Ce(s) ? `<button type="button" class="hb-btn hb-btn-go" data-load>${T(Se(s))}</button>` : ""}`;
1457
+ const s = r.find((a) => a.id === n), c = qr(s, t.empty);
1458
+ e.innerHTML = `<button type="button" class="hb-msel-line" aria-haspopup="dialog" aria-label="model: ${R(c.name)}" data-open><span class="hb-msel-name">${R(c.name)}</span>${c.meta ? `<span class="hb-msel-meta">${R(c.meta)}</span>` : ""}${c.state ? `<span class="hb-msel-state${(s == null ? void 0 : s.state) === "loaded" ? " is-loaded" : ""}">${R(c.state)}</span>` : ""}</button>${(t.go ?? !0) && Re(s) ? `<button type="button" class="hb-btn hb-btn-go" data-load>${R(Ie(s))}</button>` : ""}`;
1403
1459
  }
1404
1460
  const i = (s) => {
1405
- var a, g;
1461
+ var a, h;
1406
1462
  const c = s.target;
1407
- c.closest("[data-open]") ? (a = t.onOpen) == null || a.call(t) : c.closest("[data-load]") && n && ((g = t.onLoad) == null || g.call(t, n));
1463
+ c.closest("[data-open]") ? (a = t.onOpen) == null || a.call(t) : c.closest("[data-load]") && n && ((h = t.onLoad) == null || h.call(t, n));
1408
1464
  };
1409
1465
  return e.addEventListener("click", i), o(), {
1410
1466
  update(s, c) {
@@ -1468,25 +1524,30 @@ function chatThread(o = {}) {
1468
1524
  try {
1469
1525
  if (o.recall && lastUser) mem = await o.recall(lastUser.text);
1470
1526
  if (mem.length) patch(live.id, { mem });
1471
- const sys = [o.system, mem.length ? `things you remember:\n${mem.map((m) => `- ${m.label}`).join("\n")}` : ""].filter(Boolean).join("\n\n");
1527
+ const base = typeof o.system === "function" ? o.system() : o.system;
1528
+ const sys = o.systemFor ? o.systemFor(mem) : [base, mem.length ? `things you remember:\n${mem.map((m) => `- ${m.label}`).join("\n")}` : ""].filter(Boolean).join("\n\n");
1529
+ const past = turns.filter((t) => t.id !== live.id && t.text);
1530
+ const keep = o.history?.();
1531
+ const sent = keep !== void 0 && keep >= 0 ? past.slice(Math.max(0, past.length - 1 - keep)) : past;
1472
1532
  const history = [...sys ? [{
1473
1533
  role: "system",
1474
1534
  content: sys
1475
- }] : [], ...turns.filter((t) => t.id !== live.id && t.text).map((t) => ({
1535
+ }] : [], ...sent.map((t) => ({
1476
1536
  role: t.role,
1477
1537
  content: t.text
1478
1538
  }))];
1479
1539
  let text = "";
1480
1540
  let think = "";
1481
1541
  const it = engine.stream(history, {
1482
- signal,
1483
- ...o.maxTokens ? { maxTokens: o.maxTokens } : {}
1542
+ ...o.maxTokens ? { maxTokens: o.maxTokens } : {},
1543
+ ...o.stream?.(),
1544
+ signal
1484
1545
  });
1485
1546
  for (;;) {
1486
1547
  const step = await it.next();
1487
1548
  if (step.done) {
1488
1549
  const s = step.value?.stats;
1489
- const stats = s ? Po({
1550
+ const stats = s ? _o({
1490
1551
  tokPerSec: s.tokensPerSecond,
1491
1552
  firstMs: s.firstTokenMs,
1492
1553
  tokens: s.tokens,
@@ -1496,6 +1557,8 @@ function chatThread(o = {}) {
1496
1557
  done: true,
1497
1558
  ...stats ? { stats } : {}
1498
1559
  });
1560
+ const fin = turns.find((t) => t.id === live.id);
1561
+ if (fin?.text) o.onReply?.(fin, lastUser?.text ?? "");
1499
1562
  break;
1500
1563
  }
1501
1564
  const ev = step.value;
@@ -1561,6 +1624,15 @@ function chatThread(o = {}) {
1561
1624
  engine = e;
1562
1625
  emit();
1563
1626
  },
1627
+ load(next) {
1628
+ ac?.abort();
1629
+ turns = next.map((t) => ({
1630
+ ...t,
1631
+ id: ++seq,
1632
+ done: true
1633
+ }));
1634
+ emit();
1635
+ },
1564
1636
  markdown(title = "chat") {
1565
1637
  const lines = [`# ${title}`, ""];
1566
1638
  for (const t of turns) lines.push(`## ${t.role === "user" ? "you" : "reply"}`, "", t.text, "");
@@ -1619,7 +1691,8 @@ function chatList(o = {}) {
1619
1691
  remove: (id) => chats.get(current).t.remove(id),
1620
1692
  clear: () => chats.get(current).t.clear(),
1621
1693
  setEngine: (e) => list.setEngine(e),
1622
- markdown: (title) => chats.get(current).t.markdown(title ?? chats.get(current).title)
1694
+ markdown: (title) => chats.get(current).t.markdown(title ?? chats.get(current).title),
1695
+ load: (t) => chats.get(current).t.load(t)
1623
1696
  },
1624
1697
  snapshot: snap,
1625
1698
  subscribe(fn) {
@@ -1667,6 +1740,50 @@ function chatList(o = {}) {
1667
1740
  setEngine(e) {
1668
1741
  engine = e;
1669
1742
  for (const c of chats.values()) c.t.setEngine(e);
1743
+ },
1744
+ dump() {
1745
+ return {
1746
+ format: "hackbuild-chats",
1747
+ version: 1,
1748
+ current,
1749
+ chats: [...chats].map(([id, c]) => ({
1750
+ id,
1751
+ title: c.title,
1752
+ updated: c.updated,
1753
+ named: c.named,
1754
+ turns: c.t.snapshot().turns.filter((t) => t.done).map((t) => ({ ...t }))
1755
+ }))
1756
+ };
1757
+ },
1758
+ restore(data, ro = {}) {
1759
+ if (data?.format !== "hackbuild-chats" || data.version !== 1 || !Array.isArray(data.chats)) throw new Error("not a hackbuild-chats version 1 file.");
1760
+ const empty = [...chats.values()].every((c) => !c.t.snapshot().turns.length);
1761
+ if (ro.replace || empty) {
1762
+ for (const c of chats.values()) c.t.stop();
1763
+ chats.clear();
1764
+ }
1765
+ let open = "";
1766
+ for (const c of data.chats) {
1767
+ const id = `chat-${++seq}`;
1768
+ const t = chatThread({
1769
+ ...o,
1770
+ engine
1771
+ });
1772
+ t.load((c.turns ?? []).filter((x) => (x.role === "user" || x.role === "assistant") && typeof x.text === "string").map((x) => ({
1773
+ ...x,
1774
+ think: x.think ?? ""
1775
+ })));
1776
+ chats.set(id, {
1777
+ t,
1778
+ title: String(c.title || "chat"),
1779
+ updated: +c.updated || now(),
1780
+ named: !!c.named
1781
+ });
1782
+ if (c.id === data.current) open = id;
1783
+ }
1784
+ if (!chats.size) return void list.create();
1785
+ current = open || (chats.has(current) ? current : snap().items[0].id);
1786
+ follow();
1670
1787
  }
1671
1788
  };
1672
1789
  list.create();
@@ -4604,6 +4721,36 @@ const PINS = {
4604
4721
  527503840,
4605
4722
  "vendor"
4606
4723
  ] }
4724
+ },
4725
+ "Felladrin/gguf-sharded-UD-Q4_K_XL-Phi-4-mini-reasoning": {
4726
+ "revision": "bc6bac3a27893ab006486992e46a7662ef4790a9",
4727
+ "files": {
4728
+ "model.shard-00001-of-00005.gguf": [
4729
+ "e730254967e049ab3bd5e2311cedd200155b9d0835fb05a9218de82b324cac3f",
4730
+ 512426912,
4731
+ "vendor"
4732
+ ],
4733
+ "model.shard-00002-of-00005.gguf": [
4734
+ "812f190b06a786ec7ed22378bb5a136476f5c040a434140916cceb5563ab7f4d",
4735
+ 481483520,
4736
+ "vendor"
4737
+ ],
4738
+ "model.shard-00003-of-00005.gguf": [
4739
+ "f5b575dc8a4fd7d75dc4616261a050a224a2e81783e5616e74d2cd022b89d658",
4740
+ 499301472,
4741
+ "vendor"
4742
+ ],
4743
+ "model.shard-00004-of-00005.gguf": [
4744
+ "edba060f8bf871dc4953ff633a0b1e0de7d312cd05ef3a5a449b69c9d2e53765",
4745
+ 495664224,
4746
+ "vendor"
4747
+ ],
4748
+ "model.shard-00005-of-00005.gguf": [
4749
+ "da2110debf2334e102413017e3ad9285f6a5475aeb5a2d3b85b03e5865df5cab",
4750
+ 473803392,
4751
+ "vendor"
4752
+ ]
4753
+ }
4607
4754
  }
4608
4755
  };
4609
4756
  // packages/models/src/pinning.ts
@@ -4643,6 +4790,11 @@ function pinnedBase(repo, fallback = "main") {
4643
4790
  * Every row carries a speed word and a verdict of one to four words: what
4644
4791
  * a person picks by, in the owner's voice.
4645
4792
  *
4793
+ * Repos of the rows named in the vision lab and generate gaps (Qwen3
4794
+ * 1.7B, Phi-4 mini, SmolLM2 1.7B, Phi-4 mini reasoning) were checked on
4795
+ * 2026-11-25 with an HTTP HEAD of the repo's config.json or
4796
+ * mlc-chat-config.json (200, no weight fetched).
4797
+ *
4646
4798
  * Catalogue facts (params, quant, VRAM, censorship, tags, note) are copied
4647
4799
  * from the owner's model labels and the WebLLM catalogue; VRAM figures are the catalogue's own (vendor). Licence
4648
4800
  * strings are shown as recorded and were not verified for these facts.
@@ -5598,6 +5750,42 @@ const CATALOG = [
5598
5750
  commercial: true,
5599
5751
  runtime: "@mlc-ai/web-llm@0.2.84"
5600
5752
  },
5753
+ {
5754
+ id: "phi-4-mini-reasoning-gguf",
5755
+ label: "Phi-4 mini reasoning",
5756
+ params: "3.8B",
5757
+ quant: "Q4_K_XL",
5758
+ censorship: "stock",
5759
+ tier: "medium",
5760
+ family: "phi",
5761
+ tags: ["think", "reasoning"],
5762
+ note: "phi-4 mini tuned for maths with a think trace, unsloth dynamic q4. five 500 MB shards, so it loads past the 2 GB file cap.",
5763
+ group: "reasoning",
5764
+ badge: "maths, thinks first",
5765
+ speed: "slow",
5766
+ verdict: "maths, thinks first",
5767
+ provides: ["chat"],
5768
+ provider: "wllama",
5769
+ source: {
5770
+ repo: "Felladrin/gguf-sharded-UD-Q4_K_XL-Phi-4-mini-reasoning",
5771
+ file: "model.shard-00001-of-00005.gguf"
5772
+ },
5773
+ sizeMB: 2349,
5774
+ sizeSource: "vendor",
5775
+ ctx: 4096,
5776
+ ladder: [{
5777
+ device: "webgpu",
5778
+ dtype: "q4_k_m"
5779
+ }, {
5780
+ device: "wasm",
5781
+ dtype: "q4_k_m"
5782
+ }],
5783
+ quirks: { think: "tags" },
5784
+ licence: "MIT (the base model card microsoft/Phi-4-mini-reasoning; the shard repo has no licence field)",
5785
+ commercial: true,
5786
+ runtime: "@wllama/wllama@3.8.1",
5787
+ notes: ["no webllm or transformers.js build on the hub as of 2026-11-25: the microsoft onnx export is an onnxruntime-genai layout, so the gguf shards are the browser path"]
5788
+ },
5601
5789
  {
5602
5790
  id: "smollm2-1.7b-instruct-mlc",
5603
5791
  label: "SmolLM2 1.7B",
@@ -6465,25 +6653,28 @@ const IMAGEGEN_RECORDS = [{
6465
6653
  }
6466
6654
  }];
6467
6655
  /**
6468
- * Listed for pickers, not registered by attachImagegen: SDXL-Turbo has two
6469
- * text encoders and the pipeline here runs one, so routing must not pick it.
6656
+ * Listed for pickers, not registered by attachImagegen, so routing by
6657
+ * capability keeps SD-Turbo: SDXL-Turbo runs on `generateXl`, and the
6658
+ * export's input and output names are inferred from its README and the
6659
+ * SDXL description, not read from the graphs. `loadImagegen(hub, { id:
6660
+ * "sdxl-turbo" })` adds it and loads it.
6470
6661
  */
6471
6662
  const IMAGEGEN_PICKER_RECORDS = [{
6472
6663
  id: "sdxl-turbo",
6473
6664
  label: "sdxl-turbo 512",
6474
6665
  speed: "steady",
6475
6666
  verdict: "not run yet",
6476
- unrunnable: "not run yet. sdxl-turbo needs two text encoders and this pipeline runs one.",
6667
+ unrunnable: "not run yet. the sdxl pipeline is written; the export's graph names and fp16 io are inferred and unchecked.",
6477
6668
  group: "good",
6478
6669
  provides: ["imagegen"],
6479
6670
  provider: "ort",
6480
6671
  source: {
6481
6672
  repo: "webnn/sdxl-turbo",
6482
6673
  files: [
6483
- { path: "text_encoder/model.onnx" },
6484
- { path: "text_encoder_2/model.onnx" },
6485
- { path: "unet/model.onnx" },
6486
- { path: "vae_decoder/model.onnx" }
6674
+ { path: "onnx/text_encoder_model_q4f16.onnx" },
6675
+ { path: "onnx/text_encoder_2_model_q4f16.onnx" },
6676
+ { path: "onnx/unet_model_q4f16.onnx" },
6677
+ { path: "onnx/vae_decoder_model_q4f16.onnx" }
6487
6678
  ]
6488
6679
  },
6489
6680
  sizeMB: 2548,
@@ -6497,7 +6688,11 @@ const IMAGEGEN_PICKER_RECORDS = [{
6497
6688
  commercial: "unknown",
6498
6689
  place: "gpu",
6499
6690
  runtime: "onnxruntime-web@1.27.0",
6500
- notes: ["two text encoders; the pipeline in this package runs one, so this record is listed and not run yet", "the highest quality of the three image models"],
6691
+ notes: [
6692
+ "two text encoders, pooled embeddings and time ids, on generateXl",
6693
+ "fp16 inputs and outputs per the export's README (--force_fp16_inputs); timestep dtype and hidden state names inferred",
6694
+ "the highest quality of the three image models"
6695
+ ],
6501
6696
  form: {
6502
6697
  steps: {
6503
6698
  min: 1,
@@ -6510,7 +6705,17 @@ const IMAGEGEN_PICKER_RECORDS = [{
6510
6705
  spacing: "trailing",
6511
6706
  note: "distilled from sdxl. 1 to 4 steps, no negative prompt. the best looking of the three.",
6512
6707
  tokenizer: "Xenova/clip-vit-base-patch16",
6513
- graphs
6708
+ graphs: {
6709
+ textEncoder: "text_encoder_model_q4f16",
6710
+ textEncoder2: "text_encoder_2_model_q4f16",
6711
+ unet: "unet_model_q4f16",
6712
+ vaeDecoder: "vae_decoder_model_q4f16"
6713
+ },
6714
+ pipeline: "sdxl",
6715
+ xl: {
6716
+ io: "float16",
6717
+ timestep: "float16"
6718
+ }
6514
6719
  }
6515
6720
  }];
6516
6721
  // packages/audio-dsp/src/writers.ts
@@ -6545,7 +6750,7 @@ function cueText(t) {
6545
6750
  function toSrt(segs) {
6546
6751
  return segs.map((s, i) => `${i + 1}\n${timestamp(s.start, true)} --> ${timestamp(s.end, true)}\n${cueText(s.text)}\n`).join("\n");
6547
6752
  }
6548
- (() => {
6753
+ const CRC = (() => {
6549
6754
  const t = /* @__PURE__ */ new Uint32Array(256);
6550
6755
  for (let i = 0; i < 256; i++) {
6551
6756
  let c = i;
@@ -6554,6 +6759,75 @@ function toSrt(segs) {
6554
6759
  }
6555
6760
  return t;
6556
6761
  })();
6762
+ /** The CRC-32 of the bytes, as zip uses it. */
6763
+ function crc32(b) {
6764
+ let c = 4294967295;
6765
+ for (let i = 0; i < b.length; i++) c = CRC[(c ^ b[i]) & 255] ^ c >>> 8;
6766
+ return (c ^ 4294967295) >>> 0;
6767
+ }
6768
+ /** A store only zip (no compression), UTF-8 names. `date` sets the DOS time stamp; pass one for reproducible bytes. */
6769
+ function zipStore(entries, date = /* @__PURE__ */ new Date()) {
6770
+ const enc = new TextEncoder();
6771
+ const tt = (date.getHours() & 31) << 11 | (date.getMinutes() & 63) << 5 | date.getSeconds() / 2 & 31;
6772
+ const dd = (date.getFullYear() - 1980 & 127) << 9 | (date.getMonth() + 1 & 15) << 5 | date.getDate() & 31;
6773
+ const parts = [];
6774
+ const cd = [];
6775
+ let off = 0;
6776
+ for (const e of entries) {
6777
+ const nm = enc.encode(e.name);
6778
+ const data = typeof e.data === "string" ? enc.encode(e.data) : e.data;
6779
+ const crc = crc32(data);
6780
+ const lh = new Uint8Array(30 + nm.length);
6781
+ const lv = new DataView(lh.buffer);
6782
+ lv.setUint32(0, 67324752, true);
6783
+ lv.setUint16(4, 20, true);
6784
+ lv.setUint16(6, 2048, true);
6785
+ lv.setUint16(10, tt, true);
6786
+ lv.setUint16(12, dd, true);
6787
+ lv.setUint32(14, crc, true);
6788
+ lv.setUint32(18, data.length, true);
6789
+ lv.setUint32(22, data.length, true);
6790
+ lv.setUint16(26, nm.length, true);
6791
+ lh.set(nm, 30);
6792
+ parts.push(lh, data);
6793
+ const ch = new Uint8Array(46 + nm.length);
6794
+ const cv = new DataView(ch.buffer);
6795
+ cv.setUint32(0, 33639248, true);
6796
+ cv.setUint16(4, 20, true);
6797
+ cv.setUint16(6, 20, true);
6798
+ cv.setUint16(8, 2048, true);
6799
+ cv.setUint16(12, tt, true);
6800
+ cv.setUint16(14, dd, true);
6801
+ cv.setUint32(16, crc, true);
6802
+ cv.setUint32(20, data.length, true);
6803
+ cv.setUint32(24, data.length, true);
6804
+ cv.setUint16(28, nm.length, true);
6805
+ cv.setUint32(42, off, true);
6806
+ ch.set(nm, 46);
6807
+ cd.push(ch);
6808
+ off += lh.length + data.length;
6809
+ }
6810
+ const cds = cd.reduce((a, c) => a + c.length, 0);
6811
+ const end = /* @__PURE__ */ new Uint8Array(22);
6812
+ const ev = new DataView(end.buffer);
6813
+ ev.setUint32(0, 101010256, true);
6814
+ ev.setUint16(8, entries.length, true);
6815
+ ev.setUint16(10, entries.length, true);
6816
+ ev.setUint32(12, cds, true);
6817
+ ev.setUint32(16, off, true);
6818
+ const all = [
6819
+ ...parts,
6820
+ ...cd,
6821
+ end
6822
+ ];
6823
+ const out = new Uint8Array(all.reduce((a, p) => a + p.length, 0));
6824
+ let p = 0;
6825
+ for (const a of all) {
6826
+ out.set(a, p);
6827
+ p += a.length;
6828
+ }
6829
+ return out;
6830
+ }
6557
6831
  // packages/speak/src/records.ts
6558
6832
  /** Model records for the voices this package drives, for pickers and the models registry. */
6559
6833
  const SPEAK_RECORDS = [
@@ -6823,15 +7097,88 @@ function asJson(doc) {
6823
7097
  function baseName(name) {
6824
7098
  return (name.split(/[\\/]/).pop() ?? name).replace(/\.[^.]+$/, "").replace(/[\u0000-\u001f:*?"<>|]/g, "_").trim() || "transcript";
6825
7099
  }
7100
+ const r1 = (x) => +(x ?? 0).toFixed(1);
7101
+ const one = (xs) => xs.length && xs.every((x) => x === xs[0]) ? xs[0] : xs.length ? "mixed" : "";
7102
+ /**
7103
+ * The zip of every document: txt, srt, vtt and json per source, and
7104
+ * `manifest.json` first. Two sources with one base name get "-2", "-3".
7105
+ * Pass `date` for reproducible bytes.
7106
+ */
7107
+ function bundle(docs, o = {}) {
7108
+ const date = o.date ?? /* @__PURE__ */ new Date();
7109
+ const used = /* @__PURE__ */ new Set();
7110
+ const entries = [];
7111
+ const files = [];
7112
+ for (const d of docs) {
7113
+ let b = baseName(d.source);
7114
+ for (let i = 2; used.has(b.toLowerCase()); i++) b = `${baseName(d.source)}-${i}`;
7115
+ used.add(b.toLowerCase());
7116
+ const out = [
7117
+ `${b}.txt`,
7118
+ `${b}.srt`,
7119
+ `${b}.vtt`,
7120
+ `${b}.json`
7121
+ ];
7122
+ entries.push({
7123
+ name: out[0],
7124
+ data: asTxt(d.segments)
7125
+ }, {
7126
+ name: out[1],
7127
+ data: asSrt(d.segments)
7128
+ }, {
7129
+ name: out[2],
7130
+ data: asVtt(d.segments)
7131
+ }, {
7132
+ name: out[3],
7133
+ data: asJson(d)
7134
+ });
7135
+ const s = d.stats;
7136
+ files.push({
7137
+ source: d.source,
7138
+ model: d.model,
7139
+ language: d.language,
7140
+ duration: d.duration ?? s?.dur ?? null,
7141
+ lines: d.segments.length,
7142
+ dropped: d.dropped?.length ?? 0,
7143
+ levels: s ? {
7144
+ noise_dbfs: r1(s.noiseDb),
7145
+ speech_dbfs: r1(s.speechDb),
7146
+ snr_db: r1(s.snrDb),
7147
+ lift_db: r1(s.gainDb),
7148
+ speech_density: +(s.density ?? 0).toFixed(3),
7149
+ realtime_factor: +(s.rtf ?? 0).toFixed(2)
7150
+ } : null,
7151
+ outputs: out
7152
+ });
7153
+ }
7154
+ const manifest = {
7155
+ tool: o.tool ?? "hackbuild-transcribe",
7156
+ generated: date.toISOString(),
7157
+ model: one(docs.map((d) => d.model)),
7158
+ language: one(docs.map((d) => d.language)),
7159
+ capture: o.capture ?? null,
7160
+ files
7161
+ };
7162
+ entries.unshift({
7163
+ name: "manifest.json",
7164
+ data: JSON.stringify(manifest, null, 2)
7165
+ });
7166
+ return {
7167
+ zip: zipStore(entries, date),
7168
+ manifest
7169
+ };
7170
+ }
6826
7171
  // packages/vision/src/records.ts
6827
7172
  /**
6828
7173
  * Vision records for the models hub. Licences are the model cards' as of
6829
7174
  * 2026-11-22; sizes are inferred from the builds and parameter counts, except where
6830
7175
  * a row says vendor: those sum the hub listing's files (no download), in MiB.
6831
7176
  * YOLO weights are AGPL-3.0 (Ultralytics): they are never registered by
6832
- * default. YOLOv8n has no public hub repo, so `yoloRecord` builds a record
7177
+ * default. YOLOv8n has no onnx-community or Xenova repo (an HTTP HEAD of
7178
+ * their config.json gave 401 on 2026-11-25), so `yoloRecord` builds a record
6833
7179
  * only for a URL the app supplies; YOLOv10 n, s and m, FastSAM and the face
6834
- * swap set sit in PICKER_RECORDS.
7180
+ * swap set sit in PICKER_RECORDS. The YOLOv10 n, s and m, SmolVLM 500M,
7181
+ * Gemma 4 E2B and FastSAM repos answered that HEAD with 200 the same day.
6835
7182
  */
6836
7183
  /** The MediaPipe model storage base URL the MediaPipe records load from. */
6837
7184
  const MP_MODELS = "https://storage.googleapis.com/mediapipe-models/";
@@ -7117,7 +7464,7 @@ const PICKER_RECORDS = [
7117
7464
  licence: "AGPL-3.0 upstream (Ultralytics FastSAM); the export's card says apache-2.0",
7118
7465
  commercial: false,
7119
7466
  place: "cpu-worker",
7120
- notes: ["finds every mask in one pass on onnxruntime-web (93 MB, vendor)", "segment everything: prototype masks, nms, then a pick by click"]
7467
+ notes: ["finds every mask in one pass on onnxruntime-web; the original page loaded a 93 MB build (vendor, its review)", "segment everything: prototype masks, nms, then a pick by click (segmentEverything, instanceAt)"]
7121
7468
  },
7122
7469
  {
7123
7470
  id: "scrfd-10g",
@@ -7365,7 +7712,7 @@ function backendOf(r, env) {
7365
7712
  /** Download words: "1.7 gb". Null for a record with no download or an unknown size. */
7366
7713
  function sizeWords(r) {
7367
7714
  if (isNoDownload(r) || r.sizeMB === null) return void 0;
7368
- return Lr(r.sizeMB * MIB);
7715
+ return Dr(r.sizeMB * MIB);
7369
7716
  }
7370
7717
  /** The record's label, else its id made readable: "hermes 3 llama 3.2 3b". */
7371
7718
  const pretty = (r) => r.label ?? r.id.replace(/-(mlc|gguf)$/, "").replace(/-/g, " ");
@@ -7384,11 +7731,11 @@ function detailOf(r) {
7384
7731
  });
7385
7732
  if (r.sizeMB !== null && !isNoDownload(r)) out.push({
7386
7733
  label: "size",
7387
- value: `${Lr(r.sizeMB * MIB)}, ${r.sizeSource}`
7734
+ value: `${Dr(r.sizeMB * MIB)}, ${r.sizeSource}`
7388
7735
  });
7389
7736
  if (r.vramMB != null) out.push({
7390
7737
  label: "gpu memory",
7391
- value: `${Lr(r.vramMB * MIB)}, ${r.vramSource ?? "unknown"}`
7738
+ value: `${Dr(r.vramMB * MIB)}, ${r.vramSource ?? "unknown"}`
7392
7739
  });
7393
7740
  if (r.ctx) out.push({
7394
7741
  label: "context",
@@ -7484,7 +7831,7 @@ function rowOf(r, ctx = {}) {
7484
7831
  state
7485
7832
  };
7486
7833
  if (size) row.size = size;
7487
- if (r.vramMB != null) row.memory = `needs ${Lr(r.vramMB * MIB)}`;
7834
+ if (r.vramMB != null) row.memory = `needs ${Dr(r.vramMB * MIB)}`;
7488
7835
  if (r.sizeMB !== null && !isNoDownload(r)) row.bytes = r.sizeMB * MIB;
7489
7836
  const speed = fit.fit === "fits on cpu, slow" ? "slow" : r.speed;
7490
7837
  if (speed) row.speed = speed;
@@ -7636,7 +7983,7 @@ function useModelPick(job, o = {}) {
7636
7983
  estimate,
7637
7984
  state: state.get(id)
7638
7985
  });
7639
- if (!rec || !Ce(row)) return;
7986
+ if (!rec || !Re(row)) return;
7640
7987
  if (!loader) {
7641
7988
  state.set(id, "error");
7642
7989
  errors.set(id, "no loader. the page passes one to load a model.");
@@ -7705,6 +8052,7 @@ function useModelPick(job, o = {}) {
7705
8052
  if (n.records) records = jobRecords(job, n.records);
7706
8053
  if (n.loader) loader = n.loader;
7707
8054
  if (n.onRemove) onRemove = n.onRemove;
8055
+ for (const id of n.stored ?? []) if (!state.has(id) || state.get(id) === "none") state.set(id, "stored");
7708
8056
  emit();
7709
8057
  },
7710
8058
  result: (id) => results.get(id),
@@ -7739,7 +8087,7 @@ function useJobsPick(jobs, initialPresets = [], shared = {}) {
7739
8087
  return {
7740
8088
  id: pr.id,
7741
8089
  label: pr.label,
7742
- total: bytes > 0 ? `about ${Lr(bytes)}` : "nothing to fetch"
8090
+ total: bytes > 0 ? `about ${Dr(bytes)}` : "nothing to fetch"
7743
8091
  };
7744
8092
  }),
7745
8093
  applyPreset(id) {
@@ -7747,7 +8095,7 @@ function useJobsPick(jobs, initialPresets = [], shared = {}) {
7747
8095
  if (!pr) return;
7748
8096
  for (const [job, mid] of Object.entries(pr.picks)) picks.get(job)?.choose(mid);
7749
8097
  },
7750
- all: () => Hs(chosenRows()),
8098
+ all: () => Zs(chosenRows()),
7751
8099
  async loadAll() {
7752
8100
  await Promise.all([...picks.values()].map((p) => p.load().catch(() => void 0)));
7753
8101
  },
@@ -7862,7 +8210,7 @@ function mountChatPane(host, thread, o = {}) {
7862
8210
  const l = listeners();
7863
8211
  const draw = (s) => {
7864
8212
  const sc = scroller(host);
7865
- const stick = Bo(sc);
8213
+ const stick = ei(sc);
7866
8214
  if (!s.turns.length) {
7867
8215
  host.innerHTML = `<div class="hb-lay-convempty"><h2 class="hb-lay-convempty-name">${esc(o.emptyName ?? "what are we working on?")}</h2>${o.emptyNote ? `<p class="hb-lay-convempty-note">${esc(o.emptyNote)}</p>` : ""}</div>`;
7868
8216
  return;
@@ -7904,7 +8252,7 @@ function mountComposer(host, thread, o = {}) {
7904
8252
  const text = area.value.trim();
7905
8253
  if (!text || busy) return;
7906
8254
  area.value = "";
7907
- Ho(area);
8255
+ Zo(area);
7908
8256
  thread.send(text);
7909
8257
  };
7910
8258
  const l = listeners();
@@ -7915,12 +8263,12 @@ function mountComposer(host, thread, o = {}) {
7915
8263
  l.on(act, "click", (e) => {
7916
8264
  if (e.target.closest("[data-stop]")) thread.stop();
7917
8265
  });
7918
- l.on(area, "input", () => Ho(area));
8266
+ l.on(area, "input", () => Zo(area));
7919
8267
  l.on(area, "keydown", (e) => {
7920
- const k = Ko(e, {
8268
+ const k = Jo(e, {
7921
8269
  busy,
7922
8270
  empty: !area.value,
7923
- coarse: jo()
8271
+ coarse: Qo()
7924
8272
  });
7925
8273
  if (k === "send") {
7926
8274
  e.preventDefault();
@@ -7941,7 +8289,7 @@ function mountChatList(host, list, o = {}) {
7941
8289
  let renaming = "";
7942
8290
  const head = o.label ?? "chats";
7943
8291
  const draw = (s) => {
7944
- host.innerHTML = `<nav class="hb-convs" aria-label="${esc(head)}"><div class="hb-convs-hd"><span>${esc(head)}</span><button type="button" class="hb-convs-new" data-new aria-label="new chat">${ICON.plus}</button></div><ul class="hb-convs-list">` + s.items.map((c) => renaming === c.id ? `<li class="hb-convs-item"><form class="hb-convs-rename" data-rename="${esc(c.id)}"><input class="hb-input" aria-label="chat name" value="${esc(c.title)}"></form></li>` : `<li class="hb-convs-item"${c.id === s.current ? " aria-current=\"true\"" : ""}><button type="button" class="hb-convs-open" data-open="${esc(c.id)}"><span class="hb-convs-title">${esc(c.title)}</span><span class="hb-convs-meta">${esc(Wo({
8292
+ host.innerHTML = `<nav class="hb-convs" aria-label="${esc(head)}"><div class="hb-convs-hd"><span>${esc(head)}</span><button type="button" class="hb-convs-new" data-new aria-label="new chat">${ICON.plus}</button></div><ul class="hb-convs-list">` + s.items.map((c) => renaming === c.id ? `<li class="hb-convs-item"><form class="hb-convs-rename" data-rename="${esc(c.id)}"><input class="hb-input" aria-label="chat name" value="${esc(c.title)}"></form></li>` : `<li class="hb-convs-item"${c.id === s.current ? " aria-current=\"true\"" : ""}><button type="button" class="hb-convs-open" data-open="${esc(c.id)}"><span class="hb-convs-title">${esc(c.title)}</span><span class="hb-convs-meta">${esc(ni({
7945
8293
  updated: c.updated,
7946
8294
  count: c.count
7947
8295
  }))}</span></button><span class="hb-convs-acts"><button type="button" class="hb-convs-act" data-ren="${esc(c.id)}" aria-label="rename ${esc(c.title)}" title="rename">${ICON.pen}</button><button type="button" class="hb-convs-act is-del${armed === c.id ? " is-armed" : ""}" data-del="${esc(c.id)}" aria-label="${armed === c.id ? `press again to delete ${esc(c.title)}` : `delete ${esc(c.title)}`}">${armed === c.id ? "delete?" : ICON.trash}</button></span></li>`).join("") + `</ul></nav>`;
@@ -7977,7 +8325,7 @@ function mountContextMeter(host, thread, o = {}) {
7977
8325
  const l = listeners();
7978
8326
  const val = (v, d) => typeof v === "function" ? v() : v ?? d;
7979
8327
  const draw = (s) => {
7980
- const use = Uo(contextSegments(s, val(o.system, "")), val(o.budget, 4096));
8328
+ const use = ti(contextSegments(s, val(o.system, "")), val(o.budget, 4096));
7981
8329
  host.innerHTML = `<div class="hb-ctxmeter is-${use.tone}"><div class="hb-ctxmeter-hd"><span class="hb-ctxmeter-label">context</span><span class="hb-ctxmeter-words">${esc(use.words)}</span></div><div class="hb-ctxmeter-bar" role="meter" aria-label="context used" aria-valuemin="0" aria-valuemax="${use.budget}" aria-valuenow="${use.used}" aria-valuetext="${esc(use.words)}">${use.rows.map((r, n) => `<i class="hb-ctxmeter-p${n % 6}" style="width:${Math.min(100, r.fraction * 100)}%"></i>`).join("")}</div><ul class="hb-ctxmeter-legend">${use.rows.map((r, n) => `<li><i class="hb-ctxmeter-p${n % 6}" aria-hidden="true"></i>${esc(r.label)} <b>${r.tokens.toLocaleString("en-US")}</b></li>`).join("")}</ul></div>`;
7982
8330
  };
7983
8331
  l.add(thread.subscribe(draw));
@@ -8052,7 +8400,7 @@ function mountFrameView(host, o = {}) {
8052
8400
  const none = host.querySelector(".hb-camtile-none");
8053
8401
  const tag = host.querySelector(".hb-camtile-tag");
8054
8402
  const cap = host.querySelector("[data-caption]");
8055
- const palette = o.palette ?? ut;
8403
+ const palette = o.palette ?? ht;
8056
8404
  let src = null;
8057
8405
  let results = {};
8058
8406
  let mirror = !!o.mirror;
@@ -8237,7 +8585,7 @@ function mountCameraFeed(host, o = {}) {
8237
8585
  if (stream) return;
8238
8586
  error = "";
8239
8587
  try {
8240
- stream = await wi({
8588
+ stream = await qi({
8241
8589
  facingMode: o.facingMode ?? "user",
8242
8590
  width: { ideal: 640 },
8243
8591
  height: { ideal: 480 }
@@ -8250,7 +8598,7 @@ function mountCameraFeed(host, o = {}) {
8250
8598
  Promise.resolve(o.onFrame(video)).finally(() => working = false);
8251
8599
  }, 1e3 / (o.fps ?? 4));
8252
8600
  } catch (e) {
8253
- error = Mi(e).text;
8601
+ error = Di(e).text;
8254
8602
  stream = null;
8255
8603
  }
8256
8604
  emit();
@@ -8258,7 +8606,7 @@ function mountCameraFeed(host, o = {}) {
8258
8606
  stop() {
8259
8607
  if (timer) clearInterval(timer);
8260
8608
  timer = null;
8261
- ki(stream);
8609
+ Oi(stream);
8262
8610
  stream = null;
8263
8611
  video.srcObject = null;
8264
8612
  emit();
@@ -8288,7 +8636,11 @@ function mountCameraFeed(host, o = {}) {
8288
8636
  * export the mask, a matte or the cutout. With a segment everything model
8289
8637
  * (FastSAM) one press finds every object; each lands in the found list and
8290
8638
  * a press adds it to the mask. Models are functions the page passes, so
8291
- * stubs run the studio with no weights.
8639
+ * stubs run the studio with no weights. Three views (composite, mask,
8640
+ * found objects) paint over the canvas; the pointer previews the click cut
8641
+ * or lights the found object under it; two fingers or ctrl and the wheel
8642
+ * zoom; a page that loads models on demand hears `onWant` when a tool needs
8643
+ * one.
8292
8644
  */
8293
8645
  const ZOOMS = [
8294
8646
  .5,
@@ -8299,6 +8651,25 @@ const ZOOMS = [
8299
8651
  3,
8300
8652
  4
8301
8653
  ];
8654
+ const clampZoom = (z) => Math.max(.25, Math.min(6, z));
8655
+ /** Paint `rgb` at `alpha` (0 to 255) where the mask keeps, leaving the other pixels as they are. */
8656
+ function tintInto(rgba, mask, rgb, alpha) {
8657
+ for (let i = 0, j = 0; i < mask.length; i++, j += 4) {
8658
+ if (!mask[i]) continue;
8659
+ rgba[j] = rgb[0];
8660
+ rgba[j + 1] = rgb[1];
8661
+ rgba[j + 2] = rgb[2];
8662
+ rgba[j + 3] = alpha;
8663
+ }
8664
+ }
8665
+ /** ImageData to a png Blob. */
8666
+ function pngOf(img) {
8667
+ const c = document.createElement("canvas");
8668
+ c.width = img.width;
8669
+ c.height = img.height;
8670
+ c.getContext("2d")?.putImageData(img, 0, 0);
8671
+ return new Promise((ok) => c.toBlob((b) => ok(b), "image/png"));
8672
+ }
8302
8673
  /** Pixels of a drawable, for a model. */
8303
8674
  function pixelsOf(src) {
8304
8675
  const c = document.createElement("canvas");
@@ -8332,17 +8703,22 @@ function thumbOf(img) {
8332
8703
  function mountMaskStudio(host, o = {}) {
8333
8704
  let models = o.models ?? {};
8334
8705
  const l = listeners();
8335
- host.innerHTML = `<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><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><input type="file" accept="image/*" hidden>`;
8706
+ host.innerHTML = `<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><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><input type="file" accept="image/*" hidden>`;
8336
8707
  const empty = host.querySelector("[data-empty]");
8337
8708
  const studio = host.querySelector("[data-studio]");
8338
8709
  const well = host.querySelector(".hb-mask-well");
8339
8710
  host.querySelector(".hb-mask-frame");
8340
- const canvas = host.querySelector("canvas");
8711
+ const canvas = host.querySelector(".hb-mask-canvas");
8712
+ const over = host.querySelector("[data-over]");
8341
8713
  const hint = host.querySelector(".hb-mask-hint");
8342
8714
  const input = host.querySelector("input[type=file]");
8343
8715
  const subs = /* @__PURE__ */ new Set();
8344
8716
  let tool = models.segment ? "point" : "wand";
8345
8717
  let zoom = 1;
8718
+ let view = "composite";
8719
+ let hover = -1;
8720
+ let preview = null;
8721
+ let wantAll = null;
8346
8722
  let busy = "";
8347
8723
  let error = "";
8348
8724
  let pixels = null;
@@ -8361,6 +8737,9 @@ function mountMaskStudio(host, o = {}) {
8361
8737
  coverage: ed?.coverage ?? 0,
8362
8738
  zoom,
8363
8739
  busy,
8740
+ contiguous: ed?.contiguous ?? true,
8741
+ view,
8742
+ hover,
8364
8743
  found,
8365
8744
  saved: saved.map(({ bytes: _b, ...rest }) => rest),
8366
8745
  width: ed?.width ?? 0,
@@ -8369,10 +8748,61 @@ function mountMaskStudio(host, o = {}) {
8369
8748
  });
8370
8749
  const emit = () => {
8371
8750
  const s = state();
8372
- hint.textContent = s.busy || s.error || (tool === "point" ? "press a thing to cut it out. x takes it away instead." : ft.find((t) => t.id === tool)?.hint ?? "");
8751
+ hint.textContent = s.busy || s.error || (tool === "point" ? "press a thing to cut it out. x takes it away instead." : gt.find((t) => t.id === tool)?.hint ?? "");
8373
8752
  for (const fn of subs) fn(s);
8753
+ paint();
8754
+ };
8755
+ let painted = "";
8756
+ let frameReq = 0;
8757
+ const paint = () => {
8758
+ if (frameReq) return;
8759
+ frameReq = typeof requestAnimationFrame === "function" ? requestAnimationFrame(drawOver) : (drawOver(), 0);
8760
+ };
8761
+ const drawOver = () => {
8762
+ frameReq = 0;
8763
+ const w = ed?.width ?? 0;
8764
+ const h = ed?.height ?? 0;
8765
+ const g = over.getContext("2d");
8766
+ if (!g || !w || !h || !pixels) return;
8767
+ if (over.width !== w || over.height !== h) {
8768
+ over.width = w;
8769
+ over.height = h;
8770
+ }
8771
+ const key = `${view}:${hover}:${preview ? "p" : ""}:${view === "mask" ? editor.state.coverage + ":" + (ed?.canUndo ? 1 : 0) : ""}:${found.map((f) => f.hidden ? 0 : 1).join("")}`;
8772
+ if (view === "composite" && hover < 0 && !preview) {
8773
+ if (painted !== "clear") g.clearRect(0, 0, w, h);
8774
+ painted = "clear";
8775
+ return;
8776
+ }
8777
+ if (key === painted && view !== "mask") return;
8778
+ painted = key;
8779
+ if (view === "mask") {
8780
+ g.putImageData(new ImageData(er(editor.mask(), "matte"), w, h), 0, 0);
8781
+ return;
8782
+ }
8783
+ const rgba = new Uint8ClampedArray(w * h * 4);
8784
+ if (view === "instances") found.forEach((f, i) => !f.hidden && i !== hover && tintInto(rgba, f.mask, nr(f.colour), 150));
8785
+ const hot = hover >= 0 ? found[hover] : void 0;
8786
+ if (hot) tintInto(rgba, hot.mask, nr(hot.colour), 220);
8787
+ else if (preview) tintInto(rgba, preview, [
8788
+ 254,
8789
+ 3,
8790
+ 134
8791
+ ], 110);
8792
+ g.putImageData(new ImageData(rgba, w, h), 0, 0);
8793
+ if (view === "instances") {
8794
+ g.lineWidth = Math.max(1, w / 400);
8795
+ g.font = `${Math.max(10, Math.round(w / 60))}px monospace`;
8796
+ for (const f of found) {
8797
+ if (f.hidden || !f.box) continue;
8798
+ g.strokeStyle = f.colour;
8799
+ g.fillStyle = f.colour;
8800
+ g.strokeRect(f.box.x, f.box.y, f.box.w, f.box.h);
8801
+ g.fillText(`${f.label} ${Math.round(f.score * 100)}`, f.box.x + 3, Math.max(12, f.box.y - 4));
8802
+ }
8803
+ }
8374
8804
  };
8375
- const editor = Wi(canvas, {
8805
+ const editor = ns(canvas, {
8376
8806
  tool: tool === "point" ? "wand" : tool,
8377
8807
  onError: (e) => (error = `the image did not load: ${e.message}`, emit())
8378
8808
  });
@@ -8384,6 +8814,7 @@ function mountMaskStudio(host, o = {}) {
8384
8814
  studio.style.setProperty("--hb-mask-w", `${Math.round(fitW * zoom)}px`);
8385
8815
  studio.classList.toggle("is-zoomed", zoom > 1);
8386
8816
  };
8817
+ const zoomStep = (dir) => (dir > 0 ? ZOOMS.find((z) => z > zoom + .001) : [...ZOOMS].reverse().find((z) => z < zoom - .001)) ?? zoom;
8387
8818
  const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => applyZoom()) : null;
8388
8819
  ro?.observe(well);
8389
8820
  l.add(() => ro?.disconnect());
@@ -8408,17 +8839,130 @@ function mountMaskStudio(host, o = {}) {
8408
8839
  emit();
8409
8840
  }
8410
8841
  };
8842
+ const at = (pe) => {
8843
+ const r = canvas.getBoundingClientRect();
8844
+ const w = ed?.width ?? 0;
8845
+ const h = ed?.height ?? 0;
8846
+ return {
8847
+ x: Math.max(0, Math.min(w - 1, Math.round((pe.clientX - r.left) / r.width * w))),
8848
+ y: Math.max(0, Math.min(h - 1, Math.round((pe.clientY - r.top) / r.height * h)))
8849
+ };
8850
+ };
8851
+ const foundAt = (x, y) => found.findIndex((f) => !f.hidden && f.mask[y * (ed?.width ?? 0) + x]);
8411
8852
  const onPoint = (e) => {
8412
8853
  if (tool !== "point") return;
8413
8854
  e.stopImmediatePropagation();
8414
8855
  e.preventDefault();
8415
8856
  const pe = e;
8416
- const r = canvas.getBoundingClientRect();
8417
8857
  if (!ed?.ready) return;
8418
- const x = Math.round((pe.clientX - r.left) / r.width * ed.width);
8419
- const y = Math.round((pe.clientY - r.top) / r.height * ed.height);
8858
+ const { x, y } = at(pe);
8859
+ const i = foundAt(x, y);
8860
+ if (i >= 0) return studioApi.toggleFound(i);
8861
+ if (!models.segment) return o.onWant?.("segment");
8862
+ preview = null;
8420
8863
  cut(x, y, ed.mode === "erase" !== pe.shiftKey);
8421
8864
  };
8865
+ let asking = false;
8866
+ let next = null;
8867
+ const ask = async (p) => {
8868
+ if (!pixels || !models.segment) return;
8869
+ asking = true;
8870
+ try {
8871
+ const m = await models.segment(pixels, p);
8872
+ if (tool === "point" && next !== null) preview = m;
8873
+ } catch {
8874
+ preview = null;
8875
+ } finally {
8876
+ asking = false;
8877
+ }
8878
+ paint();
8879
+ const n = next;
8880
+ if (n && (n.x !== p.x || n.y !== p.y)) ask(n);
8881
+ };
8882
+ const onHover = (e) => {
8883
+ const pe = e;
8884
+ if (!ed?.ready || pe.buttons || pe.pointerType === "touch") return;
8885
+ const p = at(pe);
8886
+ const i = found.length && (tool === "point" || view === "instances") ? foundAt(p.x, p.y) : -1;
8887
+ if (i !== hover) {
8888
+ hover = i;
8889
+ emit();
8890
+ }
8891
+ if (i >= 0 || tool !== "point" || !models.segment) {
8892
+ next = null;
8893
+ if (preview) preview = null, paint();
8894
+ return;
8895
+ }
8896
+ next = p;
8897
+ if (!asking) ask(p);
8898
+ };
8899
+ const offHover = () => {
8900
+ next = null;
8901
+ preview = null;
8902
+ if (hover >= 0) hover = -1, emit();
8903
+ else paint();
8904
+ };
8905
+ canvas.addEventListener("pointermove", onHover);
8906
+ canvas.addEventListener("pointerleave", offHover);
8907
+ l.add(() => (canvas.removeEventListener("pointermove", onHover), canvas.removeEventListener("pointerleave", offHover)));
8908
+ const touches = /* @__PURE__ */ new Map();
8909
+ let pinch = null;
8910
+ const spread = () => {
8911
+ const [a, b] = [...touches.values()];
8912
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
8913
+ };
8914
+ l.on(well, "pointerdown", (e) => {
8915
+ const pe = e;
8916
+ if (pe.pointerType !== "touch") return;
8917
+ touches.set(pe.pointerId, {
8918
+ x: pe.clientX,
8919
+ y: pe.clientY
8920
+ });
8921
+ if (touches.size === 2) {
8922
+ editor.cancel();
8923
+ pinch = {
8924
+ d: spread() || 1,
8925
+ z: zoom
8926
+ };
8927
+ }
8928
+ });
8929
+ l.on(well, "pointermove", (e) => {
8930
+ const pe = e;
8931
+ if (!touches.has(pe.pointerId)) return;
8932
+ touches.set(pe.pointerId, {
8933
+ x: pe.clientX,
8934
+ y: pe.clientY
8935
+ });
8936
+ if (pinch && touches.size === 2) studioApi.zoomTo(pinch.z * (spread() / pinch.d));
8937
+ });
8938
+ const lift = (e) => {
8939
+ touches.delete(e.pointerId);
8940
+ if (touches.size < 2) pinch = null;
8941
+ };
8942
+ l.on(well, "pointerup", lift);
8943
+ l.on(well, "pointercancel", lift);
8944
+ l.on(well, "wheel", (e) => {
8945
+ const we = e;
8946
+ if (!we.ctrlKey || !ed?.ready) return;
8947
+ we.preventDefault();
8948
+ studioApi.zoomTo(zoom * Math.exp(-we.deltaY / 200));
8949
+ });
8950
+ l.on(document, "keydown", (e) => {
8951
+ const ke = e;
8952
+ if (ke.defaultPrevented || ke.target.closest?.("input,textarea,select,[contenteditable]")) return;
8953
+ const k = ke.key.toLowerCase();
8954
+ const cmd = ke.ctrlKey || ke.metaKey;
8955
+ if (cmd && k === "o") return ke.preventDefault(), input.click();
8956
+ if (!ed?.ready) return;
8957
+ if (cmd && (k === "z" || k === "y")) return ke.preventDefault(), void (k === "y" || ke.shiftKey ? editor.redo() : editor.undo());
8958
+ 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));
8959
+ if (cmd && k === "i") return ke.preventDefault(), editor.invert();
8960
+ if (cmd) return;
8961
+ if (k === "delete") return ke.preventDefault(), editor.clear();
8962
+ if (k === "+" || k === "=") return studioApi.zoom(1);
8963
+ if (k === "-") return studioApi.zoom(-1);
8964
+ if (k === "0") return studioApi.zoom(0);
8965
+ });
8422
8966
  canvas.addEventListener("pointerdown", onPoint, true);
8423
8967
  l.add(() => canvas.removeEventListener("pointerdown", onPoint, true));
8424
8968
  const take = (f) => {
@@ -8445,6 +8989,8 @@ function mountMaskStudio(host, o = {}) {
8445
8989
  error = "";
8446
8990
  found = [];
8447
8991
  saved = [];
8992
+ hover = -1;
8993
+ preview = null;
8448
8994
  let drawable = null;
8449
8995
  if (typeof src === "string") {
8450
8996
  const img = new Image();
@@ -8464,8 +9010,12 @@ function mountMaskStudio(host, o = {}) {
8464
9010
  canvas.focus({ preventScroll: true });
8465
9011
  },
8466
9012
  setTool(t) {
8467
- if (t === "point" && !models.segment) return;
9013
+ if (t === "point" && !models.segment) {
9014
+ if (!o.onWant) return;
9015
+ o.onWant("segment");
9016
+ }
8468
9017
  tool = t;
9018
+ preview = null;
8469
9019
  if (t !== "point") editor.setTool(t);
8470
9020
  canvas.dataset.tool = t;
8471
9021
  emit();
@@ -8503,25 +9053,83 @@ function mountMaskStudio(host, o = {}) {
8503
9053
  },
8504
9054
  mask: (kind = "alpha") => ed?.ready ? editor.toImageData(kind) : null,
8505
9055
  zoom(dir) {
8506
- if (dir === 0) zoom = 1;
8507
- else {
8508
- const i = ZOOMS.indexOf(zoom);
8509
- zoom = ZOOMS[Math.max(0, Math.min(ZOOMS.length - 1, i + dir))];
8510
- }
9056
+ zoom = dir === 0 ? 1 : zoomStep(dir);
9057
+ applyZoom();
9058
+ emit();
9059
+ },
9060
+ zoomTo(z) {
9061
+ zoom = clampZoom(z);
8511
9062
  applyZoom();
8512
9063
  emit();
8513
9064
  },
8514
- async everything() {
8515
- if (!models.everything || !pixels) return;
9065
+ setView(v) {
9066
+ view = v;
9067
+ emit();
9068
+ },
9069
+ setContiguous: (on) => editor.setContiguous(on),
9070
+ setMask(m) {
9071
+ if (ed?.ready && m.length === ed.width * ed.height) editor.setMask(m);
9072
+ },
9073
+ addFound(list) {
9074
+ const n = found.length;
9075
+ found = [...found, ...list.filter((f) => f.mask.length === (ed?.width ?? 0) * (ed?.height ?? 0)).map((f, i) => ({
9076
+ ...f,
9077
+ on: false,
9078
+ hidden: false,
9079
+ colour: ht[(n + i) % ht.length]
9080
+ }))];
9081
+ if (found.length > n && view === "composite") view = "instances";
9082
+ emit();
9083
+ },
9084
+ showFound(i, on) {
9085
+ found = found.map((x, k) => k === i ? {
9086
+ ...x,
9087
+ hidden: !on
9088
+ } : x);
9089
+ emit();
9090
+ },
9091
+ removeFound(i) {
9092
+ found = found.filter((_, k) => k !== i);
9093
+ hover = -1;
9094
+ emit();
9095
+ },
9096
+ mergeFound() {
9097
+ if (!ed?.ready || !found.length) return;
9098
+ const cur = editor.mask();
9099
+ for (const f of found) if (!f.hidden) {
9100
+ for (let p = 0; p < cur.length; p++) if (f.mask[p]) cur[p] = 255;
9101
+ }
9102
+ found = found.map((x) => x.hidden ? x : {
9103
+ ...x,
9104
+ on: true
9105
+ });
9106
+ editor.setMask(cur);
9107
+ },
9108
+ clearFound() {
9109
+ found = [];
9110
+ hover = -1;
9111
+ if (view === "instances") view = "composite";
9112
+ emit();
9113
+ },
9114
+ pixels: () => pixels,
9115
+ async everything(eo) {
9116
+ if (!pixels) return;
9117
+ if (!models.everything) {
9118
+ wantAll = eo ?? {};
9119
+ return o.onWant?.("everything");
9120
+ }
9121
+ wantAll = null;
8516
9122
  busy = "finding every object";
8517
9123
  error = "";
8518
9124
  emit();
8519
9125
  try {
8520
- found = (await models.everything(pixels)).map((f, i) => ({
9126
+ found = (await models.everything(pixels, eo)).map((f, i) => ({
8521
9127
  ...f,
8522
9128
  on: false,
8523
- colour: ut[i % ut.length]
9129
+ hidden: false,
9130
+ colour: ht[i % ht.length]
8524
9131
  }));
9132
+ if (found.length) view = "instances";
8525
9133
  } catch (e) {
8526
9134
  error = `segment everything failed: ${e instanceof Error ? e.message : String(e)}`;
8527
9135
  } finally {
@@ -8543,6 +9151,7 @@ function mountMaskStudio(host, o = {}) {
8543
9151
  },
8544
9152
  async exportAs(kind) {
8545
9153
  if (!ed?.ready) return null;
9154
+ if (kind === "inverse") return pngOf(new ImageData(er(Jn(editor.mask()), "matte"), ed.width, ed.height));
8546
9155
  return editor.toBlob(kind);
8547
9156
  },
8548
9157
  get hasEverything() {
@@ -8551,6 +9160,9 @@ function mountMaskStudio(host, o = {}) {
8551
9160
  get hasSegment() {
8552
9161
  return !!models.segment;
8553
9162
  },
9163
+ get canWant() {
9164
+ return !!o.onWant;
9165
+ },
8554
9166
  state,
8555
9167
  subscribe(fn) {
8556
9168
  subs.add(fn);
@@ -8564,8 +9176,9 @@ function mountMaskStudio(host, o = {}) {
8564
9176
  tool = "point";
8565
9177
  canvas.dataset.tool = "point";
8566
9178
  }
8567
- if (tool === "point" && !m.segment) studioApi.setTool("wand");
9179
+ if (tool === "point" && !m.segment && !o.onWant) studioApi.setTool("wand");
8568
9180
  emit();
9181
+ if (wantAll && m.everything) studioApi.everything(wantAll);
8569
9182
  },
8570
9183
  pick: () => input.click(),
8571
9184
  dispose() {
@@ -8582,17 +9195,17 @@ function mountMaskStudio(host, o = {}) {
8582
9195
  function mountMaskTools(host, studio) {
8583
9196
  const l = listeners();
8584
9197
  const draw = (s) => {
8585
- host.innerHTML = [...studio.hasSegment ? [{
9198
+ host.innerHTML = [...studio.hasSegment || studio.canWant ? [{
8586
9199
  id: "point",
8587
9200
  label: "cut out a thing",
8588
9201
  key: "a",
8589
9202
  icon: "crosshairs"
8590
- }] : [], ...ft.map((t) => ({
9203
+ }] : [], ...gt.map((t) => ({
8591
9204
  id: t.id,
8592
9205
  label: t.label,
8593
9206
  key: t.key,
8594
9207
  icon: t.icon
8595
- }))].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}">${Qt(t.icon, { size: 18 })}</button>`).join("");
9208
+ }))].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("");
8596
9209
  };
8597
9210
  l.on(host, "click", (e) => {
8598
9211
  const t = e.target.closest("[data-tool]");
@@ -8600,12 +9213,7 @@ function mountMaskTools(host, studio) {
8600
9213
  });
8601
9214
  l.on(document, "keydown", (e) => {
8602
9215
  const ke = e;
8603
- if (!!!ke.target.closest?.("input,textarea,[contenteditable]") && !ke.ctrlKey && !ke.metaKey && studio.state().ready) {
8604
- if (ke.key === "+" || ke.key === "=") return studio.zoom(1);
8605
- if (ke.key === "-") return studio.zoom(-1);
8606
- if (ke.key === "0") return studio.zoom(0);
8607
- }
8608
- if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && studio.hasSegment && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
9216
+ if (ke.key === "a" && !ke.ctrlKey && !ke.metaKey && (studio.hasSegment || studio.canWant) && !ke.target.closest?.("input,textarea,[contenteditable]")) studio.setTool("point");
8609
9217
  });
8610
9218
  l.add(studio.subscribe(draw));
8611
9219
  return { dispose: () => l.off() };
@@ -8615,11 +9223,17 @@ function mountMaskVerbs(host, studio) {
8615
9223
  const l = listeners();
8616
9224
  let last = "";
8617
9225
  const draw = (s) => {
8618
- 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>` : "";
9226
+ 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">${[
9227
+ "composite",
9228
+ "mask",
9229
+ "instances"
9230
+ ].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>` : "") : "";
8619
9231
  if (html !== last) host.innerHTML = last = html;
8620
9232
  host.hidden = !html;
8621
9233
  };
8622
9234
  l.on(host, "click", (e) => {
9235
+ const view = e.target.closest("[data-view]")?.dataset.view;
9236
+ if (view) return studio.setView(view);
8623
9237
  const v = e.target.closest("[data-v]")?.dataset.v;
8624
9238
  if (v === "undo") studio.undo();
8625
9239
  else if (v === "redo") studio.redo();
@@ -8637,11 +9251,11 @@ function mountMaskRack(host, studio, part, o = {}) {
8637
9251
  const draw = (s) => {
8638
9252
  let html = "";
8639
9253
  if (part === "found") {
8640
- html = s.found.length ? `<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>` : `<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>` + (s.ready && studio.hasEverything && !s.busy ? `<button type="button" class="hb-btn hb-btn-go" data-all>find every object</button>` : "");
9254
+ 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>` : "");
8641
9255
  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>` : "";
8642
- } 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.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>` : "");
9256
+ } 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>` : "");
8643
9257
  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>`);
8644
- 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></div>` : `<p class="hb-lay-empty-note">exports show once there is a mask.</p>`;
9258
+ 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>`;
8645
9259
  if (html !== last) host.innerHTML = last = html;
8646
9260
  };
8647
9261
  l.on(host, "click", (e) => {
@@ -8650,7 +9264,13 @@ function mountMaskRack(host, studio, part, o = {}) {
8650
9264
  if (f) return studio.toggleFound(Number(f.dataset.found));
8651
9265
  const m = t.closest("[data-mode]");
8652
9266
  if (m) return studio.setMode(m.dataset.mode);
9267
+ const show = t.closest("[data-show]");
9268
+ if (show) return studio.showFound(Number(show.dataset.show), show.getAttribute("aria-pressed") !== "true");
9269
+ const drop = t.closest("[data-drop]");
9270
+ if (drop) return studio.removeFound(Number(drop.dataset.drop));
8653
9271
  const op = t.closest("[data-op]")?.dataset.op;
9272
+ if (op === "merge") return studio.mergeFound();
9273
+ if (op === "unfind") return studio.clearFound();
8654
9274
  if (op === "invert") return studio.invert();
8655
9275
  if (op === "clear") return studio.clear();
8656
9276
  if (op === "smooth") return studio.smooth();
@@ -8673,6 +9293,7 @@ function mountMaskRack(host, studio, part, o = {}) {
8673
9293
  const i = e.target;
8674
9294
  if (i.dataset.size !== void 0) studio.setSize(Number(i.value));
8675
9295
  if (i.dataset.tol !== void 0) studio.setTolerance(Number(i.value));
9296
+ if (i.dataset.contig !== void 0) studio.setContiguous(i.checked);
8676
9297
  });
8677
9298
  l.add(studio.subscribe(draw));
8678
9299
  return { dispose: () => l.off() };
@@ -8692,7 +9313,7 @@ function pickSheet(pick) {
8692
9313
  const s0 = pick.snapshot();
8693
9314
  root.innerHTML = `<div class="hb-drawer-panel" role="dialog" aria-modal="true"><div class="hb-drawer-hd"><span>${esc(s0.title)}</span><button type="button" class="hb-iconbtn" aria-label="close" data-hb-close><svg class="hb-icon is-stroke" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg></button></div><div class="hb-msheet-host"></div></div>`;
8694
9315
  doc.body.append(root);
8695
- const sheet = Bs(root.querySelector(".hb-msheet-host"), {
9316
+ const sheet = ea(root.querySelector(".hb-msheet-host"), {
8696
9317
  rows: s0.rows,
8697
9318
  chosen: s0.chosen,
8698
9319
  title: s0.title,
@@ -8704,7 +9325,7 @@ function pickSheet(pick) {
8704
9325
  onCustom: (kind, values) => void pick.custom(kind, values)
8705
9326
  });
8706
9327
  const l = listeners();
8707
- const handle = qr(root, {
9328
+ const handle = Wr(root, {
8708
9329
  side: "auto",
8709
9330
  breakpoint: 641,
8710
9331
  label: s0.title
@@ -8720,9 +9341,29 @@ function pickSheet(pick) {
8720
9341
  }
8721
9342
  };
8722
9343
  }
9344
+ const FILLER = /^(instruct|chat|it|mlc|onnx|gguf|hf|q\d\w*|f16|f32|fp16|int8|bf16|uniform)$/i;
9345
+ /**
9346
+ * A model name cut for the bar chip: filler words (instruct, chat, quant tags)
9347
+ * go, and a name of more than three words keeps its first two and its last,
9348
+ * which is usually the size: "hermes 3 llama 3.2 3b" reads "hermes 3 3b".
9349
+ * A note in brackets goes first: "slimsam 77 uniform (point prompts)" reads "slimsam 77".
9350
+ */
9351
+ function shortName(name) {
9352
+ const w = name.replace(/\s*\([^)]*\)/g, "").split(/\s+/).filter((x) => x && !FILLER.test(x));
9353
+ return (w.length > 3 ? [
9354
+ w[0],
9355
+ w[1],
9356
+ w[w.length - 1]
9357
+ ] : w).join(" ") || name;
9358
+ }
9359
+ /** The chip's words: the short name, then the download size, or the state once it moves. */
8723
9360
  function chipWords(s) {
8724
- const w = $r(s.row, s.empty);
8725
- return w.state ? `${w.name}, ${w.state}` : w.name;
9361
+ const r = s.row;
9362
+ if (!r) return s.empty;
9363
+ const w = qr(r, s.empty);
9364
+ const name = shortName(r.name);
9365
+ if ((r.state === "loading" || r.state === "loaded" || r.state === "error") && w.state) return `${name}, ${w.state}`;
9366
+ return `${name}, ${r.noDownload ? "no download" : r.size ?? "size unknown"}`;
8726
9367
  }
8727
9368
  /** The closed picker over a host; pressing it opens the sheet. */
8728
9369
  function mountModelSelect(host, pick, o = {}) {
@@ -8732,7 +9373,8 @@ function mountModelSelect(host, pick, o = {}) {
8732
9373
  if (o.variant === "chip") {
8733
9374
  const draw = (s) => {
8734
9375
  const words = chipWords(s);
8735
- host.innerHTML = `<button type="button" class="hb-msel-chip${s.row?.state ? ` is-${s.row.state}` : ""}" aria-haspopup="dialog" aria-label="model: ${esc(words)}"><span>${esc(words)}</span></button>`;
9376
+ const full = s.row ? `model: ${s.row.name}${s.row.size ? `, ${s.row.size}` : ""}${qr(s.row, s.empty).state ? `, ${qr(s.row, s.empty).state}` : ""}` : `model: ${s.empty}`;
9377
+ host.innerHTML = `<button type="button" class="hb-msel-chip${s.row?.state ? ` is-${s.row.state}` : ""}" aria-haspopup="dialog" aria-label="${esc(full)}" title="${esc(full)}"><span>${esc(words)}</span></button>`;
8736
9378
  };
8737
9379
  l.on(host, "click", (e) => {
8738
9380
  if (e.target.closest(".hb-msel-chip")) sheet.open();
@@ -8742,7 +9384,7 @@ function mountModelSelect(host, pick, o = {}) {
8742
9384
  const inner = document.createElement("div");
8743
9385
  host.replaceChildren(inner);
8744
9386
  const s0 = pick.snapshot();
8745
- const sel = Us(inner, {
9387
+ const sel = ta(inner, {
8746
9388
  rows: s0.rows,
8747
9389
  chosen: s0.chosen,
8748
9390
  go: o.go ?? true,
@@ -8760,7 +9402,7 @@ function mountModelSelect(host, pick, o = {}) {
8760
9402
  }
8761
9403
  /** The words of a gate's one pink button for a pick: "load, 1.7 gb", then "ready". */
8762
9404
  function gateWords(row) {
8763
- return row && Ce(row) ? Se(row) : row?.state === "loaded" ? "ready" : Se(row);
9405
+ return row && Re(row) ? Ie(row) : row?.state === "loaded" ? "ready" : Ie(row);
8764
9406
  }
8765
9407
  /** Several jobs: one line per job, presets with totals, and one pink "load all, <total>". */
8766
9408
  function mountModelJobs(host, jobs, o = {}) {
@@ -8770,7 +9412,7 @@ function mountModelJobs(host, jobs, o = {}) {
8770
9412
  const presets = jobs.presets();
8771
9413
  const all = jobs.all();
8772
9414
  host.innerHTML = `<div class="hb-msel-jobs">` + (presets.length ? `<div class="hb-msel-presets" role="group" aria-label="presets">${presets.map((p) => `<button type="button" class="hb-chip" data-preset="${esc(p.id)}">${esc(p.label)}, ${esc(p.total)}</button>`).join("")}</div>` : "") + jobs.lines().map((j) => {
8773
- const w = $r(j.row, "no model");
9415
+ const w = qr(j.row, "no model");
8774
9416
  return `<div class="hb-msel-job"><span class="hb-msel-joblabel">${esc(j.label)}${j.required ? "<b> required</b>" : ""}</span><button type="button" class="hb-msel-line" data-job="${j.job}" aria-haspopup="dialog" aria-label="${esc(j.label)}: ${esc(w.name)}"><span class="hb-msel-name">${esc(w.name)}</span>${w.meta ? `<span class="hb-msel-meta">${esc(w.meta)}</span>` : ""}${w.state ? `<span class="hb-msel-state${j.row?.state === "loaded" ? " is-loaded" : ""}">${esc(w.state)}</span>` : ""}</button></div>`;
8775
9417
  }).join("") + ((o.go ?? true) && all.ids.length ? `<div class="hb-msel"><button type="button" class="hb-btn hb-btn-go" data-all>${esc(all.label)}</button></div>` : "") + `</div>`;
8776
9418
  };
@@ -8799,13 +9441,13 @@ function mountModelJobs(host, jobs, o = {}) {
8799
9441
  /** The HTML of one channel's transcript, or an empty note when there is none. */
8800
9442
  function transcriptHtml(c, o = {}) {
8801
9443
  if (!c) return `<p class="hb-lay-empty-note">nothing yet. drop a file.</p>`;
8802
- const st = di(c.status);
9444
+ const st = ki(c.status);
8803
9445
  const head = `<div class="hb-panel-hd-inst" role="status">${esc(c.name)}, ${esc(st.word)}${c.status === "working" ? `, ${c.pct}%` : ""}</div>${c.error ? `<p class="hb-lay-empty-note">${esc(c.error)}</p>` : ""}`;
8804
9446
  if (!c.segments.length) return `<section class="hb-panel">${head}</section>`;
8805
- return `<section class="hb-panel">${head}<ol class="hb-transcript is-edit" aria-label="transcript">${c.dropped.length ? `<li class="hb-tseg-note">${esc(si(c.dropped))}</li>` : ""}${c.segments.map((s, i) => {
8806
- const t = te(s.start);
9447
+ return `<section class="hb-panel">${head}<ol class="hb-transcript is-edit" aria-label="transcript">${c.dropped.length ? `<li class="hb-tseg-note">${esc(yi(c.dropped))}</li>` : ""}${c.segments.map((s, i) => {
9448
+ const t = ie(s.start);
8807
9449
  return `<li><div class="hb-tseg"><span class="hb-tseg-body">${o.onSeek ? `<button type="button" class="hb-tseg-t" data-seek="${s.start}" aria-label="play from ${t}">${t}</button>` : `<span class="hb-tseg-t">${t}</span>`}${o.speakers ? `<input class="hb-tseg-who" data-who="${i}" placeholder="speaker" aria-label="speaker at ${t}" value="${esc(s.speaker ?? "")}">` : s.speaker ? `<b>${esc(s.speaker)}: </b>` : ""}<span class="hb-tseg-text" contenteditable="true" role="textbox" aria-label="text at ${t}" data-line="${i}">${esc(s.text)}</span>${s.edited ? `<span class="hb-tseg-why">edited</span>` : ""}</span></div></li>`;
8808
- }).join("")}${o.showDropped ? c.dropped.map((d) => `<li><div class="hb-tseg is-dropped"><span class="hb-tseg-body"><span class="hb-tseg-t">${te(d.start)}</span><span class="hb-tseg-text">${esc(d.text)}</span><span class="hb-tseg-why">[${esc(d.why)}]</span></span></div></li>`).join("") : ""}</ol></section>`;
9450
+ }).join("")}${o.showDropped ? c.dropped.map((d) => `<li><div class="hb-tseg is-dropped"><span class="hb-tseg-body"><span class="hb-tseg-t">${ie(d.start)}</span><span class="hb-tseg-text">${esc(d.text)}</span><span class="hb-tseg-why">[${esc(d.why)}]</span></span></div></li>`).join("") : ""}</ol></section>`;
8809
9451
  }
8810
9452
  const pickedOf = (s) => s.channels.find((c) => c.id === s.selected);
8811
9453
  /** The selected channel's transcript over a host. */
@@ -8843,6 +9485,29 @@ function mountTranscriptView(host, queue, o = {}) {
8843
9485
  l.add(queue.subscribe(draw));
8844
9486
  return { dispose: () => l.off() };
8845
9487
  }
9488
+ const AV = /\.(mp4|m4v|mov|webm|mkv|avi|mpe?g|ogv|m4a|mp3|wav|flac|ogg|opus|aac|wma|3gp)$/i;
9489
+ /** A file a speech run can read: audio or video by type or by name. */
9490
+ const isMedia = (f) => /^(audio|video)\//.test(f.type) || AV.test(f.name);
9491
+ async function walk$1(e, out, depth = 0) {
9492
+ if (e.isFile && e.file) out.push(await new Promise((ok, bad) => e.file(ok, bad)));
9493
+ else if (e.isDirectory && e.createReader && depth < 8) {
9494
+ const r = e.createReader();
9495
+ for (;;) {
9496
+ const batch = await new Promise((ok, bad) => r.readEntries(ok, bad));
9497
+ if (!batch.length) break;
9498
+ for (const c of batch) await walk$1(c, out, depth + 1);
9499
+ }
9500
+ }
9501
+ }
9502
+ /** The files of a drop, with dropped folders read through, media only. */
9503
+ async function droppedFiles(dt) {
9504
+ if (!dt) return [];
9505
+ const entries = [...dt.items ?? []].map((i) => i.webkitGetAsEntry?.()).filter((x) => x !== null && x !== void 0);
9506
+ if (!entries.length) return [...dt.files].filter(isMedia);
9507
+ const out = [];
9508
+ for (const e of entries) await walk$1(e, out).catch(() => void 0);
9509
+ return out.filter(isMedia);
9510
+ }
8846
9511
  /** The drop zone that becomes the transcript. */
8847
9512
  function mountTranscribeDrop(host, queue, o = {}) {
8848
9513
  const l = listeners();
@@ -8851,15 +9516,19 @@ function mountTranscribeDrop(host, queue, o = {}) {
8851
9516
  input.hidden = true;
8852
9517
  input.multiple = true;
8853
9518
  input.accept = o.accept ?? "audio/*,video/*";
9519
+ const dir = document.createElement("input");
9520
+ dir.type = "file";
9521
+ dir.hidden = true;
9522
+ dir.setAttribute("webkitdirectory", "");
8854
9523
  const zone = document.createElement("div");
8855
9524
  const result = document.createElement("div");
8856
- host.replaceChildren(zone, result, input);
9525
+ host.replaceChildren(zone, result, input, dir);
8857
9526
  zone.className = "hb-lay-drop";
8858
9527
  result.className = "hb-lay-scroll";
8859
- zone.innerHTML = `<div class="hb-lay-empty"><span class="hb-lay-empty-name">${esc(o.title ?? "drop audio or video")}</span><p class="hb-lay-empty-note">${esc(o.note ?? "any length. the words are worked out on this machine and the file never leaves it.")}</p><div class="hb-lay-empty-acts"><button type="button" class="hb-btn hb-btn-go" data-pick>${esc(o.pickLabel ?? "choose a file")}</button>${o.sampleLabel ? `<button type="button" class="hb-btn" data-sample>${esc(o.sampleLabel)}</button>` : ""}</div></div>`;
9528
+ zone.innerHTML = `<div class="hb-lay-empty"><span class="hb-lay-empty-name">${esc(o.title ?? "drop audio or video")}</span><p class="hb-lay-empty-note">${esc(o.note ?? "any length. the words are worked out on this machine and the file never leaves it.")}</p><div class="hb-lay-empty-acts"><button type="button" class="hb-btn hb-btn-go" data-pick>${esc(o.pickLabel ?? "choose a file")}</button>${o.folders ? `<button type="button" class="hb-btn" data-folder>a folder</button>` : ""}${o.sampleLabel ? `<button type="button" class="hb-btn" data-sample>${esc(o.sampleLabel)}</button>` : ""}</div></div>`;
8860
9529
  const view = mountTranscriptView(result, queue, o);
8861
9530
  const take = (list) => {
8862
- const files = list ? [...list] : [];
9531
+ const files = list ? [...list].filter(isMedia) : [];
8863
9532
  if (files.length) queue.add(files);
8864
9533
  };
8865
9534
  l.on(host, "dragover", (e) => {
@@ -8870,7 +9539,11 @@ function mountTranscribeDrop(host, queue, o = {}) {
8870
9539
  l.on(host, "drop", (e) => {
8871
9540
  e.preventDefault();
8872
9541
  zone.classList.remove("is-hot");
8873
- take(e.dataTransfer?.files);
9542
+ droppedFiles(e.dataTransfer).then((fs) => fs.length && queue.add(fs));
9543
+ });
9544
+ l.on(dir, "change", () => {
9545
+ take(dir.files);
9546
+ dir.value = "";
8874
9547
  });
8875
9548
  l.on(input, "change", () => {
8876
9549
  take(input.files);
@@ -8879,6 +9552,7 @@ function mountTranscribeDrop(host, queue, o = {}) {
8879
9552
  l.on(zone, "click", (e) => {
8880
9553
  const t = e.target;
8881
9554
  if (t.closest("[data-pick]")) input.click();
9555
+ else if (t.closest("[data-folder]")) dir.click();
8882
9556
  else if (t.closest("[data-sample]")) o.onSample?.();
8883
9557
  });
8884
9558
  l.add(queue.subscribe((s) => {
@@ -8888,6 +9562,7 @@ function mountTranscribeDrop(host, queue, o = {}) {
8888
9562
  }));
8889
9563
  return {
8890
9564
  pick: () => input.click(),
9565
+ pickFolder: () => dir.click(),
8891
9566
  dispose() {
8892
9567
  l.off();
8893
9568
  view.dispose();
@@ -8899,7 +9574,7 @@ function mountTranscribeQueue(host, queue) {
8899
9574
  const l = listeners();
8900
9575
  const draw = (s) => {
8901
9576
  const strips = s.channels.map((c, i) => {
8902
- const st = di(c.status);
9577
+ const st = ki(c.status);
8903
9578
  return `<li class="hb-qstrip is-${st.tone || "idle"}${c.id === s.selected ? " is-sel" : ""}${c.status === "done" ? " is-done" : ""}"><button type="button" class="hb-qstrip-main" data-sel="${c.id}" aria-pressed="${c.id === s.selected}"><span class="hb-qstrip-n">${String(i + 1).padStart(2, "0")}</span><span class="hb-qstrip-body"><span class="hb-qstrip-hd"><span class="hb-qstrip-name">${esc(c.name)}</span><span class="hb-qstrip-stat">${esc(st.word)}</span></span>` + (c.meta.length || c.error ? `<span class="hb-qstrip-meta">${c.meta.map((m) => `<span>${m.label ? `${esc(m.label)} ` : ""}<b${m.tone ? ` class="is-${m.tone}"` : ""}>${esc(m.value)}</b></span>`).join("")}${c.error ? `<span class="is-lo">${esc(c.error)}</span>` : ""}</span>` : "") + (c.status === "working" ? `<span class="hb-qstrip-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${c.pct}" aria-label="${esc(c.name)} progress"><i style="--hb-v:${c.pct / 100}"></i></span>` : "") + `</span></button>` + (s.running ? "" : `<button type="button" class="hb-qstrip-x" data-rm="${c.id}" aria-label="remove ${esc(c.name)}" title="remove">${ICON.x}</button>`) + `</li>`;
8904
9579
  }).join("");
8905
9580
  const queued = s.channels.some((c) => c.status === "queued");
@@ -8951,6 +9626,50 @@ function mountTranscriptExports(host, queue, o = {}) {
8951
9626
  l.add(queue.subscribe(draw));
8952
9627
  return { dispose: () => l.off() };
8953
9628
  }
9629
+ /**
9630
+ * ExportMenu: the selected transcript as txt, srt, vtt or json, a copy, and
9631
+ * every finished transcript as one zip with a manifest, plus undo and redo of
9632
+ * edits. Nothing shows until there is text; undo shows once there is a change.
9633
+ * `go` makes the first export the one pink action.
9634
+ */
9635
+ function mountExportMenu(host, queue, o = {}) {
9636
+ const l = listeners();
9637
+ const save = o.save ?? ((name, data, type) => download(name, typeof data === "string" ? data : new Blob([data], { type }), type));
9638
+ const draw = (s) => {
9639
+ const c = pickedOf(s);
9640
+ const done = s.channels.filter((x) => x.segments.length).length;
9641
+ host.innerHTML = c?.segments.length ? `<div class="hb-toolbar" role="group" aria-label="export">${[
9642
+ "txt",
9643
+ "srt",
9644
+ "vtt",
9645
+ "json"
9646
+ ].map((k, i) => `<button type="button" class="hb-btn${o.go && i === 0 ? " hb-btn-go" : ""}" data-ex="${k}">${o.go && i === 0 ? `save ${k}` : k}</button>`).join("")}<button type="button" class="hb-btn" data-copy>${ICON.copy}copy</button>${done ? `<button type="button" class="hb-btn" data-zip>all ${done} as zip</button>` : ""}${s.canUndo ? `<button type="button" class="hb-iconbtn" data-undo aria-label="undo the last edit" title="undo">${ICON.undo}</button>` : ""}${s.canRedo ? `<button type="button" class="hb-iconbtn" data-redo aria-label="redo" title="redo">${ICON.redo}</button>` : ""}</div>` : "";
9647
+ };
9648
+ l.on(host, "click", (e) => {
9649
+ const t = e.target;
9650
+ const ex = t.closest("[data-ex]");
9651
+ if (ex) {
9652
+ const f = queue.exportAs(ex.dataset.ex);
9653
+ if (f) save(f.name, f.text, f.type);
9654
+ return;
9655
+ }
9656
+ if (t.closest("[data-zip]")) {
9657
+ const z = queue.zip(o.tool ? { tool: o.tool } : {});
9658
+ if (z) save(z.name, z.data, "application/zip");
9659
+ return;
9660
+ }
9661
+ const cp = t.closest("[data-copy]");
9662
+ if (cp) {
9663
+ const f = queue.exportAs("txt");
9664
+ if (f) navigator.clipboard?.writeText(f.text).then(() => cp.lastChild.textContent = "copied").catch(() => cp.lastChild.textContent = "copy blocked");
9665
+ return;
9666
+ }
9667
+ if (t.closest("[data-undo]")) queue.undo();
9668
+ else if (t.closest("[data-redo]")) queue.redo();
9669
+ });
9670
+ l.add(queue.subscribe(draw));
9671
+ return { dispose: () => l.off() };
9672
+ }
8954
9673
  // packages/ai-views/src/transcribe.ts
8955
9674
  /**
8956
9675
  * The state behind TranscribeDrop and TranscriptView: drop files, they queue as channels, run one at a
@@ -8994,11 +9713,20 @@ function transcribeQueue(o) {
8994
9713
  } : c);
8995
9714
  emit();
8996
9715
  };
8997
- const metaOf = (c) => fi({
8998
- size: c.size,
8999
- ...c.duration ? { duration: c.duration } : {},
9000
- ...c.status === "done" ? { lines: c.segments.length } : {}
9001
- });
9716
+ const metaOf = (c) => {
9717
+ const s = c.stats;
9718
+ return xi({
9719
+ size: c.size,
9720
+ ...c.duration ? { duration: c.duration } : {},
9721
+ ...s ? {
9722
+ snrDb: s.snrDb,
9723
+ gainDb: s.gainDb,
9724
+ density: s.density,
9725
+ rtf: s.rtf
9726
+ } : {},
9727
+ ...c.status === "done" ? { lines: c.segments.length } : {}
9728
+ });
9729
+ };
9002
9730
  const q = {
9003
9731
  snapshot: snap,
9004
9732
  subscribe(fn) {
@@ -9043,7 +9771,8 @@ function transcribeQueue(o) {
9043
9771
  try {
9044
9772
  const r = await run(file, {
9045
9773
  signal: ac.signal,
9046
- onProgress: (f) => patch(next.id, { pct: Math.round(Math.min(1, Math.max(0, f)) * 100) })
9774
+ onProgress: (f) => patch(next.id, { pct: Math.round(Math.min(1, Math.max(0, f)) * 100) }),
9775
+ ...o.options ? { options: o.options() } : {}
9047
9776
  });
9048
9777
  const c = channels.find((x) => x.id === next.id);
9049
9778
  if (!c) continue;
@@ -9057,6 +9786,8 @@ function transcribeQueue(o) {
9057
9786
  if (r.duration !== void 0) done.duration = r.duration;
9058
9787
  if (r.language) done.language = r.language;
9059
9788
  if (r.model) done.model = r.model;
9789
+ if (r.stats) done.stats = r.stats;
9790
+ if (r.rail) done.rail = r.rail;
9060
9791
  done.meta = metaOf(done);
9061
9792
  patch(next.id, done);
9062
9793
  if (selected === null || channels.find((x) => x.id === selected)?.status !== "done") selected = next.id;
@@ -9159,6 +9890,30 @@ function transcribeQueue(o) {
9159
9890
  type: TYPES[kind]
9160
9891
  };
9161
9892
  },
9893
+ zip(zo = {}) {
9894
+ const done = channels.filter((c) => c.segments.length);
9895
+ if (!done.length) return null;
9896
+ const docs = done.map((c) => ({
9897
+ source: c.name,
9898
+ segments: c.segments,
9899
+ dropped: c.dropped,
9900
+ model: c.model ?? "unknown",
9901
+ language: c.language ?? "unknown",
9902
+ ...c.stats ? { stats: c.stats } : {},
9903
+ ...c.duration !== void 0 ? { duration: c.duration } : {}
9904
+ }));
9905
+ const capture = o.options?.() ?? null;
9906
+ const out = bundle(docs, {
9907
+ ...zo.tool ? { tool: zo.tool } : {},
9908
+ capture,
9909
+ ...zo.date ? { date: zo.date } : {}
9910
+ });
9911
+ return {
9912
+ name: `transcripts-${(zo.date ?? /* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.zip`,
9913
+ data: out.zip,
9914
+ manifest: out.manifest
9915
+ };
9916
+ },
9162
9917
  setTranscriber(t) {
9163
9918
  run = t;
9164
9919
  }
@@ -9197,6 +9952,418 @@ function mountMemoryInspector(host, rec = null) {
9197
9952
  dispose() {}
9198
9953
  };
9199
9954
  }
9955
+ // packages/ai-views/src/mount-talk.ts
9956
+ /** True when an item is kept out of cleanup: decay never drops it. */
9957
+ const isProtected = (it) => it.meta?.protected === true;
9958
+ /** Protect an item from cleanup (it becomes lore, which never decays) or give it back its kind. */
9959
+ async function protect(mem, it, on) {
9960
+ if (on === isProtected(it)) return;
9961
+ const meta = { ...it.meta ?? {} };
9962
+ if (on) await mem.edit(it.id, {
9963
+ kind: "lore",
9964
+ meta: {
9965
+ ...meta,
9966
+ protected: true,
9967
+ was: it.kind
9968
+ }
9969
+ });
9970
+ else {
9971
+ const was = meta.was ?? "fact";
9972
+ delete meta.protected;
9973
+ delete meta.was;
9974
+ await mem.edit(it.id, {
9975
+ kind: was,
9976
+ meta
9977
+ });
9978
+ }
9979
+ }
9980
+ const sourceOf = (it) => typeof it.meta?.source === "string" ? it.meta.source.split("/")[0] : it.kind === "doc" ? it.section ?? "file" : "notes";
9981
+ /** The memory pane: counts, search, a source or kind filter, add a note, the list with protect and forget, export, import, erase. */
9982
+ function mountMemoryPane(host, mem, o = {}) {
9983
+ const l = listeners();
9984
+ let query = "";
9985
+ let source = "";
9986
+ let armed = 0;
9987
+ let wipe = false;
9988
+ let used = /* @__PURE__ */ new Set();
9989
+ let hits = null;
9990
+ let seq = 0;
9991
+ const file = document.createElement("input");
9992
+ file.type = "file";
9993
+ file.accept = ".json,application/json";
9994
+ file.hidden = true;
9995
+ const box = document.createElement("div");
9996
+ host.replaceChildren(box, file);
9997
+ const changed = () => (o.onChange?.(), draw());
9998
+ const groupOf = (it) => o.by === "kind" ? isProtected(it) ? String(it.meta?.was ?? it.kind) : it.kind : sourceOf(it);
9999
+ const groupWord = (g) => o.by === "kind" ? o.kinds?.[g] ?? g : g;
10000
+ const draw = () => {
10001
+ const all = mem.all();
10002
+ const sources = [...new Set(all.map(groupOf))];
10003
+ let shown = all.filter((it) => !source || groupOf(it) === source);
10004
+ if (hits) shown = shown.filter((it) => hits.has(it.id)).sort((a, b) => hits.get(b.id) - hits.get(a.id));
10005
+ else shown = shown.slice().sort((a, b) => b.created - a.created);
10006
+ const focus = document.activeElement === box.querySelector("[data-q]");
10007
+ box.innerHTML = `<section class="hb-mempanel" aria-label="${esc(o.name ?? "memory")}"><div class="hb-mempanel-sec"><p class="hb-mempanel-counts">${esc(oi(all.map((it) => ({
10008
+ id: String(it.id),
10009
+ text: it.text,
10010
+ kind: it.kind
10011
+ }))) || "nothing stored")}</p></div><div class="hb-mempanel-sec"><input class="hb-input" type="search" data-q placeholder="search memory" aria-label="search memory" value="${esc(query)}">` + (sources.length > 1 ? `<div class="hb-chipgroup" role="group" aria-label="${o.by === "kind" ? "kind" : "source"}"><button type="button" class="hb-chip${source ? "" : " is-on"}" data-src="" aria-pressed="${!source}">all</button>${sources.map((s) => `<button type="button" class="hb-chip${s === source ? " is-on" : ""}" data-src="${esc(s)}" aria-pressed="${s === source}">${esc(groupWord(s))}</button>`).join("")}</div>` : "") + `</div><div class="hb-mempanel-sec"><textarea class="hb-textarea" rows="2" data-note placeholder="a fact to keep" aria-label="add a note"></textarea><div class="hb-mempanel-row"><button type="button" class="hb-btn hb-btn-sm" data-add>add</button></div></div><div class="hb-mempanel-sec"><h3 class="hb-mempanel-hd">${query ? "matches" : "notes"} (${shown.length})</h3>` + (shown.length ? `<div class="hb-mempanel-list">${shown.slice(0, 200).map((it) => {
10012
+ const p = isProtected(it);
10013
+ const u = used.has(it.text);
10014
+ return `<div class="hb-mem${u ? " is-used" : ""}${p ? " is-pinned" : ""}"><div class="hb-mem-body">${p ? `<span class="hb-mem-pin">kept</span>` : ""}<span class="hb-mem-kind">${esc(p ? String(it.meta?.was ?? it.kind) : it.kind)}${hits?.has(it.id) ? `<b class="hb-mem-score">${esc(ii(hits.get(it.id)))}</b>` : ""}</span><span class="hb-mem-text">${esc(it.text.length > 280 ? `${it.text.slice(0, 277)}...` : it.text)}</span><span class="hb-mem-when">${esc([u ? "used last reply" : "", sourceOf(it) === "notes" ? "" : sourceOf(it)].filter(Boolean).join(", "))}</span></div><div class="hb-mem-acts"><button type="button" class="hb-mem-act${p ? " is-on" : ""}" data-keep="${it.id}" aria-pressed="${p}" aria-label="${p ? "let cleanup drop it" : "keep from cleanup"}" title="${p ? "kept from cleanup" : "keep"}">keep</button><button type="button" class="hb-mem-act is-forget${armed === it.id ? " is-armed" : ""}" data-forget="${it.id}">${armed === it.id ? "forget?" : "forget"}</button></div></div>`;
10015
+ }).join("")}</div>` : `<p class="hb-mempanel-empty">${query ? "nothing matches. try other words." : "nothing stored yet. add a note, drop a file, or talk and it fills."}</p>`) + `</div><div class="hb-mempanel-foot">${all.length ? (o.acts ?? []).map((a) => `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-act="${esc(a.id)}">${esc(a.label)}</button>`).join("") : ""}<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-export>${esc(o.exportLabel ?? "export")}</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-import>import</button>${all.length ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm hb-mempanel-wipe${wipe ? " is-armed" : ""}" data-wipe>${wipe ? "erase everything?" : "erase all"}</button>` : ""}</div></section>`;
10016
+ if (focus) {
10017
+ const q = box.querySelector("[data-q]");
10018
+ q.focus();
10019
+ q.setSelectionRange(q.value.length, q.value.length);
10020
+ }
10021
+ };
10022
+ const search = async () => {
10023
+ const mine = ++seq;
10024
+ if (!query.trim()) hits = null;
10025
+ else {
10026
+ const r = await mem.recall(query, { k: 50 });
10027
+ if (mine !== seq) return;
10028
+ hits = new Map(r.hits.map((h) => [h.item.id, h.score]));
10029
+ }
10030
+ draw();
10031
+ };
10032
+ l.on(box, "input", (e) => {
10033
+ const t = e.target;
10034
+ if (t.matches("[data-q]")) {
10035
+ query = t.value;
10036
+ search();
10037
+ }
10038
+ });
10039
+ l.on(box, "keydown", (e) => {
10040
+ const ke = e;
10041
+ if (ke.target.matches("[data-note]") && ke.key === "Enter" && !ke.shiftKey) {
10042
+ ke.preventDefault();
10043
+ box.querySelector("[data-add]")?.click();
10044
+ }
10045
+ });
10046
+ l.on(box, "click", (e) => {
10047
+ const t = e.target;
10048
+ const src = t.closest("[data-src]");
10049
+ if (src) return source = src.dataset.src ?? "", draw();
10050
+ const all = () => mem.all();
10051
+ const keep = t.closest("[data-keep]");
10052
+ if (keep) {
10053
+ const it = all().find((x) => x.id === Number(keep.dataset.keep));
10054
+ if (it) protect(mem, it, !isProtected(it)).then(changed);
10055
+ return;
10056
+ }
10057
+ const fg = t.closest("[data-forget]");
10058
+ if (fg) {
10059
+ const id = Number(fg.dataset.forget);
10060
+ if (armed !== id) return armed = id, draw();
10061
+ armed = 0;
10062
+ mem.remove([id]).then(changed);
10063
+ return;
10064
+ }
10065
+ if (t.closest("[data-add]")) {
10066
+ const text = box.querySelector("[data-note]").value.trim();
10067
+ if (text) mem.add(text, { kind: "fact" }).then(changed);
10068
+ return;
10069
+ }
10070
+ const act = t.closest("[data-act]");
10071
+ if (act) return o.onAct?.(act.dataset.act ?? "");
10072
+ if (t.closest("[data-export]")) return download(`memory-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.json`, JSON.stringify(mem.export(), null, 2), "application/json");
10073
+ if (t.closest("[data-import]")) return file.click();
10074
+ if (t.closest("[data-wipe]")) {
10075
+ if (!wipe) return wipe = true, draw();
10076
+ wipe = false;
10077
+ mem.remove(all().map((x) => x.id)).then(changed);
10078
+ }
10079
+ });
10080
+ l.on(file, "change", () => {
10081
+ const f = file.files?.[0];
10082
+ file.value = "";
10083
+ if (!f) return;
10084
+ f.text().then((t) => mem.import(JSON.parse(t), { replace: false })).then(changed).catch((err) => {
10085
+ box.querySelector(".hb-mempanel-foot")?.insertAdjacentHTML("beforeend", `<p class="hb-error" role="alert">that file did not import: ${esc(err instanceof Error ? err.message : String(err))}</p>`);
10086
+ });
10087
+ });
10088
+ draw();
10089
+ return {
10090
+ refresh: () => void search(),
10091
+ used(labels) {
10092
+ used = new Set(labels);
10093
+ draw();
10094
+ },
10095
+ dispose: () => l.off()
10096
+ };
10097
+ }
10098
+ async function walk(e, out, path, depth = 0) {
10099
+ if (e.isFile && e.file) {
10100
+ const f = await new Promise((ok, bad) => e.file(ok, bad));
10101
+ out.push(path ? Object.assign(new File([f], f.name, { type: f.type }), { webkitRelativePath: `${path}/${f.name}` }) : f);
10102
+ } else if (e.isDirectory && e.createReader && depth < 8) {
10103
+ const r = e.createReader();
10104
+ for (;;) {
10105
+ const batch = await new Promise((ok, bad) => r.readEntries(ok, bad));
10106
+ if (!batch.length) break;
10107
+ for (const c of batch) await walk(c, out, path ? `${path}/${e.name}` : e.name, depth + 1);
10108
+ }
10109
+ }
10110
+ }
10111
+ /** 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. */
10112
+ function mountSourcesDrop(host, o) {
10113
+ const l = listeners();
10114
+ const pick = (dir) => {
10115
+ const i = document.createElement("input");
10116
+ i.type = "file";
10117
+ i.hidden = true;
10118
+ i.multiple = true;
10119
+ if (dir) i.setAttribute("webkitdirectory", "");
10120
+ else i.accept = o.accept ?? ".txt,.md,.csv,.json,.html,.htm,.pdf,.docx,.zip,.eml,text/*";
10121
+ return i;
10122
+ };
10123
+ const files = pick(false);
10124
+ const dir = pick(true);
10125
+ const zone = document.createElement("div");
10126
+ const log = document.createElement("ul");
10127
+ zone.className = "hb-dropzone";
10128
+ zone.innerHTML = `<p class="hb-note">drop files or a folder: text, pdf, docx, zip, mail. they are read here and kept in this browser.</p><div class="hb-toolbar"><button type="button" class="hb-btn hb-btn-sm" data-files>add files</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-dir>a folder</button></div>`;
10129
+ log.className = "hb-list";
10130
+ log.setAttribute("aria-live", "polite");
10131
+ host.replaceChildren(zone, log, files, dir);
10132
+ const line = (t, err = false) => log.insertAdjacentHTML("afterbegin", `<li${err ? ` class="hb-error"` : ""}>${esc(t)}</li>`);
10133
+ const run = (list) => {
10134
+ if (!list.length) return;
10135
+ zone.classList.add("is-busy");
10136
+ line(`reading ${list.length} file${list.length === 1 ? "" : "s"}`);
10137
+ o.ingest(list, { onFile: (e) => line(e.note ? `${e.name}: ${e.note}` : `${e.name}: ${e.chunks} part${e.chunks === 1 ? "" : "s"}`, !!e.note && e.note.startsWith("failed")) }).then((r) => line(`done. ${r.files} file${r.files === 1 ? "" : "s"}, ${r.chunks} parts in memory.`)).catch((err) => line(`stopped: ${err instanceof Error ? err.message : String(err)}`, true)).finally(() => zone.classList.remove("is-busy"));
10138
+ };
10139
+ l.on(zone, "click", (e) => {
10140
+ const t = e.target;
10141
+ if (t.closest("[data-files]")) files.click();
10142
+ else if (t.closest("[data-dir]")) dir.click();
10143
+ });
10144
+ for (const i of [files, dir]) l.on(i, "change", () => {
10145
+ run([...i.files ?? []]);
10146
+ i.value = "";
10147
+ });
10148
+ l.on(zone, "dragover", (e) => (e.preventDefault(), zone.classList.add("is-over")));
10149
+ l.on(zone, "dragleave", () => zone.classList.remove("is-over"));
10150
+ l.on(zone, "drop", (e) => {
10151
+ e.preventDefault();
10152
+ zone.classList.remove("is-over");
10153
+ const dt = e.dataTransfer;
10154
+ const entries = [...dt?.items ?? []].map((i) => i.webkitGetAsEntry?.()).filter((x) => x !== null && x !== void 0);
10155
+ if (!entries.length) return run([...dt?.files ?? []]);
10156
+ const out = [];
10157
+ Promise.all(entries.map((en) => walk(en, out, "").catch(() => void 0))).then(() => run(out));
10158
+ });
10159
+ return { dispose: () => l.off() };
10160
+ }
10161
+ /** The persona rack: presets one press away, name, the three parts with their cost, the template, save, and the persona as a file. */
10162
+ function mountPersonaRack(host, rack) {
10163
+ const l = listeners();
10164
+ const file = document.createElement("input");
10165
+ file.type = "file";
10166
+ file.accept = ".json,application/json";
10167
+ file.hidden = true;
10168
+ const box = document.createElement("div");
10169
+ host.replaceChildren(box, file);
10170
+ let err = "";
10171
+ const field = (key, label, hint, rows, v) => `<div class="hb-field"><span class="hb-field-head"><label class="hb-label" for="pr-${key}">${label}</label></span><textarea id="pr-${key}" class="hb-textarea" rows="${rows}" data-k="${key}" placeholder="${esc(hint)}">${esc(v)}</textarea><span class="hb-field-foot"><span class="hb-hint">${esc(Ds(Ts(v)))}</span></span></div>`;
10172
+ const draw = () => {
10173
+ if (box.contains(document.activeElement) && document.activeElement.matches("[data-k]")) return;
10174
+ const { persona: p, presets, on, builtIn } = rack.snapshot();
10175
+ box.innerHTML = `<div class="hb-persona"><div class="hb-persona-presets"><div class="hb-persona-chips" role="group" aria-label="personas">${presets.map((x, i) => `<span class="hb-persona-chip${i === on ? " is-on" : ""}"><button type="button" class="hb-persona-chip-n" data-load="${i}" aria-pressed="${i === on}">${esc(x.label)}</button>${i < builtIn ? "" : `<button type="button" class="hb-persona-chip-x" data-rm="${i}" aria-label="remove ${esc(x.label)}">&times;</button>`}</span>`).join("")}</div></div><div class="hb-field"><span class="hb-field-head"><label class="hb-label" for="pr-name">name</label></span><input id="pr-name" class="hb-input" data-k="name" value="${esc(p.name)}" autocomplete="off"></div>` + field("profile", "profile", "who you are talking to and how to answer. always sent.", 5, p.profile) + `<div class="hb-persona-row"><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-tpl>insert template</button></div>` + field("notes", "extra notes", "sent after memory; dropped before the profile when room runs out.", 3, p.notes) + field("rules", "extra rules", "dropped first when room runs out.", 3, p.rules) + `<form class="hb-persona-save" data-save><input class="hb-input" data-label placeholder="${esc(p.name || "preset name")}" aria-label="preset name" autocomplete="off"><button type="submit" class="hb-btn hb-btn-2 hb-btn-sm">save</button></form><div class="hb-persona-row"><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-import>import</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-export>export</button></div>${err ? `<p class="hb-error" role="alert">${esc(err)}</p>` : ""}</div>`;
10176
+ };
10177
+ l.on(box, "input", (e) => {
10178
+ const t = e.target;
10179
+ const k = t.dataset.k;
10180
+ if (k) {
10181
+ rack.set({ [k]: t.value });
10182
+ const foot = t.parentElement?.querySelector(".hb-hint");
10183
+ if (foot) foot.textContent = Ds(Ts(t.value));
10184
+ }
10185
+ });
10186
+ l.on(box, "focusout", () => setTimeout(draw, 0));
10187
+ l.on(box, "submit", (e) => {
10188
+ e.preventDefault();
10189
+ rack.save(box.querySelector("[data-label]")?.value ?? "");
10190
+ });
10191
+ l.on(box, "click", (e) => {
10192
+ const t = e.target;
10193
+ const ld = t.closest("[data-load]");
10194
+ if (ld) return rack.load(Number(ld.dataset.load));
10195
+ const rm = t.closest("[data-rm]");
10196
+ if (rm) return rack.removePreset(Number(rm.dataset.rm));
10197
+ if (t.closest("[data-tpl]")) {
10198
+ const p = rack.snapshot().persona;
10199
+ rack.set({ profile: qs(p.profile, br, p.name) });
10200
+ return draw();
10201
+ }
10202
+ if (t.closest("[data-export]")) {
10203
+ const p = rack.snapshot().persona;
10204
+ return download(`${(p.name || "persona").replace(/[^a-z0-9]+/gi, "-").toLowerCase()}.persona.json`, JSON.stringify({
10205
+ v: 1,
10206
+ name: p.name,
10207
+ prompt: p.profile,
10208
+ notes: p.notes,
10209
+ rules: p.rules,
10210
+ ...p.first ? { first: p.first } : {}
10211
+ }, null, 2), "application/json");
10212
+ }
10213
+ if (t.closest("[data-import]")) file.click();
10214
+ });
10215
+ l.on(file, "change", () => {
10216
+ const f = file.files?.[0];
10217
+ file.value = "";
10218
+ if (!f) return;
10219
+ f.text().then((t) => {
10220
+ try {
10221
+ const j = JSON.parse(t);
10222
+ const profile = typeof j.prompt === "string" ? j.prompt : typeof j.system_prompt === "string" ? j.system_prompt : typeof j.description === "string" ? j.description : "";
10223
+ if (!profile && typeof j.name !== "string") throw new Error("no name or prompt in it");
10224
+ err = "";
10225
+ rack.set({
10226
+ name: String(j.name ?? "assistant"),
10227
+ profile,
10228
+ notes: String(j.notes ?? ""),
10229
+ rules: String(j.rules ?? ""),
10230
+ ...typeof j.first === "string" ? { first: j.first } : {}
10231
+ });
10232
+ } catch (e2) {
10233
+ err = `that file is not a persona: ${e2 instanceof Error ? e2.message : String(e2)}`;
10234
+ }
10235
+ draw();
10236
+ });
10237
+ });
10238
+ l.add(rack.subscribe(draw));
10239
+ return { dispose: () => l.off() };
10240
+ }
10241
+ /** The voice row: auto speak, voice, rate, pitch, test and stop. */
10242
+ function mountVoiceRow(host, row, o = {}) {
10243
+ const l = listeners();
10244
+ const draw = () => {
10245
+ if (host.contains(document.activeElement) && document.activeElement.matches("input[type=range]")) return;
10246
+ const s = row.snapshot();
10247
+ host.innerHTML = `<div class="hb-panel"><label class="hb-check"><input type="checkbox" data-auto${s.auto ? " checked" : ""}> speak each reply</label><div class="hb-field"><span class="hb-field-head"><label class="hb-label" for="vr-voice">voice</label></span><select id="vr-voice" class="hb-select" data-voice><option value="">system default</option>${s.voices.map((v) => `<option${v === s.voice ? " selected" : ""}>${esc(v)}</option>`).join("")}</select></div><div class="hb-slider"><span class="hb-label">rate</span><span class="hb-readout">${s.rate.toFixed(1)}</span><input type="range" min="0.5" max="2" step="0.1" value="${s.rate}" data-rate aria-label="rate"></div><div class="hb-slider"><span class="hb-label">pitch</span><span class="hb-readout">${s.pitch.toFixed(1)}</span><input type="range" min="0" max="2" step="0.1" value="${s.pitch}" data-pitch aria-label="pitch"></div><div class="hb-toolbar">${s.speaking ? `<button type="button" class="hb-btn hb-btn-sm" data-stop>stop</button>` : `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-test>test</button>`}</div>${s.error ? `<p class="hb-error" role="alert">${esc(s.error)}</p>` : ""}</div>`;
10248
+ };
10249
+ l.on(host, "input", (e) => {
10250
+ const t = e.target;
10251
+ if (t.matches("[data-rate]")) row.set({ rate: Number(t.value) });
10252
+ else if (t.matches("[data-pitch]")) row.set({ pitch: Number(t.value) });
10253
+ const r = t.parentElement?.querySelector(".hb-readout");
10254
+ if (r && t.type === "range") r.textContent = Number(t.value).toFixed(1);
10255
+ });
10256
+ l.on(host, "change", (e) => {
10257
+ const t = e.target;
10258
+ if (t.matches("[data-auto]")) row.set({ auto: t.checked });
10259
+ else if (t.matches("[data-voice]")) row.set({ voice: t.value });
10260
+ else if (t.type === "range") draw();
10261
+ });
10262
+ l.on(host, "click", (e) => {
10263
+ const t = e.target;
10264
+ if (t.closest("[data-test]")) row.speak(o.test ?? "this is how replies will sound.");
10265
+ else if (t.closest("[data-stop]")) row.stop();
10266
+ });
10267
+ l.add(row.subscribe(draw));
10268
+ return { dispose: () => (row.stop(), l.off()) };
10269
+ }
10270
+ /** The voice clone row of a speaker: clone from an audio file, record `seconds` of mic, download the clone as wav, clear it. */
10271
+ function mountVoiceClone(host, sp, o = {}) {
10272
+ const l = listeners();
10273
+ const secs = o.seconds ?? 10;
10274
+ const file = document.createElement("input");
10275
+ file.type = "file";
10276
+ file.accept = "audio/*";
10277
+ file.hidden = true;
10278
+ const box = document.createElement("div");
10279
+ host.replaceChildren(box, file);
10280
+ let note = "";
10281
+ let busy = false;
10282
+ const draw = () => {
10283
+ const can = o.can?.() ?? true;
10284
+ box.innerHTML = `<div>` + (can ? `<div class="hb-toolbar" role="group" aria-label="voice clone"><button type="button" class="hb-btn hb-btn-sm" data-file${busy ? " disabled" : ""}>clone from audio file</button><button type="button" class="hb-btn hb-btn-sm" data-rec${busy ? " disabled" : ""}>record ${secs} s</button>${sp.cloned ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-wav>download clone, wav</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-clear>clear clone</button>` : ""}</div>` : "") + `<p class="hb-note" role="status">${esc(note || (can ? o.hint ?? `clones a voice from ${secs} s of audio. nothing leaves this tab.` : "this voice cannot clone. load pocket in the voice list."))}</p></div>`;
10285
+ };
10286
+ const fail = (err) => {
10287
+ const name = err.name ?? "";
10288
+ note = name === "NotAllowedError" || name === "SecurityError" ? "the mic is blocked. allow it in the address bar, or clone from a file." : err instanceof Error ? err.message : String(err);
10289
+ };
10290
+ l.on(box, "click", (e) => {
10291
+ const t = e.target;
10292
+ if (t.closest("[data-file]")) return file.click();
10293
+ if (t.closest("[data-wav]")) {
10294
+ const w = sp.cloneWav();
10295
+ if (w) download("voice-clone.wav", w, "audio/wav");
10296
+ return;
10297
+ }
10298
+ if (t.closest("[data-clear]")) {
10299
+ sp.clearClone();
10300
+ note = "clone cleared. the voice is its own again.";
10301
+ return draw();
10302
+ }
10303
+ if (t.closest("[data-rec]") && !busy) {
10304
+ busy = true;
10305
+ sp.cloneMic(secs, (left) => (note = `recording, ${left} s left`, draw())).then((s) => note = `cloned from ${s.toFixed(1)} s of your mic.`, fail).finally(() => (busy = false, draw()));
10306
+ }
10307
+ });
10308
+ l.on(file, "change", () => {
10309
+ const f = file.files?.[0];
10310
+ file.value = "";
10311
+ if (!f) return;
10312
+ busy = true;
10313
+ note = "cloning...";
10314
+ draw();
10315
+ sp.cloneFile(f).then((s) => note = `cloned from ${s.toFixed(1)} s of ${f.name}.`, fail).finally(() => (busy = false, draw()));
10316
+ });
10317
+ l.add(sp.subscribe(draw));
10318
+ draw();
10319
+ return { dispose: () => l.off() };
10320
+ }
10321
+ /** The session menu of a chat list: clear the open chat, export it as markdown, every chat as json, and import. */
10322
+ function mountSessionMenu(host, list, o = {}) {
10323
+ const l = listeners();
10324
+ const file = document.createElement("input");
10325
+ file.type = "file";
10326
+ file.accept = ".json,application/json";
10327
+ file.hidden = true;
10328
+ const box = document.createElement("div");
10329
+ host.replaceChildren(box, file);
10330
+ let armed = false;
10331
+ let note = "";
10332
+ const draw = () => {
10333
+ const has = list.thread.snapshot().turns.length > 0;
10334
+ box.innerHTML = `<div class="hb-toolbar" role="group" aria-label="session">${has ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-md>save as markdown</button>` : ""}<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-json>export chats</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-import>import chats</button>${has ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm${armed ? " is-armed" : ""}" data-clear>${armed ? "clear this chat?" : "clear"}</button>` : ""}</div>${note ? `<p class="hb-note" role="status">${esc(note)}</p>` : ""}`;
10335
+ };
10336
+ l.on(box, "click", (e) => {
10337
+ const t = e.target;
10338
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
10339
+ if (t.closest("[data-md]")) return download(`chat-${day}.md`, list.thread.markdown(), "text/markdown");
10340
+ if (t.closest("[data-json]")) return download(`chats-${day}.json`, JSON.stringify(list.dump(), null, 2), "application/json");
10341
+ if (t.closest("[data-import]")) return file.click();
10342
+ if (t.closest("[data-clear]")) {
10343
+ if (!armed) return armed = true, draw();
10344
+ armed = false;
10345
+ list.thread.clear();
10346
+ }
10347
+ });
10348
+ l.on(file, "change", () => {
10349
+ const f = file.files?.[0];
10350
+ file.value = "";
10351
+ if (!f) return;
10352
+ f.text().then((t) => {
10353
+ try {
10354
+ const data = JSON.parse(t);
10355
+ list.restore(data);
10356
+ note = `${data.chats.length} chat${data.chats.length === 1 ? "" : "s"} imported.`;
10357
+ o.onImport?.(data.chats.length);
10358
+ } catch (err) {
10359
+ note = `that file did not import: ${err instanceof Error ? err.message : String(err)}`;
10360
+ }
10361
+ draw();
10362
+ });
10363
+ });
10364
+ l.add(list.subscribe(() => draw()));
10365
+ return { dispose: () => l.off() };
10366
+ }
9200
10367
  // packages/ai-views/src/elements.ts
9201
10368
  /** The tag names define() registers, before any prefix. */
9202
10369
  const ELEMENT_NAMES = [
@@ -9570,4 +10737,4 @@ function define(prefix = "", registry, Base) {
9570
10737
  return tag;
9571
10738
  });
9572
10739
  }
9573
- export { ELEMENT_NAMES, define, gateWords, mountCameraFeed, mountChatList, mountChatPane, mountComposer, mountContextMeter, mountFrameView, mountMaskRack, mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMemoryInspector, mountModelJobs, mountModelSelect, mountTranscribeDrop, mountTranscribeQueue, mountTranscriptExports, mountTranscriptView, pickSheet, transcriptHtml, turnHtml };
10740
+ export { ELEMENT_NAMES, chipWords, define, droppedFiles, gateWords, isMedia, isProtected, mountCameraFeed, mountChatList, mountChatPane, mountComposer, mountContextMeter, mountExportMenu, mountFrameView, mountMaskRack, mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMemoryInspector, mountMemoryPane, mountModelJobs, mountModelSelect, mountPersonaRack, mountSessionMenu, mountSourcesDrop, mountTranscribeDrop, mountTranscribeQueue, mountTranscriptExports, mountTranscriptView, mountVoiceClone, mountVoiceRow, pickSheet, protect, shortName, transcriptHtml, turnHtml };