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

413 lines
15 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,
} from "@/components/ui/field";
import {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuItem,
ContextMenuGroup
} from "@/components/ui/context-menu";
import {
Calendar,
Check,
Clock,
Copy,
ExternalLink,
Maximize2,
Users,
} from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
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/form-answer-values";
import { normalizeStoredAnswerSnapshot } from "@/lib/form/submission-intake";
import { updateSubmissionAdminNote } from "@/app/admin/form/actions";
import {
useDebouncedAutoSave,
} from "@/hooks/use-debounced-autosave";
import {
DiscordProfileDropdown,
type DiscordMemberProfile,
} from "@/components/avatar";
import { SaveStatusIndicator } from "@/components/save-status-indicator";
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 bg-primary/15 px-1 font-medium text-primary transition-colors hover:bg-primary hover:text-primary-foreground"
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>Note</CardTitle>
</CardHeader>
<CardContent>
<FieldGroup>
<Field data-invalid={noteAutoSave.status === "error"}>
<Textarea
id="admin-note"
value={adminNote}
onChange={(event) => {
setAdminNote(event.target.value);
noteAutoSave.schedule();
}}
placeholder="This kinda sigma"
aria-invalid={noteAutoSave.status === "error"}
/>
<FieldDescription>
Autosaves after you stop typing.
</FieldDescription>
<SaveStatusIndicator
status={noteAutoSave.status}
error={noteAutoSave.error}
onRetry={noteAutoSave.retry}
fallbackError="Could not save the note."
/>
</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 size-24 shrink-0 overflow-hidden border">
<Image
src={q.imageUrl}
alt="Question image"
fill
unoptimized
className="object-cover"
/>
</div>
)}
</CardHeader>
<CardContent className="flex flex-col gap-4">
{answerValue && (
<div className="group flex items-start justify-between gap-4 bg-muted p-3">
<div className="flex flex-col min-w-0">
<span className="text-sm whitespace-pre-wrap break-all">
{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 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="group/image relative h-auto w-fit p-2"
aria-label={`Open image answer for ${label}`}
>
<Image
src={src}
alt={`${label} image answer`}
width={224}
height={160}
unoptimized
className="max-h-40 max-w-56 rounded object-contain"
onError={() => setUnavailable(true)}
/>
<span className="absolute right-3 bottom-3 bg-background/90 p-1.5 opacity-0 shadow-sm transition-opacity group-hover/image:opacity-100 group-focus-visible/image:opacity-100">
<Maximize2 />
</span>
</Button>
</DialogTrigger>
<DialogContent className="max-h-[calc(100vh-2rem)] max-w-[calc(100vw-2rem)] sm:max-w-[calc(100vw-4rem)]">
<DialogHeader>
<DialogTitle>Image answer</DialogTitle>
<DialogDescription>{label}</DialogDescription>
</DialogHeader>
<Image
src={src}
alt={`${label} image answer`}
width={1920}
height={1080}
unoptimized
className="max-h-[calc(100vh-10rem)] w-full object-contain"
onError={() => setUnavailable(true)}
/>
<DialogFooter>
<Button asChild variant="outline">
<a href={src} target="_blank" rel="noopener noreferrer">
<ExternalLink data-icon="inline-start" />
Open original
</a>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}