Simplify: общий загрузчик файлов и единые ключи на фронте

- Четыре копии «ресайз → FormData → CSRF из cookie → fetch → разбор конверта
  ошибки» (аватар, фото партии, фото из админки, иконка ачивки) сведены в
  lib/upload.ts. Иконка по-прежнему уходит оригиналом: ресайз в JPEG убил бы
  прозрачность герба.
- Три копии readCsrfToken и вторая копия resizeImage удалены — берём readCookie
  из api/client.ts и resizeImage из lib/image.ts с параметром размера.
- Ключи, протухающие от партии, собраны в matchAffectedKeys: раньше они были
  написаны строками мимо реестра qk в двух местах, и переименование ключа
  сломало бы инвалидацию молча.
- Различение «нет сессии» и «нет связи» вынесено в authProbeRetry и применено к
  обеим пробам. Прошлый заход чинил только игроцкие гварды, и RequireAdmin
  по-прежнему выкидывал админа на страницу входа при обрыве связи.
- ToastContext больше не пересоздаёт значение контекста: провайдер обёрнут
  вокруг всего приложения, и каждый тост перерисовывал всех потребителей.
- PlaceEditor не трогает DOM, пока цель подсветки не изменилась (было
  querySelectorAll на каждый pointermove).

#8

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BoiJK9ux8peeyjLb8TYjFf
This commit is contained in:
2026-09-09 18:52:06 +03:00
co-authored by Claude Opus 5
parent 94e2c09952
commit a9de68f27c
11 changed files with 123 additions and 168 deletions
+10 -51
View File
@@ -1,14 +1,9 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ApiError, api, unwrap } from "../api/client";
import { api, authProbeRetry, unwrap } from "../api/client";
import { qk } from "../api/queryKeys";
import type { AdminMe, MatchUpdate } from "../domain/types";
import { resizeImage } from "../lib/image";
function readCsrfToken(): string | null {
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]*)/);
return m ? decodeURIComponent(m[1]) : null;
}
import { uploadFile } from "../lib/upload";
export function useAdminMe() {
return useQuery({
@@ -18,6 +13,7 @@ export function useAdminMe() {
if (r.response.status === 401 || r.response.status === 403) return null;
return unwrap(r);
},
retry: authProbeRetry,
});
}
@@ -106,29 +102,8 @@ export function useAdminMatchAttachments(matchId: number | null) {
export function useAdminUploadAttachment(matchId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (file: File) => {
const blob = await resizeImage(file);
const form = new FormData();
form.append("file", blob, "photo.jpg");
const csrf = readCsrfToken();
const base = import.meta.env.VITE_API_BASE_URL || "";
const r = await fetch(`${base}/api/admin/matches/${matchId}/attachments`, {
method: "POST",
body: form,
credentials: "include",
headers: csrf ? { "X-CSRF-Token": csrf } : {},
});
if (!r.ok) {
let env: { code?: string; message?: string } | undefined;
try {
env = ((await r.json()) as { error?: typeof env }).error;
} catch {
/* тело без JSON */
}
throw new ApiError(env?.message || "Не удалось загрузить", env?.code || "ERROR", r.status);
}
return await r.json();
},
mutationFn: async (file: File) =>
uploadFile(`/api/admin/matches/${matchId}/attachments`, file),
onSuccess: () => qc.invalidateQueries({ queryKey: ["adminMatchAttachments", matchId] }),
});
}
@@ -283,28 +258,12 @@ export function useDeleteAchievement() {
export function useUploadAchievementIcon() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ slug, file }: { slug: string; file: File }) => {
const form = new FormData();
form.append("file", file, file.name);
const csrf = readCsrfToken();
const base = import.meta.env.VITE_API_BASE_URL || "";
const r = await fetch(`${base}/api/admin/achievements/${slug}/icon`, {
// Иконку шлём оригиналом: ресайз в JPEG убил бы прозрачность герба.
mutationFn: async ({ slug, file }: { slug: string; file: File }) =>
uploadFile(`/api/admin/achievements/${slug}/icon`, file, {
method: "PUT",
body: form,
credentials: "include",
headers: csrf ? { "X-CSRF-Token": csrf } : {},
});
if (!r.ok) {
let env: { code?: string; message?: string } | undefined;
try {
env = ((await r.json()) as { error?: typeof env }).error;
} catch {
/* тело без JSON */
}
throw new ApiError(env?.message || "Не удалось загрузить", env?.code || "ERROR", r.status);
}
return await r.json();
},
maxSide: null,
}),
onSuccess: () => qc.invalidateQueries({ queryKey: qk.adminAchievements }),
});
}
+9 -68
View File
@@ -1,7 +1,8 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ApiError, api, unwrap } from "../api/client";
import { api, authProbeRetry, unwrap } from "../api/client";
import { qk } from "../api/queryKeys";
import { uploadFile } from "../lib/upload";
import type { AuthConfig, Me } from "../domain/types";
export function useMe() {
@@ -12,9 +13,7 @@ export function useMe() {
if (r.response.status === 401) return null;
return unwrap(r);
},
// «Нет сессии» — это только 401 (выше, null). Обрыв связи не ответ сервера:
// без повторов гварды принимали бы его за разлогин и уводили на /login.
retry: (count, err) => !(err instanceof ApiError) && count < 2,
retry: authProbeRetry,
});
}
@@ -157,74 +156,16 @@ export function useUpdateHistoryPrefs() {
});
}
// Аватар. Картинку уменьшаем на клиенте (≤512px) и грузим multipart'ом отдельным
// fetch (openapi-fetch неудобен для файлов); CSRF-токен из cookie ставим вручную.
function readCsrfToken(): string | null {
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]*)/);
return m ? decodeURIComponent(m[1]) : null;
}
async function resizeImage(file: File, max = 512): Promise<Blob> {
try {
const dataUrl = await new Promise<string>((res, rej) => {
const fr = new FileReader();
fr.onload = () => res(fr.result as string);
fr.onerror = () => rej(fr.error);
fr.readAsDataURL(file);
});
const img = await new Promise<HTMLImageElement>((res, rej) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = () => rej(new Error("image load failed"));
i.src = dataUrl;
});
let { width, height } = img;
if (width > max || height > max) {
const scale = Math.min(max / width, max / height);
width = Math.round(width * scale);
height = Math.round(height * scale);
}
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
if (!ctx) return file;
ctx.drawImage(img, 0, 0, width, height);
const blob = await new Promise<Blob | null>((res) =>
canvas.toBlob(res, "image/jpeg", 0.85),
);
return blob ?? file;
} catch {
return file; // не вышло уменьшить — отправим как есть (сервер проверит тип/размер)
}
}
// Аватар: картинку уменьшаем на клиенте (≤512px) и грузим общим загрузчиком.
export function useUploadAvatar() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (file: File): Promise<Me> => {
const blob = await resizeImage(file);
const form = new FormData();
form.append("file", blob, "avatar.jpg");
const csrf = readCsrfToken();
const base = import.meta.env.VITE_API_BASE_URL || "";
const r = await fetch(`${base}/api/users/me/avatar`, {
mutationFn: async (file: File): Promise<Me> =>
uploadFile<Me>("/api/users/me/avatar", file, {
method: "PUT",
body: form,
credentials: "include",
headers: csrf ? { "X-CSRF-Token": csrf } : {},
});
if (!r.ok) {
let env: { code?: string; message?: string; details?: unknown } | undefined;
try {
env = ((await r.json()) as { error?: typeof env }).error;
} catch {
/* тело без JSON */
}
throw new ApiError(env?.message || "Не удалось загрузить", env?.code || "ERROR", r.status, env?.details);
}
return (await r.json()) as Me;
},
fieldName: "avatar.jpg",
maxSide: 512,
}),
onSuccess: (me) => {
qc.setQueryData(qk.me, me);
qc.invalidateQueries();
+6 -37
View File
@@ -1,14 +1,9 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ApiError, api, unwrap } from "../api/client";
import { qk } from "../api/queryKeys";
import { api, unwrap } from "../api/client";
import { matchAffectedKeys, qk } from "../api/queryKeys";
import type { FactionRead, MatchCreate, MatchFinish, MatchRead } from "../domain/types";
import { resizeImage } from "../lib/image";
function readCsrfToken(): string | null {
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]*)/);
return m ? decodeURIComponent(m[1]) : null;
}
import { uploadFile } from "../lib/upload";
export function useMatch(matchId: number | null) {
return useQuery({
@@ -62,12 +57,7 @@ export function useFinishMatch() {
qc.invalidateQueries({ queryKey: qk.match(m.id) });
qc.invalidateQueries({ queryKey: qk.groupMatches(m.group_id) });
qc.invalidateQueries({ queryKey: qk.groupStats(m.group_id) });
qc.invalidateQueries({ queryKey: qk.leaderboard });
qc.invalidateQueries({ queryKey: qk.home });
qc.invalidateQueries({ queryKey: qk.myStats });
// Завершённая партия попадает в историю игр и в публичные профили участников.
qc.invalidateQueries({ queryKey: ["userMatches"] });
qc.invalidateQueries({ queryKey: ["publicProfile"] });
for (const key of matchAffectedKeys) qc.invalidateQueries({ queryKey: key });
},
});
}
@@ -93,29 +83,8 @@ export function useDeleteMatch() {
export function useUploadMatchAttachment(matchId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (file: File) => {
const blob = await resizeImage(file);
const form = new FormData();
form.append("file", blob, "photo.jpg");
const csrf = readCsrfToken();
const base = import.meta.env.VITE_API_BASE_URL || "";
const r = await fetch(`${base}/api/matches/${matchId}/attachments`, {
method: "POST",
body: form,
credentials: "include",
headers: csrf ? { "X-CSRF-Token": csrf } : {},
});
if (!r.ok) {
let env: { code?: string; message?: string } | undefined;
try {
env = ((await r.json()) as { error?: typeof env }).error;
} catch {
/* тело без JSON */
}
throw new ApiError(env?.message || "Не удалось загрузить", env?.code || "ERROR", r.status);
}
return await r.json();
},
mutationFn: async (file: File) =>
uploadFile(`/api/matches/${matchId}/attachments`, file),
onSuccess: () => qc.invalidateQueries({ queryKey: qk.match(matchId) }),
});
}
+3 -8
View File
@@ -1,7 +1,7 @@
import { useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import { qk } from "../api/queryKeys";
import { matchAffectedKeys, qk } from "../api/queryKeys";
interface ServerEvent {
type: "match" | "group" | "invitations" | "notifications";
@@ -38,13 +38,8 @@ export function useServerEvents(enabled: boolean) {
qc.invalidateQueries({ queryKey: qk.groupMatches(ev.group_id) });
qc.invalidateQueries({ queryKey: qk.groupStats(ev.group_id) });
}
qc.invalidateQueries({ queryKey: qk.home });
qc.invalidateQueries({ queryKey: qk.leaderboard });
// История игр и публичный профиль тоже меняются от чужой партии: без этих
// двух ключей открытый профиль показывал бы состав до завершения.
qc.invalidateQueries({ queryKey: ["userMatches"] });
qc.invalidateQueries({ queryKey: ["publicProfile"] });
qc.invalidateQueries({ queryKey: qk.myStats });
// История игр и публичные профили тоже меняются от чужой партии.
for (const key of matchAffectedKeys) qc.invalidateQueries({ queryKey: key });
} else if (ev.type === "group") {
if (ev.group_id != null) {
qc.invalidateQueries({ queryKey: qk.group(ev.group_id) });