Booking page - Migrated from Shadcn Form to Shadcn Field components
CI / Docker Lint (push) Successful in 32s

This commit is contained in:
2026-01-13 21:18:06 +01:00
parent 25364deb8e
commit 4a3378573b
5 changed files with 373 additions and 271 deletions
-9
View File
@@ -39,15 +39,6 @@ function RoomBooking({
newCount: number,
price: number,
) {
console.log(
"Room " +
roomCategoryId +
" Guestnumber: " +
guestNumber +
" Count: " +
newCount,
);
const newRoom: NewBookingRoom = {
roomCategory: roomCategoryId,
guestNumber: guestNumber,
+246
View File
@@ -0,0 +1,246 @@
import { useMemo } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className,
)}
{...props}
/>
);
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className,
)}
{...props}
/>
);
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className,
)}
{...props}
/>
);
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"[&>[data-slot=field-label]]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
},
);
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
);
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className,
)}
{...props}
/>
);
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
"has-data-[state=checked]:border-primary has-data-[state=checked]:bg-primary/5 dark:has-data-[state=checked]:bg-primary/10",
className,
)}
{...props}
/>
);
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className,
)}
{...props}
/>
);
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-sm leading-normal font-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className,
)}
{...props}
/>
);
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode;
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className,
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
);
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>;
}) {
const content = useMemo(() => {
if (children) {
return children;
}
if (!errors?.length) {
return null;
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
];
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message;
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>,
)}
</ul>
);
}, [children, errors]);
if (!content) {
return null;
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{content}
</div>
);
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
};
-169
View File
@@ -1,169 +0,0 @@
import * as React from "react";
import { Label as LabelPrimitive, Slot as SlotPrimitive } from "radix-ui";
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form";
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue,
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState } = useFormContext();
const formState = useFormState({ name: fieldContext.name });
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue,
);
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
);
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField();
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
}
function FormControl({
...props
}: React.ComponentProps<typeof SlotPrimitive.Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<SlotPrimitive.Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField();
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message ?? "") : props.children;
if (!body) {
return null;
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-sm text-destructive", className)}
{...props}
>
{body}
</p>
);
}
export {
// eslint-disable-next-line react-refresh/only-export-components
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};
+118 -80
View File
@@ -1,21 +1,13 @@
import { APISendCreateBooking } from "@/api/api-booking";
import { BookingDetails } from "@/components/booking/booking-details";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Typography } from "@/components/ui/typography";
import { BookingFormSchema } from "@/model/FormSchema";
import { useAppStore } from "@/store";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { Controller, useForm } from "react-hook-form";
import { useNavigate } from "react-router";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -23,6 +15,15 @@ import { eBookingState } from "@/utils/AppStateManager";
import { useBookingStateDispacher } from "@/utils/hooks";
import { ConstsNav } from "@/utils/Consts";
import { NewBookingCustomerDetails } from "@/model/Bookings";
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
FieldLegend,
FieldSet,
} from "@/components/ui/field";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
enum PageState {
showForm,
@@ -40,6 +41,7 @@ function BookPage() {
const navigate = useNavigate();
const { setBookingStateBooked } = useBookingStateDispacher();
const bookingFormId = "booking-form";
const bookingForm = useForm<z.infer<typeof BookingFormSchema>>({
resolver: zodResolver(BookingFormSchema),
defaultValues: {
@@ -50,8 +52,8 @@ function BookPage() {
},
});
useEffect(() => {
//Redirect to home if no booking is active.
useEffect(() => {
if (
!appBookingState ||
!bookingData ||
@@ -62,6 +64,25 @@ function BookPage() {
}
}, [appBookingState, bookingData, navigate]);
//Send booking request to API
useEffect(() => {
async function sendCreateRequestAsync() {
const rs = await APISendCreateBooking(bookingData);
if (rs.isError) {
setPageState(PageState.error);
} else {
setBookingStateBooked();
navigate(ConstsNav.page_Success, { state: rs.bookingResponse });
}
}
if (pageState != PageState.sending) {
return;
}
sendCreateRequestAsync();
}, [pageState, bookingData, navigate, setBookingStateBooked]);
function onSubmit(values: z.infer<typeof BookingFormSchema>) {
if (bookingData == null) {
return;
@@ -76,21 +97,8 @@ function BookPage() {
setCustomerData(newCustomerData);
setPageState(PageState.sending);
console.log(bookingData);
sendCreateRequest();
}
const sendCreateRequest = async () => {
const rs = await APISendCreateBooking(bookingData);
if (rs.isError) {
setPageState(PageState.error);
} else {
setBookingStateBooked();
navigate(ConstsNav.page_Success, { state: rs.bookingResponse });
}
};
const errorMsg = (
<div>
<Typography variant={"inlineCode"}>
@@ -102,78 +110,108 @@ function BookPage() {
return (
<>
<Typography variant={"h1"}>Booking Details</Typography>
<Separator className="my-10" />
<Separator className="my-8" />
<div className="lg:grid lg:grid-cols-40/60 lg:gap-x-10">
<div>
<Typography variant={"h3"} className="my-4">
Personal Details
</Typography>
<Form {...bookingForm}>
<Card>
<CardHeader>
<Typography variant={"h2"}>Personal Details</Typography>
</CardHeader>
<CardContent>
<form
id={bookingFormId}
onSubmit={bookingForm.handleSubmit(onSubmit)}
className="space-y-8"
>
<div className="flex w-full flex-row gap-x-3">
<FormField
control={bookingForm.control}
<FieldSet>
<FieldLegend>Customer Details</FieldLegend>
<FieldGroup className="flex flex-row">
<Controller
name="name"
render={({ field }) => (
<FormItem className="flex-1">
<FormLabel>Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
></FormField>
<FormField
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Name</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
name="surname"
render={({ field }) => (
<FormItem className="flex-1">
<FormLabel>Surname</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
></FormField>
</div>
<FormField
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Surname</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
<FieldGroup className="flex flex-col">
<Controller
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
></FormField>
<FormField
control={bookingForm.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Phone</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Email</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
></FormField>
<Button type="submit" disabled={pageState == PageState.sending}>
</Field>
)}
/>
<Controller
name="phone"
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>
Phone Number
</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</FieldSet>
<Field orientation="vertical">
<Button
type="submit"
form={bookingFormId}
disabled={pageState == PageState.sending}
>
Submit
</Button>
</Field>
</form>
</Form>
{pageState == PageState.error ? errorMsg : null}
</div>
{pageState == PageState.error && errorMsg}
</CardContent>
</Card>
<Separator className="my-10 lg:hidden" />
<BookingDetails mode="View"></BookingDetails>
</div>
-4
View File
@@ -74,7 +74,6 @@ function addNewBookingRoom(
}
return false;
});
console.log(filteredRooms);
if (newRoom.amount > 0) {
filteredRooms.push(newRoom);
@@ -85,9 +84,6 @@ function addNewBookingRoom(
rooms: filteredRooms ?? [],
};
console.log("Updated 'currentBooking' state:");
console.log(newState);
return newState;
}