455 lines
16 KiB
TypeScript
455 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useState, 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 { testDiscordWebhook, updateForm } from "@/app/admin/form/actions";
|
|
import { Loader2, ChevronDown, Check, AlertCircle, Send } from "lucide-react";
|
|
import { getGuildRoles } from "@/app/actions/discord";
|
|
import type { DiscordRole } from "@/lib/discord/discord";
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuCheckboxItem,
|
|
DropdownMenuContent,
|
|
DropdownMenuTrigger,
|
|
} from "@/components/ui/dropdown-menu";
|
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
|
import { getErrorMessage } from "@/lib/utils";
|
|
import {
|
|
isValidDiscordWebhookUrl,
|
|
previewWebhookTemplate,
|
|
} from "@/lib/discord/discord-webhook-settings";
|
|
import {
|
|
useDebouncedAutoSave,
|
|
type AutoSaveStatus,
|
|
} from "@/hooks/use-debounced-autosave";
|
|
import { Badge } from "@/components/ui/badge";
|
|
|
|
interface FormExtraClientProps {
|
|
form: {
|
|
id: string;
|
|
discordWebhookUrl: string | null;
|
|
discordWebhookTemplate: string | null;
|
|
discordWebhookUpdateTemplate: string | null;
|
|
allowedRoles?: string[] | null;
|
|
deniedRoles?: string[] | null;
|
|
};
|
|
}
|
|
|
|
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 [roleSearch, setRoleSearch] = useState("");
|
|
|
|
const [lastEdited, setLastEdited] = useState<"access" | "webhook" | null>(null);
|
|
const [testingWebhook, setTestingWebhook] = useState(false);
|
|
|
|
const valuesRef = useRef({
|
|
webhookUrl,
|
|
webhookTemplate,
|
|
webhookUpdateTemplate,
|
|
allowedRoles,
|
|
deniedRoles,
|
|
});
|
|
|
|
useEffect(() => {
|
|
getGuildRoles()
|
|
.then(r => setRoles(r))
|
|
.catch(() => toast.error("Failed to load Discord roles."))
|
|
.finally(() => setLoadingRoles(false));
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
valuesRef.current = {
|
|
webhookUrl,
|
|
webhookTemplate,
|
|
webhookUpdateTemplate,
|
|
allowedRoles,
|
|
deniedRoles,
|
|
};
|
|
}, [
|
|
allowedRoles,
|
|
deniedRoles,
|
|
webhookTemplate,
|
|
webhookUpdateTemplate,
|
|
webhookUrl,
|
|
]);
|
|
|
|
const saveSettings = useCallback(async () => {
|
|
const values = valuesRef.current;
|
|
await updateForm(form.id, {
|
|
discordWebhookUrl: values.webhookUrl.trim() || null,
|
|
discordWebhookTemplate: values.webhookTemplate.trim() || null,
|
|
discordWebhookUpdateTemplate: values.webhookUpdateTemplate.trim() || null,
|
|
allowedRoles: values.allowedRoles,
|
|
deniedRoles: values.deniedRoles,
|
|
});
|
|
router.refresh();
|
|
}, [form.id, router]);
|
|
|
|
const autoSave = useDebouncedAutoSave({ save: saveSettings, delay: 1000 });
|
|
|
|
const markEdited = (section: "access" | "webhook") => {
|
|
setLastEdited(section);
|
|
autoSave.schedule();
|
|
};
|
|
|
|
const toggleRole = (kind: "allowed" | "denied", roleId: string) => {
|
|
const list = kind === "allowed" ? allowedRoles : deniedRoles;
|
|
const nextList = list.includes(roleId)
|
|
? list.filter((id) => id !== roleId)
|
|
: [...list, roleId];
|
|
if (kind === "allowed") {
|
|
const nextDenied = deniedRoles.filter((id) => id !== roleId);
|
|
setAllowedRoles(nextList);
|
|
setDeniedRoles(nextDenied);
|
|
valuesRef.current = {
|
|
...valuesRef.current,
|
|
allowedRoles: nextList,
|
|
deniedRoles: nextDenied,
|
|
};
|
|
} else {
|
|
const nextAllowed = allowedRoles.filter((id) => id !== roleId);
|
|
setDeniedRoles(nextList);
|
|
setAllowedRoles(nextAllowed);
|
|
valuesRef.current = {
|
|
...valuesRef.current,
|
|
allowedRoles: nextAllowed,
|
|
deniedRoles: nextList,
|
|
};
|
|
}
|
|
markEdited("access");
|
|
};
|
|
|
|
const renderRoleList = (kind: "allowed" | "denied", list: string[], 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">
|
|
<div className="p-1">
|
|
<Input
|
|
value={roleSearch}
|
|
onChange={(event) => setRoleSearch(event.target.value)}
|
|
onKeyDown={(event) => event.stopPropagation()}
|
|
placeholder="Search roles"
|
|
aria-label={`Search ${label.toLowerCase()}`}
|
|
/>
|
|
</div>
|
|
{roles.filter((role) =>
|
|
role.name.toLowerCase().includes(roleSearch.toLowerCase())
|
|
).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(kind, 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.filter((role) =>
|
|
role.name.toLowerCase().includes(roleSearch.toLowerCase())
|
|
).length === 0 && (
|
|
<div className="p-2 text-sm text-muted-foreground text-center">No roles found.</div>
|
|
)}
|
|
</div>
|
|
</ScrollArea>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const webhookUrlValid =
|
|
!webhookUrl.trim() || isValidDiscordWebhookUrl(webhookUrl.trim());
|
|
|
|
const insertVariable = (
|
|
variable: string,
|
|
target: "new" | "update"
|
|
) => {
|
|
if (target === "new") {
|
|
const next = `${webhookTemplate}${webhookTemplate ? " " : ""}{${variable}}`;
|
|
setWebhookTemplate(next);
|
|
valuesRef.current = { ...valuesRef.current, webhookTemplate: next };
|
|
} else {
|
|
const next = `${webhookUpdateTemplate}${webhookUpdateTemplate ? " " : ""}{${variable}}`;
|
|
setWebhookUpdateTemplate(next);
|
|
valuesRef.current = { ...valuesRef.current, webhookUpdateTemplate: next };
|
|
}
|
|
markEdited("webhook");
|
|
};
|
|
|
|
const updateWebhookValue = (
|
|
field: "webhookUrl" | "webhookTemplate" | "webhookUpdateTemplate",
|
|
value: string
|
|
) => {
|
|
valuesRef.current = { ...valuesRef.current, [field]: value };
|
|
if (field === "webhookUrl") setWebhookUrl(value);
|
|
if (field === "webhookTemplate") setWebhookTemplate(value);
|
|
if (field === "webhookUpdateTemplate") setWebhookUpdateTemplate(value);
|
|
markEdited("webhook");
|
|
};
|
|
|
|
const handleTestWebhook = async () => {
|
|
setTestingWebhook(true);
|
|
try {
|
|
await testDiscordWebhook(
|
|
webhookUrl,
|
|
previewWebhookTemplate(webhookTemplate)
|
|
);
|
|
toast.success("Test message sent.");
|
|
} catch (error) {
|
|
toast.error(getErrorMessage(error, "Could not send the test message."));
|
|
} finally {
|
|
setTestingWebhook(false);
|
|
}
|
|
};
|
|
|
|
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" ? autoSave.status : "clean"}
|
|
error={autoSave.error}
|
|
onRetry={autoSave.retry}
|
|
/>
|
|
</CardHeader>
|
|
<CardContent className="space-y-6">
|
|
{renderRoleList(
|
|
"allowed",
|
|
allowedRoles,
|
|
"Allowed Roles",
|
|
"Users must have at least one of these roles to access the form. Leave empty to allow all."
|
|
)}
|
|
{renderRoleList(
|
|
"denied",
|
|
deniedRoles,
|
|
"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" ? autoSave.status : "clean"}
|
|
error={autoSave.error}
|
|
onRetry={autoSave.retry}
|
|
/>
|
|
</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) => updateWebhookValue("webhookUrl", e.target.value)}
|
|
placeholder="https://discord.com/api/webhooks/..."
|
|
aria-invalid={!webhookUrlValid}
|
|
/>
|
|
{!webhookUrlValid && (
|
|
<p className="text-sm text-destructive">
|
|
Enter a valid Discord webhook URL.
|
|
</p>
|
|
)}
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="webhook-template">New Submission</Label>
|
|
<Textarea
|
|
id="webhook-template"
|
|
value={webhookTemplate}
|
|
onChange={(e) => updateWebhookValue("webhookTemplate", 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, <code>{`{link}`}</code> for the admin result link, and <code>{`{username}`}</code>, <code>{`{displayname}`}</code>, <code>{`{id}`}</code> for user info.
|
|
</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
{["username", "displayname", "id", "link", "1", "2"].map((variable) => (
|
|
<Button
|
|
key={variable}
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => insertVariable(variable, "new")}
|
|
>
|
|
{`{${variable}}`}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
<div className="border bg-muted/30 p-3">
|
|
<Badge variant="secondary">Preview</Badge>
|
|
<p className="mt-2 whitespace-pre-wrap text-sm">
|
|
{previewWebhookTemplate(webhookTemplate)}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="webhook-update-template">Update Submission</Label>
|
|
<Textarea
|
|
id="webhook-update-template"
|
|
value={webhookUpdateTemplate}
|
|
onChange={(e) => updateWebhookValue("webhookUpdateTemplate", 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, <code>{`{link}`}</code> for the admin result link, and <code>{`{username}`}</code>, <code>{`{displayname}`}</code>, <code>{`{id}`}</code> for user info.
|
|
</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
{["username", "displayname", "id", "link", "update", "1", "2"].map((variable) => (
|
|
<Button
|
|
key={variable}
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => insertVariable(variable, "update")}
|
|
>
|
|
{`{${variable}}`}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
<div className="border bg-muted/30 p-3">
|
|
<Badge variant="secondary">Preview</Badge>
|
|
<p className="mt-2 whitespace-pre-wrap text-sm">
|
|
{previewWebhookTemplate(webhookUpdateTemplate, { update: true })}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={handleTestWebhook}
|
|
disabled={!webhookUrlValid || !webhookUrl.trim() || testingWebhook}
|
|
>
|
|
{testingWebhook ? (
|
|
<Loader2 data-icon="inline-start" className="animate-spin" />
|
|
) : (
|
|
<Send data-icon="inline-start" />
|
|
)}
|
|
{testingWebhook ? "Sending test" : "Send test message"}
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
</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">
|
|
{status === "dirty" && "Unsaved"}
|
|
{status === "saving" && (
|
|
<>
|
|
<Loader2 className="animate-spin" />
|
|
Saving
|
|
</>
|
|
)}
|
|
{status === "saved" && (
|
|
<>
|
|
<Check />
|
|
Saved
|
|
</>
|
|
)}
|
|
{status === "error" && (
|
|
<>
|
|
<AlertCircle />
|
|
<span>{error || "Could not save."}</span>
|
|
<Button
|
|
variant="link"
|
|
size="sm"
|
|
className="h-auto px-1"
|
|
onClick={() => void onRetry().catch(() => undefined)}
|
|
>
|
|
Retry
|
|
</Button>
|
|
</>
|
|
)}
|
|
</span>
|
|
);
|
|
}
|