Files
erika/app/admin/form/[id]/result/[submissionId]/client.tsx
T

460 lines
16 KiB
TypeScript

"use client";
import React, { useCallback, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
Field,
FieldDescription,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
import {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuItem,
ContextMenuGroup
} from "@/components/ui/context-menu";
import {
AlertCircle,
Calendar,
Check,
Clock,
Copy,
Loader2,
Users,
} from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import Image from 'next/image';
import { stripHtml } from "@/lib/utils";
import { HtmlDisplay } from "@/components/html-display";
import { formatStoredAnswer } from "@/lib/form-answer-values";
import { normalizeStoredAnswerSnapshot } from "@/lib/submission-intake";
import { updateSubmissionAdminNote } from "@/app/admin/form/actions";
import {
useDebouncedAutoSave,
type AutoSaveStatus,
} from "@/hooks/use-debounced-autosave";
import {
DiscordProfileDropdown,
type DiscordMemberProfile,
} from "@/components/dropdown-menu-avatar";
interface Question {
id: string;
label: string;
type: string;
imageUrl: string | null;
}
interface SubmissionDetailClientProps {
submission: {
id: string;
formId: string;
userName: string | null;
userDiscordId: string | null;
userProfile: DiscordMemberProfile | null;
submittedAt: Date;
adminNote: string | null;
editHistory?: { editedAt: string; oldAnswers: Record<string, string | { value: string; imageCdnId: string | null }> }[] | null;
};
questions: Question[];
answers: Record<string, { value: string; imageCdnId: string | null }>;
}
export default function SubmissionDetailClient({
submission,
questions,
answers,
}: SubmissionDetailClientProps) {
const [copiedId, setCopiedId] = useState<string | null>(null);
const [adminNote, setAdminNote] = useState(submission.adminNote ?? "");
const handleCopy = (text: string, id: string) => {
if (!text) return;
navigator.clipboard.writeText(text);
setCopiedId(id);
setTimeout(() => setCopiedId(null), 2000);
};
const userLabel = submission.userName
? `${submission.userName} (${submission.userDiscordId || "N/A"})`
: submission.userDiscordId || "Anonymous";
const editHistory = Array.isArray(submission.editHistory) ? submission.editHistory : [];
const saveAdminNote = useCallback(
() =>
updateSubmissionAdminNote(
submission.formId,
submission.id,
adminNote
).then(() => undefined),
[adminNote, submission.formId, submission.id]
);
const noteAutoSave = useDebouncedAutoSave({
save: saveAdminNote,
delay: 1000,
});
return (
<div className="space-y-6">
{/* Submission Metadata Card */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-xl">Submission Info</CardTitle>
<CardDescription>Details about this respondent.</CardDescription>
</CardHeader>
<CardContent className="grid gap-2 text-sm">
<div className="flex flex-wrap items-center gap-2 text-muted-foreground">
<Users className="w-4 h-4 shrink-0" />
<span className="font-semibold text-foreground">Respondent:</span>
<span>{userLabel}</span>
{submission.userProfile?.globalName && (
<DiscordProfileDropdown
userName={submission.userName || submission.userProfile.username}
profile={submission.userProfile}
>
<button
type="button"
className="cursor-pointer rounded-sm bg-[#5865f2]/30 px-1 font-medium text-[#c9cdfb] transition-colors hover:bg-[#5865f2] hover:text-white"
aria-label={`View Discord profile for ${submission.userProfile.globalName}`}
>
@{submission.userProfile.globalName}
</button>
</DiscordProfileDropdown>
)}
</div>
<div className="flex items-center gap-2 text-muted-foreground">
<Calendar className="w-4 h-4 shrink-0" />
<span className="font-semibold text-foreground">Initial Submission:</span>
<span>{new Date(submission.submittedAt).toLocaleString("en-GB", { timeZone: "Asia/Bangkok", hour12: false })}</span>
</div>
{editHistory.length > 0 && (
<div className="flex flex-col mt-2 pt-2 border-t">
<span className="font-semibold text-foreground mb-1">Edit History:</span>
<ul className="list-disc list-inside text-xs text-muted-foreground space-y-1">
{editHistory.map((edit, idx) => (
<li key={idx}>Edited at {new Date(edit.editedAt).toLocaleString("en-GB", { timeZone: "Asia/Bangkok", hour12: false })}</li>
))}
</ul>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Admin note</CardTitle>
<CardDescription>
Private context for administrators. Respondents cannot see this note.
</CardDescription>
</CardHeader>
<CardContent>
<FieldGroup>
<Field data-invalid={noteAutoSave.status === "error"}>
<FieldLabel htmlFor="admin-note">Note</FieldLabel>
<Textarea
id="admin-note"
value={adminNote}
onChange={(event) => {
setAdminNote(event.target.value);
noteAutoSave.schedule();
}}
placeholder="Add a private note about this submission..."
maxLength={10_000}
aria-invalid={noteAutoSave.status === "error"}
/>
<FieldDescription>
Autosaves after you stop typing. Only administrators can view
this note.
</FieldDescription>
<SaveStatusIndicator
status={noteAutoSave.status}
error={noteAutoSave.error}
onRetry={noteAutoSave.retry}
/>
</Field>
</FieldGroup>
</CardContent>
</Card>
{/* Answers List */}
<div className="space-y-4">
{questions.map((q) => {
const rawAnswer = answers[q.id] ?? { value: "", imageCdnId: null };
const rawAnswerValue = rawAnswer.value;
const answerValue = formatStoredAnswer(rawAnswerValue, q.type);
const imageUrl = rawAnswer.imageCdnId ? `/cdn/${rawAnswer.imageCdnId}` : "";
const wasEdited = editHistory.some(
(edit) => {
const oldSnapshot = normalizeStoredAnswerSnapshot(edit.oldAnswers[q.id]);
return oldSnapshot.value !== rawAnswerValue || oldSnapshot.imageCdnId !== rawAnswer.imageCdnId;
}
);
const qAnswerHistory = editHistory.map((edit) => ({
editedAt: edit.editedAt,
answer: (() => {
const snapshot = normalizeStoredAnswerSnapshot(edit.oldAnswers[q.id]);
const text = formatStoredAnswer(snapshot.value, q.type);
return text || (snapshot.imageCdnId ? `/cdn/${snapshot.imageCdnId}` : "");
})(),
}));
return (
<ContextMenu key={q.id}>
<ContextMenuTrigger asChild>
<Card
className={wasEdited ? "cursor-context-menu" : ""}
>
<CardHeader className="pb-3 flex flex-row items-start justify-between space-y-0 gap-4">
<div className="space-y-1">
<div className="text-base font-semibold leading-normal">
<HtmlDisplay html={q.label} />
</div>
{wasEdited && (
<Dialog>
<DialogTrigger asChild>
<Button variant="outline" size="sm">View history</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Answer history</DialogTitle>
<DialogDescription>
Previous values for {stripHtml(q.label)}
</DialogDescription>
</DialogHeader>
<ScrollArea className="max-h-72">
<div className="flex flex-col gap-3 pr-4">
{qAnswerHistory.map((entry, idx) => (
<div key={idx} className="flex flex-col gap-1 text-sm">
<span className="text-xs text-muted-foreground">
{new Date(entry.editedAt).toLocaleString("en-GB", {
timeZone: "Asia/Bangkok",
hour12: false,
})}
</span>
<span className="whitespace-pre-wrap">
{entry.answer || "No response"}
</span>
</div>
))}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
)}
</div>
{q.imageUrl && (
<div className="relative w-24 h-24 overflow-hidden rounded-md border shrink-0">
<Image
src={q.imageUrl}
alt="Question image"
fill
unoptimized
className="object-cover"
/>
</div>
)}
</CardHeader>
<CardContent className="flex flex-col gap-4">
{answerValue && (
<div className="flex items-start justify-between gap-4 p-3 bg-muted rounded-md group">
<div className="flex flex-col min-w-0">
{wasEdited && (
<span className="text-xs font-semibold text-muted-foreground mb-1">
Current Answer:
</span>
)}
<span className="text-sm whitespace-pre-wrap break-all leading-relaxed">
{answerValue}
</span>
</div>
<Button
variant="ghost"
size="icon"
className="shrink-0 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 sm:group-focus-within:opacity-100"
onClick={() => handleCopy(answerValue, q.id)}
aria-label={`Copy answer for ${stripHtml(q.label)}`}
>
{copiedId === q.id ? (
<Check />
) : (
<Copy />
)}
</Button>
</div>
)}
{imageUrl && (
<AnswerImagePreview src={imageUrl} label={stripHtml(q.label)} />
)}
{!answerValue && !imageUrl && (
<span className="text-sm text-muted-foreground italic pl-3 border-l-2 border-muted block">
No response provided
</span>
)}
</CardContent>
</Card>
</ContextMenuTrigger>
{wasEdited && (
<ContextMenuContent className="w-72 max-w-sm">
<ContextMenuLabel className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
History
</ContextMenuLabel>
<ContextMenuLabel className="text-sm font-medium text-foreground truncate pb-2">
{stripHtml(q.label)}
</ContextMenuLabel>
<ContextMenuSeparator />
<ContextMenuLabel className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-1">
Previous Answers:
</ContextMenuLabel>
{qAnswerHistory.length === 0 ? (
<ContextMenuItem disabled className="text-xs text-muted-foreground italic">
No edit history for this question.
</ContextMenuItem>
) : (
<ScrollArea className="h-72">
<ContextMenuGroup>
{qAnswerHistory.map((entry, idx) => (
<ContextMenuItem
key={idx}
className="flex flex-col items-start gap-1 p-2 focus:bg-transparent cursor-default"
>
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Clock className="w-3 h-3 shrink-0" />
<span>{new Date(entry.editedAt).toLocaleString("en-GB", { timeZone: "Asia/Bangkok", hour12: false })}</span>
</div>
<span className="text-sm text-foreground/80 whitespace-pre-wrap leading-relaxed">
{entry.answer || <span className="italic text-muted-foreground">No response</span>}
</span>
</ContextMenuItem>
))}
</ContextMenuGroup>
</ScrollArea>
)}
</ContextMenuContent>
)}
</ContextMenu>
);
})}
</div>
</div>
);
}
function SaveStatusIndicator({
status,
error,
onRetry,
}: {
status: AutoSaveStatus;
error: string | null;
onRetry: () => Promise<void>;
}) {
if (status === "clean") return null;
return (
<span
className="flex items-center gap-1.5 text-xs text-muted-foreground"
aria-live="polite"
>
{status === "dirty" && "Unsaved"}
{status === "saving" && (
<>
<Loader2 className="animate-spin" />
Saving
</>
)}
{status === "saved" && (
<>
<Check />
Saved
</>
)}
{status === "error" && (
<>
<AlertCircle />
<span>{error || "Could not save the note."}</span>
<Button
type="button"
variant="link"
size="sm"
className="h-auto px-1"
onClick={() => void onRetry().catch(() => undefined)}
>
Retry
</Button>
</>
)}
</span>
);
}
function AnswerImagePreview({ src, label }: { src: string; label: string }) {
const [unavailable, setUnavailable] = useState(false);
if (unavailable) {
return (
<span className="text-sm text-muted-foreground italic">
Image unavailable
</span>
);
}
return (
<Dialog>
<DialogTrigger asChild>
<Button
type="button"
variant="outline"
className="h-auto w-fit p-2"
aria-label={`Open image answer for ${label}`}
>
<Image
src={src}
alt=""
width={224}
height={160}
unoptimized
className="max-h-40 max-w-56 rounded object-contain"
onError={() => setUnavailable(true)}
/>
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle>Image answer</DialogTitle>
<DialogDescription>{label}</DialogDescription>
</DialogHeader>
<Image
src={src}
alt=""
width={1200}
height={800}
unoptimized
className="max-h-[70vh] w-full rounded-md object-contain"
onError={() => setUnavailable(true)}
/>
</DialogContent>
</Dialog>
);
}