peppa/apps/web/components/AttachField.tsx
Асель ea6f848f09 Merge branch 'main' into task/pep-160
Конфликты: addTask связывает вложения (PEP-159) и возвращает на доску (PEP-160);
поле вложений в форме новой задачи; AttachField очищается вместе с формой.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:10:01 +05:00

187 lines
8.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { FileText, Loader2, Paperclip, X } from "lucide-react";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { useT } from "@/components/I18n";
import { cn } from "@/lib/utils";
const MAX_FILES = 5;
const MAX_BYTES = 20 * 1024 * 1024;
const ACCEPT = ".png,.jpg,.jpeg,.webp,.gif,.pdf,.txt,.md,.csv,.json,.docx,.xlsx,.pptx";
interface Item {
key: string;
name: string;
size: number;
/** Server id once uploaded. */
id?: number;
preview?: string;
state: "uploading" | "ok" | "error";
}
const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${Math.round(n / 1024)} KB` : `${(n / 1048576).toFixed(1).replace(/\.0$/, "")} MB`);
/**
* PEP-159: a paperclip next to a message field — pick files, drop them on the field or paste a
* picture (Ctrl+V). Each file goes up at once (`POST /api/attachments`); the form carries the
* returned ids as hidden `attachment` fields and the action links them to the message.
*/
export function AttachField({ projectId, target, className }: { projectId: number; /** id of the textarea that takes drops and pastes */ target?: string; className?: string }) {
const t = useT();
const inputId = useId();
const picker = useRef<HTMLInputElement>(null);
const root = useRef<HTMLDivElement>(null);
const [items, setItems] = useState<Item[]>([]);
const [error, setError] = useState<string | null>(null);
const [over, setOver] = useState(false);
// The latest list for handlers attached once (drop, paste, form submit).
const live = useRef<Item[]>([]);
live.current = items;
const upload = useCallback(
async (file: File, key: string) => {
const body = new FormData();
body.set("projectId", String(projectId));
body.append("files", file);
try {
const res = await fetch("/api/attachments", { method: "POST", body });
const json = (await res.json().catch(() => ({}))) as { files?: Array<{ id: number }>; errors?: string[]; error?: string };
const ok = json.files?.[0];
if (!res.ok || !ok) throw new Error(json.errors?.[0] ?? json.error ?? t("Не получилось загрузить файл. Попробуйте ещё раз."));
setItems((cur) => cur.map((i) => (i.key === key ? { ...i, id: ok.id, state: "ok" } : i)));
} catch (e) {
setItems((cur) => cur.filter((i) => i.key !== key));
setError((e as Error).message);
}
},
[projectId, t],
);
const add = useCallback(
(files: Iterable<File>) => {
setError(null);
const fresh: Array<{ file: Item; raw: File }> = [];
let count = live.current.length;
for (const raw of files) {
if (raw.size > MAX_BYTES) {
setError(t("Файл «{name}» больше 20 МБ. Приложите файл поменьше.", { name: raw.name }));
continue;
}
if (count >= MAX_FILES) {
setError(t("Можно приложить не больше {n} файлов.", { n: MAX_FILES }));
break;
}
count++;
const key = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
fresh.push({ raw, file: { key, name: raw.name || "image.png", size: raw.size, state: "uploading", preview: raw.type.startsWith("image/") && raw.type !== "image/svg+xml" ? URL.createObjectURL(raw) : undefined } });
}
if (!fresh.length) return;
setItems((cur) => [...cur, ...fresh.map((f) => f.file)]);
for (const f of fresh) void upload(f.raw, f.file.key);
},
[t, upload],
);
const remove = (item: Item) => {
setItems((cur) => cur.filter((i) => i.key !== item.key));
if (item.preview) URL.revokeObjectURL(item.preview);
if (item.id) void fetch(`/api/attachments/${item.id}`, { method: "DELETE" }).catch(() => {});
};
// Drops and pastes on the message field; sending waits for files still going up.
useEffect(() => {
const form = root.current?.closest("form");
const field = (target ? document.getElementById(target) : form?.querySelector("textarea")) as HTMLElement | null;
if (!form) return;
const onDrop = (e: DragEvent) => {
if (!e.dataTransfer?.files.length) return;
e.preventDefault();
setOver(false);
add(Array.from(e.dataTransfer.files));
};
const onOver = (e: DragEvent) => {
if (!e.dataTransfer?.types.includes("Files")) return;
e.preventDefault();
setOver(true);
};
const onLeave = () => setOver(false);
const onPaste = (e: ClipboardEvent) => {
const files = Array.from(e.clipboardData?.files ?? []);
if (!files.length) return;
e.preventDefault();
add(files);
};
const onSubmit = (e: Event) => {
if (live.current.some((i) => i.state === "uploading")) {
e.preventDefault();
e.stopPropagation();
setError(t("Файлы ещё загружаются. Подождите секунду и отправьте снова."));
}
};
// PEP-160: a create form is cleared in place after success — the files go with it.
const onReset = () => {
setItems([]);
setError(null);
};
field?.addEventListener("drop", onDrop);
field?.addEventListener("dragover", onOver);
field?.addEventListener("dragleave", onLeave);
field?.addEventListener("paste", onPaste);
form.addEventListener("submit", onSubmit, true);
form.addEventListener("reset", onReset);
return () => {
form.removeEventListener("reset", onReset);
field?.removeEventListener("drop", onDrop);
field?.removeEventListener("dragover", onOver);
field?.removeEventListener("dragleave", onLeave);
field?.removeEventListener("paste", onPaste);
form.removeEventListener("submit", onSubmit, true);
};
}, [add, target, t]);
return (
<div ref={root} className={cn("flex min-w-0 flex-col gap-1.5", className)} data-attach-field>
{items.map((i) => i.id && <input key={i.key} type="hidden" name="attachment" value={i.id} />)}
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => picker.current?.click()}
className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", over && "border-primary bg-accent text-foreground")}
aria-label={t("Приложить файл")}
title={t("Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.")}
>
<Paperclip className="size-4" />
<span>{over ? t("Отпустите файл здесь") : t("Файл")}</span>
</button>
<input id={inputId} ref={picker} type="file" multiple accept={ACCEPT} className="sr-only" tabIndex={-1} onChange={(e) => (add(Array.from(e.target.files ?? [])), (e.target.value = ""))} />
</div>
{items.length > 0 && (
<ul className="m-0 flex list-none flex-wrap gap-2 p-0" aria-label={t("Приложенные файлы")}>
{items.map((i) => (
<li key={i.key} className="flex max-w-full items-center gap-2 rounded-md border bg-background py-1 pr-1 pl-2 text-xs" data-attachment-item>
{i.preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={i.preview} alt="" className="size-8 rounded object-cover" />
) : (
<FileText className="size-4 shrink-0 text-muted-foreground" />
)}
<span className="min-w-0 max-w-[14rem] truncate" title={i.name}>
{i.name}
</span>
<span className="shrink-0 text-muted-foreground">{i.state === "uploading" ? <Loader2 className="size-3.5 animate-spin" aria-label={t("загружается")} /> : fmt(i.size)}</span>
<button type="button" onClick={() => remove(i)} className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" aria-label={t("Убрать файл {name}", { name: i.name })}>
<X className="size-3.5" />
</button>
</li>
))}
</ul>
)}
{error && (
<p role="alert" className="m-0 text-xs text-destructive">
{error}
</p>
)}
</div>
);
}