218 lines
8.9 KiB
TypeScript
218 lines
8.9 KiB
TypeScript
import { RotateCcw, Send, Volume2 } from 'lucide-react';
|
|
import { useEffect, useRef, useState } from 'react';
|
|
import { fetchExerciseAudio, fetchNextLesson } from '../api/lessons';
|
|
import { submitAttempt } from '../api/practice';
|
|
import type { AttemptResponse, Exercise, Lesson } from '../api/types';
|
|
import { AudioRecorder } from '../components/AudioRecorder';
|
|
import { PhonemeAnalysis } from '../components/PhonemeAnalysis';
|
|
import { PronunciationText } from '../components/PronunciationText';
|
|
import { ScoreBadge } from '../components/ScoreBadge';
|
|
|
|
type Props = {
|
|
initialSelection?: { lesson: Lesson; exercise: Exercise } | null;
|
|
};
|
|
|
|
export function PracticePage({ initialSelection }: Props) {
|
|
const [lesson, setLesson] = useState<Lesson | null>(initialSelection?.lesson ?? null);
|
|
const [exercise, setExercise] = useState<Exercise | null>(initialSelection?.exercise ?? null);
|
|
const [audio, setAudio] = useState<Blob | null>(null);
|
|
const [audioUrl, setAudioUrl] = useState<string | null>(null);
|
|
const [result, setResult] = useState<AttemptResponse | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [loadingNext, setLoadingNext] = useState(false);
|
|
const [recording, setRecording] = useState(false);
|
|
const [audioLoading, setAudioLoading] = useState(false);
|
|
const [audioError, setAudioError] = useState('');
|
|
const [error, setError] = useState('');
|
|
const [notice, setNotice] = useState('');
|
|
const submittingRef = useRef(false);
|
|
const referenceAudioRef = useRef<{ exerciseId: string; url: string; player: HTMLAudioElement } | null>(null);
|
|
const audioRequestRef = useRef<AbortController | null>(null);
|
|
const audioGenerationRef = useRef(0);
|
|
const recentExerciseIds = useRef<string[]>(initialSelection?.exercise.id ? [initialSelection.exercise.id] : []);
|
|
|
|
useEffect(() => {
|
|
if (!initialSelection) void loadNext();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!audio) {
|
|
setAudioUrl(null);
|
|
return;
|
|
}
|
|
const url = URL.createObjectURL(audio);
|
|
setAudioUrl(url);
|
|
return () => URL.revokeObjectURL(url);
|
|
}, [audio]);
|
|
|
|
useEffect(() => () => {
|
|
audioGenerationRef.current += 1;
|
|
audioRequestRef.current?.abort();
|
|
audioRequestRef.current = null;
|
|
referenceAudioRef.current?.player.pause();
|
|
if (referenceAudioRef.current) URL.revokeObjectURL(referenceAudioRef.current.url);
|
|
referenceAudioRef.current = null;
|
|
}, [exercise?.id]);
|
|
|
|
async function playReference() {
|
|
if (!exercise || audioLoading || audioRequestRef.current || recording) return;
|
|
setAudioError('');
|
|
const exerciseId = exercise.id;
|
|
const generation = audioGenerationRef.current;
|
|
let controller: AbortController | null = null;
|
|
try {
|
|
if (!referenceAudioRef.current || referenceAudioRef.current.exerciseId !== exerciseId) {
|
|
setAudioLoading(true);
|
|
controller = new AbortController();
|
|
audioRequestRef.current = controller;
|
|
const blob = await fetchExerciseAudio(exerciseId, controller.signal);
|
|
if (controller.signal.aborted || audioGenerationRef.current !== generation) return;
|
|
const url = URL.createObjectURL(blob);
|
|
referenceAudioRef.current = { exerciseId, url, player: new Audio(url) };
|
|
}
|
|
const player = referenceAudioRef.current.player;
|
|
player.currentTime = 0;
|
|
await player.play();
|
|
} catch {
|
|
if (audioGenerationRef.current !== generation || controller?.signal.aborted) return;
|
|
setAudioError('Satz konnte nicht abgespielt werden. Bitte erneut versuchen.');
|
|
} finally {
|
|
if (audioGenerationRef.current === generation) setAudioLoading(false);
|
|
if (audioRequestRef.current === controller) audioRequestRef.current = null;
|
|
}
|
|
}
|
|
|
|
async function loadNext(fresh = false) {
|
|
if (loadingNext || recording || submittingRef.current) return;
|
|
audioGenerationRef.current += 1;
|
|
audioRequestRef.current?.abort();
|
|
audioRequestRef.current = null;
|
|
referenceAudioRef.current?.player.pause();
|
|
setAudioLoading(false);
|
|
setLoadingNext(true);
|
|
setError('');
|
|
setNotice('');
|
|
setAudioError('');
|
|
setAudio(null);
|
|
setResult(null);
|
|
try {
|
|
const next = await fetchNextLesson(fresh, fresh ? recentExerciseIds.current : []);
|
|
if (fresh && exercise?.target_text.trim().toLowerCase() === next.exercise.target_text.trim().toLowerCase()) {
|
|
setNotice('Der Agent hat denselben Satz erneut erzeugt. Bitte versuche es noch einmal.');
|
|
}
|
|
setLesson(next.lesson);
|
|
setExercise(next.exercise);
|
|
if (next.exercise.id && recentExerciseIds.current[recentExerciseIds.current.length - 1] !== next.exercise.id) {
|
|
recentExerciseIds.current = [...recentExerciseIds.current, next.exercise.id].slice(-3);
|
|
}
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'Uebung konnte nicht geladen werden');
|
|
} finally {
|
|
setLoadingNext(false);
|
|
}
|
|
}
|
|
|
|
async function evaluateRecording() {
|
|
if (!exercise || !audio || submittingRef.current) return;
|
|
submittingRef.current = true;
|
|
setAudio(null);
|
|
setLoading(true);
|
|
setError('');
|
|
try {
|
|
setResult(await submitAttempt(exercise.id, audio));
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'Bewertung fehlgeschlagen');
|
|
} finally {
|
|
submittingRef.current = false;
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
if (!lesson || !exercise) {
|
|
return (
|
|
<div className="view-stack">
|
|
<p className={error ? 'form-error' : 'muted'}>{error || 'Lade Uebung...'}</p>
|
|
{error && <button className="ghost-button" disabled={loadingNext} onClick={() => void loadNext(true)}>Erneut versuchen</button>}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="view-stack">
|
|
<header className="view-header">
|
|
<div>
|
|
<p className="eyebrow">{lesson.title}</p>
|
|
<h1>Aussprache</h1>
|
|
</div>
|
|
<button className="ghost-button" disabled={loadingNext || loading || recording} onClick={() => void loadNext(true)}>
|
|
<RotateCcw size={18} /> {loadingNext ? 'Lade neue Uebung...' : 'Andere Uebung'}
|
|
</button>
|
|
</header>
|
|
|
|
{error && <p className="form-error">{error}</p>}
|
|
{notice && <p className="muted">{notice}</p>}
|
|
|
|
<section className="panel practice-panel">
|
|
<p className="muted">{exercise.prompt_text}</p>
|
|
<PronunciationText targetText={exercise.target_text} words={result?.attempt.word_scores} />
|
|
<button className="ghost-button" type="button" disabled={loadingNext || audioLoading || recording} onClick={() => void playReference()}>
|
|
<Volume2 size={18} /> {audioLoading ? 'Satz wird geladen...' : 'Satz anhören'}
|
|
</button>
|
|
{audioError && <p className="form-error">{audioError}</p>}
|
|
<div className="action-row">
|
|
<AudioRecorder
|
|
key={exercise.id}
|
|
onRecorded={setAudio}
|
|
onRecordingStart={() => {
|
|
audioGenerationRef.current += 1;
|
|
audioRequestRef.current?.abort();
|
|
audioRequestRef.current = null;
|
|
referenceAudioRef.current?.player.pause();
|
|
setAudioLoading(false);
|
|
setAudio(null);
|
|
setResult(null);
|
|
setError('');
|
|
}}
|
|
onRecordingChange={setRecording}
|
|
disabled={loading || loadingNext}
|
|
buttonLabel={loading ? 'Bewertung läuft...' : audio || result ? 'Erneut aufnehmen' : 'Aufnehmen'}
|
|
secondary={Boolean(audio)}
|
|
/>
|
|
{audio && !recording && (
|
|
<button className="primary-button" disabled={loading || loadingNext} onClick={() => void evaluateRecording()} type="button">
|
|
<Send size={18} /> Bewerten
|
|
</button>
|
|
)}
|
|
</div>
|
|
{audio && !recording && (
|
|
<div className="recording-preview">
|
|
<p className="muted">Aufnahme noch nicht gesendet. Anhören, erneut aufnehmen oder bewerten.</p>
|
|
{audioUrl && <audio controls src={audioUrl} aria-label="Eigene Aufnahme anhören" />}
|
|
</div>
|
|
)}
|
|
{loading && <p className="muted">Die Aussprache wird bewertet...</p>}
|
|
</section>
|
|
|
|
{result && (
|
|
<section className="result-grid">
|
|
<div className="panel result-panel">
|
|
<h2>Bewertung</h2>
|
|
<div className="score-grid">
|
|
<ScoreBadge label="Gesamt" value={result.attempt.overall_score} />
|
|
<ScoreBadge label="Accuracy" value={result.attempt.accuracy_score} />
|
|
<ScoreBadge label="Fluency" value={result.attempt.fluency_score} />
|
|
<ScoreBadge label="Completeness" value={result.attempt.completeness_score} />
|
|
</div>
|
|
</div>
|
|
<div className="panel result-panel">
|
|
<h2>Lehrerfeedback</h2>
|
|
<p>{result.teacher.teacher_feedback}</p>
|
|
<p className="muted">{result.teacher.next_recommendation}</p>
|
|
</div>
|
|
<PhonemeAnalysis words={result.attempt.word_scores} />
|
|
</section>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|