@gemboss/ui 0.68.0 → 0.69.0

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +89 -9
  3. package/catalog/editor.html +10 -8
  4. package/catalog/index.html +617 -566
  5. package/gemboss-ui.css +3 -3
  6. package/package.json +5 -2
  7. package/parts/components.css +1 -1
  8. package/parts/core.css +1 -1
  9. package/parts/shell.css +1 -1
  10. package/src/assistant/attachments.tsx +486 -0
  11. package/src/assistant/chat-cards.tsx +343 -0
  12. package/src/assistant/chat.tsx +29 -6
  13. package/src/assistant/host.tsx +8 -11
  14. package/src/assistant/index.ts +8 -1
  15. package/src/assistant-chat.css +1 -1
  16. package/src/assistant-plain.js +1 -1
  17. package/src/assistant.css +1 -1
  18. package/src/auth-field.css +1 -1
  19. package/src/auth.tsx +4 -2
  20. package/src/chat-attachments.css +1 -0
  21. package/src/chat-cards.css +1 -0
  22. package/src/chat-plain.js +5 -5
  23. package/src/collections.tsx +8 -1
  24. package/src/editor/controls.tsx +51 -10
  25. package/src/editor/field-frame.tsx +4 -10
  26. package/src/editor/index.ts +2 -4
  27. package/src/editor/inspector-frame.tsx +143 -32
  28. package/src/editor/items-field.tsx +8 -3
  29. package/src/editor/items.ts +30 -6
  30. package/src/editor/panel.tsx +4 -5
  31. package/src/editor-inspector-frame.css +1 -1
  32. package/src/editor-media.css +1 -0
  33. package/src/editor-plain.js +1 -1
  34. package/src/editor-rail.css +1 -1
  35. package/src/editor.css +1 -1
  36. package/src/email-editor/editor.tsx +96 -69
  37. package/src/email-editor.css +1 -1
  38. package/src/gem-at-work.css +1 -1
  39. package/src/gem-at-work.ts +177 -33
  40. package/src/gem-holo.css +1 -1
  41. package/src/icons.tsx +42 -0
  42. package/src/index-table-extras.css +1 -0
  43. package/src/index-table.tsx +37 -16
  44. package/src/menu.tsx +7 -3
  45. package/src/narration.css +1 -1
  46. package/src/selection.tsx +22 -12
  47. package/src/editor/chips.tsx +0 -24
  48. package/src/editor-chips.css +0 -1
