Updated the FillBlanks to the new format

This commit is contained in:
Tiago Ribeiro
2024-07-27 14:38:45 +01:00
parent 9ef04b822a
commit 8f5b27e9ce
6 changed files with 523 additions and 579 deletions

View File

@@ -77,15 +77,8 @@ export default function FillBlanks({
onBack, onBack,
}: FillBlanksExercise & CommonProps) { }: FillBlanksExercise & CommonProps) {
const [answers, setAnswers] = useState<{id: string; solution: string}[]>(userSolutions); const [answers, setAnswers] = useState<{id: string; solution: string}[]>(userSolutions);
const [currentBlankId, setCurrentBlankId] = useState<string>();
const [isDrawerShowing, setIsDrawerShowing] = useState(false);
const hasExamEnded = useExamStore((state) => state.hasExamEnded); const hasExamEnded = useExamStore((state) => state.hasExamEnded);
const allBlanks = Array.from(text.match(/({{\d+}})/g) || []).map((x) => x.replaceAll("{", "").replaceAll("}", ""));
useEffect(() => {
setTimeout(() => setIsDrawerShowing(!!currentBlankId), 100);
}, [currentBlankId]);
useEffect(() => { useEffect(() => {
if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type}); if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type});
@@ -94,9 +87,17 @@ export default function FillBlanks({
const calculateScore = () => { const calculateScore = () => {
const total = text.match(/({{\d+}})/g)?.length || 0; const total = text.match(/({{\d+}})/g)?.length || 0;
const correct = answers.filter( const correct = answers.filter((x) => {
(x) => solutions.find((y) => x.id.toString() === y.id.toString())?.solution === x.solution.toLowerCase() || false, const solution = solutions.find((y) => x.id.toString() === y.id.toString())?.solution.toLowerCase();
).length; if (!solution) return false;
const option = words.find((w) =>
typeof w === "string" ? w.toLowerCase() === x.solution.toLowerCase() : w.letter.toLowerCase() === x.solution.toLowerCase(),
);
if (!option) return false;
return solution === (typeof option === "string" ? option.toLowerCase() : option.word.toLowerCase());
}).length;
const missing = total - answers.filter((x) => solutions.find((y) => x.id.toString() === y.id.toString())).length; const missing = total - answers.filter((x) => solutions.find((y) => x.id.toString() === y.id.toString())).length;
return {total, correct, missing}; return {total, correct, missing};
@@ -104,49 +105,29 @@ export default function FillBlanks({
const renderLines = (line: string) => { const renderLines = (line: string) => {
return ( return (
<span className="text-base leading-5"> <div className="text-base leading-5">
{reactStringReplace(line, /({{\d+}})/g, (match) => { {reactStringReplace(line, /({{\d+}})/g, (match) => {
const id = match.replaceAll(/[\{\}]/g, ""); const id = match.replaceAll(/[\{\}]/g, "");
const userSolution = answers.find((x) => x.id === id); const userSolution = answers.find((x) => x.id === id);
return ( return (
<button <input
className={clsx( className={clsx(
"rounded-full hover:text-white hover:bg-mti-purple transition duration-300 ease-in-out my-1", "rounded-full hover:text-white focus:ring-0 focus:outline-none focus:!text-white focus:bg-mti-purple transition duration-300 ease-in-out my-1 px-5 py-2 text-center",
!userSolution && "w-6 h-6 text-center text-mti-purple-light bg-mti-purple-ultralight", !userSolution && "text-center text-mti-purple-light bg-mti-purple-ultralight",
currentBlankId === id && "text-white !bg-mti-purple-light ", userSolution && "px-5 py-2 text-center text-mti-purple-dark bg-mti-purple-ultralight",
userSolution && "px-5 py-2 text-center text-white bg-mti-purple-light",
)} )}
onClick={() => setCurrentBlankId(id)}> onChange={(e) => setAnswers((prev) => [...prev.filter((x) => x.id !== id), {id, solution: e.target.value}])}
{userSolution ? userSolution.solution : id} value={userSolution?.solution}></input>
</button>
); );
})} })}
</span> </div>
); );
}; };
return ( return (
<> <>
<div className="flex flex-col gap-4 mt-4 h-full w-full mb-20"> <div className="flex flex-col gap-4 mt-4 h-full w-full mb-20">
{(!!currentBlankId || isDrawerShowing) && (
<WordsDrawer
key={currentBlankId}
blankId={currentBlankId}
words={words.map((word) => ({word, isDisabled: allowRepetition ? false : answers.map((x) => x.solution).includes(word)}))}
previouslySelectedWord={currentBlankId ? answers.find((x) => x.id === currentBlankId)?.solution : undefined}
isOpen={isDrawerShowing}
onCancel={() => setCurrentBlankId(undefined)}
onAnswer={(solution: string) => {
setAnswers((prev) => [...prev.filter((x) => x.id !== currentBlankId), {id: currentBlankId!, solution}]);
if (allBlanks.findIndex((x) => x === currentBlankId) + 1 < allBlanks.length) {
setCurrentBlankId(allBlanks[allBlanks.findIndex((x) => x === currentBlankId) + 1]);
return;
}
setCurrentBlankId(undefined);
}}
/>
)}
<span className="text-sm w-full leading-6"> <span className="text-sm w-full leading-6">
{prompt.split("\\n").map((line, index) => ( {prompt.split("\\n").map((line, index) => (
<Fragment key={index}> <Fragment key={index}>
@@ -163,6 +144,26 @@ export default function FillBlanks({
</p> </p>
))} ))}
</span> </span>
<div className="bg-mti-gray-smoke rounded-xl px-5 py-6 flex flex-col gap-4">
<span className="font-medium text-mti-purple-dark">Options</span>
<div className="flex gap-4 flex-wrap">
{words.map((v) => {
const text = typeof v === "string" ? v : `${v.letter} - ${v.word}`;
return (
<span
className={clsx(
"border border-mti-purple-light rounded-full px-3 py-0.5 transition ease-in-out duration-300",
!!answers.find((x) => x.solution.toLowerCase() === (typeof v === "string" ? v : v.letter).toLowerCase()) &&
"bg-mti-purple-dark text-white",
)}
key={text}>
{text}
</span>
);
})}
</div>
</div>
</div> </div>
<div className="self-end flex justify-between w-full gap-8 absolute bottom-8 left-0 px-8"> <div className="self-end flex justify-between w-full gap-8 absolute bottom-8 left-0 px-8">

View File

@@ -1,84 +1,82 @@
import { FillBlanksExercise } from "@/interfaces/exam"; import {FillBlanksExercise} from "@/interfaces/exam";
import React from "react"; import React from "react";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
interface Props { interface Props {
exercise: FillBlanksExercise; exercise: FillBlanksExercise;
updateExercise: (data: any) => void; updateExercise: (data: any) => void;
} }
const FillBlanksEdit = (props: Props) => { const FillBlanksEdit = (props: Props) => {
const { exercise, updateExercise } = props; const {exercise, updateExercise} = props;
return ( return (
<> <>
<Input <Input
type="text" type="text"
label="Prompt" label="Prompt"
name="prompt" name="prompt"
required required
value={exercise.prompt} value={exercise.prompt}
onChange={(value) => onChange={(value) =>
updateExercise({ updateExercise({
prompt: value, prompt: value,
}) })
} }
/> />
<Input <Input
type="text" type="text"
label="Text" label="Text"
name="text" name="text"
required required
value={exercise.text} value={exercise.text}
onChange={(value) => onChange={(value) =>
updateExercise({ updateExercise({
text: value, text: value,
}) })
} }
/> />
<h1>Solutions</h1> <h1>Solutions</h1>
<div className="w-full flex flex-wrap -mx-2"> <div className="w-full flex flex-wrap -mx-2">
{exercise.solutions.map((solution, index) => ( {exercise.solutions.map((solution, index) => (
<div key={solution.id} className="flex sm:w-1/2 lg:w-1/4 px-2"> <div key={solution.id} className="flex sm:w-1/2 lg:w-1/4 px-2">
<Input <Input
type="text" type="text"
label={`Solution ${index + 1}`} label={`Solution ${index + 1}`}
name="solution" name="solution"
required required
value={solution.solution} value={solution.solution}
onChange={(value) => onChange={(value) =>
updateExercise({ updateExercise({
solutions: exercise.solutions.map((sol) => solutions: exercise.solutions.map((sol) => (sol.id === solution.id ? {...sol, solution: value} : sol)),
sol.id === solution.id ? { ...sol, solution: value } : sol })
), }
}) />
} </div>
/> ))}
</div> </div>
))} <h1>Words</h1>
</div> <div className="w-full flex flex-wrap -mx-2">
<h1>Words</h1> {exercise.words.map((word, index) => (
<div className="w-full flex flex-wrap -mx-2"> <div key={index} className="flex sm:w-1/2 lg:w-1/4 px-2">
{exercise.words.map((word, index) => ( <Input
<div key={index} className="flex sm:w-1/2 lg:w-1/4 px-2"> type="text"
<Input label={`Word ${index + 1}`}
type="text" name="word"
label={`Word ${index + 1}`} required
name="word" value={typeof word === "string" ? word : word.word}
required onChange={(value) =>
value={word} updateExercise({
onChange={(value) => words: exercise.words.map((sol, idx) =>
updateExercise({ index === idx ? (typeof word === "string" ? value : {...word, word: value}) : sol,
words: exercise.words.map((sol, idx) => ),
index === idx ? value : sol })
), }
}) />
} </div>
/> ))}
</div> </div>
))} </>
</div> );
</>
);
}; };
export default FillBlanksEdit; export default FillBlanksEdit;

View File

@@ -5,12 +5,30 @@ import {CommonProps} from ".";
import {Fragment} from "react"; import {Fragment} from "react";
import Button from "../Low/Button"; import Button from "../Low/Button";
export default function FillBlanksSolutions({id, type, prompt, solutions, text, userSolutions, onNext, onBack}: FillBlanksExercise & CommonProps) { export default function FillBlanksSolutions({
id,
type,
prompt,
solutions,
words,
text,
userSolutions,
onNext,
onBack,
}: FillBlanksExercise & CommonProps) {
const calculateScore = () => { const calculateScore = () => {
const total = text.match(/({{\d+}})/g)?.length || 0; const total = text.match(/({{\d+}})/g)?.length || 0;
const correct = userSolutions.filter( const correct = userSolutions.filter((x) => {
(x) => solutions.find((y) => x.id.toString() === y.id.toString())?.solution === x.solution.toLowerCase() || false, const solution = solutions.find((y) => x.id.toString() === y.id.toString())?.solution.toLowerCase();
).length; if (!solution) return false;
const option = words.find((w) =>
typeof w === "string" ? w.toLowerCase() === x.solution.toLowerCase() : w.letter.toLowerCase() === x.solution.toLowerCase(),
);
if (!option) return false;
return solution === (typeof option === "string" ? option.toLowerCase() : option.word.toLowerCase());
}).length;
const missing = total - userSolutions.filter((x) => solutions.find((y) => x.id.toString() === y.id.toString())).length; const missing = total - userSolutions.filter((x) => solutions.find((y) => x.id.toString() === y.id.toString())).length;
return {total, correct, missing}; return {total, correct, missing};
@@ -35,7 +53,14 @@ export default function FillBlanksSolutions({id, type, prompt, solutions, text,
); );
} }
if (userSolution.solution === solution.solution) { const userSolutionWord = words.find((w) =>
typeof w === "string"
? w.toLowerCase() === userSolution.solution.toLowerCase()
: w.letter.toLowerCase() === userSolution.solution.toLowerCase(),
);
const userSolutionText = typeof userSolutionWord === "string" ? userSolutionWord : userSolutionWord?.word;
if (userSolutionText === solution.solution) {
return ( return (
<button <button
className={clsx( className={clsx(
@@ -47,7 +72,7 @@ export default function FillBlanksSolutions({id, type, prompt, solutions, text,
); );
} }
if (userSolution.solution !== solution.solution) { if (userSolutionText !== solution.solution) {
return ( return (
<> <>
<button <button
@@ -55,7 +80,7 @@ export default function FillBlanksSolutions({id, type, prompt, solutions, text,
"rounded-full hover:text-white hover:bg-mti-rose transition duration-300 ease-in-out my-1 mr-1", "rounded-full hover:text-white hover:bg-mti-rose transition duration-300 ease-in-out my-1 mr-1",
userSolution && "px-5 py-2 text-center text-white bg-mti-rose-light", userSolution && "px-5 py-2 text-center text-white bg-mti-rose-light",
)}> )}>
{userSolution.solution} {userSolutionText}
</button> </button>
<button <button

View File

@@ -158,21 +158,21 @@ export interface WritingExercise {
} }
export interface AIDetectionAttributes { export interface AIDetectionAttributes {
predicted_class: 'ai' | 'mixed' | 'human'; predicted_class: "ai" | "mixed" | "human";
confidence_category: 'high' | 'medium' | 'low'; confidence_category: "high" | "medium" | "low";
class_probabilities: { class_probabilities: {
ai: number; ai: number;
human: number; human: number;
mixed: number; mixed: number;
}, };
sentences: { sentences: {
sentence: string; sentence: string;
highlight_sentence_for_ai: boolean highlight_sentence_for_ai: boolean;
}[] }[];
} }
export interface WritingEvaluation extends CommonEvaluation { export interface WritingEvaluation extends CommonEvaluation {
ai_detection?: AIDetectionAttributes ai_detection?: AIDetectionAttributes;
} }
export interface SpeakingExercise { export interface SpeakingExercise {
@@ -214,7 +214,7 @@ export interface FillBlanksExercise {
prompt: string; // *EXAMPLE: "Complete the summary below. Click a blank to select the corresponding word for it." prompt: string; // *EXAMPLE: "Complete the summary below. Click a blank to select the corresponding word for it."
type: "fillBlanks"; type: "fillBlanks";
id: string; id: string;
words: string[]; // *EXAMPLE: ["preserve", "unaware"] words: (string | {letter: string; word: string})[]; // *EXAMPLE: ["preserve", "unaware"]
text: string; // *EXAMPLE: "They tried to {{1}} burning" text: string; // *EXAMPLE: "They tried to {{1}} burning"
allowRepetition: boolean; allowRepetition: boolean;
solutions: { solutions: {

View File

@@ -334,7 +334,7 @@ const LevelGeneration = () => {
prompt: "Complete the summary below. Click a blank to select the corresponding word for it.", prompt: "Complete the summary below. Click a blank to select the corresponding word for it.",
allowRepetition: false, allowRepetition: false,
text: currentExercise.text, text: currentExercise.text,
words: currentExercise.words.map((x: any) => x.text), words: currentExercise.words,
solutions: currentExercise.words.map((x: any) => ({id: x.id, solution: x.text})), solutions: currentExercise.words.map((x: any) => ({id: x.id, solution: x.text})),
type: "fillBlanks", type: "fillBlanks",
userSolutions: [], userSolutions: [],

View File

@@ -1,24 +1,19 @@
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 { import {Difficulty, Exercise, ReadingExam, ReadingPart} from "@/interfaces/exam";
Difficulty,
Exercise,
ReadingExam,
ReadingPart,
} 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, Dispatch, SetStateAction } 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";
import { v4 } from "uuid"; import {v4} from "uuid";
import FillBlanksEdit from "@/components/Generation/fill.blanks.edit"; import FillBlanksEdit from "@/components/Generation/fill.blanks.edit";
import TrueFalseEdit from "@/components/Generation/true.false.edit"; import TrueFalseEdit from "@/components/Generation/true.false.edit";
import WriteBlanksEdit from "@/components/Generation/write.blanks.edit"; import WriteBlanksEdit from "@/components/Generation/write.blanks.edit";
@@ -27,472 +22,397 @@ import MatchSentencesEdit from "@/components/Generation/match.sentences.edit";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"]; const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
const availableTypes = [ const availableTypes = [
{ type: "fillBlanks", label: "Fill the Blanks" }, {type: "fillBlanks", label: "Fill the Blanks"},
{ type: "trueFalse", label: "True or False" }, {type: "trueFalse", label: "True or False"},
{ type: "writeBlanks", label: "Write the Blanks" }, {type: "writeBlanks", label: "Write the Blanks"},
{ type: "paragraphMatch", label: "Match Sentences" }, {type: "paragraphMatch", label: "Match Sentences"},
]; ];
const PartTab = ({ const PartTab = ({
part, part,
difficulty, difficulty,
index, index,
setPart, setPart,
updatePart, updatePart,
}: { }: {
part?: ReadingPart; part?: ReadingPart;
index: number; index: number;
difficulty: Difficulty; difficulty: Difficulty;
setPart: (part?: ReadingPart) => void; setPart: (part?: ReadingPart) => void;
updatePart: Dispatch<SetStateAction<ReadingPart | undefined>>; updatePart: Dispatch<SetStateAction<ReadingPart | undefined>>;
// updatePart: (updater: (part: ReadingPart) => ReadingPart) => void;
}) => { }) => {
const [topic, setTopic] = useState(""); const [topic, setTopic] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [types, setTypes] = useState<string[]>([]); const [types, setTypes] = useState<string[]>([]);
const toggleType = (type: string) => const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type]));
setTypes((prev) =>
prev.includes(type)
? [...prev.filter((x) => x !== type)]
: [...prev, type]
);
const generate = () => { const generate = () => {
const url = new URLSearchParams(); const url = new URLSearchParams();
url.append("difficulty", difficulty); url.append("difficulty", difficulty);
if (topic) url.append("topic", topic); if (topic) url.append("topic", topic);
if (types) types.forEach((t) => url.append("exercises", t)); if (types) types.forEach((t) => url.append("exercises", t));
setPart(undefined); setPart(undefined);
setIsLoading(true); setIsLoading(true);
axios axios
.get( .get(`/api/exam/reading/generate/reading_passage_${index}${topic || types ? `?${url.toString()}` : ""}`)
`/api/exam/reading/generate/reading_passage_${index}${ .then((result) => {
topic || types ? `?${url.toString()}` : "" playSound(typeof result.data === "string" ? "error" : "check");
}` if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again.");
) setPart(result.data);
.then((result) => { })
playSound(typeof result.data === "string" ? "error" : "check"); .catch((error) => {
if (typeof result.data === "string") console.log(error);
return toast.error( toast.error("Something went wrong!");
"Something went wrong, please try to generate again." })
); .finally(() => setIsLoading(false));
setPart(result.data); };
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const renderExercises = () => { const renderExercises = () => {
return part?.exercises.map((exercise) => { return part?.exercises.map((exercise) => {
switch (exercise.type) { switch (exercise.type) {
case "fillBlanks": case "fillBlanks":
return ( return (
<> <>
<h1>Exercise: Fill Blanks</h1> <h1>Exercise: Fill Blanks</h1>
<FillBlanksEdit <FillBlanksEdit
exercise={exercise} exercise={exercise}
key={exercise.id} key={exercise.id}
updateExercise={(data: any) => updateExercise={(data: any) =>
updatePart((part?: ReadingPart) => { updatePart((part?: ReadingPart) => {
if (part) { if (part) {
const exercises = part.exercises.map((x) => const exercises = part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)) as Exercise[];
x.id === exercise.id ? { ...x, ...data } : x const updatedPart = {...part, exercises} as ReadingPart;
) as Exercise[]; return updatedPart;
const updatedPart = { ...part, exercises } as ReadingPart; }
return updatedPart;
}
return part; return part;
}) })
} }
/> />
</> </>
); );
case "trueFalse": case "trueFalse":
return ( return (
<> <>
<h1>Exercise: True or False</h1> <h1>Exercise: True or False</h1>
<TrueFalseEdit <TrueFalseEdit
exercise={exercise} exercise={exercise}
key={exercise.id} key={exercise.id}
updateExercise={(data: any) => { updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => { updatePart((part?: ReadingPart) => {
if (part) { if (part) {
return { return {
...part, ...part,
exercises: part.exercises.map((x) => exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
x.id === exercise.id ? { ...x, ...data } : x } as ReadingPart;
), }
} as ReadingPart;
}
return part; return part;
}); });
}} }}
/> />
</> </>
); );
case "writeBlanks": case "writeBlanks":
return ( return (
<> <>
<h1>Exercise: Write Blanks</h1> <h1>Exercise: Write Blanks</h1>
<WriteBlanksEdit <WriteBlanksEdit
exercise={exercise} exercise={exercise}
key={exercise.id} key={exercise.id}
updateExercise={(data: any) => { updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => { updatePart((part?: ReadingPart) => {
if (part) { if (part) {
return { return {
...part, ...part,
exercises: part.exercises.map((x) => exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
x.id === exercise.id ? { ...x, ...data } : x } as ReadingPart;
), }
} as ReadingPart;
}
return part; return part;
}); });
}} }}
/> />
</> </>
); );
case "matchSentences": case "matchSentences":
return ( return (
<> <>
<h1>Exercise: Match Sentences</h1> <h1>Exercise: Match Sentences</h1>
<MatchSentencesEdit <MatchSentencesEdit
exercise={exercise} exercise={exercise}
key={exercise.id} key={exercise.id}
updateExercise={(data: any) => { updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => { updatePart((part?: ReadingPart) => {
if (part) { if (part) {
return { return {
...part, ...part,
exercises: part.exercises.map((x) => exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
x.id === exercise.id ? { ...x, ...data } : x } as ReadingPart;
), }
} as ReadingPart;
}
return part; return part;
}); });
}} }}
/> />
</> </>
); );
default: default:
return null; return null;
} }
}); });
}; };
return ( return (
<Tab.Panel className="w-full bg-ielts-reading/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4"> <Tab.Panel className="w-full bg-ielts-reading/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">Exercises</label>
Exercises <div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
</label> {availableTypes.map((x) => (
<div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between"> <span
{availableTypes.map((x) => ( onClick={() => toggleType(x.type)}
<span key={x.type}
onClick={() => toggleType(x.type)} className={clsx(
key={x.type} "px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
className={clsx( "transition duration-300 ease-in-out",
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", !types.includes(x.type) ? "bg-white border-mti-gray-platinum" : "bg-ielts-reading/70 border-ielts-reading text-white",
"transition duration-300 ease-in-out", )}>
!types.includes(x.type) {x.label}
? "bg-white border-mti-gray-platinum" </span>
: "bg-ielts-reading/70 border-ielts-reading text-white" ))}
)} </div>
> </div>
{x.label} <div className="flex gap-4 items-end">
</span> <Input type="text" placeholder="Grand Canyon..." name="topic" label="Topic" onChange={setTopic} roundness="xl" defaultValue={topic} />
))} <button
</div> onClick={generate}
</div> disabled={isLoading || types.length === 0}
<div className="flex gap-4 items-end"> data-tip="The passage is currently being generated"
<Input className={clsx(
type="text" "bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px]",
placeholder="Grand Canyon..." "hover:bg-ielts-reading disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
name="topic" "transition ease-in-out duration-300",
label="Topic" isLoading && "tooltip",
onChange={setTopic} )}>
roundness="xl" {isLoading ? (
defaultValue={topic} <div className="flex items-center justify-center">
/> <BsArrowRepeat className="text-white animate-spin" size={25} />
<button </div>
onClick={generate} ) : (
disabled={isLoading || types.length === 0} "Generate"
data-tip="The passage is currently being generated" )}
className={clsx( </button>
"bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px]", </div>
"hover:bg-ielts-reading disabled:bg-ielts-reading/40 disabled:cursor-not-allowed", {isLoading && (
"transition ease-in-out duration-300", <div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
isLoading && "tooltip" <span className={clsx("loading loading-infinity w-32 text-ielts-reading")} />
)} <span className={clsx("font-bold text-2xl text-ielts-reading")}>Generating...</span>
> </div>
{isLoading ? ( )}
<div className="flex items-center justify-center"> {part && (
<BsArrowRepeat className="text-white animate-spin" size={25} /> <>
</div> <div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
) : ( <div className="flex gap-4">
"Generate" {part.exercises.map((x) => (
)} <span className="rounded-xl bg-white border border-ielts-reading p-1 px-4" key={x.id}>
</button> {x.type && convertCamelCaseToReadable(x.type)}
</div> </span>
{isLoading && ( ))}
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center"> </div>
<span <h3 className="text-xl font-semibold">{part.text.title}</h3>
className={clsx("loading loading-infinity w-32 text-ielts-reading")} <span className="w-full h-96">{part.text.content}</span>
/> </div>
<span className={clsx("font-bold text-2xl text-ielts-reading")}> {renderExercises()}
Generating... </>
</span> )}
</div> </Tab.Panel>
)} );
{part && (
<>
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
<div className="flex gap-4">
{part.exercises.map((x) => (
<span
className="rounded-xl bg-white border border-ielts-reading p-1 px-4"
key={x.id}
>
{x.type && convertCamelCaseToReadable(x.type)}
</span>
))}
</div>
<h3 className="text-xl font-semibold">{part.text.title}</h3>
<span className="w-full h-96">{part.text.content}</span>
</div>
{renderExercises()}
</>
)}
</Tab.Panel>
);
}; };
const ReadingGeneration = () => { const ReadingGeneration = () => {
const [part1, setPart1] = useState<ReadingPart>(); const [part1, setPart1] = useState<ReadingPart>();
const [part2, setPart2] = useState<ReadingPart>(); const [part2, setPart2] = useState<ReadingPart>();
const [part3, setPart3] = useState<ReadingPart>(); const [part3, setPart3] = useState<ReadingPart>();
const [minTimer, setMinTimer] = useState(60); const [minTimer, setMinTimer] = useState(60);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ReadingExam>(); const [resultingExam, setResultingExam] = useState<ReadingExam>();
const [difficulty, setDifficulty] = useState<Difficulty>( const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
sample(DIFFICULTIES)!
);
useEffect(() => { useEffect(() => {
const parts = [part1, part2, part3].filter((x) => !!x); const parts = [part1, part2, part3].filter((x) => !!x);
setMinTimer(parts.length === 0 ? 60 : parts.length * 20); setMinTimer(parts.length === 0 ? 60 : parts.length * 20);
}, [part1, part2, part3]); }, [part1, part2, part3]);
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("reading", examId.trim()); const exam = await getExamById("reading", examId.trim());
if (!exam) { if (!exam) {
toast.error( toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
"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;
} }
setExams([exam]); setExams([exam]);
setSelectedModules(["reading"]); setSelectedModules(["reading"]);
router.push("/exercises"); router.push("/exercises");
}; };
const submitExam = () => { const submitExam = () => {
const parts = [part1, part2, part3].filter((x) => !!x) as ReadingPart[]; const parts = [part1, part2, part3].filter((x) => !!x) as ReadingPart[];
if (parts.length === 0) { if (parts.length === 0) {
toast.error("Please generate at least one passage before submitting"); toast.error("Please generate at least one passage before submitting");
return; return;
} }
setIsLoading(true); setIsLoading(true);
const exam: ReadingExam = { const exam: ReadingExam = {
parts, parts,
isDiagnostic: false, isDiagnostic: false,
minTimer, minTimer,
module: "reading", module: "reading",
id: v4(), id: v4(),
type: "academic", type: "academic",
variant: parts.length === 3 ? "full" : "partial", variant: parts.length === 3 ? "full" : "partial",
difficulty, difficulty,
}; };
axios axios
.post(`/api/exam/reading`, exam) .post(`/api/exam/reading`, exam)
.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( toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
"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);
setPart2(undefined); setPart2(undefined);
setPart3(undefined); setPart3(undefined);
setDifficulty(sample(DIFFICULTIES)!); setDifficulty(sample(DIFFICULTIES)!);
setMinTimer(60); setMinTimer(60);
}) })
.catch((error) => { .catch((error) => {
console.log(error); console.log(error);
toast.error( toast.error("Something went wrong while generating, please try again later.");
"Something went wrong while generating, please try again later." })
); .finally(() => setIsLoading(false));
}) };
.finally(() => setIsLoading(false));
};
return ( return (
<> <>
<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"> <label className="font-normal text-base text-mti-gray-dim">Timer</label>
Timer <Input
</label> type="number"
<Input name="minTimer"
type="number" onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))}
name="minTimer" value={minTimer}
onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))} className="max-w-[300px]"
value={minTimer} />
className="max-w-[300px]" </div>
/> <div className="flex flex-col gap-3 w-full">
</div> <label className="font-normal text-base text-mti-gray-dim">Difficulty</label>
<div className="flex flex-col gap-3 w-full"> <Select
<label className="font-normal text-base text-mti-gray-dim"> options={DIFFICULTIES.map((x) => ({
Difficulty value: x,
</label> label: capitalize(x),
<Select }))}
options={DIFFICULTIES.map((x) => ({ onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)}
value: x, value={{value: difficulty, label: capitalize(difficulty)}}
label: capitalize(x), disabled={!!part1 || !!part2 || !!part3}
}))} />
onChange={(value) => </div>
value ? setDifficulty(value.value as Difficulty) : null </div>
} <Tab.Group>
value={{ value: difficulty, label: capitalize(difficulty) }} <Tab.List className="flex space-x-1 rounded-xl bg-ielts-reading/20 p-1">
disabled={!!part1 || !!part2 || !!part3} <Tab
/> className={({selected}) =>
</div> clsx(
</div> "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center",
<Tab.Group> "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading focus:outline-none focus:ring-2",
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-reading/20 p-1"> "transition duration-300 ease-in-out",
<Tab selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-reading",
className={({ selected }) => )
clsx( }>
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center", Passage 1 {part1 && <BsCheck />}
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading focus:outline-none focus:ring-2", </Tab>
"transition duration-300 ease-in-out", <Tab
selected className={({selected}) =>
? "bg-white shadow" clsx(
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-reading" "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center",
) "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading focus:outline-none focus:ring-2",
} "transition duration-300 ease-in-out",
> selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-reading",
Passage 1 {part1 && <BsCheck />} )
</Tab> }>
<Tab Passage 2 {part2 && <BsCheck />}
className={({ selected }) => </Tab>
clsx( <Tab
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center", className={({selected}) =>
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading focus:outline-none focus:ring-2", clsx(
"transition duration-300 ease-in-out", "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center",
selected "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading focus:outline-none focus:ring-2",
? "bg-white shadow" "transition duration-300 ease-in-out",
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-reading" selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-reading",
) )
} }>
> Passage 3 {part3 && <BsCheck />}
Passage 2 {part2 && <BsCheck />} </Tab>
</Tab> </Tab.List>
<Tab <Tab.Panels>
className={({ selected }) => {[
clsx( {part: part1, setPart: setPart1},
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center", {part: part2, setPart: setPart2},
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading focus:outline-none focus:ring-2", {part: part3, setPart: setPart3},
"transition duration-300 ease-in-out", ].map(({part, setPart}, index) => (
selected <PartTab part={part} difficulty={difficulty} index={index + 1} key={index} setPart={setPart} updatePart={setPart} />
? "bg-white shadow" ))}
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-reading" </Tab.Panels>
) </Tab.Group>
} <div className="w-full flex justify-end gap-4">
> {resultingExam && (
Passage 3 {part3 && <BsCheck />} <button
</Tab> disabled={isLoading}
</Tab.List> onClick={() => loadExam(resultingExam.id)}
<Tab.Panels> className={clsx(
{[ "bg-white border border-ielts-reading text-ielts-reading w-full max-w-[200px] rounded-xl h-[70px] self-end",
{ part: part1, setPart: setPart1 }, "hover:bg-ielts-reading hover:text-white disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
{ part: part2, setPart: setPart2 }, "transition ease-in-out duration-300",
{ part: part3, setPart: setPart3 }, )}>
].map(({ part, setPart }, index) => ( Perform Exam
<PartTab </button>
part={part} )}
difficulty={difficulty} <button
index={index + 1} disabled={(!part1 && !part2 && !part3) || isLoading}
key={index} data-tip="Please generate all three passages"
setPart={setPart} onClick={submitExam}
updatePart={setPart} className={clsx(
/> "bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
))} "hover:bg-ielts-reading disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
</Tab.Panels> "transition ease-in-out duration-300",
</Tab.Group> !part1 && !part2 && !part3 && "tooltip",
<div className="w-full flex justify-end gap-4"> )}>
{resultingExam && ( {isLoading ? (
<button <div className="flex items-center justify-center">
disabled={isLoading} <BsArrowRepeat className="text-white animate-spin" size={25} />
onClick={() => loadExam(resultingExam.id)} </div>
className={clsx( ) : (
"bg-white border border-ielts-reading text-ielts-reading w-full max-w-[200px] rounded-xl h-[70px] self-end", "Submit"
"hover:bg-ielts-reading hover:text-white disabled:bg-ielts-reading/40 disabled:cursor-not-allowed", )}
"transition ease-in-out duration-300" </button>
)} </div>
> </>
Perform Exam );
</button>
)}
<button
disabled={(!part1 && !part2 && !part3) || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-reading disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
!part1 && !part2 && !part3 && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
}; };
export default ReadingGeneration; export default ReadingGeneration;