implemented tanstack form

This commit is contained in:
2026-05-24 13:07:06 +02:00
parent 9dead72e1e
commit 6915e60cec
7 changed files with 622 additions and 193 deletions
+439 -184
View File
@@ -1,6 +1,5 @@
import { useTranslation } from "react-i18next";
import { useState, useEffect } from "react";
import * as React from "react";
import Cookies from "js-cookie";
import {
Sheet,
@@ -25,6 +24,10 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { confirmUser, fetchUsers } from "../utils/api/users";
import { QRcodeModal } from "../components/modals/QR-CodeModal";
import { SelectUserModal } from "../components/modals/SelectUserModal";
import { useForm } from "@tanstack/react-form";
import { changeTranslation } from "../utils/uxFncs";
import { createFormSchema } from "../config/interfaces.config";
import type { ZodObject, ZodRawShape } from "zod";
const PAYMENT_METHODS = ["bar", "paypal", "andere"] as const;
const PAYMENT_LABELS: Record<string, string> = {
@@ -33,65 +36,93 @@ const PAYMENT_LABELS: Record<string, string> = {
andere: "Transfer",
};
const DEFAULT_FORM: FormData = {
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
tickets: 1,
companyName: "",
cmpFirstName: "",
cpmLastName: "",
cpmEmail: "",
cpmPhoneNumber: "",
street: "",
postalCode: "",
paymentMethod: "",
};
// ─── Field component lives OUTSIDE MainForm so React doesn't treat it as a
// new component type on every render, which would cause inputs to lose focus.
const Field = ({
label,
name,
type = "text",
required = true,
formData,
onChange,
}: {
label: string;
name: keyof FormData;
type?: string;
required?: boolean;
formData: FormData;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}) => (
<FormControl required={required}>
<FormLabel>{label}</FormLabel>
<Input
name={name}
type={type}
value={formData[name] as string}
onChange={onChange}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
</FormControl>
);
/**
* Validates a single field against the full Zod schema.
* Returns the first error message for that field, or undefined if valid.
*/
function validateFieldWithZod(
schema: ZodObject<ZodRawShape>,
fieldName: string,
allValues: Record<string, unknown>,
): string | undefined {
const result = schema.safeParse(allValues);
if (result.success) return undefined;
const issue = result.error.issues.find(
(i) => i.path.length === 1 && i.path[0] === fieldName,
);
return issue?.message;
}
export const MainForm = () => {
const { t, i18n } = useTranslation();
const { t } = useTranslation();
const queryClient = useQueryClient();
const [invoice, setInvoice] = useState(false);
const [msg, setMsg] = useState<Message | null>(null);
const [selectedUser, setSelectedUser] = useState<string | null>(null);
const [formData, setFormData] = useState<FormData>(DEFAULT_FORM);
const [showSelectUser, setShowSelectUser] = useState(false);
const [QRmodal, setQRmodal] = useState(false);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
const formSchema = createFormSchema(t, invoice);
const makeFieldValidator = (fieldName: string) => ({
onSubmit: ({
value,
fieldApi,
}: {
value: unknown;
fieldApi: { form: { state: { values: Record<string, unknown> } } };
}) => {
const allValues = fieldApi.form.state.values;
return validateFieldWithZod(formSchema, fieldName, allValues);
},
onBlur: ({
value,
fieldApi,
}: {
value: unknown;
fieldApi: { form: { state: { values: Record<string, unknown> } } };
}) => {
const allValues = fieldApi.form.state.values;
return validateFieldWithZod(formSchema, fieldName, allValues);
},
});
const { Field, Subscribe, handleSubmit, setFieldValue } = useForm({
defaultValues: {
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
tickets: 1,
companyName: "",
cmpFirstName: "",
cpmLastName: "",
cpmEmail: "",
cpmPhoneNumber: "",
street: "",
postalCode: "",
paymentMethod: "",
},
onSubmit: async ({ value }) => {
const result = formSchema.safeParse(value);
if (!result.success) return;
mutateForm(value as FormData);
},
});
const getErrors = (field: {
state: { meta: { errorMap: Record<string, unknown> } };
}) => {
const normalizeErrors = (value: unknown) => {
if (Array.isArray(value)) return value as string[];
if (typeof value === "string" && value.length > 0) return [value];
return [] as string[];
};
const blurErrors = normalizeErrors(field.state.meta.errorMap["onBlur"]);
const submitErrors = normalizeErrors(field.state.meta.errorMap["onSubmit"]);
return [...blurErrors, ...submitErrors].filter(Boolean);
};
useEffect(() => {
@@ -119,10 +150,10 @@ export const MainForm = () => {
});
const { mutate: mutateForm, isPending: mutateFormIsPending } = useMutation({
mutationFn: () => submitFormData(formData, selectedUser),
onSuccess: () => {
mutationFn: (values: FormData) => submitFormData(values, selectedUser),
onSuccess: (_, values) => {
queryClient.invalidateQueries({ queryKey: ["user", selectedUser] });
document.location.href = `/success?id=${nextID}&tickets=${formData.tickets}`;
document.location.href = `/success?id=${nextID}&tickets=${values.tickets}`;
},
onError: () => {
queryClient.invalidateQueries({ queryKey: ["user", selectedUser] });
@@ -134,38 +165,15 @@ export const MainForm = () => {
},
});
// Setting the nextID after a user is selected
const nextID = userData?.nextID ?? "N/A";
const handleUserSelection = (username: string | null) => {
if (username == null || username == "") {
return;
}
setSelectedUser(username);
};
const changeTranslation = () => {
const clientLng = i18n.language;
if (clientLng === "en") {
i18n.changeLanguage("de");
Cookies.set("language", "de");
} else if (clientLng === "de") {
i18n.changeLanguage("en");
Cookies.set("language", "en");
} else {
setMsg({
type: "danger",
headline: "Error",
text: "Cannot change langugage.",
});
}
};
// Shorthand so we don't repeat formData + onChange on every Field usage
const fieldProps = { formData, onChange: handleChange };
return (
<>
<SelectUserModal
@@ -205,7 +213,6 @@ export const MainForm = () => {
<IconButton onClick={() => setQRmodal(true)}>
<QrCodeIcon />
</IconButton>
{/* Language toggle */}
<IconButton onClick={changeTranslation}>
<TranslateIcon />
</IconButton>
@@ -225,11 +232,10 @@ export const MainForm = () => {
<form
onSubmit={(e) => {
e.preventDefault();
mutateForm();
handleSubmit();
}}
className="flex flex-col gap-4"
>
{/* Next ID badge */}
<Chip
size="lg"
variant="solid"
@@ -246,41 +252,155 @@ export const MainForm = () => {
{/* Name row */}
<div className="grid grid-cols-2 gap-3">
<Field label={t("first-name")} name="firstName" {...fieldProps} />
<Field label={t("last-name")} name="lastName" {...fieldProps} />
<FormLabel>{t("first-name")}</FormLabel>
<Field
name="firstName"
validators={makeFieldValidator("firstName")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
<FormLabel>{t("last-name")}</FormLabel>
<Field
name="lastName"
validators={makeFieldValidator("lastName")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
</div>
<FormLabel>{t("email")}</FormLabel>
<Field name="email" validators={makeFieldValidator("email")}>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
type="email"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">{errors[0]}</span>
)}
</>
);
}}
</Field>
<FormLabel>{t("phone-number")}</FormLabel>
<Field
label={t("email")}
name="email"
type="email"
{...fieldProps}
/>
<Field
label={t("phone-number")}
name="phoneNumber"
type="tel"
{...fieldProps}
/>
validators={makeFieldValidator("phoneNumber")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
type="tel"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">{errors[0]}</span>
)}
</>
);
}}
</Field>
{/* Tickets + Invoice toggle */}
<div className="grid grid-cols-2 gap-3 items-end">
<FormControl required>
<FormLabel>{t("tickets")}</FormLabel>
<Input
<Field
name="tickets"
type="number"
value={formData.tickets}
onChange={handleChange}
slotProps={{ input: { min: 1 } }}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
validators={makeFieldValidator("tickets")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
type="number"
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) =>
field.handleChange(Number(e.target.value))
}
slotProps={{ input: { min: 1 } }}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
</FormControl>
<div className="flex items-center pb-2">
<Checkbox
checked={invoice}
onChange={(e) => setInvoice(e.target.checked)}
onChange={(e) => {
const checked = e.target.checked;
setInvoice(checked);
if (!checked) {
setFieldValue("companyName", "");
setFieldValue("cmpFirstName", "");
setFieldValue("cpmLastName", "");
setFieldValue("cpmEmail", "");
setFieldValue("cpmPhoneNumber", "");
setFieldValue("street", "");
setFieldValue("postalCode", "");
}
}}
label={t("invoice")}
variant="outlined"
/>
@@ -293,92 +413,224 @@ export const MainForm = () => {
<Typography level="title-sm" color="primary">
{t("invoice-details")}
</Typography>
<FormLabel>{t("company-name")}</FormLabel>
<Field
label={t("company-name")}
name="companyName"
{...fieldProps}
/>
validators={makeFieldValidator("companyName")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
<div className="grid grid-cols-2 gap-3">
<FormLabel>{t("first-name")}</FormLabel>
<Field
label={t("first-name")}
name="cmpFirstName"
{...fieldProps}
/>
validators={makeFieldValidator("cmpFirstName")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
<FormLabel>{t("last-name")}</FormLabel>
<Field
label={t("last-name")}
name="cpmLastName"
{...fieldProps}
/>
validators={makeFieldValidator("cpmLastName")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
</div>
<Field label={t("street")} name="street" {...fieldProps} />
<FormLabel>{t("street")}</FormLabel>
<Field name="street" validators={makeFieldValidator("street")}>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
<FormLabel>{t("postal-code")}</FormLabel>
<Field
label={t("postal-code")}
name="postalCode"
{...fieldProps}
/>
validators={makeFieldValidator("postalCode")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
<FormLabel>{t("phone-number")}</FormLabel>
<Field
label={t("phone-number")}
name="cpmPhoneNumber"
type="tel"
{...fieldProps}
/>
validators={makeFieldValidator("cpmPhoneNumber")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
type="tel"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
<FormLabel>{t("email")}</FormLabel>
<Field
label={t("email")}
name="cpmEmail"
type="email"
{...fieldProps}
/>
validators={makeFieldValidator("cpmEmail")}
>
{(field) => {
const errors = getErrors(field);
return (
<>
<Input
value={field.state.value ?? ""}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
variant="soft"
type="email"
sx={{ borderRadius: "10px" }}
/>
{errors.length > 0 && (
<span className="text-red-500 text-sm">
{errors[0]}
</span>
)}
</>
);
}}
</Field>
</div>
)}
{/* Payment method selection */}
<FormControl required>
<FormLabel>{t("select-payment-method")}</FormLabel>
<div className="flex gap-2 flex-wrap mt-1">
{PAYMENT_METHODS.map((method) => (
<Button
key={method}
variant={
formData.paymentMethod === method ? "solid" : "soft"
}
color="primary"
onClick={() => {
setFormData((prev) => ({
...prev,
paymentMethod: method,
}));
if (method === "paypal") {
setQRmodal(true);
}
}}
sx={{
flex: 1,
minWidth: "90px",
borderRadius: "12px",
py: 1.5,
textTransform: "none",
fontWeight: formData.paymentMethod === method ? 700 : 400,
}}
>
{PAYMENT_LABELS[method]}
</Button>
))}
</div>
{/* Hidden required input to enforce payment selection on submit */}
{!formData.paymentMethod && (
<input
tabIndex={-1}
required
value=""
onChange={() => {}}
style={{
opacity: 0,
width: 0,
height: 0,
position: "absolute",
}}
/>
)}
<Subscribe selector={(state) => state.values.paymentMethod}>
{(paymentMethod) => (
<div className="flex gap-2 flex-wrap mt-1">
{PAYMENT_METHODS.map((method) => (
<Button
key={method}
variant={paymentMethod === method ? "solid" : "soft"}
color="primary"
onClick={() => {
setFieldValue("paymentMethod", method);
if (method === "paypal") {
setQRmodal(true);
}
}}
sx={{
flex: 1,
minWidth: "90px",
borderRadius: "12px",
py: 1.5,
textTransform: "none",
fontWeight: paymentMethod === method ? 700 : 400,
}}
>
{PAYMENT_LABELS[method]}
</Button>
))}
</div>
)}
</Subscribe>
</FormControl>
{mutateFormIsPending ? (
@@ -386,26 +638,29 @@ export const MainForm = () => {
<CircularProgress />
</div>
) : (
<Button
type="submit"
disabled={!formData.paymentMethod}
size="lg"
sx={{
mt: 2,
borderRadius: "14px",
fontWeight: 700,
letterSpacing: "0.05em",
background: "linear-gradient(135deg, #2563eb, #1d4ed8)",
"&:hover": {
background: "linear-gradient(135deg, #1d4ed8, #1e40af)",
},
}}
>
{t("submit")}
</Button>
<Subscribe selector={(state) => state.values.paymentMethod}>
{(paymentMethod) => (
<Button
type="submit"
disabled={!paymentMethod}
size="lg"
sx={{
mt: 2,
borderRadius: "14px",
fontWeight: 700,
letterSpacing: "0.05em",
background: "linear-gradient(135deg, #2563eb, #1d4ed8)",
"&:hover": {
background: "linear-gradient(135deg, #1d4ed8, #1e40af)",
},
}}
>
{t("submit")}
</Button>
)}
</Subscribe>
)}
{/* Message */}
{msg && (
<Alert
color={msg.type}