Added Listening Multiple Choice Edit

This commit is contained in:
Joao Ramos
2024-07-04 01:15:33 +01:00
parent 0b3e686f3f
commit e5e4e87752
2 changed files with 557 additions and 308 deletions

View File

@@ -1,7 +1,137 @@
import React from 'react'; import React from "react";
import Input from "@/components/Low/Input";
import {
MultipleChoiceExercise,
MultipleChoiceQuestion,
} from "@/interfaces/exam";
import Select from "@/components/Low/Select";
const MultipleChoiceEdit = () => { interface Props {
return null; exercise: MultipleChoiceExercise;
updateExercise: (data: any) => void;
} }
const variantOptions = [
{ value: "text", label: "Text", key: "text" },
{ value: "image", label: "Image", key: "src" },
];
const MultipleChoiceEdit = (props: Props) => {
const { exercise, updateExercise } = props;
return (
<>
<h1>Questions</h1>
<div className="w-full flex-no-wrap -mx-2">
{exercise.questions.map((question: MultipleChoiceQuestion, index) => {
const variantValue = variantOptions.find(
(o) => o.value === question.variant
);
const solutionsOptions = question.options.map((option) => ({
value: option.id,
label: option.id,
}));
const solutionValue = solutionsOptions.find(
(o) => o.value === question.solution
);
return (
<div key={question.id} className="flex w-full px-2 flex-col">
<span>Question ID: {question.id}</span>
<Input
type="text"
label="Prompt"
name="prompt"
required
value={question.prompt}
onChange={(value) =>
updateExercise({
questions: exercise.questions.map((sol) =>
sol.id === question.id ? { ...sol, prompt: value } : sol
),
})
}
/>
<div className="flex w-full">
<div className="w-48 flex items-end px-2">
<Select
value={solutionValue}
options={solutionsOptions}
onChange={(value) => {
updateExercise({
questions: exercise.questions.map((sol) =>
sol.id === question.id
? { ...sol, solution: value?.value }
: sol
),
});
}}
/>
</div>
<div className="w-48 flex items-end px-2">
<Select
value={variantValue}
options={variantOptions}
onChange={(value) => {
updateExercise({
questions: exercise.questions.map((sol) =>
sol.id === question.id
? { ...sol, variant: value?.value }
: sol
),
});
}}
/>
</div>
</div>
<div className="flex w-full flex-wrap -mx-2">
{question.options.map((option) => (
<div
key={option.id}
className="flex sm:w-1/2 lg:w-1/4 px-2 px-2"
>
<Input
type="text"
label={`Option ${option.id}`}
name="option"
required
value={option.text}
onChange={(value) =>
updateExercise({
questions: exercise.questions.map((sol) =>
sol.id === question.id
? {
...sol,
options: sol.options.map((opt) => {
if (
opt.id === option.id &&
variantValue?.key
) {
return {
...opt,
[variantValue.key]: value,
};
}
return opt;
}),
}
: sol
),
})
}
/>
</div>
))}
</div>
</div>
);
})}
</div>
</>
);
};
export default MultipleChoiceEdit; export default MultipleChoiceEdit;

View File

