Адаптировать frontend к асинхронным вложениям

This commit is contained in:
TAskMAster339
2026-11-05 23:48:42 +03:00
parent 1b8f49e211
commit d3c153f702
6 changed files with 152 additions and 29 deletions
+12 -5
View File
@@ -3,6 +3,7 @@ import { api, ApiError, type Attachment, type Chat, type Session, type User } fr
import AttachmentImage from "./AttachmentImage";
import { uploadDirect, type DirectProgress } from "./directUpload";
import UploadStatus from "./UploadStatus";
import Pagination from "./Pagination";
import { useCursorPage } from "./useCursorPage";
@@ -122,7 +123,10 @@ function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) {
);
}
type UploadDraft = { localId: string; file: File; mode: "proxy" | "direct"; direct: DirectProgress; status: "preparing" | "uploading" | "checking" | "ready" | "error"; attachment?: Attachment; error?: string };
type UploadDraft = { localId: string; file: File; mode: "proxy" | "direct"; direct: DirectProgress; status: "preparing" | "uploading" | "checking" | "accepted" | "error"; attachment?: Attachment; error?: string };
function canSendUpload(item: UploadDraft) {
return item.status === "accepted" && item.attachment && item.attachment.status !== "failed";
}
function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) {
const [selectedChat, setSelectedChat] = useState<Chat | null>(null);
@@ -148,6 +152,9 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
if (cause instanceof ApiError && cause.status === 401) onLogout("Сессия истекла. Войдите снова.");
else setError(errorText(cause));
}, [onLogout]);
const updateAttachment = useCallback((chat: string, local: string, attachment: Attachment) => {
setUploads(current => ({ ...current, [chat]: (current[chat] || []).map(item => item.localId === local ? { ...item, attachment } : item) }));
}, []);
const fetchChats = useCallback((cursor: string | undefined, limit: number) => api.chats(token, cursor, limit), [token]);
const chatId = selectedChat?.id || "";
const fetchMessages = useCallback((cursor: string | undefined, limit: number) => api.messages(token, chatId, cursor, limit), [token, chatId]);
@@ -182,7 +189,7 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
? await uploadDirect(token, targetChat, item.file, item.direct, signal, status => { if (!signal.aborted) update(item.localId, { status }); })
: await api.uploadAttachment(token, targetChat, item.file, signal);
if (signal.aborted) break;
update(item.localId, { status: "ready", attachment });
update(item.localId, { status: "accepted", attachment });
} catch (cause) {
if (signal.aborted) break;
update(item.localId, { status: "error", error: errorText(cause) });
@@ -210,7 +217,7 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
event.preventDefault();
const text = (drafts[chatId] || "").trim();
const selected = uploads[chatId] || [];
if (uploading || selected.some(item => item.status !== "ready") || (!text && selected.length === 0)) return;
if (uploading || selected.some(item => !canSendUpload(item)) || (!text && selected.length === 0)) return;
const attachmentIds = selected.map(item => item.attachment!.id);
const body = JSON.stringify({ text, attachment_ids: attachmentIds });
const previous = pendingMessages.current[chatId];
@@ -287,12 +294,12 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog
</label>
<ul className="upload-list" aria-live="polite">{(uploads[chatId] || []).map(item => <li key={item.localId}>
<span><strong>{item.file.name}</strong> · {(item.file.size / 1048576).toFixed(2)} МиБ<br />
{item.mode === "direct" ? "Напрямую в S3 · " : "Через API · "}{item.status === "preparing" ? "Подготовка…" : item.status === "uploading" ? "Загрузка…" : item.status === "checking" ? "Проверка…" : item.status === "ready" ? "Готово к отправке" : item.error}</span>
{item.status === "preparing" ? "Подготовка…" : item.status === "uploading" ? "Загрузка…" : item.status === "checking" ? "Подтверждение загрузки…" : item.status === "accepted" && item.attachment ? <UploadStatus token={token} id={item.attachment.id} chatId={chatId} localId={item.localId} onUpdate={updateAttachment} onError={reportError} /> : item.error}</span>
{item.status === "error" && <button type="button" disabled={uploading || sending} onClick={() => void uploadFiles(chatId, [item])}>Повторить</button>}
<button type="button" disabled={uploading || sending} aria-label={`Убрать ${item.file.name}`} onClick={() => setUploads(previous => ({ ...previous, [chatId]: (previous[chatId] || []).filter(upload => upload.localId !== item.localId) }))}>Убрать</button>
</li>)}</ul>
</div>
<button className="primary" disabled={sending || uploading || messages.busy || (uploads[chatId] || []).some(item => item.status !== "ready") || (!(drafts[chatId] || "").trim() && !(uploads[chatId] || []).length)}>{sending ? "Отправка…" : uploading ? "Загрузка…" : "Отправить"}</button>
<button className="primary" disabled={sending || uploading || messages.busy || (uploads[chatId] || []).some(item => !canSendUpload(item)) || (!(drafts[chatId] || "").trim() && !(uploads[chatId] || []).length)}>{sending ? "Отправка…" : uploading ? "Загрузка…" : "Отправить"}</button>
</form>
</>}
</main>
+52 -21
View File
@@ -1,41 +1,72 @@
import { useEffect, useState } from "react";
import { api } from "./api";
import { useEffect, useRef, useState } from "react";
import { api, ApiError, type VariantName } from "./api";
import { attachmentStatus, processingError, useAttachment } from "./useAttachment";
export default function AttachmentImage({ id, token, onError }: {
id: string; token: string; onError: (error: unknown) => void;
}) {
const [source, setSource] = useState("");
const [filename, setFilename] = useState("Изображение");
const [failed, setFailed] = useState(false);
const [error, setError] = useState("");
const [variant, setVariant] = useState<VariantName>("thumbnail");
const [attempt, setAttempt] = useState(0);
const [downloading, setDownloading] = useState(false);
const downloadController = useRef<AbortController | null>(null);
useEffect(() => () => downloadController.current?.abort(), []);
const { attachment, error: statusError, busy, retry } = useAttachment(token, id, onError);
useEffect(() => {
if (attachment?.status !== "ready") { setSource(""); return; }
const controller = new AbortController();
let objectURL = "";
setSource(""); setFailed(false);
setSource(""); setError("");
async function load() {
try {
let attachment = await api.attachment(token, id, controller.signal);
while (attachment.status === "queued" || attachment.status === "processing") {
await new Promise(resolve => setTimeout(resolve, 1000));
if (controller.signal.aborted) return;
attachment = await api.attachment(token,id,controller.signal);
}
if (attachment.status === "failed") throw new Error("Обработка изображения завершилась ошибкой");
const content = await api.attachmentContent(token, id, controller.signal);
const content = await api.attachmentContent(token, id, controller.signal, variant);
if (controller.signal.aborted) return;
objectURL = URL.createObjectURL(content);
setFilename(attachment.filename); setSource(objectURL);
} catch (error) {
if (!controller.signal.aborted) { setFailed(true); onError(error); }
setSource(objectURL);
} catch (cause) {
if (!controller.signal.aborted) {
setError(cause instanceof Error ? cause.message : "Не удалось загрузить изображение.");
if (cause instanceof ApiError && cause.status === 401) onError(cause);
}
}
}
void load();
return () => { controller.abort(); if (objectURL) URL.revokeObjectURL(objectURL); };
}, [id, token, attempt, onError]);
}, [id, token, attachment, variant, attempt, onError]);
async function downloadOriginal() {
const controller = new AbortController();
downloadController.current = controller;
setDownloading(true); setError("");
try {
const content = await api.attachmentContent(token, id, controller.signal);
if (controller.signal.aborted) return;
const url = URL.createObjectURL(content);
const link = document.createElement("a");
link.href = url; link.download = attachment?.filename || "image";
document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (cause) {
if (controller.signal.aborted) return;
setError(cause instanceof Error ? cause.message : "Не удалось скачать оригинал.");
if (cause instanceof ApiError && cause.status === 401) onError(cause);
} finally { if (!controller.signal.aborted) setDownloading(false); }
}
return <figure className="attachment-image">
{source ? <a href={source} download={filename} aria-label={`Скачать ${filename}`}><img src={source} alt={filename} /></a>
: failed ? <button type="button" onClick={() => setAttempt(attempt + 1)}>Повторить загрузку изображения</button>
: <span role="status">Загрузка изображения…</span>}
{source && <figcaption>{filename} · нажмите, чтобы скачать</figcaption>}
{attachment?.status === "ready" ? <>
{source ? <img src={source} alt={attachment.filename} /> : !error && <span role="status">Загрузка изображения…</span>}
<figcaption>{attachment.filename}</figcaption>
<div className="attachment-actions">
<label>Предпросмотр <select value={variant} onChange={event => setVariant(event.target.value as VariantName)}>
{attachment.variants.map(item => <option key={item.name} value={item.name}>{({ thumbnail: "Миниатюра", crop: "Квадрат", optimized: "WebP" })[item.name]} · {item.width}×{item.height}</option>)}
</select></label>
<button type="button" disabled={downloading} onClick={() => void downloadOriginal()}>{downloading ? "Скачивание…" : "Скачать оригинал"}</button>
</div>
</> : <span role="status">{attachment ? attachment.status === "failed" ? processingError(attachment.error_code) : attachmentStatus[attachment.status] : "Проверка состояния изображения…"}</span>}
{attachment?.status === "failed" && !statusError && <button type="button" disabled={busy} onClick={retry}>Проверить состояние</button>}
{statusError && <p role="alert">{statusError} <button type="button" disabled={busy} onClick={retry}>Проверить состояние</button></p>}
{error && <p role="alert">{error} <button type="button" onClick={() => setAttempt(value => value + 1)}>Загрузить снова</button></p>}
</figure>;
}
+17
View File
@@ -0,0 +1,17 @@
import { useEffect } from "react";
import type { Attachment } from "./api";
import { attachmentStatus, processingError, useAttachment } from "./useAttachment";
export default function UploadStatus({ token, id, chatId, localId, onUpdate, onError }: {
token: string; id: string; chatId: string; localId: string;
onUpdate: (chat: string, local: string, attachment: Attachment) => void;
onError: (cause: unknown) => void;
}) {
const { attachment, error, busy, retry } = useAttachment(token, id, onError);
useEffect(() => { if (attachment) onUpdate(chatId, localId, attachment); }, [attachment, chatId, localId, onUpdate]);
return <span>
<span role="status">{attachment ? attachment.status === "failed" ? processingError(attachment.error_code) : attachmentStatus[attachment.status] : "Файл принят. Проверка состояния…"}</span>
{attachment?.status === "failed" && !error && <button type="button" disabled={busy} onClick={retry}>Проверить состояние</button>}
{error && <><span role="alert"> · {error} </span><button type="button" disabled={busy} onClick={retry}>Проверить состояние</button></>}
</span>;
}
+10 -3
View File
@@ -12,10 +12,16 @@ export interface Chat {
created_at: string;
}
export type VariantName = "thumbnail" | "crop" | "optimized";
export interface AttachmentVariant {
name: VariantName; content_type: "image/jpeg" | "image/webp";
width: number; height: number; size_bytes: number; sha256: string;
}
export interface Attachment {
id: string; chat_id: string; owner_id: string; filename: string;
content_type: "image/png" | "image/jpeg"; size_bytes: number; sha256: string;
status: "queued" | "processing" | "ready" | "failed"; variants: unknown[]; error_code: string | null; created_at: string; updated_at: string;
status: "queued" | "processing" | "ready" | "failed"; variants: AttachmentVariant[]; error_code: string | null; created_at: string; updated_at: string;
}
export interface DirectUpload {
@@ -150,8 +156,9 @@ export const api = {
}),
attachment: (token: string, id: string, signal?: AbortSignal) =>
request<Attachment>(`/api/v1/attachments/${encodeURIComponent(id)}`, { headers: bearer(token), signal }),
attachmentContent: async (token: string, id: string, signal?: AbortSignal) => {
const response = await fetch(`/api/v1/attachments/${encodeURIComponent(id)}/content`, { headers: bearer(token), signal });
attachmentContent: async (token: string, id: string, signal?: AbortSignal, variant?: VariantName) => {
const query = variant ? `?${new URLSearchParams({ variant })}` : "";
const response = await fetch(`/api/v1/attachments/${encodeURIComponent(id)}/content${query}`, { headers: bearer(token), signal });
if (!response.ok) {
const data = await response.json().catch(() => null);
throw new ApiError(data?.error?.message || `Ошибка HTTP ${response.status}`, response.status, response.headers.get("X-Request-Id") || undefined);
+20
View File
@@ -842,3 +842,23 @@ textarea {
color: inherit;
font: inherit;
}
.attachment-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 8px;
}
.attachment-actions select {
max-width: 100%;
font: inherit;
}
.attachment-actions label {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
+41
View File
@@ -0,0 +1,41 @@
import { useEffect, useState } from "react";
import { api, ApiError, type Attachment } from "./api";
export const attachmentStatus: Record<Attachment["status"], string> = {
queued: "В очереди на обработку", processing: "Обработка изображения…",
ready: "Изображение готово", failed: "Не удалось обработать изображение",
};
export function processingError(code: string | null) {
if (code === "invalid_image") return "Файл повреждён или превышает лимит обработки (8 млн пикселей).";
if (code === "retry_exhausted") return "Обработка не завершилась после нескольких попыток. Обратитесь к администратору.";
return "Не удалось обработать изображение. Обратитесь к администратору.";
}
export function useAttachment(token: string, id: string, onError: (error: unknown) => void) {
const [attachment, setAttachment] = useState<Attachment>();
const [error, setError] = useState("");
const [attempt, setAttempt] = useState(0);
const [busy, setBusy] = useState(true);
useEffect(() => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout>;
setAttachment(undefined); setError(""); setBusy(true);
async function poll() {
try {
const value = await api.attachment(token, id, controller.signal);
if (controller.signal.aborted) return;
setAttachment(value); setBusy(false);
if (value.status === "queued" || value.status === "processing") timer = setTimeout(poll, 1000);
} catch (cause) {
if (controller.signal.aborted) return;
setBusy(false);
setError(cause instanceof Error ? cause.message : "Не удалось проверить состояние файла.");
if (cause instanceof ApiError && cause.status === 401) onError(cause);
}
}
void poll();
return () => { controller.abort(); clearTimeout(timer); };
}, [token, id, attempt, onError]);
return { attachment, error, busy, retry: () => setAttempt(value => value + 1) };
}