291 lines
11 KiB
TypeScript
291 lines
11 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useState, useTransition, useEffect, useRef } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { Label } from "@/components/ui/label";
|
|
import { toast } from "sonner";
|
|
import { updateForm } from "@/app/admin/form/actions";
|
|
import { Loader2, ChevronDown, Check } from "lucide-react";
|
|
import { getGuildRoles } from "@/app/actions/discord";
|
|
import type { DiscordRole } from "@/lib/discord";
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuCheckboxItem,
|
|
DropdownMenuContent,
|
|
DropdownMenuTrigger,
|
|
} from "@/components/ui/dropdown-menu";
|
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
|
import { getErrorMessage } from "@/lib/errors";
|
|
|
|
interface FormExtraClientProps {
|
|
form: {
|
|
id: string;
|
|
discordWebhookUrl: string | null;
|
|
discordWebhookTemplate: string | null;
|
|
discordWebhookUpdateTemplate: string | null;
|
|
allowedRoles?: string[] | null;
|
|
deniedRoles?: string[] | null;
|
|
};
|
|
}
|
|
|
|
type AutoSaveStatus = "idle" | "saving" | "saved";
|
|
|
|
export default function FormExtraClient({ form }: FormExtraClientProps) {
|
|
const router = useRouter();
|
|
const [webhookUrl, setWebhookUrl] = useState(form.discordWebhookUrl || "");
|
|
const [webhookTemplate, setWebhookTemplate] = useState(form.discordWebhookTemplate || "");
|
|
const [webhookUpdateTemplate, setWebhookUpdateTemplate] = useState(form.discordWebhookUpdateTemplate || "");
|
|
|
|
const [allowedRoles, setAllowedRoles] = useState<string[]>(form.allowedRoles || []);
|
|
const [deniedRoles, setDeniedRoles] = useState<string[]>(form.deniedRoles || []);
|
|
const [roles, setRoles] = useState<DiscordRole[]>([]);
|
|
const [loadingRoles, setLoadingRoles] = useState(true);
|
|
|
|
const [, startSaveTransition] = useTransition();
|
|
const [saveStatus, setSaveStatus] = useState<AutoSaveStatus>("idle");
|
|
const [lastEdited, setLastEdited] = useState<"access" | "webhook" | null>(null);
|
|
|
|
const isFirstRender = useRef(true);
|
|
const saveTimeout = useRef<NodeJS.Timeout | null>(null);
|
|
|
|
useEffect(() => {
|
|
getGuildRoles()
|
|
.then(r => setRoles(r))
|
|
.catch(() => toast.error("Failed to load Discord roles."))
|
|
.finally(() => setLoadingRoles(false));
|
|
}, []);
|
|
|
|
const handleSave = useCallback(() => {
|
|
setSaveStatus("saving");
|
|
startSaveTransition(async () => {
|
|
try {
|
|
await updateForm(form.id, {
|
|
discordWebhookUrl: webhookUrl.trim() || null,
|
|
discordWebhookTemplate: webhookTemplate.trim() || null,
|
|
discordWebhookUpdateTemplate: webhookUpdateTemplate.trim() || null,
|
|
allowedRoles,
|
|
deniedRoles,
|
|
});
|
|
setSaveStatus("saved");
|
|
setTimeout(() => setSaveStatus("idle"), 2000);
|
|
router.refresh();
|
|
} catch (err: unknown) {
|
|
setSaveStatus("idle");
|
|
toast.error(getErrorMessage(err, "Failed to update settings."));
|
|
}
|
|
});
|
|
}, [
|
|
allowedRoles,
|
|
deniedRoles,
|
|
form.id,
|
|
router,
|
|
startSaveTransition,
|
|
webhookTemplate,
|
|
webhookUpdateTemplate,
|
|
webhookUrl,
|
|
]);
|
|
|
|
useEffect(() => {
|
|
if (isFirstRender.current) {
|
|
isFirstRender.current = false;
|
|
return;
|
|
}
|
|
|
|
if (saveTimeout.current) clearTimeout(saveTimeout.current);
|
|
|
|
saveTimeout.current = setTimeout(() => {
|
|
handleSave();
|
|
}, 1000);
|
|
|
|
return () => {
|
|
if (saveTimeout.current) clearTimeout(saveTimeout.current);
|
|
};
|
|
}, [handleSave]);
|
|
|
|
const toggleRole = (list: string[], setList: (v: string[]) => void, roleId: string) => {
|
|
setLastEdited("access");
|
|
if (list.includes(roleId)) {
|
|
setList(list.filter(id => id !== roleId));
|
|
} else {
|
|
setList([...list, roleId]);
|
|
}
|
|
};
|
|
|
|
const renderRoleList = (list: string[], setList: (v: string[]) => void, label: string, desc: string) => {
|
|
const selectedRoles = roles.filter(r => list.includes(r.id));
|
|
|
|
return (
|
|
<div className="space-y-2 flex flex-col items-start">
|
|
<Label>{label}</Label>
|
|
<p className="text-sm text-muted-foreground mb-1">{desc}</p>
|
|
{loadingRoles ? (
|
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
|
<Loader2 className="w-4 h-4 animate-spin" /> Loading roles...
|
|
</div>
|
|
) : (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="outline" className="w-full justify-between text-left">
|
|
<div className="flex flex-wrap gap-1">
|
|
{selectedRoles.length > 0 ? (
|
|
selectedRoles.map(role => {
|
|
const colorHex = role.color === 0 ? "#99aab5" : `#${role.color.toString(16).padStart(6, '0')}`;
|
|
return (
|
|
<div
|
|
key={role.id}
|
|
className="inline-flex items-center gap-1.5 rounded px-2 py-0.5 text-xs font-medium border"
|
|
style={{
|
|
backgroundColor: `${colorHex}1a`,
|
|
borderColor: `${colorHex}33`,
|
|
color: colorHex
|
|
}}
|
|
>
|
|
<div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: colorHex }} />
|
|
@{role.name}
|
|
</div>
|
|
);
|
|
})
|
|
) : (
|
|
<span className="text-muted-foreground my-auto">Select roles...</span>
|
|
)}
|
|
</div>
|
|
<ChevronDown className="w-4 h-4 opacity-50" />
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent className="w-64 p-0">
|
|
<ScrollArea className="h-72 max-h-[calc(var(--radix-dropdown-menu-content-available-height)-2rem)]">
|
|
<div className="p-1">
|
|
{roles.map(role => {
|
|
const colorHex = role.color === 0 ? "#99aab5" : `#${role.color.toString(16).padStart(6, '0')}`;
|
|
return (
|
|
<DropdownMenuCheckboxItem
|
|
key={role.id}
|
|
checked={list.includes(role.id)}
|
|
onCheckedChange={() => toggleRole(list, setList, role.id)}
|
|
onSelect={(e) => e.preventDefault()}
|
|
>
|
|
<div className="flex items-center gap-2">
|
|
<div className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: colorHex }} />
|
|
<span className="text-sm">{role.name}</span>
|
|
</div>
|
|
</DropdownMenuCheckboxItem>
|
|
);
|
|
})}
|
|
{roles.length === 0 && (
|
|
<div className="p-2 text-sm text-muted-foreground text-center">No roles found.</div>
|
|
)}
|
|
</div>
|
|
</ScrollArea>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<Card>
|
|
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4">
|
|
<div className="space-y-1">
|
|
<CardTitle>Access Control</CardTitle>
|
|
<CardDescription>
|
|
Restrict form access to specific Discord roles.
|
|
</CardDescription>
|
|
</div>
|
|
<SaveStatusIndicator status={lastEdited === "access" ? saveStatus : "idle"} />
|
|
</CardHeader>
|
|
<CardContent className="space-y-6">
|
|
{renderRoleList(
|
|
allowedRoles,
|
|
setAllowedRoles,
|
|
"Allowed Roles",
|
|
"Users must have at least one of these roles to access the form. Leave empty to allow all."
|
|
)}
|
|
{renderRoleList(
|
|
deniedRoles,
|
|
setDeniedRoles,
|
|
"Denied Roles",
|
|
"Users with any of these roles will be blocked from accessing the form, even if they have an allowed role."
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4">
|
|
<div className="space-y-1">
|
|
<CardTitle>Discord Webhook</CardTitle>
|
|
<CardDescription>
|
|
Send notifications to a Discord channel when a new submission is received.
|
|
Leave URL empty to disable.
|
|
</CardDescription>
|
|
</div>
|
|
<SaveStatusIndicator status={lastEdited === "webhook" ? saveStatus : "idle"} />
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="webhook-url">Webhook URL</Label>
|
|
<Input
|
|
id="webhook-url"
|
|
value={webhookUrl}
|
|
onChange={(e) => { setLastEdited("webhook"); setWebhookUrl(e.target.value); }}
|
|
placeholder="https://discord.com/api/webhooks/..."
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="webhook-template">New Submission</Label>
|
|
<Textarea
|
|
id="webhook-template"
|
|
value={webhookTemplate}
|
|
onChange={(e) => { setLastEdited("webhook"); setWebhookTemplate(e.target.value); }}
|
|
placeholder="New submission received from {Name} for skill: {skill}!"
|
|
className="min-h-24"
|
|
/>
|
|
<p className="text-sm text-muted-foreground">
|
|
Use <code>{`{1}`}</code>, <code>{`{2}`}</code> to insert answers according to question order, and <code>{`{username}`}</code>, <code>{`{displayname}`}</code>, <code>{`{id}`}</code> for user info.
|
|
</p>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="webhook-update-template">Update Submission</Label>
|
|
<Textarea
|
|
id="webhook-update-template"
|
|
value={webhookUpdateTemplate}
|
|
onChange={(e) => { setLastEdited("webhook"); setWebhookUpdateTemplate(e.target.value); }}
|
|
placeholder="Submission updated by {Name} for skill: {skill}!"
|
|
className="min-h-24"
|
|
/>
|
|
<p className="text-sm text-muted-foreground">
|
|
Used when a user updates their existing submission. Use <code>{`{1}`}</code>, <code>{`{2}`}</code> for answers, <code>{`{update}`}</code> to show what was changed, and <code>{`{username}`}</code>, <code>{`{displayname}`}</code>, <code>{`{id}`}</code> for user info.
|
|
</p>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function SaveStatusIndicator({ status }: { status: AutoSaveStatus }) {
|
|
if (status === "idle") return null;
|
|
|
|
return (
|
|
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
|
{status === "saving" && (
|
|
<>
|
|
<Loader2 className="w-3 h-3 animate-spin" />
|
|
Saving...
|
|
</>
|
|
)}
|
|
{status === "saved" && (
|
|
<>
|
|
<Check className="w-3 h-3 text-green-500" />
|
|
Saved
|
|
</>
|
|
)}
|
|
</span>
|
|
);
|
|
}
|