import { useEffect, useRef, useState } from 'react'; import { MESSAGE_MAX_ATTACHMENTS, MESSAGE_MAX_LENGTH, sendMessageSchema, } from '@repo/contracts'; import type { Attachment } from '@repo/contracts'; import { CircleAlert, Paperclip, SendHorizontal, X } from 'lucide-react'; import { Button } from '@repo/ui/components/button'; import { Spinner } from '@repo/ui/components/spinner'; import { Textarea } from '@repo/ui/components/textarea'; import { discardAttachment, fileProblem, formatFileSize, uploadAttachment, } from '@/lib/attachments'; import { useSendMessage } from '@/lib/conversations'; import { errorMessage } from '@/lib/errors'; /** A file picked for the next message, on its way up or already there. */ interface PickedFile { key: number; file: File; /** Set once the upload is done; its id goes in the message. */ attachment?: Attachment; /** Why the upload failed, in words to show. */ problem?: string; /** Stops the upload if the file is removed first. */ abort: AbortController; } interface ComposerProps { conversationId: string; /** The conversation is a realm's cauldron. */ inRealm: boolean; /** Who or what the message goes to, for the placeholder. */ recipient: string; /** Called as a message goes out, before it shows up in the list. */ onSend: () => void; } /** * The box a message is written in, with the files picked for it. Files * start uploading as soon as they are picked (with the button, by pasting * or by dropping them on the page) and go out with the next message. */ export function Composer({ conversationId, inRealm, recipient, onSend, }: ComposerProps) { const sendMessage = useSendMessage(conversationId, inRealm); const [draft, setDraft] = useState(''); const [files, setFiles] = useState([]); const [error, setError] = useState(null); const fileInput = useRef(null); const nextKey = useRef(0); // Uploads go one after another, so files keep the order they were picked in. const queue = useRef>(Promise.resolve()); const picked = useRef(files); useEffect(() => { picked.current = files; }, [files]); // Leaving the chat stops what is still going up. useEffect( () => () => { for (const file of picked.current) file.abort.abort(); }, [], ); // Files dropped anywhere on the page are attached, not opened in place // of the app. Set up again on each render, so it sees the current files. useEffect(() => { const allow = (event: DragEvent) => { if (event.dataTransfer?.types.includes('Files')) event.preventDefault(); }; const take = (event: DragEvent) => { const dropped = event.dataTransfer?.files; if (!dropped || dropped.length === 0) return; event.preventDefault(); addFiles([...dropped]); }; window.addEventListener('dragover', allow); window.addEventListener('drop', take); return () => { window.removeEventListener('dragover', allow); window.removeEventListener('drop', take); }; }); function update(key: number, change: Partial) { setFiles((current) => current.map((item) => (item.key === key ? { ...item, ...change } : item)), ); } function addFiles(chosen: File[]) { if (chosen.length === 0) return; setError(null); const room = MESSAGE_MAX_ATTACHMENTS - files.length; if (chosen.length > room) { setError(`A message can have at most ${MESSAGE_MAX_ATTACHMENTS} files.`); } const added: PickedFile[] = []; for (const file of chosen.slice(0, Math.max(room, 0))) { const problem = fileProblem(file); if (problem) { setError(problem); continue; } added.push({ key: nextKey.current++, file, abort: new AbortController(), }); } setFiles((current) => [...current, ...added]); for (const item of added) { // Asked afresh each time: the file may be removed at any point. const isRemoved = () => item.abort.signal.aborted; queue.current = queue.current.then(async () => { if (isRemoved()) return; try { const attachment = await uploadAttachment( item.file, item.abort.signal, ); // Removed while the last bytes went up: the API can forget it. if (isRemoved()) { void discardAttachment(attachment.id).catch(() => undefined); } else { update(item.key, { attachment }); } } catch (failure) { if (isRemoved()) return; update(item.key, { problem: errorMessage(failure, 'The upload failed.'), }); } }); } } function remove(item: PickedFile) { item.abort.abort(); if (item.attachment) { void discardAttachment(item.attachment.id).catch(() => undefined); } setFiles((current) => current.filter((other) => other.key !== item.key)); } const isUploading = files.some((item) => !item.attachment && !item.problem); const ready = files.flatMap((item) => item.attachment ? [item.attachment.id] : [], ); const parsed = sendMessageSchema.safeParse({ content: draft, attachmentIds: ready, }); // Nothing goes out while a file is still on its way. const canSend = parsed.success && !isUploading; function send() { if (!parsed.success || isUploading) return; const sent = { draft, files }; setDraft(''); setFiles([]); setError(null); onSend(); sendMessage.mutate(parsed.data, { onError: (failure) => { // Give it all back, unless something new was started meanwhile. setDraft((current) => (current === '' ? sent.draft : current)); setFiles((current) => (current.length === 0 ? sent.files : current)); setError( errorMessage( failure, 'Could not send the message. Please try again.', ), ); }, }); } return (
{ event.preventDefault(); send(); }} > {error && (

{error}

)} {files.length > 0 && (
    {files.map((item) => (
  • {item.problem ? (
  • ))}
)}
{ addFiles([...(event.target.files ?? [])]); // So picking the same file again is noticed. event.target.value = ''; }} />