import { useState, type FormEvent } from "react"; import { useTranslation } from "react-i18next"; import type { components } from "../api/schema"; import { useCreateFieldDefinition, useVocabularies } from "../api/queries"; import { LabelEditor } from "../components/label-editor"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Checkbox } from "@/components/ui/checkbox"; type LabelInput = components["schemas"]["LabelInput"]; const TYPES = ["text", "localized_text", "integer", "date", "boolean", "term", "authority"] as const; const KINDS = ["person", "organisation", "place"] as const; export function FieldForm() { const { t } = useTranslation(); const create = useCreateFieldDefinition(); const { data: vocabularies } = useVocabularies(); const [key, setKey] = useState(""); const [labels, setLabels] = useState([]); const [dataType, setDataType] = useState("text"); const [vocabularyId, setVocabularyId] = useState(""); const [authorityKind, setAuthorityKind] = useState(""); const [group, setGroup] = useState(""); const [required, setRequired] = useState(false); const [error, setError] = useState(false); const reset = () => { setKey(""); setLabels([]); setDataType("text"); setVocabularyId(""); setAuthorityKind(""); setGroup(""); setRequired(false); setError(false); }; const onSubmit = (event: FormEvent) => { event.preventDefault(); const hasEn = labels.some((l) => l.lang === "en" && l.label); const termNeedsVocab = dataType === "term" && !vocabularyId; if (!key.trim() || !hasEn || termNeedsVocab) { setError(true); return; } setError(false); create.mutate( { key: key.trim(), data_type: dataType, vocabulary_id: dataType === "term" ? vocabularyId : null, authority_kind: dataType === "authority" ? authorityKind || null : null, required, group: group.trim() || null, labels, }, { onSuccess: reset }, ); }; return (
{t("fields.newField")}
setKey(e.target.value)} />
{dataType === "term" && (
)} {dataType === "authority" && (
)}
setGroup(e.target.value)} />
{error && (

{t("form.required")}

)} {create.isError && (

{t("form.rejected")}

)} ); }