- new ui/combobox primitive (popover plus cmdk): search input, scrolling list, trigger-width popover, per-option disabled and hint lines - converts every data-driven single-value select site-wide (blueprints, factions, accounts, assignments, NPCs, structures, locker items, seats, missions, ranks, resources, mod lists, event targets, sprints) - long multi-select checkbox menus (event log types, kanban labels) gain search inputs following the resource picker pattern - static short enum selects stay as plain selects
294 lines
9.5 KiB
TypeScript
294 lines
9.5 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { toast } from "sonner";
|
|
import { ArrowLeftRightIcon, Loader2Icon } from "lucide-react";
|
|
import { Alert, AlertDescription } from "@/components/ui/alert";
|
|
import { Combobox } from "@/components/ui/combobox";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogTrigger,
|
|
} from "@/components/ui/dialog";
|
|
import { Label } from "@/components/ui/label";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectGroup,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/components/ui/select";
|
|
import { Skeleton } from "@/components/ui/skeleton";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { requestTransfer } from "@/app/(frontend)/transfers/actions";
|
|
import {
|
|
parseAssignmentPage,
|
|
relationId,
|
|
type AccountAssignment,
|
|
type TransferAssignmentSummary,
|
|
} from "@/components/frontend/transfers/transferTypes";
|
|
|
|
interface RequestTransferDialogProps {
|
|
readonly currentAssignments: readonly AccountAssignment[];
|
|
readonly currentUserId: number;
|
|
}
|
|
|
|
function isMemberOf(assignment: TransferAssignmentSummary, userId: number): boolean {
|
|
if (relationId(assignment.leader) === userId) return true;
|
|
return (assignment.members ?? []).some((member) => relationId(member) === userId);
|
|
}
|
|
|
|
export function RequestTransferDialog({
|
|
currentAssignments,
|
|
currentUserId,
|
|
}: RequestTransferDialogProps) {
|
|
const router = useRouter();
|
|
const [internalOpen, setInternalOpen] = useState(false);
|
|
const [sourceId, setSourceId] = useState("");
|
|
const [destinationId, setDestinationId] = useState("");
|
|
const [destinations, setDestinations] = useState<readonly TransferAssignmentSummary[]>([]);
|
|
const [note, setNote] = useState("");
|
|
const [loadingDestinations, setLoadingDestinations] = useState(false);
|
|
const [pending, setPending] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const requestableAssignments = useMemo(
|
|
() => currentAssignments.filter((assignment) => assignment.leaderId !== currentUserId),
|
|
[currentAssignments, currentUserId],
|
|
);
|
|
const currentAssignmentIds = useMemo(
|
|
() => new Set(currentAssignments.map((assignment) => assignment.id)),
|
|
[currentAssignments],
|
|
);
|
|
const currentAssignmentKey = currentAssignments.map((assignment) => assignment.id).join(",");
|
|
const open = internalOpen;
|
|
|
|
useEffect(() => {
|
|
if (!requestableAssignments.some((assignment) => String(assignment.id) === sourceId)) {
|
|
setSourceId(String(requestableAssignments[0]?.id ?? ""));
|
|
}
|
|
}, [requestableAssignments, sourceId]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
|
|
const controller = new AbortController();
|
|
setLoadingDestinations(true);
|
|
setError(null);
|
|
|
|
async function loadDestinations() {
|
|
try {
|
|
const response = await fetch("/api/assignments?depth=1&limit=100&sort=name", {
|
|
signal: controller.signal,
|
|
cache: "no-store",
|
|
});
|
|
if (!response.ok) throw new Error("Could not load eligible assignments.");
|
|
|
|
const body: unknown = await response.json();
|
|
const parsed = parseAssignmentPage(body);
|
|
if (!parsed) throw new Error("The assignment response was invalid.");
|
|
|
|
const available = parsed.filter(
|
|
(assignment) =>
|
|
!currentAssignmentIds.has(assignment.id) && !isMemberOf(assignment, currentUserId),
|
|
);
|
|
setDestinations(available);
|
|
setDestinationId((previous) =>
|
|
available.some((assignment) => String(assignment.id) === previous)
|
|
? previous
|
|
: String(available[0]?.id ?? ""),
|
|
);
|
|
} catch (caughtError) {
|
|
if (caughtError instanceof DOMException && caughtError.name === "AbortError") return;
|
|
setError(
|
|
caughtError instanceof Error
|
|
? caughtError.message
|
|
: "Could not load eligible assignments.",
|
|
);
|
|
} finally {
|
|
if (!controller.signal.aborted) setLoadingDestinations(false);
|
|
}
|
|
}
|
|
|
|
void loadDestinations();
|
|
return () => controller.abort();
|
|
}, [currentAssignmentIds, currentAssignmentKey, currentUserId, open]);
|
|
|
|
function reset() {
|
|
setDestinationId("");
|
|
setDestinations([]);
|
|
setNote("");
|
|
setError(null);
|
|
setPending(false);
|
|
}
|
|
|
|
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
const fromAssignmentId = Number(sourceId);
|
|
const toAssignmentId = Number(destinationId);
|
|
|
|
if (!Number.isInteger(fromAssignmentId) || fromAssignmentId <= 0) {
|
|
setError("Choose a current assignment.");
|
|
return;
|
|
}
|
|
if (!Number.isInteger(toAssignmentId) || toAssignmentId <= 0) {
|
|
setError("Choose a destination assignment.");
|
|
return;
|
|
}
|
|
if (fromAssignmentId === toAssignmentId) {
|
|
setError("Choose an assignment different from your current one.");
|
|
return;
|
|
}
|
|
|
|
setPending(true);
|
|
setError(null);
|
|
try {
|
|
const result = await requestTransfer({
|
|
fromAssignmentId,
|
|
toAssignmentId,
|
|
note: note.trim() || undefined,
|
|
});
|
|
if (!result.success) {
|
|
setError(result.error ?? "Could not submit the transfer request.");
|
|
return;
|
|
}
|
|
|
|
toast.success("Transfer request submitted");
|
|
setInternalOpen(false);
|
|
reset();
|
|
router.refresh();
|
|
} catch (caughtError) {
|
|
setError(
|
|
caughtError instanceof Error
|
|
? caughtError.message
|
|
: "Could not submit the transfer request.",
|
|
);
|
|
} finally {
|
|
setPending(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Dialog
|
|
open={open}
|
|
onOpenChange={(nextOpen) => {
|
|
setInternalOpen(nextOpen);
|
|
if (!nextOpen) reset();
|
|
}}
|
|
>
|
|
<DialogTrigger asChild>
|
|
<Button
|
|
size="sm"
|
|
disabled={requestableAssignments.length === 0}
|
|
title={
|
|
requestableAssignments.length === 0
|
|
? "Leaders cannot request assignment transfers"
|
|
: undefined
|
|
}
|
|
>
|
|
<ArrowLeftRightIcon data-icon="inline-start" />
|
|
Request transfer
|
|
</Button>
|
|
</DialogTrigger>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>Request assignment transfer</DialogTitle>
|
|
<DialogDescription>
|
|
Choose an assignment you are not already part of. Leaders cannot request transfers.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label htmlFor="transfer-source">Current assignment</Label>
|
|
<Combobox
|
|
id="transfer-source"
|
|
value={sourceId}
|
|
onValueChange={setSourceId}
|
|
disabled={pending}
|
|
placeholder="Select current assignment"
|
|
searchPlaceholder="Search assignments..."
|
|
options={requestableAssignments.map((assignment) => ({
|
|
value: String(assignment.id),
|
|
label: assignment.callsign
|
|
? `${assignment.name} · ${assignment.callsign}`
|
|
: assignment.name,
|
|
}))}
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex flex-col gap-1.5" aria-busy={loadingDestinations}>
|
|
<Label htmlFor="transfer-destination">Destination assignment</Label>
|
|
{loadingDestinations ? (
|
|
<Skeleton className="h-9 w-full" />
|
|
) : destinations.length > 0 ? (
|
|
<Combobox
|
|
id="transfer-destination"
|
|
value={destinationId}
|
|
onValueChange={setDestinationId}
|
|
disabled={pending}
|
|
placeholder="Select destination assignment"
|
|
searchPlaceholder="Search assignments..."
|
|
options={destinations.map((assignment) => ({
|
|
value: String(assignment.id),
|
|
label: assignment.callsign
|
|
? `${assignment.name} · ${assignment.callsign}`
|
|
: assignment.name,
|
|
}))}
|
|
/>
|
|
) : (
|
|
<Alert>
|
|
<AlertDescription>
|
|
No eligible destination assignments are available right now.
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
</div>
|
|
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label htmlFor="transfer-note">Note (optional)</Label>
|
|
<Textarea
|
|
id="transfer-note"
|
|
value={note}
|
|
onChange={(event) => setNote(event.target.value)}
|
|
placeholder="Tell both assignment leaders why you would like to move..."
|
|
rows={4}
|
|
maxLength={1000}
|
|
disabled={pending}
|
|
/>
|
|
</div>
|
|
|
|
{error && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{error}
|
|
</p>
|
|
)}
|
|
|
|
<DialogFooter>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={() => setInternalOpen(false)}
|
|
disabled={pending}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
<Button
|
|
type="submit"
|
|
disabled={pending || loadingDestinations || destinations.length === 0}
|
|
>
|
|
{pending && <Loader2Icon data-icon="inline-start" className="animate-spin" />}
|
|
{pending ? "Submitting..." : "Submit request"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|