Updated Level Generation

This commit is contained in:
Joao Ramos
2024-07-17 23:44:53 +01:00
parent 4996417218
commit 13fd7e1ee5

View File

@@ -1,294 +1,375 @@
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import {Difficulty, LevelExam, MultipleChoiceExercise, MultipleChoiceQuestion} from "@/interfaces/exam"; import {
Difficulty,
LevelExam,
MultipleChoiceExercise,
MultipleChoiceQuestion,
LevelPart,
} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams"; import { getExamById } from "@/utils/exams";
import {playSound} from "@/utils/sound"; import { playSound } from "@/utils/sound";
import {Tab} from "@headlessui/react"; import { Tab } from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import {capitalize, sample} from "lodash"; import { capitalize, sample } from "lodash";
import {useRouter} from "next/router"; import { useRouter } from "next/router";
import {useState} from "react"; import { useState } from "react";
import {BsArrowRepeat, BsCheck, BsPencilSquare, BsX} from "react-icons/bs"; import { BsArrowRepeat, BsCheck, BsPencilSquare, BsX } from "react-icons/bs";
import {toast} from "react-toastify"; import { toast } from "react-toastify";
import {v4} from "uuid"; import { v4 } from "uuid";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"]; const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
const QuestionDisplay = ({question, onUpdate}: {question: MultipleChoiceQuestion; onUpdate: (question: MultipleChoiceQuestion) => void}) => { const QuestionDisplay = ({
const [isEditing, setIsEditing] = useState(false); question,
const [options, setOptions] = useState(question.options); onUpdate,
}: {
question: MultipleChoiceQuestion;
onUpdate: (question: MultipleChoiceQuestion) => void;
}) => {
const [isEditing, setIsEditing] = useState(false);
const [options, setOptions] = useState(question.options);
const [answer, setAnswer] = useState(question.solution);
return ( return (
<div key={question.id} className="flex flex-col gap-1"> <div key={question.id} className="flex flex-col gap-1">
<span className="font-semibold"> <span className="font-semibold">
{question.id}. {question.prompt}{" "} {question.id}. {question.prompt}{" "}
</span> </span>
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{question.options.map((option, index) => ( {question.options.map((option, index) => (
<span key={option.id} className={clsx(question.solution === option.id && "font-bold")}> <span
<span className={clsx("font-semibold", question.solution === option.id ? "text-mti-green-light" : "text-ielts-level")}> key={option.id}
({option.id}) className={clsx(answer === option.id && "font-bold")}
</span>{" "} >
{isEditing ? ( <span
<input className={clsx(
defaultValue={option.text} "font-semibold",
className="w-60" answer === option.id
onChange={(e) => setOptions((prev) => prev.map((x, idx) => (idx === index ? {...x, text: e.target.value} : x)))} ? "text-mti-green-light"
/> : "text-ielts-level"
) : ( )}
<span>{option.text}</span> onClick={() => setAnswer(option.id)}
)} >
</span> ({option.id})
))} </span>{" "}
</div> {isEditing ? (
<div className="flex gap-2 mt-2 w-full"> <input
{!isEditing && ( defaultValue={option.text}
<button className="w-60"
onClick={() => setIsEditing(true)} onChange={(e) =>
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300"> setOptions((prev) =>
<BsPencilSquare /> prev.map((x, idx) =>
</button> idx === index ? { ...x, text: e.target.value } : x
)} )
{isEditing && ( )
<> }
<button />
onClick={() => { ) : (
onUpdate({...question, options}); <span>{option.text}</span>
setIsEditing(false); )}
}} </span>
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300"> ))}
<BsCheck /> </div>
</button> <div className="flex gap-2 mt-2 w-full">
<button {!isEditing && (
onClick={() => setIsEditing(false)} <button
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300"> onClick={() => setIsEditing(true)}
<BsX /> className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300"
</button> >
</> <BsPencilSquare />
)} </button>
</div> )}
</div> {isEditing && (
); <>
<button
onClick={() => {
onUpdate({ ...question, options, solution: answer });
setIsEditing(false);
}}
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300"
>
<BsCheck />
</button>
<button
onClick={() => setIsEditing(false)}
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300"
>
<BsX />
</button>
</>
)}
</div>
</div>
);
}; };
const TaskTab = ({exam, difficulty, setExam}: {exam?: LevelExam; difficulty: Difficulty; setExam: (exam: LevelExam) => void}) => { const TaskTab = ({
const [isLoading, setIsLoading] = useState(false); exam,
difficulty,
setExam,
}: {
exam?: LevelPart;
difficulty: Difficulty;
setExam: (exam: LevelPart) => void;
}) => {
const [isLoading, setIsLoading] = useState(false);
const generate = () => { const generate = () => {
const url = new URLSearchParams(); const url = new URLSearchParams();
url.append("difficulty", difficulty); url.append("difficulty", difficulty);
setIsLoading(true); setIsLoading(true);
axios axios
.get(`/api/exam/level/generate/level?${url.toString()}`) .get(`/api/exam/level/generate/level?${url.toString()}`)
.then((result) => { .then((result) => {
playSound(typeof result.data === "string" ? "error" : "check"); playSound(typeof result.data === "string" ? "error" : "check");
if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again."); if (typeof result.data === "string")
setExam(result.data); return toast.error(
}) "Something went wrong, please try to generate again."
.catch((error) => { );
console.log(error); setExam(result.data);
toast.error("Something went wrong!"); })
}) .catch((error) => {
.finally(() => setIsLoading(false)); console.log(error);
}; toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const onUpdate = (question: MultipleChoiceQuestion) => { const onUpdate = (question: MultipleChoiceQuestion) => {
if (!exam) return; if (!exam) return;
const updatedExam = { const updatedExam = {
...exam, ...exam,
parts: exam.parts.map((p) => exercises: exam.exercises.map((x) => ({
p.exercises.map((x) => ({ ...x,
...x, questions: (x as MultipleChoiceExercise).questions.map((q) =>
questions: (x as MultipleChoiceExercise).questions.map((q) => (q.id === question.id ? question : q)), q.id === question.id ? question : q
})), ),
), }),
}; ),
console.log(updatedExam); };
setExam(updatedExam as any); console.log(updatedExam);
}; setExam(updatedExam as any);
};
return ( return (
<Tab.Panel className="w-full bg-ielts-level/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4"> <Tab.Panel className="w-full bg-ielts-level/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex gap-4 items-end"> <div className="flex gap-4 items-end">
<button <button
onClick={generate} onClick={generate}
disabled={isLoading} disabled={isLoading}
className={clsx( className={clsx(
"bg-ielts-level/70 border border-ielts-level text-white w-full px-6 py-6 rounded-xl h-[70px]", "bg-ielts-level/70 border border-ielts-level text-white w-full px-6 py-6 rounded-xl h-[70px]",
"hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed", "hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300"
)}> )}
{isLoading ? ( >
<div className="flex items-center justify-center"> {isLoading ? (
<BsArrowRepeat className="text-white animate-spin" size={25} /> <div className="flex items-center justify-center">
</div> <BsArrowRepeat className="text-white animate-spin" size={25} />
) : ( </div>
"Generate" ) : (
)} "Generate"
</button> )}
</div> </button>
{isLoading && ( </div>
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center"> {isLoading && (
<span className={clsx("loading loading-infinity w-32 text-ielts-level")} /> <div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span className={clsx("font-bold text-2xl text-ielts-level")}>Generating...</span> <span
</div> className={clsx("loading loading-infinity w-32 text-ielts-level")}
)} />
{exam && ( <span className={clsx("font-bold text-2xl text-ielts-level")}>
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-full"> Generating...
{exam.parts </span>
.flatMap((x) => x.exercises) </div>
.filter((x) => x.type === "multipleChoice") )}
.map((ex) => { {exam && (
const exercise = ex as MultipleChoiceExercise; <div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-full">
{exam.exercises
.filter((x) => x.type === "multipleChoice")
.map((ex) => {
const exercise = ex as MultipleChoiceExercise;
return ( return (
<div key={ex.id} className="w-full h-full flex flex-col gap-2"> <div key={ex.id} className="w-full h-full flex flex-col gap-2">
<div className="flex gap-2"> <div className="flex gap-2">
<span className="text-xl font-semibold">Multiple Choice</span> <span className="text-xl font-semibold">
<span className="rounded-xl bg-white border border-ielts-level p-1 px-4 w-fit"> Multiple Choice
{exercise.questions.length} questions </span>
</span> <span className="rounded-xl bg-white border border-ielts-level p-1 px-4 w-fit">
</div> {exercise.questions.length} questions
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> </span>
{exercise.questions.map((question) => ( </div>
<QuestionDisplay question={question} onUpdate={onUpdate} key={question.id} /> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
))} {exercise.questions.map((question) => (
</div> <QuestionDisplay
</div> question={question}
); onUpdate={onUpdate}
})} key={question.id}
</div> />
)} ))}
</Tab.Panel> </div>
); </div>
);
})}
</div>
)}
</Tab.Panel>
);
}; };
const LevelGeneration = () => { const LevelGeneration = () => {
const [generatedExam, setGeneratedExam] = useState<LevelExam>(); const [generatedExam, setGeneratedExam] = useState<LevelPart>();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<LevelExam>(); const [resultingExam, setResultingExam] = useState<LevelExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!); const [difficulty, setDifficulty] = useState<Difficulty>(
sample(DIFFICULTIES)!
);
const router = useRouter(); const router = useRouter();
const setExams = useExamStore((state) => state.setExams); const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules); const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const loadExam = async (examId: string) => { const loadExam = async (examId: string) => {
const exam = await getExamById("level", examId.trim()); const exam = await getExamById("level", examId.trim());
if (!exam) { if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", { toast.error(
toastId: "invalid-exam-id", "Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
}); {
toastId: "invalid-exam-id",
}
);
return; return;
} }
setExams([exam]); setExams([exam]);
setSelectedModules(["level"]); setSelectedModules(["level"]);
router.push("/exercises"); router.push("/exercises");
}; };
const submitExam = () => { const submitExam = () => {
if (!generatedExam) { if (!generatedExam) {
toast.error("Please generate all tasks before submitting"); toast.error("Please generate all tasks before submitting");
return; return;
} }
setIsLoading(true); setIsLoading(true);
const exam: LevelExam = {
...generatedExam,
isDiagnostic: false,
minTimer: 25,
module: "level",
id: v4(),
};
axios const exam: LevelExam = {
.post(`/api/exam/level`, exam) isDiagnostic: false,
.then((result) => { minTimer: 25,
playSound("sent"); module: "level",
console.log(`Generated Exam ID: ${result.data.id}`); id: v4(),
toast.success("This new exam has been generated successfully! Check the ID in our browser's console."); parts: [generatedExam],
setResultingExam(result.data); };
setGeneratedExam(undefined); axios
}) .post(`/api/exam/level`, exam)
.catch((error) => { .then((result) => {
console.log(error); playSound("sent");
toast.error("Something went wrong while generating, please try again later."); console.log(`Generated Exam ID: ${result.data.id}`);
}) toast.success(
.finally(() => setIsLoading(false)); "This new exam has been generated successfully! Check the ID in our browser's console."
}; );
setResultingExam(result.data);
return ( setGeneratedExam(undefined);
<> })
<div className="flex gap-4 w-1/2"> .catch((error) => {
<div className="flex flex-col gap-3 w-full"> console.log(error);
<label className="font-normal text-base text-mti-gray-dim">Difficulty</label> toast.error(
<Select "Something went wrong while generating, please try again later."
options={DIFFICULTIES.map((x) => ({value: x, label: capitalize(x)}))} );
onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)} })
value={{value: difficulty, label: capitalize(difficulty)}} .finally(() => setIsLoading(false));
/> };
</div>
</div> return (
<Tab.Group> <>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-level/20 p-1"> <div className="flex gap-4 w-1/2">
<Tab <div className="flex flex-col gap-3 w-full">
className={({selected}) => <label className="font-normal text-base text-mti-gray-dim">
clsx( Difficulty
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-level/70", </label>
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-level focus:outline-none focus:ring-2", <Select
"transition duration-300 ease-in-out", options={DIFFICULTIES.map((x) => ({
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-level", value: x,
) label: capitalize(x),
}> }))}
Exam onChange={(value) =>
</Tab> value ? setDifficulty(value.value as Difficulty) : null
</Tab.List> }
<Tab.Panels> value={{ value: difficulty, label: capitalize(difficulty) }}
<TaskTab difficulty={difficulty} exam={generatedExam} setExam={setGeneratedExam} /> />
</Tab.Panels> </div>
</Tab.Group> </div>
<div className="w-full flex justify-end gap-4"> <Tab.Group>
{resultingExam && ( <Tab.List className="flex space-x-1 rounded-xl bg-ielts-level/20 p-1">
<button <Tab
disabled={isLoading} className={({ selected }) =>
onClick={() => loadExam(resultingExam.id)} clsx(
className={clsx( "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-level/70",
"bg-white border border-ielts-level text-ielts-level w-full max-w-[200px] rounded-xl h-[70px] self-end", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-level focus:outline-none focus:ring-2",
"hover:bg-ielts-level hover:text-white disabled:bg-ielts-level/40 disabled:cursor-not-allowed", "transition duration-300 ease-in-out",
"transition ease-in-out duration-300", selected
)}> ? "bg-white shadow"
Perform Exam : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-level"
</button> )
)} }
<button >
disabled={!generatedExam || isLoading} Exam
data-tip="Please generate all three passages" </Tab>
onClick={submitExam} </Tab.List>
className={clsx( <Tab.Panels>
"bg-ielts-level/70 border border-ielts-level text-white w-full max-w-[200px] rounded-xl h-[70px] self-end", <TaskTab
"hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed", difficulty={difficulty}
"transition ease-in-out duration-300", exam={generatedExam}
!generatedExam && "tooltip", setExam={setGeneratedExam}
)}> />
{isLoading ? ( </Tab.Panels>
<div className="flex items-center justify-center"> </Tab.Group>
<BsArrowRepeat className="text-white animate-spin" size={25} /> <div className="w-full flex justify-end gap-4">
</div> {resultingExam && (
) : ( <button
"Submit" disabled={isLoading}
)} onClick={() => loadExam(resultingExam.id)}
</button> className={clsx(
</div> "bg-white border border-ielts-level text-ielts-level w-full max-w-[200px] rounded-xl h-[70px] self-end",
</> "hover:bg-ielts-level hover:text-white disabled:bg-ielts-level/40 disabled:cursor-not-allowed",
); "transition ease-in-out duration-300"
)}
>
Perform Exam
</button>
)}
<button
disabled={!generatedExam || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-level/70 border border-ielts-level text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
!generatedExam && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
}; };
export default LevelGeneration; export default LevelGeneration;