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,
}: FillBlanksExercise & CommonProps) {
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 allBlanks = Array.from(text.match(/({{\d+}})/g) || []).map((x) => x.replaceAll("{", "").replaceAll("}", ""));
useEffect(() => {
setTimeout(() => setIsDrawerShowing(!!currentBlankId), 100);
}, [currentBlankId]);
useEffect(() => {
if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type});
@@ -94,9 +87,17 @@ export default function FillBlanks({
const calculateScore = () => {
const total = text.match(/({{\d+}})/g)?.length || 0;
const correct = answers.filter(
(x) => solutions.find((y) => x.id.toString() === y.id.toString())?.solution === x.solution.toLowerCase() || false,
).length;
const correct = answers.filter((x) => {
const solution = solutions.find((y) => x.id.toString() === y.id.toString())?.solution.toLowerCase();
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;
return {total, correct, missing};
@@ -104,49 +105,29 @@ export default function FillBlanks({
const renderLines = (line: string) => {
return (
<span className="text-base leading-5">
<div className="text-base leading-5">
{reactStringReplace(line, /({{\d+}})/g, (match) => {
const id = match.replaceAll(/[\{\}]/g, "");
const userSolution = answers.find((x) => x.id === id);
return (
<button
<input
className={clsx(
"rounded-full hover:text-white hover:bg-mti-purple transition duration-300 ease-in-out my-1",
!userSolution && "w-6 h-6 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-white bg-mti-purple-light",
"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 && "text-center text-mti-purple-light bg-mti-purple-ultralight",
userSolution && "px-5 py-2 text-center text-mti-purple-dark bg-mti-purple-ultralight",
)}
onClick={() => setCurrentBlankId(id)}>
{userSolution ? userSolution.solution : id}
</button>
onChange={(e) => setAnswers((prev) => [...prev.filter((x) => x.id !== id), {id, solution: e.target.value}])}
value={userSolution?.solution}></input>
);
})}
</span>
</div>
);
};
return (
<>
<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">
{prompt.split("\\n").map((line, index) => (
<Fragment key={index}>
@@ -163,6 +144,26 @@ export default function FillBlanks({
</p>
))}
</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 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 Input from "@/components/Low/Input";
interface Props {
exercise: FillBlanksExercise;
updateExercise: (data: any) => void;
exercise: FillBlanksExercise;
updateExercise: (data: any) => void;
}
const FillBlanksEdit = (props: Props) => {
const { exercise, updateExercise } = props;
return (
<>
<Input
type="text"
label="Prompt"
name="prompt"
required
value={exercise.prompt}
onChange={(value) =>
updateExercise({
prompt: value,
})
}
/>
<Input
type="text"
label="Text"
name="text"
required
value={exercise.text}
onChange={(value) =>
updateExercise({
text: value,
})
}
/>
<h1>Solutions</h1>
<div className="w-full flex flex-wrap -mx-2">
{exercise.solutions.map((solution, index) => (
<div key={solution.id} className="flex sm:w-1/2 lg:w-1/4 px-2">
<Input
type="text"
label={`Solution ${index + 1}`}
name="solution"
required
value={solution.solution}
onChange={(value) =>
updateExercise({
solutions: exercise.solutions.map((sol) =>
sol.id === solution.id ? { ...sol, solution: value } : sol
),
})
}
/>
</div>
))}
</div>
<h1>Words</h1>
<div className="w-full flex flex-wrap -mx-2">
{exercise.words.map((word, index) => (
<div key={index} className="flex sm:w-1/2 lg:w-1/4 px-2">
<Input
type="text"
label={`Word ${index + 1}`}
name="word"
required
value={word}
onChange={(value) =>
updateExercise({
words: exercise.words.map((sol, idx) =>
index === idx ? value : sol
),
})
}
/>
</div>
))}
</div>
</>
);
const {exercise, updateExercise} = props;
return (
<>
<Input
type="text"
label="Prompt"
name="prompt"
required
value={exercise.prompt}
onChange={(value) =>
updateExercise({
prompt: value,
})
}
/>
<Input
type="text"
label="Text"
name="text"
required
value={exercise.text}
onChange={(value) =>
updateExercise({
text: value,
})
}
/>
<h1>Solutions</h1>
<div className="w-full flex flex-wrap -mx-2">
{exercise.solutions.map((solution, index) => (
<div key={solution.id} className="flex sm:w-1/2 lg:w-1/4 px-2">
<Input
type="text"
label={`Solution ${index + 1}`}
name="solution"
required
value={solution.solution}
onChange={(value) =>
updateExercise({
solutions: exercise.solutions.map((sol) => (sol.id === solution.id ? {...sol, solution: value} : sol)),
})
}
/>
</div>
))}
</div>
<h1>Words</h1>
<div className="w-full flex flex-wrap -mx-2">
{exercise.words.map((word, index) => (
<div key={index} className="flex sm:w-1/2 lg:w-1/4 px-2">
<Input
type="text"
label={`Word ${index + 1}`}
name="word"
required
value={typeof word === "string" ? word : word.word}
onChange={(value) =>
updateExercise({
words: exercise.words.map((sol, idx) =>
index === idx ? (typeof word === "string" ? value : {...word, word: value}) : sol,
),
})
}
/>
</div>
))}
</div>
</>
);
};
export default FillBlanksEdit;

View File

@@ -5,12 +5,30 @@ import {CommonProps} from ".";
import {Fragment} from "react";
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 total = text.match(/({{\d+}})/g)?.length || 0;
const correct = userSolutions.filter(
(x) => solutions.find((y) => x.id.toString() === y.id.toString())?.solution === x.solution.toLowerCase() || false,
).length;
const correct = userSolutions.filter((x) => {
const solution = solutions.find((y) => x.id.toString() === y.id.toString())?.solution.toLowerCase();
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;
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 (
<button
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 (
<>
<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",
userSolution && "px-5 py-2 text-center text-white bg-mti-rose-light",
)}>
{userSolution.solution}
{userSolutionText}
</button>
<button

View File

@@ -158,21 +158,21 @@ export interface WritingExercise {
}
export interface AIDetectionAttributes {
predicted_class: 'ai' | 'mixed' | 'human';
confidence_category: 'high' | 'medium' | 'low';
predicted_class: "ai" | "mixed" | "human";
confidence_category: "high" | "medium" | "low";
class_probabilities: {
ai: number;
human: number;
mixed: number;
},
};
sentences: {
sentence: string;
highlight_sentence_for_ai: boolean
}[]
highlight_sentence_for_ai: boolean;
}[];
}
export interface WritingEvaluation extends CommonEvaluation {
ai_detection?: AIDetectionAttributes
ai_detection?: AIDetectionAttributes;
}
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."
type: "fillBlanks";
id: string;
words: string[]; // *EXAMPLE: ["preserve", "unaware"]
words: (string | {letter: string; word: string})[]; // *EXAMPLE: ["preserve", "unaware"]
text: string; // *EXAMPLE: "They tried to {{1}} burning"
allowRepetition: boolean;
solutions: {

View File

@@ -334,7 +334,7 @@ const LevelGeneration = () => {
prompt: "Complete the summary below. Click a blank to select the corresponding word for it.",
allowRepetition: false,
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})),
type: "fillBlanks",
userSolutions: [],

View File

@@ -1,24 +1,19 @@
import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import {
Difficulty,
Exercise,
ReadingExam,
ReadingPart,
} from "@/interfaces/exam";
import {Difficulty, Exercise, ReadingExam, ReadingPart} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import { getExamById } from "@/utils/exams";
import { playSound } from "@/utils/sound";
import { convertCamelCaseToReadable } from "@/utils/string";
import { Tab } from "@headlessui/react";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import { capitalize, sample } from "lodash";
import { useRouter } from "next/router";
import { useEffect, useState, Dispatch, SetStateAction } from "react";
import { BsArrowRepeat, BsCheck } from "react-icons/bs";
import { toast } from "react-toastify";
import { v4 } from "uuid";
import {capitalize, sample} from "lodash";
import {useRouter} from "next/router";
import {useEffect, useState, Dispatch, SetStateAction} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
import {v4} from "uuid";
import FillBlanksEdit from "@/components/Generation/fill.blanks.edit";
import TrueFalseEdit from "@/components/Generation/true.false.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 availableTypes = [
{ type: "fillBlanks", label: "Fill the Blanks" },
{ type: "trueFalse", label: "True or False" },
{ type: "writeBlanks", label: "Write the Blanks" },
{ type: "paragraphMatch", label: "Match Sentences" },
{type: "fillBlanks", label: "Fill the Blanks"},
{type: "trueFalse", label: "True or False"},
{type: "writeBlanks", label: "Write the Blanks"},
{type: "paragraphMatch", label: "Match Sentences"},
];
const PartTab = ({
part,
difficulty,
index,
setPart,
updatePart,
part,
difficulty,
index,
setPart,
updatePart,
}: {
part?: ReadingPart;
index: number;
difficulty: Difficulty;
setPart: (part?: ReadingPart) => void;
updatePart: Dispatch<SetStateAction<ReadingPart | undefined>>;
// updatePart: (updater: (part: ReadingPart) => ReadingPart) => void;
part?: ReadingPart;
index: number;
difficulty: Difficulty;
setPart: (part?: ReadingPart) => void;
updatePart: Dispatch<SetStateAction<ReadingPart | undefined>>;
}) => {
const [topic, setTopic] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [types, setTypes] = useState<string[]>([]);
const [topic, setTopic] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [types, setTypes] = useState<string[]>([]);
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 generate = () => {
const url = new URLSearchParams();
url.append("difficulty", difficulty);
const generate = () => {
const url = new URLSearchParams();
url.append("difficulty", difficulty);
if (topic) url.append("topic", topic);
if (types) types.forEach((t) => url.append("exercises", t));
if (topic) url.append("topic", topic);
if (types) types.forEach((t) => url.append("exercises", t));
setPart(undefined);
setIsLoading(true);
axios
.get(
`/api/exam/reading/generate/reading_passage_${index}${
topic || types ? `?${url.toString()}` : ""
}`
)
.then((result) => {
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);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
setPart(undefined);
setIsLoading(true);
axios
.get(`/api/exam/reading/generate/reading_passage_${index}${topic || types ? `?${url.toString()}` : ""}`)
.then((result) => {
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);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const renderExercises = () => {
return part?.exercises.map((exercise) => {
switch (exercise.type) {
case "fillBlanks":
return (
<>
<h1>Exercise: Fill Blanks</h1>
<FillBlanksEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) =>
updatePart((part?: ReadingPart) => {
if (part) {
const exercises = part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
) as Exercise[];
const updatedPart = { ...part, exercises } as ReadingPart;
return updatedPart;
}
const renderExercises = () => {
return part?.exercises.map((exercise) => {
switch (exercise.type) {
case "fillBlanks":
return (
<>
<h1>Exercise: Fill Blanks</h1>
<FillBlanksEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) =>
updatePart((part?: ReadingPart) => {
if (part) {
const exercises = part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)) as Exercise[];
const updatedPart = {...part, exercises} as ReadingPart;
return updatedPart;
}
return part;
})
}
/>
</>
);
case "trueFalse":
return (
<>
<h1>Exercise: True or False</h1>
<TrueFalseEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
),
} as ReadingPart;
}
return part;
})
}
/>
</>
);
case "trueFalse":
return (
<>
<h1>Exercise: True or False</h1>
<TrueFalseEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
} as ReadingPart;
}
return part;
});
}}
/>
</>
);
case "writeBlanks":
return (
<>
<h1>Exercise: Write Blanks</h1>
<WriteBlanksEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
),
} as ReadingPart;
}
return part;
});
}}
/>
</>
);
case "writeBlanks":
return (
<>
<h1>Exercise: Write Blanks</h1>
<WriteBlanksEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
} as ReadingPart;
}
return part;
});
}}
/>
</>
);
case "matchSentences":
return (
<>
<h1>Exercise: Match Sentences</h1>
<MatchSentencesEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
),
} as ReadingPart;
}
return part;
});
}}
/>
</>
);
case "matchSentences":
return (
<>
<h1>Exercise: Match Sentences</h1>
<MatchSentencesEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
} as ReadingPart;
}
return part;
});
}}
/>
</>
);
default:
return null;
}
});
};
return part;
});
}}
/>
</>
);
default:
return null;
}
});
};
return (
<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">
<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">
{availableTypes.map((x) => (
<span
onClick={() => toggleType(x.type)}
key={x.type}
className={clsx(
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!types.includes(x.type)
? "bg-white border-mti-gray-platinum"
: "bg-ielts-reading/70 border-ielts-reading text-white"
)}
>
{x.label}
</span>
))}
</div>
</div>
<div className="flex gap-4 items-end">
<Input
type="text"
placeholder="Grand Canyon..."
name="topic"
label="Topic"
onChange={setTopic}
roundness="xl"
defaultValue={topic}
/>
<button
onClick={generate}
disabled={isLoading || types.length === 0}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px]",
"hover:bg-ielts-reading disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
</div>
{isLoading && (
<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-reading")}
/>
<span className={clsx("font-bold text-2xl text-ielts-reading")}>
Generating...
</span>
</div>
)}
{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>
);
return (
<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">
<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">
{availableTypes.map((x) => (
<span
onClick={() => toggleType(x.type)}
key={x.type}
className={clsx(
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!types.includes(x.type) ? "bg-white border-mti-gray-platinum" : "bg-ielts-reading/70 border-ielts-reading text-white",
)}>
{x.label}
</span>
))}
</div>
</div>
<div className="flex gap-4 items-end">
<Input type="text" placeholder="Grand Canyon..." name="topic" label="Topic" onChange={setTopic} roundness="xl" defaultValue={topic} />
<button
onClick={generate}
disabled={isLoading || types.length === 0}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px]",
"hover:bg-ielts-reading disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
</div>
{isLoading && (
<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-reading")} />
<span className={clsx("font-bold text-2xl text-ielts-reading")}>Generating...</span>
</div>
)}
{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 [part1, setPart1] = useState<ReadingPart>();
const [part2, setPart2] = useState<ReadingPart>();
const [part3, setPart3] = useState<ReadingPart>();
const [minTimer, setMinTimer] = useState(60);
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ReadingExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(
sample(DIFFICULTIES)!
);
const [part1, setPart1] = useState<ReadingPart>();
const [part2, setPart2] = useState<ReadingPart>();
const [part3, setPart3] = useState<ReadingPart>();
const [minTimer, setMinTimer] = useState(60);
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ReadingExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
useEffect(() => {
const parts = [part1, part2, part3].filter((x) => !!x);
setMinTimer(parts.length === 0 ? 60 : parts.length * 20);
}, [part1, part2, part3]);
useEffect(() => {
const parts = [part1, part2, part3].filter((x) => !!x);
setMinTimer(parts.length === 0 ? 60 : parts.length * 20);
}, [part1, part2, part3]);
const router = useRouter();
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const loadExam = async (examId: string) => {
const exam = await getExamById("reading", examId.trim());
if (!exam) {
toast.error(
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id",
}
);
const loadExam = async (examId: string) => {
const exam = await getExamById("reading", examId.trim());
if (!exam) {
toast.error("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]);
setSelectedModules(["reading"]);
setExams([exam]);
setSelectedModules(["reading"]);
router.push("/exercises");
};
router.push("/exercises");
};
const submitExam = () => {
const parts = [part1, part2, part3].filter((x) => !!x) as ReadingPart[];
if (parts.length === 0) {
toast.error("Please generate at least one passage before submitting");
return;
}
const submitExam = () => {
const parts = [part1, part2, part3].filter((x) => !!x) as ReadingPart[];
if (parts.length === 0) {
toast.error("Please generate at least one passage before submitting");
return;
}
setIsLoading(true);
const exam: ReadingExam = {
parts,
isDiagnostic: false,
minTimer,
module: "reading",
id: v4(),
type: "academic",
variant: parts.length === 3 ? "full" : "partial",
difficulty,
};
setIsLoading(true);
const exam: ReadingExam = {
parts,
isDiagnostic: false,
minTimer,
module: "reading",
id: v4(),
type: "academic",
variant: parts.length === 3 ? "full" : "partial",
difficulty,
};
axios
.post(`/api/exam/reading`, exam)
.then((result) => {
playSound("sent");
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."
);
setResultingExam(result.data);
axios
.post(`/api/exam/reading`, exam)
.then((result) => {
playSound("sent");
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.");
setResultingExam(result.data);
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setDifficulty(sample(DIFFICULTIES)!);
setMinTimer(60);
})
.catch((error) => {
console.log(error);
toast.error(
"Something went wrong while generating, please try again later."
);
})
.finally(() => setIsLoading(false));
};
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setDifficulty(sample(DIFFICULTIES)!);
setMinTimer(60);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong while generating, please try again later.");
})
.finally(() => setIsLoading(false));
};
return (
<>
<div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">
Timer
</label>
<Input
type="number"
name="minTimer"
onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))}
value={minTimer}
className="max-w-[300px]"
/>
</div>
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">
Difficulty
</label>
<Select
options={DIFFICULTIES.map((x) => ({
value: x,
label: capitalize(x),
}))}
onChange={(value) =>
value ? setDifficulty(value.value as Difficulty) : null
}
value={{ value: difficulty, label: capitalize(difficulty) }}
disabled={!!part1 || !!part2 || !!part3}
/>
</div>
</div>
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-reading/20 p-1">
<Tab
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",
"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
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",
"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 2 {part2 && <BsCheck />}
</Tab>
<Tab
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",
"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 3 {part3 && <BsCheck />}
</Tab>
</Tab.List>
<Tab.Panels>
{[
{ part: part1, setPart: setPart1 },
{ part: part2, setPart: setPart2 },
{ part: part3, setPart: setPart3 },
].map(({ part, setPart }, index) => (
<PartTab
part={part}
difficulty={difficulty}
index={index + 1}
key={index}
setPart={setPart}
updatePart={setPart}
/>
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-reading text-ielts-reading w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-reading hover:text-white disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300"
)}
>
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>
</>
);
return (
<>
<div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Timer</label>
<Input
type="number"
name="minTimer"
onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))}
value={minTimer}
className="max-w-[300px]"
/>
</div>
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Difficulty</label>
<Select
options={DIFFICULTIES.map((x) => ({
value: x,
label: capitalize(x),
}))}
onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)}
value={{value: difficulty, label: capitalize(difficulty)}}
disabled={!!part1 || !!part2 || !!part3}
/>
</div>
</div>
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-reading/20 p-1">
<Tab
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",
"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
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",
"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 2 {part2 && <BsCheck />}
</Tab>
<Tab
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",
"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 3 {part3 && <BsCheck />}
</Tab>
</Tab.List>
<Tab.Panels>
{[
{part: part1, setPart: setPart1},
{part: part2, setPart: setPart2},
{part: part3, setPart: setPart3},
].map(({part, setPart}, index) => (
<PartTab part={part} difficulty={difficulty} index={index + 1} key={index} setPart={setPart} updatePart={setPart} />
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-reading text-ielts-reading w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-reading hover:text-white disabled:bg-ielts-reading/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
)}>
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;