@@ -0,0 +1,486 @@
1
+ "use client";
2
+
3
+ /**
4
+ * FILES IN THE CHAT (11/11/2026, canvas board ChatKit states 2–11; Chris: "vẽ hết các trường hợp ảnh drag vào thì upload lên thì nó
5
+ * hiện ra ntn", then "code kỹ cái khung chat … các state đó bạn hãy làm").
6
+ *
7
+ * Until now each chat drew its own: the admin's GemChat a 52px thumbnail with a ✕ in text, "Uploading…" beside it and an error in
8
+ * red under it, one image at a time, and a dashed overlay that said "Drop an image to upload"; the other surfaces nothing. The
9
+ * pieces, for every surface:
10
+ *
11
+ * useChatAttachments what is attached: checked against the limits BEFORE it is sent (type, size, how many), uploaded with its
12
+ * progress, kept with its preview, removed, cleared on send. The surface hands in its upload and its limits.
13
+ * useChatDrop the whole panel is the target while files are dragged over it (depth counted: dragenter/dragleave fire on
14
+ * every child), and how many are coming.
15
+ * ChatDropZone what the panel says while they are: drop here, what it takes, how many.
16
+ * ChatAttachments the tray, in ChatComposer's `top` slot: thumbnails with a ring while they upload, × to remove, a click to
17
+ * see one large, a card for what is not a picture, "8 of 10", and one line for what went wrong and why.
18
+ * ChatImages the pictures of a sent message: one large, two side by side, three or more in a grid of three, "+N" last.
19
+ * ChatLightbox one picture over the page (a native modal dialog: Escape, the backdrop and × close it; focus comes back).
20
+ *
21
+ * A surface promises only what its turn can read: the limits come from the surface (the admin's are its upload route's), and a
22
+ * file outside them is refused in the tray with what to do, never kept as a card that goes nowhere.
23
+ */
24
+ import "../chat-attachments.css";
25
+ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState, type DragEvent, type ReactNode } from "react";
26
+ import { Icon } from "../icons";
27
+
28
+ const cx = (...p: Array<string | false | null | undefined>) => p.filter(Boolean).join(" ");
29
+ const useBeforePaint = typeof window === "undefined" ? useEffect : useLayoutEffect;
30
+
31
+ // ── What a turn can take ───────────────────────────────────────────────────────────────────────────────────────────────
32
+
33
+ export interface ChatAttachLimits {
34
+ /** Files one message carries. */
35
+ maxFiles: number;
36
+ /** Bytes one file may have. */
37
+ maxBytes: number;
38
+ /** The MIME types the turn reads ("image/png"…). */
39
+ types: readonly string[];
40
+ }
41
+
42
+ const NAMED: Record<string, string> = {
43
+ "image/png": "PNG", "image/jpeg": "JPG", "image/webp": "WebP", "image/gif": "GIF", "image/heic": "HEIC", "image/heif": "HEIF",
44
+ "image/svg+xml": "SVG", "application/pdf": "PDF", "text/csv": "CSV",
45
+ };
46
+
47
+ /** What a file is, in the word its owner knows it by: "PDF", "CSV", "HEIC", "MOV". */
48
+ export function fileTypeName(file: { name: string; type: string }): string {
49
+ if (Object.hasOwn(NAMED, file.type)) return NAMED[file.type];
50
+ const ext = /\.([a-z0-9]{1,5})$/i.exec(file.name)?.[1];
51
+ if (ext) return ext.toUpperCase();
52
+ const sub = file.type.split("/")[1];
53
+ return sub ? sub.toUpperCase() : "File";
54
+ }
55
+
56
+ const megabytes = (bytes: number) => { const v = bytes / 1024 / 1024; return v >= 10 ? Math.round(v) : Math.round(v * 10) / 10; };
57
+ const onlyImages = (types: readonly string[]) => types.length > 0 && types.every((t) => t.startsWith("image/"));
58
+
59
+ /** "PNG, JPG, WebP or GIF". */
60
+ export function typesInWords(types: readonly string[]): string {
61
+ const names = [...new Set(types.map((t) => (Object.hasOwn(NAMED, t) ? NAMED[t] : t.split("/")[1]?.toUpperCase() ?? t)))];
62
+ return names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
63
+ }
64
+
65
+ /** The limits as the drop zone says them: "PNG, JPG, WebP or GIF · 1 image, up to 12 MB" / "… · up to 10 files, 20 MB each". */
66
+ export function limitsInWords(l: ChatAttachLimits): string {
67
+ const noun = onlyImages(l.types) ? "image" : "file";
68
+ return l.maxFiles <= 1
69
+ ? `${typesInWords(l.types)} · 1 ${noun}, up to ${megabytes(l.maxBytes)} MB`
70
+ : `${typesInWords(l.types)} · up to ${l.maxFiles} ${noun}s, ${megabytes(l.maxBytes)} MB each`;
71
+ }
72
+
73
+ /** Why the turn cannot take this file, one sentence that says what to do; null when it can. */
74
+ export function attachmentProblem(file: { name: string; type: string; size: number }, l: ChatAttachLimits): string | null {
75
+ if (!l.types.includes(file.type)) {
76
+ const what = file.type.startsWith("video/") ? "video" : fileTypeName(file);
77
+ return `${file.name}: ${what} is not supported yet. Use ${typesInWords(l.types)}.`;
78
+ }
79
+ if (file.size === 0) return `${file.name} is empty.`;
80
+ if (file.size > l.maxBytes) return `${file.name} is ${megabytes(file.size)} MB (max ${megabytes(l.maxBytes)} MB).`;
81
+ return null;
82
+ }
83
+
84
+ // ── What is attached ───────────────────────────────────────────────────────────────────────────────────────────────────
85
+
86
+ export interface ChatAttachment {
87
+ id: string;
88
+ name: string;
89
+ /** An image draws a thumbnail; anything else a card with its type. */
90
+ kind: "image" | "file";
91
+ /** The picture shown: the local preview (kept after the upload, so the thumbnail does not blink), or the stored address. */
92
+ src?: string;
93
+ /** The stored address, once it is up: what the message carries. */
94
+ url?: string;
95
+ state: "uploading" | "ready" | "error";
96
+ /** 0..1 while it uploads; absent when the upload cannot tell (the ring turns instead). */
97
+ progress?: number;
98
+ /** Why it will not be sent (state "error"): `attachmentProblem`'s sentence or the upload's answer. */
99
+ error?: string;
100
+ /** A word beside the thumbnail: "Screenshot" for a pasted picture. */
101
+ label?: string;
102
+ /** The type on a file card ("PDF"); `fileTypeName` of the name when absent. */
103
+ type?: string;
104
+ }
105
+
106
+ /** The surface's upload: the stored address, or why not. `onProgress` (0..1) when the transport can tell; `signal` aborts when the
107
+ * file leaves the tray before it is up (removed, or replaced by the next one), so its bytes stop going. */
108
+ export type ChatUpload = (file: File, onProgress: (fraction: number) => void, signal: AbortSignal) => Promise<{ url: string } | { error: string }>;
109
+
110
+ export interface ChatAttachmentsState {
111
+ items: ChatAttachment[];
112
+ /** Up and checked: what the next message carries. */
113
+ ready: ChatAttachment[];
114
+ /** One is still uploading: the message waits (a send now would leave it behind). */
115
+ uploading: boolean;
116
+ /** What was left out, said once ("1 image per message: 2 left out."), until the next change. */
117
+ note: string | null;
118
+ /** Check, then upload. `label` marks them ("Screenshot"). With one file per message a new one takes the old one's place. */
119
+ add: (files: readonly File[], opts?: { label?: string }) => void;
120
+ /** Attach what is already stored (a picture handed back with its words): no upload. */
121
+ addStored: (src: string, opts?: { name?: string; label?: string }) => void;
122
+ remove: (id: string) => void;
123
+ /** After the message went: the tray empties (errors too: they were never going). */
124
+ clear: () => void;
125
+ }
126
+
127
+ let seq = 0;
128
+ const nextId = () => `att-${Date.now().toString(36)}-${(seq++).toString(36)}`;
129
+ // A preview only for what every browser draws: a HEIC or a TIFF would be a broken picture, so it gets its type on a tile instead.
130
+ const DRAWN = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]);
131
+ const previewOf = (file: File) => (DRAWN.has(file.type) && typeof URL !== "undefined" && URL.createObjectURL ? URL.createObjectURL(file) : undefined);
132
+ const revoke = (src?: string) => { if (src?.startsWith("blob:")) URL.revokeObjectURL(src); };
133
+
134
+ /** What is attached to the message being written, and its uploads. */
135
+ export function useChatAttachments({ limits, upload }: { limits: ChatAttachLimits; upload?: ChatUpload | null }): ChatAttachmentsState {
136
+ const [items, setItems] = useState<ChatAttachment[]>([]);
137
+ const [note, setNote] = useState<string | null>(null);
138
+ const live = useRef(new Set<string>());
139
+ // An upload per item still going: aborted when its item leaves (× or replaced), and all of them when the chat goes.
140
+ const going = useRef(new Map<string, AbortController>());
141
+ const stop = useCallback((id: string) => { going.current.get(id)?.abort(); going.current.delete(id); }, []);
142
+ const itemsRef = useRef(items);
143
+ itemsRef.current = items;
144
+ const uploadRef = useRef(upload);
145
+ uploadRef.current = upload;
146
+ const limitsRef = useRef(limits);
147
+ limitsRef.current = limits;
148
+ // Previews are object URLs: each is let go when its item goes, and all of them when the chat does.
149
+ useEffect(() => () => {
150
+ for (const it of itemsRef.current) revoke(it.src);
151
+ for (const c of going.current.values()) c.abort();
152
+ going.current.clear();
153
+ }, []);
154
+
155
+ const patch = useCallback((id: string, p: Partial<ChatAttachment>) => {
156
+ if (!live.current.has(id)) return; // removed while it uploaded: its answer has nowhere to go
157
+ setItems((xs) => {
158
+ const next = xs.map((x) => {
159
+ if (x.id !== id) return x;
160
+ if (p.src && p.src !== x.src) revoke(x.src);
161
+ return { ...x, ...p };
162
+ });
163
+ itemsRef.current = next;
164
+ return next;
165
+ });
166
+ }, []);
167
+
168
+ const add = useCallback((files: readonly File[], opts?: { label?: string }) => {
169
+ const l = limitsRef.current;
170
+ const one = l.maxFiles <= 1;
171
+ const current = itemsRef.current;
172
+ // One per message: a new one takes the place of what is there (a second paste replaced the first, as it always did here).
173
+ const room = one ? 1 : Math.max(0, l.maxFiles - current.filter((x) => x.state !== "error").length);
174
+ const fresh: ChatAttachment[] = [];
175
+ const work: Array<[ChatAttachment, File]> = [];
176
+ let leftOut = 0;
177
+ let good = 0;
178
+ for (const file of files) {
179
+ const problem = attachmentProblem(file, l);
180
+ const kind = file.type.startsWith("image/") ? "image" : "file";
181
+ if (problem) {
182
+ // Refused, but shown (a picture too large is still the seller's picture: they see which one), with the red edge.
183
+ fresh.push({ id: nextId(), name: file.name, kind, state: "error", error: problem, src: previewOf(file), type: fileTypeName(file), ...(opts?.label ? { label: opts.label } : {}) });
184
+ continue;
185
+ }
186
+ if (good >= room) { leftOut++; continue; }
187
+ good++;
188
+ const it: ChatAttachment = { id: nextId(), name: file.name, kind, state: "uploading", src: previewOf(file), type: fileTypeName(file), ...(opts?.label ? { label: opts.label } : {}) };
189
+ fresh.push(it);
190
+ work.push([it, file]);
191
+ }
192
+ const noun = onlyImages(l.types) ? "image" : "file";
193
+ setNote(leftOut ? `${l.maxFiles} ${noun}${l.maxFiles === 1 ? "" : "s"} per message: ${leftOut} left out.` : null);
194
+ if (!fresh.length) return;
195
+ // The last refusals go when new files come (their line is about the last try); with one per message, so does the one there.
196
+ const leaving = one && work.length ? current : current.filter((x) => x.state === "error");
197
+ for (const x of leaving) { live.current.delete(x.id); stop(x.id); revoke(x.src); }
198
+ const base = current.filter((x) => !leaving.includes(x));
199
+ for (const x of fresh) live.current.add(x.id);
200
+ const next = [...base, ...fresh];
201
+ itemsRef.current = next; // a second add in the same tick reads this, not the last render's
202
+ setItems(next);
203
+ for (const [it, file] of work) {
204
+ const up = uploadRef.current;
205
+ if (!up) { patch(it.id, { state: "error", error: `${file.name}: this chat does not take files.` }); continue; }
206
+ const ctl = new AbortController();
207
+ going.current.set(it.id, ctl);
208
+ up(file, (f) => patch(it.id, { progress: Math.max(0, Math.min(1, f)) }), ctl.signal)
209
+ .then((r) => patch(it.id, "error" in r ? { state: "error", error: `${file.name}: ${r.error}`, progress: undefined } : { state: "ready", url: r.url, src: it.src ?? r.url, progress: undefined }))
210
+ .catch(() => patch(it.id, { state: "error", error: `${file.name}: the upload did not finish. Try again.`, progress: undefined }))
211
+ .finally(() => { if (going.current.get(it.id) === ctl) going.current.delete(it.id); });
212
+ }
213
+ }, [patch, stop]);
214
+
215
+ const addStored = useCallback((src: string, opts?: { name?: string; label?: string }) => {
216
+ const l = limitsRef.current;
217
+ const it: ChatAttachment = { id: nextId(), name: opts?.name ?? "Image", kind: "image", state: "ready", src, url: src, ...(opts?.label ? { label: opts.label } : {}) };
218
+ const xs = itemsRef.current;
219
+ let next: ChatAttachment[];
220
+ if (l.maxFiles <= 1) { for (const x of xs) { live.current.delete(x.id); stop(x.id); revoke(x.src); } next = [it]; }
221
+ else if (xs.filter((x) => x.state !== "error").length >= l.maxFiles) {
222
+ // Full: said, as `add` says it, never dropped without a word.
223
+ setNote(`${l.maxFiles} ${onlyImages(l.types) ? "image" : "file"}s per message: 1 left out.`);
224
+ return;
225
+ } else next = [...xs, it];
226
+ live.current.add(it.id);
227
+ setNote(null);
228
+ itemsRef.current = next;
229
+ setItems(next);
230
+ }, [stop]);
231
+
232
+ const remove = useCallback((id: string) => {
233
+ live.current.delete(id);
234
+ stop(id);
235
+ setNote(null);
236
+ const next = itemsRef.current.filter((x) => { if (x.id === id) { revoke(x.src); return false; } return true; });
237
+ itemsRef.current = next;
238
+ setItems(next);
239
+ }, [stop]);
240
+
241
+ const clear = useCallback(() => {
242
+ // The sent message shows the stored address (`url`), so every preview can go; an upload still racing finds its item gone.
243
+ for (const x of itemsRef.current) { live.current.delete(x.id); stop(x.id); revoke(x.src); }
244
+ itemsRef.current = [];
245
+ setNote(null);
246
+ setItems([]);
247
+ }, [stop]);
248
+
249
+ const ready = items.filter((x) => x.state === "ready");
250
+ return { items, ready, uploading: items.some((x) => x.state === "uploading"), note, add, addStored, remove, clear };
251
+ }
252
+
253
+ // ── Dragging files over the panel ──────────────────────────────────────────────────────────────────────────────────────
254
+
255
+ const carriesFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes("Files");
256
+
257
+ export interface ChatDrop {
258
+ /** Files are over the panel. */
259
+ dragging: boolean;
260
+ /** How many, and whether they are all pictures (the browser tells the types, not the names, while they are dragged). */
261
+ count: number;
262
+ images: boolean;
263
+ /** Spread on the panel (the element whose box is the target). */
264
+ props: {
265
+ onDragEnter?: (e: DragEvent) => void;
266
+ onDragOver?: (e: DragEvent) => void;
267
+ onDragLeave?: (e: DragEvent) => void;
268
+ onDrop?: (e: DragEvent) => void;
269
+ };
270
+ }
271
+
272
+ /** The whole panel takes files while they are dragged over it. Off (`enabled` false): no handlers, a drop does what it did. */
273
+ export function useChatDrop({ enabled, onFiles }: { enabled: boolean; onFiles: (files: File[]) => void }): ChatDrop {
274
+ const [dragging, setDragging] = useState(false);
275
+ const [count, setCount] = useState(0);
276
+ const [images, setImages] = useState(true);
277
+ // dragenter/dragleave fire for every child crossed: counted, so the overlay holds until the pointer leaves the panel.
278
+ const depth = useRef(0);
279
+ const take = useRef(onFiles);
280
+ take.current = onFiles;
281
+ // Turned off mid-drag: the leave and the drop that would have reset it no longer arrive, so it is reset here, or the zone would
282
+ // come back over the panel when it is turned on again.
283
+ useEffect(() => { if (!enabled) { depth.current = 0; setDragging(false); } }, [enabled]);
284
+ if (!enabled) return { dragging: false, count: 0, images: true, props: {} };
285
+ return {
286
+ dragging, count, images,
287
+ props: {
288
+ onDragEnter: (e) => {
289
+ if (!carriesFiles(e)) return;
290
+ e.preventDefault();
291
+ depth.current += 1;
292
+ const files = Array.from(e.dataTransfer.items ?? []).filter((it) => it.kind === "file");
293
+ setCount(files.length);
294
+ setImages(files.every((it) => it.type.startsWith("image/")));
295
+ setDragging(true);
296
+ },
297
+ onDragOver: (e) => { if (carriesFiles(e)) { e.preventDefault(); e.dataTransfer.dropEffect = "copy"; } },
298
+ onDragLeave: (e) => {
299
+ if (!carriesFiles(e)) return;
300
+ depth.current = Math.max(0, depth.current - 1);
301
+ if (depth.current === 0) setDragging(false);
302
+ },
303
+ onDrop: (e) => {
304
+ if (!carriesFiles(e)) return;
305
+ e.preventDefault();
306
+ depth.current = 0;
307
+ setDragging(false);
308
+ const files = Array.from(e.dataTransfer.files ?? []);
309
+ if (files.length) take.current(files);
310
+ },
311
+ },
312
+ };
313
+ }
314
+
315
+ /** What the panel says while files are dragged over it. The panel is its positioned box (`position: relative`). */
316
+ export function ChatDropZone({ limits, count = 0, images = true, title = "Drop to add to your message" }: {
317
+ limits: ChatAttachLimits; count?: number; images?: boolean; title?: ReactNode;
318
+ }) {
319
+ const noun = images ? "image" : "file";
320
+ return (
321
+ // Hidden from a screen reader: it describes a drag, which only a pointer makes; the tray says what arrived.
322
+ <div className="gb-chat-drop" aria-hidden="true">
323
+ <div className="gb-chat-drop-card">
324
+ <Icon name="upload" size={24} />
325
+ <span className="gb-chat-drop-title">{title}</span>
326
+ <span className="gb-chat-drop-limits">{limitsInWords(limits)}</span>
327
+ {count > 0 ? <span className="gb-chat-drop-count">{count} {noun}{count === 1 ? "" : "s"}</span> : null}
328
+ </div>
329
+ </div>
330
+ );
331
+ }
332
+
333
+ // ── The tray ───────────────────────────────────────────────────────────────────────────────────────────────────────────
334
+
335
+ const RING_R = 11;
336
+ const RING_C = 2 * Math.PI * RING_R;
337
+
338
+ function UploadRing({ progress, label }: { progress?: number; label: string }) {
339
+ const known = typeof progress === "number";
340
+ return (
341
+ <span className="gb-chat-tray-scrim">
342
+ <svg className={cx("gb-chat-tray-ring", !known && "is-unknown")} viewBox="0 0 28 28" width={28} height={28} role="progressbar"
343
+ aria-label={label} aria-valuemin={known ? 0 : undefined} aria-valuemax={known ? 100 : undefined} aria-valuenow={known ? Math.round(progress! * 100) : undefined}>
344
+ <circle className="gb-chat-tray-ring-track" cx="14" cy="14" r={RING_R} />
345
+ <circle className="gb-chat-tray-ring-bar" cx="14" cy="14" r={RING_R} strokeDasharray={RING_C}
346
+ strokeDashoffset={known ? RING_C * (1 - Math.max(0.04, progress!)) : RING_C * 0.7} />
347
+ </svg>
348
+ </span>
349
+ );
350
+ }
351
+
352
+ export interface ChatAttachmentsProps {
353
+ items: readonly ChatAttachment[];
354
+ /** Files one message carries: "3 of 10" shows from the second one when more than one is allowed. */
355
+ max: number;
356
+ onRemove: (id: string) => void;
357
+ /** A click on a picture: see it large (ChatLightbox). */
358
+ onOpen?: (item: ChatAttachment) => void;
359
+ /** What was left out ("1 image per message: 2 left out."), from useChatAttachments. */
360
+ note?: string | null;
361
+ }
362
+
363
+ /** The tray in the message box (ChatComposer `top`): what goes with the next message, and what will not and why. */
364
+ export function ChatAttachments({ items, max, onRemove, onOpen, note }: ChatAttachmentsProps) {
365
+ const rowRef = useRef<HTMLUListElement>(null);
366
+ const [more, setMore] = useState(false);
367
+ // "scroll for more" only when the row really hides some: measured, at every size the box takes.
368
+ useBeforePaint(() => {
369
+ const row = rowRef.current;
370
+ if (!row) return undefined;
371
+ const measure = () => setMore(row.scrollWidth > row.clientWidth + 1 && row.scrollLeft + row.clientWidth < row.scrollWidth - 1);
372
+ measure();
373
+ if (typeof ResizeObserver === "undefined") return undefined;
374
+ const ro = new ResizeObserver(measure);
375
+ ro.observe(row);
376
+ row.addEventListener("scroll", measure, { passive: true });
377
+ return () => { ro.disconnect(); row.removeEventListener("scroll", measure); };
378
+ }, [items.length]);
379
+ // Mounted even with nothing in it (hidden, no room taken: `data-empty`), so its status line is a live region that is there BEFORE
380
+ // its words change: one that appears with its words already in it is often not read.
381
+ const empty = !items.length && !note;
382
+ const going = items.filter((x) => x.state !== "error");
383
+ const failed = items.filter((x) => x.state === "error");
384
+ const sending = items.filter((x) => x.state === "uploading");
385
+ const uploading = sending.length;
386
+ const pictures = sending.every((x) => x.kind === "image");
387
+ const what = (n: number) => (pictures ? (n === 1 ? "image" : `${n} images`) : (n === 1 ? "file" : `${n} files`));
388
+ return (
389
+ <div className="gb-chat-tray" role="group" aria-label="Attachments" data-empty={empty || undefined}>
390
+ {items.length ? (
391
+ <ul className="gb-chat-tray-row" ref={rowRef}>
392
+ {items.map((it) => (
393
+ <li key={it.id} className={cx("gb-chat-tray-item", it.state === "error" && "is-error", it.state === "uploading" && "is-uploading", (it.kind === "file" || it.label) && "is-card")}>
394
+ {it.kind === "image" && it.src ? (
395
+ <button type="button" className="gb-chat-tray-thumb" onClick={() => onOpen?.(it)} disabled={!onOpen || it.state === "error"}
396
+ aria-label={`View ${it.label ?? it.name}`}>
397
+ <img src={it.src} alt="" />
398
+ {it.state === "uploading" ? <UploadRing progress={it.progress} label={`Uploading ${it.name}`} /> : null}
399
+ </button>
400
+ ) : (
401
+ <span className="gb-chat-tray-type">
402
+ {it.state === "uploading"
403
+ ? <UploadRing progress={it.progress} label={`Uploading ${it.name}`} />
404
+ : <span aria-hidden="true">{it.type ?? fileTypeName({ name: it.name, type: "" })}</span>}
405
+ </span>
406
+ )}
407
+ {it.kind === "file" || it.label ? (
408
+ <span className="gb-chat-tray-text">
409
+ <span className="gb-chat-tray-name">{it.label ?? it.name}</span>
410
+ <span className="gb-chat-tray-sub">{it.state === "error" ? "Not sent" : it.label ? it.name : (it.type ?? fileTypeName({ name: it.name, type: "" }))}</span>
411
+ </span>
412
+ ) : null}
413
+ <button type="button" className="gb-chat-tray-x" onClick={() => onRemove(it.id)} aria-label={`Remove ${it.label ?? it.name}`} title="Remove">
414
+ <span className="gb-chat-tray-x-dot"><Icon name="close" size={12} /></span>
415
+ </button>
416
+ </li>
417
+ ))}
418
+ </ul>
419
+ ) : null}
420
+ <p className="gb-chat-tray-line" role="status">
421
+ {uploading ? `Uploading ${what(uploading)}…` : max > 1 && going.length > 1 ? `${going.length} of ${max}` : ""}
422
+ {max > 1 && more ? <span className="gb-chat-tray-more"> · scroll for more →</span> : null}
423
+ {note ? <span>{uploading || (max > 1 && going.length > 1) ? " · " : ""}{note}</span> : null}
424
+ </p>
425
+ {failed.length ? (
426
+ <p className="gb-chat-tray-line is-error" role="alert">
427
+ {failed.map((x) => x.error).filter(Boolean).join(" · ")}{" "}
428
+ {failed.length === 1 ? "It won't be sent." : "They won't be sent."}
429
+ </p>
430
+ ) : null}
431
+ </div>
432
+ );
433
+ }
434
+
435
+ // ── The pictures of a sent message ─────────────────────────────────────────────────────────────────────────────────────
436
+
437
+ export interface ChatImage { src: string; alt?: string }
438
+
439
+ /** One large, two side by side, three or more three to a row; past six, the sixth says how many more. A click opens one. */
440
+ export function ChatImages({ images, onOpen }: { images: readonly ChatImage[]; onOpen?: (index: number) => void }) {
441
+ if (!images.length) return null;
442
+ const n = images.length;
443
+ const shown = n > 6 ? images.slice(0, 6) : images;
444
+ const rest = n > 6 ? n - 5 : 0;
445
+ return (
446
+ <div className="gb-chat-images" data-layout={n === 1 ? "one" : n === 2 ? "two" : "grid"}>
447
+ {shown.map((im, i) => (
448
+ <button key={`${i}:${im.src}`} type="button" className="gb-chat-images-cell" onClick={() => onOpen?.(i)} disabled={!onOpen}
449
+ aria-label={i === 5 && rest ? `View image 6 and ${rest - 1} more` : n === 1 ? "View image full size" : `View image ${i + 1} of ${n}`}>
450
+ <img src={im.src} alt={im.alt ?? ""} loading="lazy" decoding="async" />
451
+ {i === 5 && rest ? <span className="gb-chat-images-more" aria-hidden="true">+{rest}</span> : null}
452
+ </button>
453
+ ))}
454
+ </div>
455
+ );
456
+ }
457
+
458
+ // ── One picture, large ─────────────────────────────────────────────────────────────────────────────────────────────────
459
+
460
+ /** A picture over the page: a native modal (top layer, Escape), the backdrop or × closes it, the focus goes back to what opened it. */
461
+ export function ChatLightbox({ src, alt, onClose, closeLabel = "Close" }: { src: string; alt?: string; onClose: () => void; closeLabel?: string }) {
462
+ const ref = useRef<HTMLDialogElement>(null);
463
+ const close = useRef(onClose);
464
+ close.current = onClose;
465
+ useEffect(() => {
466
+ const d = ref.current;
467
+ if (!d) return undefined;
468
+ const opener = typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
469
+ if (!d.open && typeof d.showModal === "function") d.showModal();
470
+ const onNative = () => close.current();
471
+ d.addEventListener("close", onNative);
472
+ return () => {
473
+ d.removeEventListener("close", onNative);
474
+ if (opener && opener !== document.body && opener.isConnected) opener.focus({ preventScroll: true });
475
+ };
476
+ }, []);
477
+ return (
478
+ <dialog ref={ref} className="gb-chat-lightbox" aria-label={alt || "Image"}
479
+ onClick={(e) => { if (e.target === e.currentTarget) e.currentTarget.close(); }}>
480
+ <button type="button" className="gb-chat-lightbox-close" aria-label={closeLabel} onClick={() => ref.current?.close()}>
481
+ <Icon name="close" size={20} />
482
+ </button>
483
+ <img src={src} alt={alt ?? ""} />
484
+ </dialog>
485
+ );
486
+ }