committing event form unfinished

This commit is contained in:
ashprit
2024-10-26 15:47:02 +01:00
parent 8e4e747382
commit 9e836a7de1
8 changed files with 6800 additions and 10 deletions

View File

@@ -1,10 +1,53 @@
'use client';
import React from 'react';
import EventDescription from '@/components/custom/EventDescription'; import EventDescription from '@/components/custom/EventDescription';
import Home from './Home'; import Home from '../components/Home';
import EventForm from '@/components/custom/EventForm';
export default function Page() { export default function Page() {
// Define the handleSubmit function
const handleSubmit = (data: {
name: string;
description: string;
capacity: number;
ticketPrice: number;
eventDate: Date;
eventStartTime?: string;
eventEndTime?: string;
images?: string[];
}) => {
try {
// Log the data to the console (you can replace this with an API call or other logic)
console.log('Form Submitted:', data);
// You can format the eventDate if needed (e.g., to a specific date format)
const formattedDate = new Date(data.eventDate).toISOString();
console.log('Formatted Event Date:', formattedDate);
// Example: Post data to an API endpoint
// fetch('/api/events', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ ...data, eventDate: formattedDate }),
// })
// .then((response) => response.json())
// .then((result) => {
// console.log('Success:', result);
// })
// .catch((error) => {
// console.error('Error:', error);
// });
} catch (error) {
console.error('Error submitting form:', error);
}
};
return ( return (
<> <>
<Home /> {/* <Home /> */}
<EventForm onSubmit={(data) => handleSubmit(data)} />
</> </>
); );
} }

View File

@@ -0,0 +1,219 @@
'use client';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
// Define the schema using Zod
const eventSchema = z
.object({
name: z.string().min(1, { message: 'Event name is required' }),
description: z.string().min(1, { message: 'Description is required' }),
capacity: z
.number({ invalid_type_error: 'Capacity must be a number' })
.min(1, { message: 'Capacity must be at least 1' })
.refine((val) => Number.isInteger(val), {
message: 'Capacity must be an integer',
}),
ticketPrice: z
.number({ invalid_type_error: 'Ticket price must be a number' })
.min(0, { message: 'Ticket price must be at least 0' })
.refine((val) => Number.isInteger(val), {
message: 'Ticket price must be in cents',
}),
eventDate: z.coerce.date({ message: 'Event date is required' }).refine(
(date) => {
const today = new Date();
today.setHours(0, 0, 0, 0); // Remove time component
return date >= today;
},
{
message: 'Event date must be today or in the future',
}
),
eventStartTime: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/, {
message: 'Invalid start time format',
}),
eventEndTime: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/, {
message: 'Invalid end time format',
}),
images: z
.array(
z
.string()
.url()
.regex(
/https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/,
{ message: 'Invalid image URL format' }
)
)
.optional(),
})
.superRefine((d, ctx) => {
// Parse event start time
const startTime = new Date(d.eventDate);
const [startHours, startMinutes] = d.eventStartTime.split(':').map(Number);
startTime.setHours(startHours, startMinutes, 0, 0);
// Parse event end time
const endTime = new Date(d.eventDate);
const [endHours, endMinutes] = d.eventEndTime.split(':').map(Number);
endTime.setHours(endHours, endMinutes, 0, 0);
const currentDateTime = new Date();
// Check if event start time is in the future
if (startTime <= currentDateTime) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Event start time must be in the future',
path: ['eventStartTime'],
});
}
// Check if event end time is after start time
if (endTime <= startTime) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Event end time must be after the start time',
path: ['eventEndTime'],
});
}
});
// Define the TypeScript type based on the Zod schema
type EventFormData = z.infer<typeof eventSchema>;
interface EventFormProps {
onSubmit: (data: EventFormData) => void;
}
const EventForm = ({ onSubmit }: EventFormProps) => {
const {
register,
handleSubmit,
formState: { errors },
setValue,
watch,
} = useForm<EventFormData>({
resolver: zodResolver(eventSchema),
mode: 'onChange',
});
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
const filesArray = Array.from(e.target.files).map((file) =>
URL.createObjectURL(file)
);
setValue('images', filesArray, { shouldValidate: true });
}
};
const images = watch('images') || [];
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<Label htmlFor="name">Event Name</Label>
<Input id="name" {...register('name')} />
{errors.name && <p className="text-red-500">{errors.name.message}</p>}
</div>
<div>
<Label htmlFor="description">Description</Label>
<Textarea id="description" {...register('description')} />
{errors.description && (
<p className="text-red-500">{errors.description.message}</p>
)}
</div>
<div>
<Label htmlFor="capacity">Capacity</Label>
<Input
type="number"
id="capacity"
{...register('capacity', {
valueAsNumber: true,
})}
/>
{errors.capacity && (
<p className="text-red-500">{errors.capacity.message}</p>
)}
</div>
<div>
<Label htmlFor="ticketPrice">Ticket Price (in USD cents)</Label>
<Input
type="number"
id="ticketPrice"
{...register('ticketPrice', {
valueAsNumber: true,
})}
/>
{errors.ticketPrice && (
<p className="text-red-500">{errors.ticketPrice.message}</p>
)}
</div>
<div>
<Label htmlFor="eventDate">Event Date</Label>
<Input type="date" id="eventDate" {...register('eventDate')} />
{errors.eventDate && (
<p className="text-red-500">{errors.eventDate.message}</p>
)}
</div>
<div>
<Label htmlFor="eventStartTime">Event Start Time</Label>
<Input
type="time"
id="eventStartTime"
{...register('eventStartTime')}
/>
{errors.eventStartTime && (
<p className="text-red-500">{errors.eventStartTime.message}</p>
)}
</div>
<div>
<Label htmlFor="eventEndTime">Event End Time</Label>
<Input type="time" id="eventEndTime" {...register('eventEndTime')} />
{errors.eventEndTime && (
<p className="text-red-500">{errors.eventEndTime.message}</p>
)}
</div>
<div>
<Label htmlFor="images">Event Images</Label>
<input
type="file"
id="images"
multiple
accept="image/*"
onChange={handleFileChange}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
/>
{errors.images && (
<p className="text-red-500">{errors.images.message}</p>
)}
<div className="mt-2 flex flex-wrap gap-2">
{images.map((url, index) => (
<img
key={index}
src={url}
alt={`Event Image ${index + 1}`}
className="w-24 h-24 object-cover rounded"
/>
))}
</div>
</div>
<Button type="submit">Create Event</Button>
</form>
);
};
export default EventForm;

