Files
eu/app/acts/create/editor.tsx
T
2026-07-28 17:05:45 +03:00

423 lines
17 KiB
TypeScript

"use client";
import { useState, useEffect, useRef } from "react";
import { v4 as uuidv4 } from "uuid";
import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
import { InputGroup, InputGroupInput } from "@/components/ui/input-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { PlusIcon, XIcon, ChevronDownIcon, ChevronUpIcon, Trash2Icon, ListOrderedIcon, CaseLowerIcon, UserCogIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import Image from "next/image";
import { Merriweather } from "next/font/google";
import { ActEditorData, ActType, ArticleContent, Clause, ClauseMarkerStyle, Institution, PositionOption, Region } from "@/lib/acts/types";
import { searchCitizensAction } from "@/lib/citizenship/actions";
const documentText = Merriweather({ weight: "400" });
const documentHeading = Merriweather({ weight: "700" });
type ActEditorProps = {
actTypes: ActType[];
institutions: Institution[];
regions: Region[];
positions: PositionOption[];
initial?: Partial<ActEditorData>;
onChange: (data: ActEditorData) => void;
errors?: { title?: string[]; issuingInstitutionId?: string[] };
};
const LETTER_MARKERS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
function computeMarker(style: ClauseMarkerStyle, index: number): string | null {
if (style === "NONE") return null;
if (style === "LETTERS") return `${LETTER_MARKERS[index] ?? index + 1})`;
return `${index + 1}.`;
}
function makeEmptyTextClause(): Clause {
return { id: uuidv4(), kind: "TEXT", text: "" };
}
function makeEmptyAppointmentClause(): Clause {
return { id: uuidv4(), kind: "APPOINTMENT", action: "ASSIGN", positionId: "", citizenshipId: "", citizenshipName: "" };
}
function makeEmptyArticle(): ArticleContent {
return { id: uuidv4(), title: "", markerStyle: "NONE", clauses: [makeEmptyTextClause()] };
}
export default function ActEditor({ actTypes, institutions, regions, positions, initial, onChange, errors }: ActEditorProps) {
const [issuingInstitutionId, setIssuingInstitutionId] = useState(initial?.issuingInstitutionId ?? "");
const [actTypeId, setActTypeId] = useState(initial?.actTypeId ?? "");
const [regionId, setRegionId] = useState(initial?.regionId ?? "");
const [title, setTitle] = useState(initial?.title ?? "");
const [preambleText, setPreambleText] = useState(initial?.preambleText ?? "");
const [articles, setArticles] = useState<ArticleContent[]>(initial?.articles ?? [makeEmptyArticle()]);
const onChangeRef = useRef(onChange);
useEffect(() => { onChangeRef.current = onChange; });
useEffect(() => {
onChangeRef.current({ actTypeId, issuingInstitutionId, regionId, title, preambleText, articles });
}, [actTypeId, issuingInstitutionId, regionId, title, preambleText, articles]);
const appointablePositions = positions.filter((p) => {
const owner = institutions.find((i) => i.id === p.institutionId);
const requiredIssuerId = owner?.appointedByInstitutionId ?? owner?.id;
return requiredIssuerId === issuingInstitutionId;
});
const selectedInstitution = institutions.find((i) => i.id === issuingInstitutionId);
const availableActTypes = selectedInstitution
? actTypes.filter((t) => t.allowedIssuerKind === selectedInstitution.kind)
: [];
const needsRegion = selectedInstitution?.kind === "REGION";
function updateArticle(id: string, patch: Partial<ArticleContent>) {
setArticles(articles.map((a) => (a.id === id ? { ...a, ...patch } : a)));
}
function addArticle() {
setArticles([...articles, makeEmptyArticle()]);
}
function removeArticle(id: string) {
setArticles(articles.filter((a) => a.id !== id));
}
function moveArticle(from: number, to: number) {
const updated = [...articles];
const [moved] = updated.splice(from, 1);
updated.splice(to, 0, moved);
setArticles(updated);
}
return (
<div className="flex flex-col gap-10">
<FieldSet>
<h2 className="md:mb-4">Meta</h2>
<FieldGroup>
<Field data-invalid={!!errors?.issuingInstitutionId?.length}>
<FieldLabel>Issuing institution</FieldLabel>
<Select
value={issuingInstitutionId}
onValueChange={(v) => {
setIssuingInstitutionId(v);
setActTypeId("");
setRegionId("");
}}
>
<SelectTrigger><SelectValue placeholder="Select an institution" /></SelectTrigger>
<SelectContent>
{institutions.map((i) => (
<SelectItem key={i.id} value={i.id}>{i.name}</SelectItem>
))}
</SelectContent>
</Select>
{errors?.issuingInstitutionId && <FieldError errors={errors.issuingInstitutionId.map((m) => ({ message: m }))} />}
</Field>
<Field>
<FieldLabel>Act type</FieldLabel>
<Select value={actTypeId} onValueChange={setActTypeId}>
<SelectTrigger><SelectValue placeholder={issuingInstitutionId ? "Select a type" : "Select an institution first"} /></SelectTrigger>
<SelectContent>
{availableActTypes.map((t) => (
<SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
))}
</SelectContent>
</Select>
</Field>
{needsRegion && (
<Field>
<FieldLabel>Region</FieldLabel>
<Select value={regionId} onValueChange={setRegionId}>
<SelectTrigger><SelectValue placeholder="Select a region" /></SelectTrigger>
<SelectContent>
{regions.map((r) => (
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
<Field data-invalid={!!errors?.title?.length}>
<FieldLabel htmlFor="title">Title</FieldLabel>
<InputGroup>
<InputGroupInput
id="title"
value={title}
placeholder="On Citizenship"
onChange={(e) => setTitle(e.target.value)}
/>
</InputGroup>
{errors?.title && <FieldError errors={errors.title.map((m) => ({ message: m }))} />}
</Field>
</FieldGroup>
</FieldSet>
<div className="flex flex-col gap-6">
<div className="flex flex-col items-center gap-6">
<Image src="/emblems/europe.png" width={52} height={32} alt="Emblem of the European Federation" />
<div className={cn("flex flex-col items-center gap-1", documentHeading.className)}>
<h3>{!needsRegion ? "European Federation" : regions.find((region) => region.id === regionId)?.name}</h3>
<h3>{institutions.find((i) => i.id === issuingInstitutionId)?.name}</h3>
</div>
<h3 className={documentHeading.className}>
Draft of a {actTypes.find((a) => a.id === actTypeId)?.name} {title && `“${title}”`}
</h3>
</div>
<AutoResizeTextarea
className={cn("w-full bg-transparent resize-none outline-none leading-relaxed placeholder:text-muted-foreground", documentText.className)}
placeholder="Preamble (optional)"
value={preambleText}
onChange={(e) => setPreambleText(e.target.value)}
/>
<div className="flex flex-col gap-6">
{articles.map((article, index) => (
<div key={article.id} className="group relative flex flex-row gap-2 items-start">
<div className="flex-1 min-w-0">
<ArticleEditor
content={article}
articleIndex={index}
appointablePositions={positions}
onChange={(patch) => updateArticle(article.id, patch)}
/>
</div>
<div className="flex flex-col gap-1 items-center lg:opacity-0 group-hover:opacity-100 transition-opacity shrink-0 pt-2">
<Button variant="ghost" size="icon-sm" onClick={() => moveArticle(index, index - 1)} disabled={index === 0}>
<ChevronUpIcon />
</Button>
<Button variant="ghost" size="icon-sm" onClick={() => moveArticle(index, index + 1)} disabled={index === articles.length - 1}>
<ChevronDownIcon />
</Button>
{articles.length > 1 && (
<Button variant="ghost" size="icon-sm" onClick={() => removeArticle(article.id)}>
<Trash2Icon />
</Button>
)}
</div>
</div>
))}
<Button variant="outline" size="sm" className="w-max mt-4 gap-1.5 text-muted-foreground" onClick={addArticle}>
<PlusIcon size={14} />
Add article
</Button>
</div>
</div>
</div>
);
}
function ArticleEditor({
content,
articleIndex,
appointablePositions,
onChange,
}: {
content: ArticleContent;
articleIndex: number;
appointablePositions: PositionOption[];
onChange: (patch: Partial<ArticleContent>) => void;
}) {
const clauses = content.clauses ?? [makeEmptyTextClause()];
function updateClause(id: string, patch: Partial<Clause>) {
onChange({ clauses: clauses.map((c) => (c.id === id ? { ...c, ...patch } as Clause : c)) });
}
function addClause(afterIndex: number, clause: Clause) {
const updated = [...clauses];
updated.splice(afterIndex + 1, 0, clause);
onChange({ clauses: updated });
}
function removeClause(id: string) {
const updated = clauses.filter((c) => c.id !== id);
onChange({ clauses: updated.length ? updated : [makeEmptyTextClause()] });
}
return (
<div className="flex flex-col gap-2.5">
<div className="flex items-center gap-2">
<h4 className={cn("shrink-0", documentHeading.className)}>Article {articleIndex + 1}</h4>
<input
className={cn("flex-1 min-w-0 bg-transparent outline-none placeholder:text-muted-foreground", documentHeading.className)}
placeholder="Article title (optional)"
value={content.title ?? ""}
onChange={(e) => onChange({ title: e.target.value })}
/>
<Select value={content.markerStyle} onValueChange={(v) => onChange({ markerStyle: v as ClauseMarkerStyle })}>
<SelectTrigger className="w-36 h-7"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="NONE">No markers</SelectItem>
<SelectItem value="LETTERS"><CaseLowerIcon /> Letters</SelectItem>
<SelectItem value="NUMBERS"><ListOrderedIcon /> Numbers</SelectItem>
</SelectContent>
</Select>
</div>
{content.markerStyle !== "NONE" && (
<AutoResizeTextarea
className={cn("flex-1 min-w-0 bg-transparent outline-none placeholder:text-muted-foreground", documentText.className)}
placeholder="Introductory text..."
value={content.intro ?? ""}
onChange={(e) => onChange({ intro: e.target.value })}
/>
)}
<div className="flex flex-col gap-2">
{clauses.map((clause, i) => {
const marker = computeMarker(content.markerStyle, i);
return (
<div key={clause.id} className="flex gap-2 items-start group">
{marker && <span className="text-muted-foreground shrink-0 pt-1">{marker}</span>}
{clause.kind === "APPOINTMENT" ? (
<AppointmentClauseEditor
clause={clause}
positions={appointablePositions}
onChange={(patch) => updateClause(clause.id, patch)}
/>
) : (
<AutoResizeTextarea
className={cn(
"flex-1 min-w-0 bg-transparent resize-none outline-none placeholder:text-muted-foreground",
documentText.className,
marker && "italic"
)}
placeholder="Text..."
value={clause.text}
onChange={(e) => updateClause(clause.id, { text: e.target.value })}
/>
)}
<div className="flex gap-0.5 opacity-0 group-hover:opacity-100 shrink-0">
<Button variant="ghost" size="icon-sm" title="Add text clause" onClick={() => addClause(i, makeEmptyTextClause())}><PlusIcon /></Button>
<Button
variant="ghost"
size="icon-sm"
title="Add appointment clause"
disabled={appointablePositions.length === 0}
onClick={() => addClause(i, makeEmptyAppointmentClause())}
>
<UserCogIcon />
</Button>
{clauses.length > 1 && (
<Button variant="ghost" size="icon-sm" onClick={() => removeClause(clause.id)}><XIcon /></Button>
)}
</div>
</div>
);
})}
</div>
</div>
);
}
// Renders an appointment clause inline as a fill-in-the-blank sentence:
// "[Appoint|Dismiss] [citizen] [to|from] [position]."
function AppointmentClauseEditor({
clause,
positions,
onChange,
}: {
clause: Extract<Clause, { kind: "APPOINTMENT" }>;
positions: PositionOption[];
onChange: (patch: Partial<Clause>) => void;
}) {
return (
<div className={cn("flex-1 min-w-0 flex flex-wrap items-center gap-1.5", documentText.className)}>
<Select value={clause.action} onValueChange={(v) => onChange({ action: v as "ASSIGN" | "DISMISS" })}>
<SelectTrigger className="h-7 w-28"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="ASSIGN">Appoint</SelectItem>
<SelectItem value="DISMISS">Dismiss</SelectItem>
</SelectContent>
</Select>
<CitizenshipPicker
value={clause.citizenshipId ? { id: clause.citizenshipId, name: clause.citizenshipName } : null}
onSelect={(c) => onChange({ citizenshipId: c?.id ?? "", citizenshipName: c?.name ?? "" })}
/>
<span className="text-muted-foreground">{clause.action === "ASSIGN" ? "to" : "from"}</span>
<Select value={clause.positionId} onValueChange={(v) => onChange({ positionId: v })}>
<SelectTrigger className="h-7 min-w-40"><SelectValue placeholder="a position" /></SelectTrigger>
<SelectContent>
{positions.map((p) => (
<SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
))}
</SelectContent>
</Select>
<span>.</span>
</div>
);
}
function CitizenshipPicker({
value,
onSelect,
}: {
value: { id: string; name: string } | null;
onSelect: (value: { id: string; name: string } | null) => void;
}) {
const [query, setQuery] = useState("");
const [results, setResults] = useState<{ id: string; firstName: string; secondName: string }[]>([]);
useEffect(() => {
if (!query.trim()) { setResults([]); return; }
const timeout = setTimeout(async () => {
const result = await searchCitizensAction(query);
if (result.success) setResults(result.data);
}, 250);
return () => clearTimeout(timeout);
}, [query]);
if (value) {
return (
<span className="inline-flex items-center gap-1 border-b border-dotted">
{value.name}
<Button variant="ghost" size="icon-sm" className="h-5 w-5" onClick={() => onSelect(null)}><XIcon size={12} /></Button>
</span>
);
}
return (
<span className="relative inline-block">
<input
className="bg-transparent outline-none border-b border-dotted placeholder:text-muted-foreground w-40"
placeholder="a citizen"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
{results.length > 0 && (
<div className="absolute z-10 mt-1 w-48 bg-popover border rounded-md shadow-md">
{results.map((c) => (
<button
key={c.id}
type="button"
className="w-full text-left px-3 py-1.5 hover:bg-accent text-sm not-italic"
onClick={() => { onSelect({ id: c.id, name: `${c.firstName} ${c.secondName}` }); setQuery(""); setResults([]); }}
>
{c.firstName} {c.secondName}
</button>
))}
</div>
)}
</span>
);
}
function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; className?: string; placeholder?: string }) {
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (ref.current) {
ref.current.style.height = "auto";
ref.current.style.height = `${ref.current.scrollHeight}px`;
}
}, [value]);
return <textarea ref={ref} rows={1} className={cn("overflow-hidden", className)} placeholder={placeholder} value={value} onChange={onChange} />;
}