@@ -1,18 +1,19 @@
import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import {Difficulty, Exercise, ListeningExam} from "@/interfaces/exam"; import { Difficulty, Exercise, ListeningExam } 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 {convertCamelCaseToReadable} from "@/utils/string"; import { convertCamelCaseToReadable } from "@/utils/string";
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 {useEffect, useState} from "react"; import { useEffect, useState, Dispatch, SetStateAction } from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs"; import { BsArrowRepeat, BsCheck } from "react-icons/bs";
import {toast} from "react-toastify"; import { toast } from "react-toastify";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"]; const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
@@ -22,12 +23,14 @@ const PartTab = ({
difficulty, difficulty,
index, index,
setPart, setPart,
updatePart,
}: { }: {
part?: ListeningPart; part?: ListeningPart;
difficulty: Difficulty; difficulty: Difficulty;
types: string[]; types: string[];
index: number; index: number;
setPart: (part?: ListeningPart) => void; setPart: (part?: ListeningPart) => void;
updatePart: Dispatch<SetStateAction<ListeningPart | undefined>>;
}) => { }) => {
const [topic, setTopic] = useState(""); const [topic, setTopic] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -42,10 +45,17 @@ const PartTab = ({
setPart(undefined); setPart(undefined);
setIsLoading(true); setIsLoading(true);
axios axios
.get(`/api/exam/listening/generate/listening_section_${index}${topic || types ? `?${url.toString()}` : ""}`) .get(
`/api/exam/listening/generate/listening_section_${index}${
topic || types ? `?${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")
return toast.error(
"Something went wrong, please try to generate again."
);
setPart(result.data); setPart(result.data);
}) })
.catch((error) => { .catch((error) => {
@@ -55,10 +65,51 @@ const PartTab = ({
.finally(() => setIsLoading(false)); .finally(() => setIsLoading(false));
}; };
const renderExercises = () => {
return part?.exercises.map((exercise) => {
switch (exercise.type) {
case "multipleChoice":
return (
<>
<h1>Exercise: Multiple Choice</h1>
<MultipleChoiceEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) =>
updatePart((part?: ListeningPart) => {
if (part) {
const exercises = part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
) as Exercise[];
const updatedPart = {
...part,
exercises,
} as ListeningPart;
return updatedPart;
}
})
}
/>
</>
);
default:
return null;
}
});
};
return ( return (
<Tab.Panel className="w-full bg-ielts-listening/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4"> <Tab.Panel className="w-full bg-ielts-listening/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">
<Input type="text" placeholder="Grand Canyon..." name="topic" label="Topic" onChange={setTopic} roundness="xl" defaultValue={topic} /> <Input
type="text"
placeholder="Grand Canyon..."
name="topic"
label="Topic"
onChange={setTopic}
roundness="xl"
defaultValue={topic}
/>
<button <button
onClick={generate} onClick={generate}
disabled={isLoading || types.length === 0} disabled={isLoading || types.length === 0}
@@ -67,8 +118,9 @@ const PartTab = ({
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px]", "bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px]",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed", "hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
isLoading && "tooltip", isLoading && "tooltip"
)}> )}
>
{isLoading ? ( {isLoading ? (
<div className="flex items-center justify-center"> <div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} /> <BsArrowRepeat className="text-white animate-spin" size={25} />
@@ -80,20 +132,34 @@ const PartTab = ({
</div> </div>
{isLoading && ( {isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center"> <div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span className={clsx("loading loading-infinity w-32 text-ielts-listening")} /> <span
<span className={clsx("font-bold text-2xl text-ielts-listening")}>Generating...</span> className={clsx(
"loading loading-infinity w-32 text-ielts-listening"
)}
/>
<span className={clsx("font-bold text-2xl text-ielts-listening")}>
Generating...
</span>
</div> </div>
)} )}
{part && ( {part && (
<>
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide"> <div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
<div className="flex gap-4"> <div className="flex gap-4">
{part.exercises.map((x) => ( {part.exercises.map((x) => (
<span className="rounded-xl bg-white border border-ielts-listening p-1 px-4" key={x.id}> <span
className="rounded-xl bg-white border border-ielts-listening p-1 px-4"
key={x.id}
>
{x.type && convertCamelCaseToReadable(x.type)} {x.type && convertCamelCaseToReadable(x.type)}
</span> </span>
))} ))}
</div> </div>
{typeof part.text === "string" && <span className="w-full h-96">{part.text.replaceAll("\n\n", " ")}</span>} {typeof part.text === "string" && (
<span className="w-full h-96">
{part.text.replaceAll("\n\n", " ")}
</span>
)}
{typeof part.text !== "string" && ( {typeof part.text !== "string" && (
<div className="w-full h-96 flex flex-col gap-2"> <div className="w-full h-96 flex flex-col gap-2">
{part.text.conversation.map((x, index) => ( {part.text.conversation.map((x, index) => (
@@ -105,6 +171,8 @@ const PartTab = ({
</div> </div>
)} )}
</div> </div>
{renderExercises()}
</>
)} )}
</Tab.Panel> </Tab.Panel>
); );
@@ -133,7 +201,9 @@ const ListeningGeneration = () => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ListeningExam>(); const [resultingExam, setResultingExam] = useState<ListeningExam>();
const [types, setTypes] = useState<string[]>([]); const [types, setTypes] = useState<string[]>([]);
const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!); const [difficulty, setDifficulty] = useState<Difficulty>(
sample(DIFFICULTIES)!
);
useEffect(() => { useEffect(() => {
const part1Timer = part1 ? 5 : 0; const part1Timer = part1 ? 5 : 0;
@@ -146,10 +216,10 @@ const ListeningGeneration = () => {
}, [part1, part2, part3, part4]); }, [part1, part2, part3, part4]);
const availableTypes = [ const availableTypes = [
{type: "multipleChoice", label: "Multiple Choice"}, { type: "multipleChoice", label: "Multiple Choice" },
{type: "writeBlanksQuestions", label: "Write the Blanks: Questions"}, { type: "writeBlanksQuestions", label: "Write the Blanks: Questions" },
{type: "writeBlanksFill", label: "Write the Blanks: Fill"}, { type: "writeBlanksFill", label: "Write the Blanks: Fill" },
{type: "writeBlanksForm", label: "Write the Blanks: Form"}, { type: "writeBlanksForm", label: "Write the Blanks: Form" },
]; ];
const router = useRouter(); const router = useRouter();
@@ -157,21 +227,33 @@ const ListeningGeneration = () => {
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 toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type])); const toggleType = (type: string) =>
setTypes((prev) =>
prev.includes(type)
? [...prev.filter((x) => x !== type)]
: [...prev, type]
);
const submitExam = () => { const submitExam = () => {
const parts = [part1, part2, part3, part4].filter((x) => !!x); const parts = [part1, part2, part3, part4].filter((x) => !!x);
console.log({parts}); console.log({ parts });
if (parts.length === 0) return toast.error("Please generate at least one section!"); if (parts.length === 0)
return toast.error("Please generate at least one section!");
setIsLoading(true); setIsLoading(true);
axios axios
.post(`/api/exam/listening/generate/listening`, {parts, minTimer, difficulty}) .post(`/api/exam/listening/generate/listening`, {
parts,
minTimer,
difficulty,
})
.then((result) => { .then((result) => {
playSound("sent"); playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`); console.log(`Generated Exam ID: ${result.data.id}`);
toast.success("This new exam has been generated successfully! Check the ID in our browser's console."); toast.success(
"This new exam has been generated successfully! Check the ID in our browser's console."
);
setResultingExam(result.data); setResultingExam(result.data);
setPart1(undefined); setPart1(undefined);
@@ -191,9 +273,12 @@ const ListeningGeneration = () => {
const loadExam = async (examId: string) => { const loadExam = async (examId: string) => {
const exam = await getExamById("listening", examId.trim()); const exam = await getExamById("listening", 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(
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id", toastId: "invalid-exam-id",
}); }
);
return; return;
} }
@@ -208,7 +293,9 @@ const ListeningGeneration = () => {
<> <>
<div className="flex gap-4 w-1/2"> <div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Timer</label> <label className="font-normal text-base text-mti-gray-dim">
Timer
</label>
<Input <Input
type="number" type="number"
name="minTimer" name="minTimer"
@@ -218,18 +305,27 @@ const ListeningGeneration = () => {
/> />
</div> </div>
<div className="flex flex-col gap-3 w-full"> <div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Difficulty</label> <label className="font-normal text-base text-mti-gray-dim">
Difficulty
</label>
<Select <Select
options={DIFFICULTIES.map((x) => ({value: x, label: capitalize(x)}))} options={DIFFICULTIES.map((x) => ({
onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)} value: x,
value={{value: difficulty, label: capitalize(difficulty)}} label: capitalize(x),
}))}
onChange={(value) =>
value ? setDifficulty(value.value as Difficulty) : null
}
value={{ value: difficulty, label: capitalize(difficulty) }}
disabled={!!part1 || !!part2 || !!part3 || !!part4} disabled={!!part1 || !!part2 || !!part3 || !!part4}
/> />
</div> </div>
</div> </div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Exercises</label> <label className="font-normal text-base text-mti-gray-dim">
Exercises
</label>
<div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between"> <div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
{availableTypes.map((x) => ( {availableTypes.map((x) => (
<span <span
@@ -240,8 +336,9 @@ const ListeningGeneration = () => {
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!types.includes(x.type) !types.includes(x.type)
? "bg-white border-mti-gray-platinum" ? "bg-white border-mti-gray-platinum"
: "bg-ielts-listening/70 border-ielts-listening text-white", : "bg-ielts-listening/70 border-ielts-listening text-white"
)}> )}
>
{x.label} {x.label}
</span> </span>
))} ))}
@@ -251,58 +348,78 @@ const ListeningGeneration = () => {
<Tab.Group> <Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-listening/20 p-1"> <Tab.List className="flex space-x-1 rounded-xl bg-ielts-listening/20 p-1">
<Tab <Tab
className={({selected}) => className={({ selected }) =>
clsx( clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center", "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
}> }
>
Section 1 {part1 && <BsCheck />} Section 1 {part1 && <BsCheck />}
</Tab> </Tab>
<Tab <Tab
className={({selected}) => className={({ selected }) =>
clsx( clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center", "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
}> }
>
Section 2 {part2 && <BsCheck />} Section 2 {part2 && <BsCheck />}
</Tab> </Tab>
<Tab <Tab
className={({selected}) => className={({ selected }) =>
clsx( clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center", "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
}> }
>
Section 3 {part3 && <BsCheck />} Section 3 {part3 && <BsCheck />}
</Tab> </Tab>
<Tab <Tab
className={({selected}) => className={({ selected }) =>
clsx( clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center", "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
}> }
>
Section 4 {part4 && <BsCheck />} Section 4 {part4 && <BsCheck />}
</Tab> </Tab>
</Tab.List> </Tab.List>
<Tab.Panels> <Tab.Panels>
{[ {[
{part: part1, setPart: setPart1}, { part: part1, setPart: setPart1 },
{part: part2, setPart: setPart2}, { part: part2, setPart: setPart2 },
{part: part3, setPart: setPart3}, { part: part3, setPart: setPart3 },
{part: part4, setPart: setPart4}, { part: part4, setPart: setPart4 },
].map(({part, setPart}, index) => ( ].map(({ part, setPart }, index) => (
<PartTab part={part} difficulty={difficulty} types={types} index={index + 1} key={index} setPart={setPart} /> <PartTab
part={part}
difficulty={difficulty}
types={types}
index={index + 1}
key={index}
setPart={setPart}
updatePart={setPart}
/>
))} ))}
</Tab.Panels> </Tab.Panels>
</Tab.Group> </Tab.Group>
@@ -314,8 +431,9 @@ const ListeningGeneration = () => {
className={clsx( className={clsx(
"bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end", "bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed", "hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300"
)}> )}
>
Perform Exam Perform Exam
</button> </button>
)} )}
@@ -327,8 +445,9 @@ const ListeningGeneration = () => {
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end", "bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed", "hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
!part1 && !part2 && !part3 && !part4 && "tooltip", !part1 && !part2 && !part3 && !part4 && "tooltip"
)}> )}
>
{isLoading ? ( {isLoading ? (
<div className="flex items-center justify-center"> <div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} /> <BsArrowRepeat className="text-white animate-spin" size={25} />