peppa/apps/web/components/FeedbackButton.tsx

284 lines
13 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 Link from "@/components/Link";
import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { CircleCheck, ImagePlus, MessageCircleWarning, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { useT } from "@/components/I18n";
import { cn } from "@/lib/utils";
const MAX_SHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;
const TYPES = ["image/png", "image/jpeg", "image/webp"];
interface Shot {
file: File;
url: string;
}
/**
* PEP-143: «Сообщить о проблеме» on every page — text plus up to five screenshots (file picker,
* drag and drop, paste from the clipboard). The page address, the window size and the page's
* last browser errors go along by themselves.
*/
export function FeedbackButton() {
const t = useT();
const path = usePathname();
const inChat = /^\/chats\/[^/]+/.test(path ?? "");
const dialog = useRef<HTMLDialogElement>(null);
const picker = useRef<HTMLInputElement>(null);
const [text, setText] = useState("");
const [shots, setShots] = useState<Shot[]>([]);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [sent, setSent] = useState(false);
const [over, setOver] = useState(false);
const lift = useComposerLift(inChat);
const add = useCallback(
(files: Iterable<File>) => {
setError(null);
setShots((cur) => {
const next = [...cur];
for (const file of files) {
if (!TYPES.includes(file.type)) {
setError(t("Файл не похож на картинку. Приложите скриншот в формате PNG, JPEG или WebP."));
continue;
}
if (file.size > MAX_BYTES) {
setError(t("Скриншот больше 5 МБ. Приложите файл поменьше."));
continue;
}
if (next.length >= MAX_SHOTS) {
setError(t("Можно приложить не больше {n} скриншотов.", { n: MAX_SHOTS }));
break;
}
next.push({ file, url: URL.createObjectURL(file) });
}
return next;
});
},
[t],
);
const remove = (i: number) =>
setShots((cur) => {
URL.revokeObjectURL(cur[i]!.url);
return cur.filter((_, j) => j !== i);
});
const reset = () => {
shots.forEach((s) => URL.revokeObjectURL(s.url));
setShots([]);
setText("");
setError(null);
setSent(false);
};
const open = () => {
if (sent) reset();
dialog.current?.showModal();
};
// Ctrl+V anywhere in the open form: a picture from the clipboard becomes a screenshot.
useEffect(() => {
const onPaste = (e: ClipboardEvent) => {
if (!dialog.current?.open) return;
const files = [...(e.clipboardData?.files ?? [])].filter((f) => f.type.startsWith("image/"));
if (!files.length) return;
e.preventDefault();
add(files);
};
window.addEventListener("paste", onPaste);
return () => window.removeEventListener("paste", onPaste);
}, [add]);
const submit = async () => {
if (!text.trim() && !shots.length) return setError(t("Напишите, что случилось, или приложите скриншот."));
setBusy(true);
setError(null);
try {
const form = new FormData();
form.set("text", text);
const errors = (window as unknown as { __peppaErrors?: unknown[] }).__peppaErrors ?? [];
form.set("context", JSON.stringify({ url: location.pathname + location.search, viewport: `${window.innerWidth}x${window.innerHeight}`, errors }));
shots.forEach((s) => form.append("shots", s.file, "screenshot"));
const res = await fetch("/api/feedback", { method: "POST", body: form });
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string };
if (!res.ok || !body.ok) return setError(body.error ?? t("Не получилось отправить. Проверьте интернет и попробуйте ещё раз."));
setSent(true);
} catch {
setError(t("Не получилось отправить. Проверьте интернет и попробуйте ещё раз."));
} finally {
setBusy(false);
}
};
return (
<>
<button
type="button"
onClick={open}
data-feedback-open
// Sits above the «в реальном времени» indicator of LiveRefresh (the same corner).
title={t("Сообщить о проблеме")}
aria-label={t("Сообщить о проблеме")}
style={lift != null ? { bottom: lift } : undefined}
className={cn(
"fixed right-3 z-30 flex h-11 min-w-11 justify-center cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground",
// PEP-207: in a conversation the message field is pinned to the bottom — the button goes above it, icon only.
inChat ? "bottom-[calc(11rem+env(safe-area-inset-bottom))] md:bottom-32" : "bottom-[calc(6.5rem+env(safe-area-inset-bottom))] md:bottom-12",
)}
>
<MessageCircleWarning className="size-5" />
{!inChat && <span className="hidden md:inline">{t("Сообщить о проблеме")}</span>}
</button>
<dialog
ref={dialog}
aria-label={t("Сообщить о проблеме")}
onClick={(e) => e.target === dialog.current && dialog.current.close()}
className="m-auto w-[520px] max-w-[calc(100vw-1.5rem)] rounded-xl border bg-card p-0 text-foreground backdrop:bg-black/50"
>
<div className="flex flex-col gap-4 p-5">
<div className="flex items-center gap-2">
<h2 className="m-0 text-[15px] font-semibold">{t("Сообщить о проблеме")}</h2>
<Button variant="ghost" size="icon-sm" className="ml-auto" aria-label={t("Закрыть")} onClick={() => dialog.current?.close()}>
<X />
</Button>
</div>
{sent ? (
<div className="flex flex-col items-start gap-3" data-feedback-sent>
<p className="m-0 flex items-center gap-2 font-medium">
<CircleCheck className="size-5 text-primary" />
{/* glossary-ignore: «команда» here is the team of people, not a terminal command */}
{t("Спасибо, передали команде")}
</p>
<p className="m-0 text-sm text-muted-foreground">{t("Мы разберём обращение и напишем вам, когда всё исправим. Статус виден в списке ваших обращений.")}</p>
<div className="flex flex-wrap gap-2">
<Button asChild variant="default" size="sm">
<Link href="/feedback" onClick={() => dialog.current?.close()}>
{t("Ваши обращения")}
</Link>
</Button>
<Button size="sm" onClick={reset}>
{t("Сообщить ещё об одной")}
</Button>
</div>
</div>
) : (
<>
<p className="m-0 text-sm text-muted-foreground">{t("Напишите, что случилось, и приложите скриншот. Обращение увидят те, кто делает FORGE, — мы разберёмся и ответим вам.")}</p>
<Textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} maxLength={4000} autoFocus placeholder={t("Что случилось? Что вы делали и что ожидали увидеть?")} aria-label={t("Что случилось")} />
<div
onDragOver={(e) => (e.preventDefault(), setOver(true))}
onDragLeave={() => setOver(false)}
onDrop={(e) => {
e.preventDefault();
setOver(false);
add(e.dataTransfer.files);
}}
className={cn("flex flex-col gap-3 rounded-lg border border-dashed p-3 text-sm text-muted-foreground transition-colors", over && "border-primary bg-primary/5")}
>
{shots.length > 0 && (
<ul className="m-0 flex list-none flex-wrap gap-2 p-0">
{shots.map((s, i) => (
<li key={s.url} className="relative">
<img src={s.url} alt={t("Скриншот {n}", { n: i + 1 })} className="size-20 rounded-md border object-cover" />
<button type="button" onClick={() => remove(i)} aria-label={t("Убрать скриншот {n}", { n: i + 1 })} className="absolute -top-1.5 -right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-full border bg-card text-foreground shadow-sm">
<X className="size-3" />
</button>
</li>
))}
</ul>
)}
<div className="flex flex-wrap items-center gap-2">
<Button size="sm" onClick={() => picker.current?.click()} disabled={shots.length >= MAX_SHOTS}>
<ImagePlus />
{t("Приложить скриншот")}
</Button>
<span className="text-xs">{t("Можно перетащить файл сюда или вставить из буфера (Ctrl+V). До {n} скриншотов.", { n: MAX_SHOTS })}</span>
</div>
<input
ref={picker}
type="file"
accept={TYPES.join(",")}
multiple
hidden
onChange={(e) => {
add(e.target.files ?? []);
e.target.value = "";
}}
/>
</div>
<p className="m-0 text-xs text-muted-foreground">{t("Вместе с обращением мы получим адрес страницы «{path}» и сведения о браузере — так проблему проще найти.", { path })}</p>
{error && (
<p role="alert" className="m-0 text-sm text-destructive">
{error}
</p>
)}
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => dialog.current?.close()}>
{t("Отмена")}
</Button>
<Button variant="default" onClick={submit} disabled={busy}>
{busy ? t("Отправляем…") : t("Отправить")}
</Button>
</div>
</>
)}
</div>
</dialog>
</>
);
}
/**
* PEP-274 (F-12): in a conversation the button stays above the top edge of the message field,
* however tall the field grew (lines, attached files) — measured, not a fixed height that the
* field outgrows on a phone. `null` — no field on the page, the classes place the button.
*/
function useComposerLift(inChat: boolean): number | null {
const [lift, setLift] = useState<number | null>(null);
useEffect(() => {
if (!inChat) return setLift(null);
let frame = 0;
let observed: Element | null = null;
const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => schedule());
const measure = () => {
frame = 0;
const box = document.querySelector("[data-chat-composer]");
if (box !== observed) {
if (observed) ro?.unobserve(observed);
if (box) ro?.observe(box);
observed = box;
}
if (!box) return setLift(null);
const top = box.getBoundingClientRect().top;
const viewport = window.visualViewport?.height ?? window.innerHeight;
// 8 px above the field; never under the bottom menu if the field scrolled out of view.
setLift(Math.max(Math.round(viewport - top + 8), 72));
};
const schedule = () => {
if (!frame) frame = requestAnimationFrame(measure);
};
schedule();
window.addEventListener("resize", schedule);
window.addEventListener("scroll", schedule, { passive: true, capture: true });
window.visualViewport?.addEventListener("resize", schedule);
// The page re-renders on live updates and may replace the field.
const mo = new MutationObserver(schedule);
mo.observe(document.body, { childList: true, subtree: true });
return () => {
if (frame) cancelAnimationFrame(frame);
ro?.disconnect();
mo.disconnect();
window.removeEventListener("resize", schedule);
window.removeEventListener("scroll", schedule, { capture: true });
window.visualViewport?.removeEventListener("resize", schedule);
};
}, [inChat]);
return lift;
}