Files
electro4ort/apps/web/src/components/composer.tsx
T
olehhapuk 98b2e0ce4b
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s
update
2026-12-03 10:53:09 +02:00

311 lines
9.7 KiB
TypeScript

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<PickedFile[]>([]);
const [error, setError] = useState<string | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
const nextKey = useRef(0);
// Uploads go one after another, so files keep the order they were picked in.
const queue = useRef<Promise<void>>(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<PickedFile>) {
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 (
<form
className="flex flex-col gap-2 border-t p-3"
onSubmit={(event) => {
event.preventDefault();
send();
}}
>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
{files.length > 0 && (
<ul aria-label="Files to send" className="flex flex-wrap gap-2">
{files.map((item) => (
<li
key={item.key}
className="flex max-w-60 items-center gap-2 rounded-lg border bg-muted/50 py-1 pr-1 pl-2 text-xs"
>
{item.problem ? (
<CircleAlert
className="size-4 shrink-0 text-destructive"
aria-hidden="true"
/>
) : item.attachment ? (
<Paperclip
className="size-4 shrink-0 text-muted-foreground"
aria-hidden="true"
/>
) : (
<Spinner className="shrink-0" aria-label="Uploading" />
)}
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{item.file.name}</span>
<span
className={
item.problem ? 'text-destructive' : 'text-muted-foreground'
}
>
{item.problem ??
(item.attachment
? formatFileSize(item.file.size)
: 'Uploading…')}
</span>
</span>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`Remove ${item.file.name}`}
title="Remove"
onClick={() => remove(item)}
>
<X aria-hidden="true" />
</Button>
</li>
))}
</ul>
)}
<div className="flex items-end gap-2">
<input
ref={fileInput}
type="file"
multiple
hidden
onChange={(event) => {
addFiles([...(event.target.files ?? [])]);
// So picking the same file again is noticed.
event.target.value = '';
}}
/>
<Button
type="button"
variant="ghost"
size="icon"
aria-label="Attach files"
title="Attach files"
disabled={files.length >= MESSAGE_MAX_ATTACHMENTS}
onClick={() => fileInput.current?.click()}
>
<Paperclip aria-hidden="true" />
</Button>
<Textarea
rows={1}
value={draft}
maxLength={MESSAGE_MAX_LENGTH}
placeholder={`Message ${recipient}`}
aria-label={`Message ${recipient}`}
className="max-h-40 min-h-9 resize-none"
onChange={(event) => setDraft(event.target.value)}
onPaste={(event) => {
// A pasted picture or file is attached; pasted text goes in.
if (event.clipboardData.files.length === 0) return;
event.preventDefault();
addFiles([...event.clipboardData.files]);
}}
onKeyDown={(event) => {
// Enter sends, Shift+Enter adds a line; Enter that confirms an
// IME composition (Japanese, Chinese...) does neither.
if (
event.key === 'Enter' &&
!event.shiftKey &&
!event.nativeEvent.isComposing
) {
event.preventDefault();
send();
}
}}
/>
<Button
type="submit"
size="icon"
aria-label="Send message"
disabled={!canSend}
>
<SendHorizontal aria-hidden="true" />
</Button>
</div>
</form>
);
}