peer-at-code-web/ui/Puzzle.tsx
2023-04-12 20:14:05 +02:00

106 lines
2.7 KiB
TypeScript

'use client';
import type { Puzzle as PuzzleType } from '@/lib/puzzles';
import cookies from 'js-cookie';
import { notFound } from 'next/navigation';
import { useForm } from 'react-hook-form';
import Button from './Button';
import Input from './Input';
import ToHTML from './ToHTML';
type PuzzleData = {
answer: string;
filename: string;
code_file: File[];
};
type Granted = {
[key: string]: number;
};
export default function Puzzle({ puzzle }: { puzzle: PuzzleType }) {
if (!puzzle) {
notFound();
}
// const [granted, setGranted] = useState({});
const {
register,
handleSubmit,
formState: { errors },
setError
} = useForm<PuzzleData>({
defaultValues: {
answer: '',
filename: '',
code_file: []
}
});
async function onSubmit(data: PuzzleData) {
const formData = new FormData();
// if (data.code_file[0].size > 16 * 1024 * 1024) {
// alert('Fichier trop volumineux');
// return;
// }
formData.append('answer', data.answer);
formData.append('filename', 'placeholder');
formData.append('code_file', new Blob(), 'placeholder');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/puzzleResponse/${puzzle.id}`, {
method: 'POST',
body: formData,
headers: {
Authorization: `Bearer ${cookies.get('token')}}`
}
});
if (res.ok) {
alert('Réponse correcte !');
}
}
return (
<div className="flex h-full w-full flex-col justify-between space-y-4">
<div className="flex flex-col space-y-2">
<h2 className="text-xl font-bold sm:text-2xl md:text-3xl">{puzzle.name}</h2>
{/* <p className="text-sm text-muted">Chapitre</p> */}
</div>
<div className="flex h-screen w-full overflow-y-auto">
<ToHTML className="font-code text-xs sm:text-base" data={puzzle.content} />
</div>
<form
className="flex w-full flex-col justify-between sm:flex-row"
onSubmit={handleSubmit(onSubmit)}
encType="multipart/form-data"
>
<div className="flex flex-col space-x-0 sm:flex-row sm:space-x-6">
<Input
className="w-full"
label="Réponse"
type="text"
placeholder="12"
required
{...register('answer')}
/>
{/* <Input
className="h-16 w-full sm:w-1/3"
label="Code"
type="file"
required
accept=".py,.js,.ts,.java,.rs,.c"
{...register('code_file')}
/> */}
</div>
<Button kind="brand" className="mt-6" type="submit">
Envoyer
</Button>
</form>
</div>
);
}