View File

@@ -1,3 +1,4 @@
'use client';
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Button } from '../ui/button'; // Adjust import path to where your shadcn Button component is located import { Button } from '../ui/button'; // Adjust import path to where your shadcn Button component is located
@@ -20,7 +21,9 @@ const NumberPicker: React.FC<NumberPickerProps> = ({
if (count < max) { if (count < max) {
const newCount = count + 1; const newCount = count + 1;
setCount(newCount); setCount(newCount);
onChange && onChange(newCount); if (onChange) {
onChange(newCount);
}
} }
}; };
@@ -28,7 +31,9 @@ const NumberPicker: React.FC<NumberPickerProps> = ({
if (count > min) { if (count > min) {
const newCount = count - 1; const newCount = count - 1;
setCount(newCount); setCount(newCount);
onChange && onChange(newCount); if (onChange) {
onChange(newCount);
}
} }
}; };

View File

@@ -0,0 +1,24 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
className
)}
ref={ref}
{...props}
/>
);
}
);
Textarea.displayName = 'Textarea';
export { Textarea };

6500
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
"prepare": "husky" "prepare": "husky"
}, },
"dependencies": { "dependencies": {
"@metamask/sdk-react": "^0.30.0", "@hookform/resolvers": "^3.9.0",
"@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.1.0", "@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-select": "^2.1.2", "@radix-ui/react-select": "^2.1.2",
@@ -18,18 +18,17 @@
"@radix-ui/react-slot": "^1.1.0", "@radix-ui/react-slot": "^1.1.0",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"embla-carousel-react": "^8.3.0", "embla-carousel-react": "^8.3.0",
"ethers": "^6.13.4",
"framer-motion": "^11.11.10", "framer-motion": "^11.11.10",
"ethers": "^5.7.2",
"lucide-react": "^0.446.0", "lucide-react": "^0.446.0",
"next": "14.2.13", "next": "14.2.13",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.53.1",
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7" "tailwindcss-animate": "^1.0.7",
"zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"@types/ethereum-protocol": "^1.0.5", "@types/ethereum-protocol": "^1.0.5",