Files
chatkit/dist/react/use-attachments.js
CatoandClaude e690b2254a Messenger: people talking to people, and to the agents among them (0.29.0) (#82)
* Messenger: people talking to people, and to the agents among them (0.26.0)

OrangeCat's direct messages were built in the app, so what was wrong with
them could not be fixed for the next product: an agent's answer in a
conversation between two people looked like the other person's, nothing
said an agent was taking part, top bar and a two-row box took half a
phone, and nothing could be attached. This is the messenger as a package.

@bitbaum/chatkit/messenger: Messenger (the whole screen) and its parts
useMessenger, ConversationList, MessageThread, MessageAttachments. The app
implements MessengerTransport; the package has no database, websocket or
storage. styles/messenger.css is the embedded sheet plus the Messenger's
section, without ChatApp.

- An agent is told from a person by the shape of its face, an Agent mark
  with whom it answered for, and an outlined bubble; the top bar says it
  is in the conversation; naming it shows that it is thinking, and says
  so if it never answers.
- Files: Camera, Photos, Videos, Files, checked against the attachment
  policy before an upload starts, photos shrunk in the browser, progress
  and Try again per file, a full-screen viewer, a film drawn as its still.
- The thread: runs, day lines, a New line, ticks from readState, a failed
  message kept with Try again, earlier messages loaded above with the
  reader's place kept, one bubble per message however often it arrives.
- Composer: layout="inline", attachmentsAlone, attach.take, attach.accept,
  a "videos" source, files dropped onto the box. Defaults unchanged.

The state is one pure function (messengerReducer), tested in Node.
test/browser-messenger.mjs drives demo/messenger.html at 390px, 320px
dark and 1280px. It found two defects before any product did: a read mark
that cleared the badge without telling the server, and a page of history
that pulled the reader to the end of the thread.

threadkit 0.1.2 (attachment policy, mention matcher, readState) is merged
and tagged but not on npm, so those rules are carried word for word in
src/thread-rules.ts with threadkit's own tests; the file says when it goes.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmsmMXvM981mcszxEA6

* test(messenger): wait for the opened conversation before reading its thread

Side by side, the conversation that was open can still be on screen with a
"New" line of its own, so the check read the old thread on a slow runner.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmsmMXvM981mcszxEA6

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 16:26:03 +01:00

243 lines
9.4 KiB
JavaScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { shrinkImage as shrink } from "../image.js";
import { DEFAULT_ATTACHMENT_LIMITS, DEFAULT_ATTACHMENT_NOTES, attachmentKey, acceptsImages, isImageMime, isTextFile, stripDataUrlBase64, toWire, } from "../attachments.js";
/**
* Staging screenshots and text files for a composer — paste-to-attach
* included, because on a phone that is how a screenshot arrives. Preview URLs
* are revoked on remove, clear and unmount (a preview never revoked is a leak
* that survives every send). From loki `hooks/use-attachments.ts`.
*/
export function useAttachments(options = {}, notes = {}) {
const { readFile, sources, accept: _accept, take: _take, ...given } = options;
void _accept;
void _take;
const lim = { ...DEFAULT_ATTACHMENT_LIMITS, ...given };
const { maxFiles, maxImageBytes, maxTextChars, maxImageEdge } = lim;
// Mirrored in a ref so a new `notes` or `readFile` object every render does
// not rebuild every callback below.
const say = useRef(DEFAULT_ATTACHMENT_NOTES);
const reader = useRef(undefined);
const imagesOk = acceptsImages(sources);
useEffect(() => {
say.current = { ...DEFAULT_ATTACHMENT_NOTES, ...notes };
reader.current = readFile;
});
const [attachments, setAttachments] = useState([]);
const [note, setNote] = useState(null);
const previews = useRef(new Set());
// The staged list, kept in a ref too: files are read one at a time and each
// read must see what the one before it staged.
const staged = useRef([]);
const queue = useRef(Promise.resolve());
const commit = useCallback((next) => {
staged.current = next;
setAttachments(next);
}, []);
useEffect(() => {
const urls = previews.current;
return () => {
for (const url of urls)
URL.revokeObjectURL(url);
urls.clear();
};
}, []);
const add = useCallback((item) => {
const prev = staged.current;
if (prev.length >= maxFiles)
return;
if (prev.some((p) => attachmentKey(p) === attachmentKey(item)))
return;
commit([...prev, item]);
}, [commit, maxFiles]);
const stage = useCallback(async (file) => {
const limits = { maxFiles, maxImageBytes, maxImageEdge, maxTextChars };
const read = await readAttachmentFiles(file, limits, say.current, {
preview: true,
readFile: reader.current,
noImages: !imagesOk,
images: staged.current.filter((a) => a.kind === "image").length,
room: maxFiles - staged.current.length,
progress: setNote,
});
setNote(read.note ?? null);
for (const item of read.attachments) {
if (item.previewUrl?.startsWith("blob:"))
previews.current.add(item.previewUrl);
add(item);
}
}, [add, maxFiles, maxImageBytes, maxImageEdge, maxTextChars]);
// One file at a time: a PDF that becomes pictures needs to know how many
// pictures the files before it left room for.
const enqueue = useCallback((file) => {
queue.current = queue.current.then(() => stage(file)).catch(() => undefined);
}, [stage]);
const addFiles = useCallback((files) => {
if (!files)
return;
setNote(null);
if (maxFiles - staged.current.length <= 0) {
setNote(say.current.tooMany(maxFiles));
return;
}
for (const file of Array.from(files))
enqueue(file);
}, [enqueue, maxFiles]);
const addFromPaste = useCallback((e) => {
const items = e.clipboardData?.items;
if (!items)
return false;
const images = Array.from(items).filter((i) => i.type.startsWith("image/"));
if (images.length === 0)
return false;
setNote(null);
for (const item of images) {
const file = item.getAsFile();
if (file)
enqueue(file);
}
return true;
}, [enqueue]);
const revoke = (a) => {
if (!a.previewUrl)
return;
URL.revokeObjectURL(a.previewUrl);
previews.current.delete(a.previewUrl);
};
const remove = useCallback((key) => {
const target = staged.current.find((a) => attachmentKey(a) === key);
if (target)
revoke(target);
commit(staged.current.filter((a) => attachmentKey(a) !== key));
}, [commit]);
const clear = useCallback(() => {
staged.current.forEach(revoke);
commit([]);
setNote(null);
}, [commit]);
return {
attachments,
note,
clearNote: () => setNote(null),
addFiles,
addFromPaste,
remove,
clear,
toWire: () => toWire(attachments),
keyOf: attachmentKey,
full: attachments.length >= maxFiles,
limits: lim,
};
}
/**
* One file read the way the composer stages it: an image shrunk to
* `maxImageEdge` and judged by its size after that, a text file read up to
* `maxTextChars`, anything else refused — with the reason as a sentence from
* `notes`, never a throw. `preview: true` adds an object URL the caller must
* revoke. `useAttachments` and `ChatApp`'s `send` both read files through it.
*/
export async function readAttachmentFile(file, limits = {}, notes = {}, { preview = false } = {}) {
const { maxImageBytes, maxTextChars, maxImageEdge } = { ...DEFAULT_ATTACHMENT_LIMITS, ...limits };
const say = { ...DEFAULT_ATTACHMENT_NOTES, ...notes };
const previewOf = () => (preview ? URL.createObjectURL(file) : undefined);
if (isImageMime(file.type)) {
const name = file.name || "screenshot.png";
const tooLarge = { note: say.imageTooLarge(name, Math.round(maxImageBytes / 1_000_000)) };
try {
if (maxImageEdge > 0) {
// Shrink first, then judge the size: a 4 MB screenshot is fine once it
// is the 300 KB it needed to be.
const dataUrl = await shrink(file, maxImageEdge, maxImageBytes);
if (!dataUrl)
return tooLarge;
return {
attachment: {
kind: "image",
name: name.replace(/\.(png|gif|webp|jpe?g)$/i, "") + ".jpg",
mimeType: "image/jpeg",
dataBase64: stripDataUrlBase64(dataUrl),
previewUrl: previewOf(),
},
};
}
if (file.size > maxImageBytes)
return tooLarge;
const dataUrl = await readAs(file, "dataUrl");
return {
attachment: {
kind: "image",
name,
mimeType: file.type,
dataBase64: stripDataUrlBase64(dataUrl),
previewUrl: previewOf(),
},
};
}
catch {
return { note: say.unreadable(name) };
}
}
if (!isTextFile(file.name, file.type))
return { note: say.wrongType(file.name) };
if (file.size > maxTextChars) {
return { note: say.textTooLarge(file.name, Math.round(maxTextChars / 1000)) };
}
try {
const content = await readAs(file, "text");
return {
attachment: { kind: "text", name: file.name, content: content.slice(0, maxTextChars) },
};
}
catch {
return { note: say.unreadable(file.name) };
}
}
/**
* `readAttachmentFile`, with the app's own reader first. The reader may turn
* one file into several attachments (a PDF of slide pictures) or into text, or
* decline with `undefined`, in which case chatkit's reader decides. A reader
* that throws gives the "could not read" note, never an exception.
*/
export async function readAttachmentFiles(file, limits = {}, notes = {}, options = {}) {
const full = { ...DEFAULT_ATTACHMENT_LIMITS, ...limits };
const say = { ...DEFAULT_ATTACHMENT_NOTES, ...notes };
if (options.readFile) {
const ctx = {
limits: full,
notes: say,
images: options.images ?? 0,
room: options.room ?? full.maxFiles,
progress: options.progress ?? (() => undefined),
};
try {
const mine = await options.readFile(file, ctx);
if (mine) {
return {
attachments: mine.attachments.slice(0, Math.max(0, ctx.room)),
...(mine.note ? { note: mine.note } : {}),
};
}
}
catch {
return { attachments: [], note: say.unreadable(file.name) };
}
}
if (options.noImages && isImageMime(file.type))
return { attachments: [], note: say.wrongType(file.name) };
const one = await readAttachmentFile(file, full, say, { preview: options.preview });
return one.note !== undefined
? { attachments: [], note: one.note }
: { attachments: [one.attachment] };
}
function readAs(file, as) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result ?? ""));
reader.onerror = () => reject(reader.error);
if (as === "text")
reader.readAsText(file);
else
reader.readAsDataURL(file);
});
}
//# sourceMappingURL=use-attachments.js.map