Bug fixes to training, added a spinner to record while it loads, made changes to speaking as requested

This commit is contained in:
Carlos Mesquita
2024-08-05 21:44:14 +01:00
parent 309dfba583
commit a4a40b9145
5 changed files with 92 additions and 35 deletions

View File

@@ -1,33 +1,34 @@
import {SpeakingExercise} from "@/interfaces/exam";
import {CommonProps} from ".";
import {Fragment, useEffect, useState} from "react";
import {BsCheckCircleFill, BsMicFill, BsPauseCircle, BsPlayCircle, BsTrashFill} from "react-icons/bs";
import { SpeakingExercise } from "@/interfaces/exam";
import { CommonProps } from ".";
import { Fragment, useEffect, useState } from "react";
import { BsCheckCircleFill, BsMicFill, BsPauseCircle, BsPlayCircle, BsTrashFill } from "react-icons/bs";
import dynamic from "next/dynamic";
import Button from "../Low/Button";
import useExamStore from "@/stores/examStore";
import {downloadBlob} from "@/utils/evaluation";
import { downloadBlob } from "@/utils/evaluation";
import axios from "axios";
import Modal from "../Modal";
const Waveform = dynamic(() => import("../Waveform"), {ssr: false});
const Waveform = dynamic(() => import("../Waveform"), { ssr: false });
const ReactMediaRecorder = dynamic(() => import("react-media-recorder").then((mod) => mod.ReactMediaRecorder), {
ssr: false,
});
export default function Speaking({id, title, text, video_url, type, prompts, suffix, userSolutions, onNext, onBack}: SpeakingExercise & CommonProps) {
export default function Speaking({ id, title, text, video_url, type, prompts, suffix, userSolutions, onNext, onBack }: SpeakingExercise & CommonProps) {
const [recordingDuration, setRecordingDuration] = useState(0);
const [isRecording, setIsRecording] = useState(false);
const [mediaBlob, setMediaBlob] = useState<string>();
const [audioURL, setAudioURL] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
const [isPromptsModalOpen, setIsPromptsModalOpen] = useState(false);
const [inputText, setInputText] = useState("");
const hasExamEnded = useExamStore((state) => state.hasExamEnded);
const saveToStorage = async () => {
if (mediaBlob && mediaBlob.startsWith("blob")) {
const blobBuffer = await downloadBlob(mediaBlob);
const audioFile = new File([blobBuffer], "audio.wav", {type: "audio/wav"});
const audioFile = new File([blobBuffer], "audio.wav", { type: "audio/wav" });
const seed = Math.random().toString().replace("0.", "");
@@ -41,8 +42,8 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
},
};
const response = await axios.post<{path: string}>("/api/storage/insert", formData, config);
if (audioURL) await axios.post("/api/storage/delete", {path: audioURL});
const response = await axios.post<{ path: string }>("/api/storage/insert", formData, config);
if (audioURL) await axios.post("/api/storage/delete", { path: audioURL });
return response.data.path;
}
@@ -51,7 +52,7 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
useEffect(() => {
if (userSolutions.length > 0) {
const {solution} = userSolutions[0] as {solution?: string};
const { solution } = userSolutions[0] as { solution?: string };
if (solution && !mediaBlob) setMediaBlob(solution);
if (solution && !solution.startsWith("blob")) setAudioURL(solution);
}
@@ -78,8 +79,8 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
const next = async () => {
onNext({
exercise: id,
solutions: mediaBlob ? [{id, solution: mediaBlob}] : [],
score: {correct: 0, total: 100, missing: 0},
solutions: mediaBlob ? [{ id, solution: mediaBlob }] : [],
score: { correct: 0, total: 100, missing: 0 },
type,
});
};
@@ -87,12 +88,33 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
const back = async () => {
onBack({
exercise: id,
solutions: mediaBlob ? [{id, solution: mediaBlob}] : [],
score: {correct: 0, total: 100, missing: 0},
solutions: mediaBlob ? [{ id, solution: mediaBlob }] : [],
score: { correct: 0, total: 100, missing: 0 },
type,
});
};
const handleNoteWriting = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newText = e.target.value;
const words = newText.match(/\S+/g);
const wordCount = words ? words.length : 0;
if (wordCount <= 100) {
setInputText(newText);
} else {
let count = 0;
let lastIndex = 0;
const matches = newText.matchAll(/\S+/g);
for (const match of matches) {
count++;
if (count > 100) break;
lastIndex = match.index! + match[0].length;
}
setInputText(newText.slice(0, lastIndex));
}
};
return (
<div className="flex flex-col h-full w-full gap-9">
<Modal title="Prompts" className="!w-96 aspect-square" isOpen={isPromptsModalOpen} onClose={() => setIsPromptsModalOpen(false)}>
@@ -112,7 +134,7 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
<div className="flex flex-col gap-0">
<span className="font-semibold">{title}</span>
{prompts.length > 0 && (
<span className="font-semibold">You should talk for at least 30 seconds for your answer to be valid.</span>
<span className="font-semibold">You should talk for at least 1 minute and 30 seconds for your answer to be valid.</span>
)}
</div>
{!video_url && (
@@ -138,10 +160,24 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
</div>
</div>
{prompts && prompts.length > 0 && (
<div className="w-full h-full flex flex-col gap-4">
<textarea
onContextMenu={(e) => e.preventDefault()}
className="w-full h-full min-h-[200px] cursor-text px-7 py-8 input border-2 border-mti-gray-platinum bg-white rounded-3xl"
onChange={handleNoteWriting}
value={inputText}
placeholder="Write your notes here..."
spellCheck={false}
/>
<span className="text-base self-end text-mti-gray-cool">Word Count: {(inputText.match(/\S+/g) || []).length}/100</span>
</div>
)}
<ReactMediaRecorder
audio
onStop={(blob) => setMediaBlob(blob)}
render={({status, startRecording, stopRecording, pauseRecording, resumeRecording, clearBlobUrl, mediaBlobUrl}) => (
render={({ status, startRecording, stopRecording, pauseRecording, resumeRecording, clearBlobUrl, mediaBlobUrl }) => (
<div className="w-full p-4 px-8 bg-transparent border-2 border-mti-gray-platinum rounded-2xl flex-col gap-8 items-center">
<p className="text-base font-normal">Record your answer:</p>
<div className="flex gap-8 items-center justify-center py-8">

View File

@@ -78,6 +78,7 @@ interface StatsGridItemProps {
users: User[];
training?: boolean,
selectedTrainingExams?: string[];
maxTrainingExams?: number;
setSelectedTrainingExams?: React.Dispatch<React.SetStateAction<string[]>>;
setExams: (exams: Exam[]) => void;
setShowSolutions: (show: boolean) => void;
@@ -106,7 +107,8 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
renderPdfIcon,
width = undefined,
height = undefined,
examNumber = undefined
examNumber = undefined,
maxTrainingExams = undefined
}) => {
const router = useRouter();
const correct = stats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
@@ -132,16 +134,22 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
const { timeSpent, inactivity, session } = stats[0];
const selectExam = () => {
if (training && !isDisabled && typeof setSelectedTrainingExams !== "undefined" && typeof timestamp == "string") {
if (training && !isDisabled && typeof maxTrainingExams !== "undefined" && typeof setSelectedTrainingExams !== "undefined" && typeof timestamp == "string") {
setSelectedTrainingExams(prevExams => {
const index = prevExams.indexOf(timestamp);
if (index !== -1) {
const uniqueExams = [...new Set(stats.map(stat => `${stat.module}-${stat.date}`))];
const indexes = uniqueExams.map(exam => prevExams.indexOf(exam)).filter(index => index !== -1);
if (indexes.length > 0) {
const newExams = [...prevExams];
newExams.splice(index, 1);
indexes.sort((a, b) => b - a).forEach(index => {
newExams.splice(index, 1);
});
return newExams;
} else {
return [...prevExams, timestamp];
if (prevExams.length + uniqueExams.length <= maxTrainingExams) {
return [...prevExams, ...uniqueExams];
} else {
return prevExams;
}
}
});
} else {
@@ -219,7 +227,10 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
</div>
<div className="w-full flex flex-col gap-1">
<div className="grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2">
<div className={clsx(
"grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2",
examNumber !== undefined && "pr-10"
)}>
{aggregatedLevels.map(({ module, level }) => (
<ModuleBadge key={module} module={module} level={level} />
))}
@@ -244,8 +255,9 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
correct / total >= 0.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose",
typeof selectedTrainingExams !== "undefined" && typeof timestamp === "string" && selectedTrainingExams.includes(timestamp) && "border-2 border-slate-600",
typeof selectedTrainingExams !== "undefined" && typeof timestamp === "string" && selectedTrainingExams.some(exam => exam.includes(timestamp)) && "border-2 border-slate-600",
)}
onClick={examNumber === undefined ? selectExam : undefined}
style={{
...(width !== undefined && { width }),
...(height !== undefined && { height }),

View File

@@ -17,9 +17,10 @@ const TrainingScore: React.FC<TrainingScoreProps> = ({
const scores = trainingContent.exams.map(exam => exam.score);
const highestScore = Math.max(...scores);
const lowestScore = Math.min(...scores);
const averageScore = scores.length > 0
let averageScore = scores.length > 0
? scores.reduce((sum, score) => sum + score, 0) / scores.length
: 0;
averageScore = Math.round(averageScore);
const containerClasses = clsx(
"flex flex-row mb-4",