364 lines
14 KiB
TypeScript
364 lines
14 KiB
TypeScript
"use client";
|
||
|
||
import { Bug } from "lucide-react";
|
||
import { useEffect, useRef, useState } from "react";
|
||
import { Button } from "@/components/ui/button";
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
DialogTrigger,
|
||
} from "@/components/ui/dialog";
|
||
import { captureFeedbackChat } from "@/lib/canvas/feedback-client";
|
||
import { useCanvasStore } from "@/store/canvas";
|
||
import {
|
||
feedbackCommandSchema,
|
||
formatFeedbackTime,
|
||
type FeedbackClient,
|
||
type FeedbackContext,
|
||
type FeedbackReceipt,
|
||
} from "@/lib/canvas/feedback-contract";
|
||
|
||
type Submission = Extract<ReturnType<typeof feedbackCommandSchema.parse>, { action: "submit" }>;
|
||
const terminal = (value: string) => ["sent", "unread", "read", "failed"].includes(value);
|
||
const fieldClass =
|
||
"w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
|
||
|
||
export function CanvasFeedbackDialog({ projectId }: { projectId: string }) {
|
||
const [open, setOpen] = useState(false);
|
||
const [context, setContext] = useState<FeedbackContext | null>(null);
|
||
const [selection, setSelection] = useState<string | null>(null);
|
||
const [description, setDescription] = useState("");
|
||
const [loading, setLoading] = useState(false);
|
||
const [sending, setSending] = useState(false);
|
||
const [sealed, setSealed] = useState(false);
|
||
const [error, setError] = useState("");
|
||
const [receipt, setReceipt] = useState<FeedbackReceipt | null>(null);
|
||
const captured = useRef<FeedbackClient | null>(null);
|
||
const submission = useRef<Submission | null>(null);
|
||
const errors = useRef<string[]>([]);
|
||
const submitLock = useRef(false);
|
||
const endpoint = `/api/canvas/${projectId}/feedback`;
|
||
const storageKey = `canvas-feedback:${projectId}`;
|
||
|
||
useEffect(() => {
|
||
const rememberError = (event: ErrorEvent) => {
|
||
errors.current = [
|
||
...errors.current,
|
||
String(event.message || "页面脚本错误").slice(0, 2000),
|
||
].slice(-5);
|
||
};
|
||
window.addEventListener("error", rememberError);
|
||
return () => window.removeEventListener("error", rememberError);
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
if (!open || receipt) return;
|
||
const controller = new AbortController();
|
||
try {
|
||
const raw = sessionStorage.getItem(storageKey);
|
||
if (raw && !submission.current) {
|
||
const command = feedbackCommandSchema.parse(JSON.parse(raw));
|
||
if (command.action === "submit") {
|
||
submission.current = command;
|
||
captured.current = command.client;
|
||
setSealed(true);
|
||
setDescription(command.description);
|
||
setSelection(command.selection);
|
||
}
|
||
}
|
||
} catch {
|
||
/* An unavailable local draft does not prevent a new feedback report. */
|
||
}
|
||
if (submission.current) {
|
||
void fetch(`${endpoint}?feedbackId=${submission.current.id}`, {
|
||
cache: "no-store",
|
||
signal: controller.signal,
|
||
})
|
||
.then(async (response) => {
|
||
const data = await response.json();
|
||
if (response.ok) setReceipt(data.feedback);
|
||
else if (response.status !== 404)
|
||
setError(data.error || "暂时无法确认反馈状态,请重试提交同一条反馈。");
|
||
})
|
||
.catch(() => {
|
||
if (!controller.signal.aborted) setError("暂时无法确认反馈状态,可重试提交同一条反馈。");
|
||
});
|
||
return () => controller.abort();
|
||
}
|
||
const canvas = useCanvasStore.getState();
|
||
const selectedIds = new Set(canvas.selectedNodeIds);
|
||
const nodes = [...canvas.nodes]
|
||
.sort((a, b) => Number(selectedIds.has(b.id)) - Number(selectedIds.has(a.id)))
|
||
.slice(0, 20);
|
||
const client: FeedbackClient = {
|
||
...captureFeedbackChat(projectId),
|
||
capturedAt: new Date().toISOString(),
|
||
pageVersion: process.env.NEXT_PUBLIC_APP_RELEASE || "development",
|
||
viewport: { width: window.innerWidth, height: window.innerHeight },
|
||
online: navigator.onLine,
|
||
errors: [...errors.current],
|
||
nodes: nodes.map((node) => {
|
||
const data = node.data as unknown as Record<string, unknown>;
|
||
const metadata = data.metadata as Record<string, unknown> | undefined;
|
||
return {
|
||
id: node.id.slice(0, 180),
|
||
type: node.type.slice(0, 64),
|
||
title: String(data.title || "").slice(0, 256),
|
||
status: String(data.status || "").slice(0, 64),
|
||
taskId: String(metadata?.taskId || "").slice(0, 180),
|
||
width: node.size?.width,
|
||
height: node.size?.height,
|
||
};
|
||
}),
|
||
};
|
||
captured.current = client;
|
||
setLoading(true);
|
||
setError("");
|
||
void fetch(endpoint, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ action: "context", client }),
|
||
signal: controller.signal,
|
||
})
|
||
.then(async (response) => {
|
||
const data = await response.json();
|
||
if (!response.ok) throw new Error(data.error || "排查资料暂时加载失败,请重新打开反馈。");
|
||
setContext(data.context);
|
||
setSelection(data.context.requests[0]?.key || null);
|
||
})
|
||
.catch((failure) => {
|
||
if (!controller.signal.aborted)
|
||
setError(failure.message || "排查资料暂时加载失败,请重新打开反馈。");
|
||
})
|
||
.finally(() => {
|
||
if (!controller.signal.aborted) setLoading(false);
|
||
});
|
||
return () => controller.abort();
|
||
}, [open, endpoint, projectId, receipt, storageKey]);
|
||
|
||
useEffect(() => {
|
||
if (!open || !receipt || terminal(receipt.status)) return;
|
||
const controller = new AbortController();
|
||
let timer: ReturnType<typeof setTimeout>;
|
||
const poll = async () => {
|
||
try {
|
||
const response = await fetch(`${endpoint}?feedbackId=${receipt.id}`, {
|
||
cache: "no-store",
|
||
signal: controller.signal,
|
||
});
|
||
const data = await response.json();
|
||
if (response.ok && !controller.signal.aborted) {
|
||
setReceipt(data.feedback);
|
||
setError("");
|
||
} else if (!controller.signal.aborted)
|
||
setError(data.error || "暂时无法刷新通知状态,已保存的反馈会继续处理。");
|
||
} catch {
|
||
if (!controller.signal.aborted)
|
||
setError("网络暂时不可用,已保存的反馈会继续处理,请勿重复提交。");
|
||
}
|
||
if (!controller.signal.aborted) timer = setTimeout(poll, 4000);
|
||
};
|
||
timer = setTimeout(poll, 1500);
|
||
return () => {
|
||
controller.abort();
|
||
clearTimeout(timer);
|
||
};
|
||
}, [open, receipt?.id, receipt?.status, endpoint]);
|
||
|
||
const send = async () => {
|
||
if (submitLock.current || receipt) return;
|
||
if (!submission.current) {
|
||
if (!captured.current || !context) return;
|
||
submission.current = {
|
||
action: "submit",
|
||
id: crypto.randomUUID(),
|
||
description,
|
||
selection,
|
||
client: captured.current,
|
||
};
|
||
try {
|
||
sessionStorage.setItem(storageKey, JSON.stringify(submission.current));
|
||
} catch {
|
||
/* In-memory retries still retain this report's id. */
|
||
}
|
||
}
|
||
submitLock.current = true;
|
||
setSending(true);
|
||
setSealed(true);
|
||
setError("");
|
||
try {
|
||
const response = await fetch(endpoint, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(submission.current),
|
||
signal: AbortSignal.timeout(20000),
|
||
});
|
||
const data = await response.json();
|
||
if (!response.ok) {
|
||
if (response.status === 400 || response.status === 409 || response.status === 413) {
|
||
submission.current = null;
|
||
sessionStorage.removeItem(storageKey);
|
||
setSealed(false);
|
||
}
|
||
throw new Error(data.error || "暂时无法确认反馈是否保存,请重试提交同一条反馈。");
|
||
}
|
||
setReceipt(data.feedback);
|
||
} catch (failure) {
|
||
setError(
|
||
failure instanceof Error && failure.name !== "TimeoutError"
|
||
? failure.message
|
||
: "提交连接超时。请重试提交同一条反馈,系统会核对原编号,避免重复通知。",
|
||
);
|
||
} finally {
|
||
submitLock.current = false;
|
||
setSending(false);
|
||
}
|
||
};
|
||
|
||
const startAnother = () => {
|
||
submission.current = null;
|
||
captured.current = null;
|
||
sessionStorage.removeItem(storageKey);
|
||
setContext(null);
|
||
setDescription("");
|
||
setSelection(null);
|
||
setError("");
|
||
setSealed(false);
|
||
setReceipt(null);
|
||
};
|
||
const selected = context?.requests.find((item) => item.key === selection);
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={setOpen}>
|
||
<DialogTrigger asChild>
|
||
<button
|
||
type="button"
|
||
className="ml-2 inline-flex shrink-0 items-center gap-2 rounded-lg px-3 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
|
||
aria-label="问题反馈"
|
||
>
|
||
<Bug className="size-4" aria-hidden="true" />
|
||
<span className="hidden sm:inline">问题反馈</span>
|
||
</button>
|
||
</DialogTrigger>
|
||
<DialogContent
|
||
className="max-h-[85dvh] overflow-y-auto sm:max-w-xl"
|
||
aria-busy={loading || sending}
|
||
>
|
||
<DialogHeader>
|
||
<DialogTitle>问题反馈</DialogTitle>
|
||
<DialogDescription className="text-pretty">
|
||
自动附上当前画布、用户和相关请求资料。你可以补充问题现象,发送给魔礼红。
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
{receipt ? (
|
||
<div className="space-y-3 py-2" role="status" aria-live="polite">
|
||
<p className="text-sm">{receipt.message}</p>
|
||
<p className="break-all text-sm text-muted-foreground">反馈编号:{receipt.id}</p>
|
||
<a
|
||
href={`/feedback/${receipt.id}`}
|
||
target="_blank"
|
||
rel="noreferrer"
|
||
className="inline-block text-sm underline underline-offset-4"
|
||
>
|
||
查看已保存的完整反馈
|
||
</a>
|
||
</div>
|
||
) : (
|
||
<div className="space-y-4">
|
||
{loading ? (
|
||
<p role="status" className="py-4 text-sm text-muted-foreground">
|
||
正在整理排查资料…
|
||
</p>
|
||
) : context ? (
|
||
<p className="text-sm text-muted-foreground">
|
||
{context.reporter.name} · {context.project.title}
|
||
</p>
|
||
) : null}
|
||
<div className="space-y-2">
|
||
<label htmlFor="canvas-feedback-request" className="text-sm font-medium">
|
||
关联请求
|
||
</label>
|
||
<select
|
||
id="canvas-feedback-request"
|
||
className={fieldClass}
|
||
value={selection || ""}
|
||
disabled={sealed || loading}
|
||
onChange={(event) => setSelection(event.target.value || null)}
|
||
>
|
||
<option value="">页面或画布问题,不关联具体请求</option>
|
||
{context?.requests.map((item) => (
|
||
<option key={item.key} value={item.key}>
|
||
{item.createdAt ? formatFeedbackTime(item.createdAt) : "时间未记录"} ·{" "}
|
||
{item.prompt.slice(0, 45)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
{selected && (
|
||
<div className="space-y-2 rounded-lg bg-muted p-3 text-sm">
|
||
<p>
|
||
请求号:
|
||
<span className="break-all">
|
||
{selected.requestId || "尚未获取,将附上消息编号"}
|
||
</span>
|
||
</p>
|
||
<p className="max-h-28 overflow-y-auto whitespace-pre-wrap break-words text-muted-foreground">
|
||
{selected.prompt}
|
||
</p>
|
||
{selected.error && (
|
||
<p className="whitespace-pre-wrap break-words">{selected.error}</p>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
<div className="space-y-2">
|
||
<label htmlFor="canvas-feedback-description" className="text-sm font-medium">
|
||
补充说明 <span className="font-normal text-muted-foreground">(选填)</span>
|
||
</label>
|
||
<textarea
|
||
id="canvas-feedback-description"
|
||
rows={4}
|
||
maxLength={2000}
|
||
className={`${fieldClass} resize-y`}
|
||
value={description}
|
||
disabled={sealed}
|
||
onChange={(event) => setDescription(event.target.value)}
|
||
placeholder="例如:点击预览后一直加载,等待约 30 秒仍无法查看。"
|
||
/>
|
||
</div>
|
||
<p className="text-xs text-muted-foreground">
|
||
将附上相关请求内容、任务状态、页面版本及已记录的错误;本次反馈不会重新执行任务。
|
||
</p>
|
||
</div>
|
||
)}
|
||
{error && (
|
||
<p role="alert" className="whitespace-pre-wrap text-sm text-destructive">
|
||
{error}
|
||
</p>
|
||
)}
|
||
<DialogFooter className="gap-2 sm:space-x-0">
|
||
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
||
{receipt ? "返回画布" : "取消"}
|
||
</Button>
|
||
{receipt ? (
|
||
<Button type="button" variant="outline" onClick={startAnother}>
|
||
反馈另一个问题
|
||
</Button>
|
||
) : (
|
||
<Button
|
||
type="button"
|
||
onClick={() => void send()}
|
||
disabled={sending || loading || (!context && !submission.current)}
|
||
>
|
||
{sending ? "正在发送…" : sealed ? "重试提交同一反馈" : "发送给魔礼红"}
|
||
</Button>
|
||
)}
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
}
|