Add B1 Meister: OeSD B1 exam trainer (German-Arabic)

Next.js app with Hoeren, Lesen, Schreiben, Sprechen, Grammatik and Wortschatz sections, flashcards with spaced repetition, speaking chat, XP/streaks/badges, daily reminders (PWA) and Docker Compose setup for Coolify.
This commit is contained in:
X4Lo committed 2026-11-05 19:11:46 +00:00
commit 1f1d28a34d
42 files changed
+8879

No files matched your search

+617
View File
@@ -0,0 +1,617 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { chatTopics, planTasks, presentationTasks, sprechRedemittel, sprechTeile, type ChatTopic, type PlanTask, type PresentationTask } from "@/data/sprechen";
import Ar from "@/components/Ar";
import { recordResult } from "@/lib/progress";
import { speak, startListening, stopSpeaking, sttSupported } from "@/lib/speech";
import { fireConfetti } from "@/components/AppShell";
import { sfx } from "@/lib/sfx";
type Mode = (typeof sprechTeile)[number]["id"];
interface Session {
id: string;
title: string;
titleAr: string;
context?: string;
intro?: { de: string; ar: string };
prompts: { de: string; ar: string; sample?: string }[];
points?: { de: string; ar: string }[];
slides?: { de: string; ar: string }[];
}
function fromTopic(t: ChatTopic): Session {
return { id: `frei-${t.id}`, title: `${t.emoji} ${t.de}`, titleAr: t.ar, prompts: t.questions.map((q) => ({ de: q.de, ar: q.ar, sample: q.sample })) };
}
function fromPlan(t: PlanTask): Session {
return {
id: `plan-${t.id}`,
title: t.title,
titleAr: t.titleAr,
context: t.situation,
intro: { de: t.situation, ar: t.situationAr },
points: t.points,
prompts: t.partner.map((p) => ({ de: p.de, ar: p.ar })),
};
}
function fromPresentation(t: PresentationTask): Session {
return {
id: `praes-${t.id}`,
title: t.title,
titleAr: t.titleAr,
context: `Der Lernende hat gerade eine Präsentation zum Thema „${t.question}“ gehalten. Stelle Fragen dazu.`,
slides: t.slides,
prompts: [
{ de: "Vielen Dank für Ihre Präsentation! Ich habe noch ein paar Fragen.", ar: "شكراً جزيلاً على عرضك! لديّ بعض الأسئلة." },
...t.followUps,
],
};
}
export default function SprechenPage() {
const [mode, setMode] = useState<Mode>("frei");
const [session, setSession] = useState<Session | null>(null);
const [mixKey, setMixKey] = useState(0);
if (session) return <SessionView key={session.id + mixKey} session={session} onBack={() => setSession(null)} />;
const randomMix = (): Session => {
const qs = chatTopics.flatMap((t) => t.questions);
const pick = [...qs].sort(() => Math.random() - 0.5).slice(0, 6);
return { id: "frei-mix", title: "🎲 Zufallsfragen", titleAr: "أسئلة عشوائية", prompts: pick.map((q) => ({ de: q.de, ar: q.ar, sample: q.sample })) };
};
return (
<div>
<h1>🗣️ Sprechen</h1>
<p className="sub">
Ein echtes Gespräch mit mir – sprich ins Mikrofon oder schreib. <Ar>محادثة حقيقية معي – تحدّث في الميكروفون أو اكتب.</Ar>
</p>
<div className="tabs">
{sprechTeile.map((t) => (
<button key={t.id} className={mode === t.id ? "active" : ""} onClick={() => setMode(t.id)}>
{t.de}
</button>
))}
</div>
<div className="ar muted" style={{ marginBottom: 10 }}>
{sprechTeile.find((t) => t.id === mode)!.ar}
</div>
{mode === "frei" && (
<div className="grid grid-3">
<button
className="tile"
style={{ background: "linear-gradient(135deg, var(--purple), var(--blue))", color: "#fff" }}
onClick={() => {
setMixKey((k) => k + 1);
setSession(randomMix());
}}
>
<div className="emoji">🎲</div>
<div className="t">Zufall</div>
<div className="s" style={{ color: "#fff" }}>
6 gemischte Fragen
</div>
</button>
{chatTopics.map((t) => (
<button key={t.id} className="tile" onClick={() => setSession(fromTopic(t))}>
<div className="emoji">{t.emoji}</div>
<div className="t">{t.de}</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.ar}
</div>
</button>
))}
</div>
)}
{mode === "planen" && (
<div className="grid">
<div className="card small" style={{ background: "var(--red-soft)", borderColor: "var(--red)" }}>
<b>So läuft Teil 1:</b> Du planst mit deinem Partner etwas (ca. 3 Min.). Mach Vorschläge, reagiere auf seine Ideen, einigt euch!
<Ar block>تخطط مع شريكك لشيء ما (حوالي 3 دقائق). قدّم اقتراحات، تفاعل مع أفكاره، واتفقا معاً!</Ar>
</div>
{planTasks.map((t) => (
<button key={t.id} className="tile" onClick={() => setSession(fromPlan(t))}>
<div className="t" style={{ marginTop: 0 }}>
🤝 {t.title}
</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.titleAr}
</div>
</button>
))}
</div>
)}
{mode === "praesentation" && (
<div className="grid">
<div className="card small" style={{ background: "var(--purple-soft)", borderColor: "var(--purple)" }}>
<b>So läuft Teil 2 & 3:</b> Du präsentierst ein Thema mit 5 Folien (ca. 3 Min.). Danach stellt der Prüfer Fragen zu deinem Thema.
<Ar block>تقدّم موضوعاً من خمس شرائح (حوالي 3 دقائق). بعد ذلك يطرح الممتحن أسئلة عن موضوعك.</Ar>
</div>
{presentationTasks.map((t) => (
<button key={t.id} className="tile" onClick={() => setSession(fromPresentation(t))}>
<div className="t" style={{ marginTop: 0 }}>
📊 {t.title}
</div>
<div className="s">{t.question}</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.titleAr}
</div>
</button>
))}
</div>
)}
<h2>Redemittel • عبارات للمحادثة</h2>
{sprechRedemittel.map((g) => (
<details key={g.title} className="card" style={{ marginTop: 8 }}>
<summary>
{g.title} <span className="ar muted small">{g.titleAr}</span>
</summary>
{g.items.map((r, i) => (
<div key={i} className="row" style={{ marginTop: 8 }}>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 700 }}>{r.de}</div>
<div className="ar small muted">{r.ar}</div>
</div>
<button className="btn secondary small" onClick={() => speak(r.de)}>
🔊
</button>
</div>
))}
</details>
))}
</div>
);
}
// ---------------- Gespräch ----------------
interface Msg {
from: "bot" | "me" | "tip";
de: string;
ar?: string;
sample?: string;
}
const reactions = [
{ de: "Interessant!", ar: "مثير للاهتمام!" },
{ de: "Ah, verstehe.", ar: "آه، فهمت." },
{ de: "Das klingt gut!", ar: "يبدو هذا جيداً!" },
{ de: "Okay, danke!", ar: "حسناً، شكراً!" },
{ de: "Wirklich? Spannend!", ar: "حقاً؟ مشوّق!" },
{ de: "Gute Idee!", ar: "فكرة جيدة!" },
{ de: "Ja, das stimmt.", ar: "نعم، هذا صحيح." },
{ de: "Super, sehr schön gesagt!", ar: "رائع، قلتها بشكل جميل جداً!" },
];
const connectorList = ["weil", "dass", "deshalb", "aber", "außerdem", "obwohl", "wenn", "denn", "trotzdem", "damit", "meiner meinung nach", "zum beispiel", "einerseits", "andererseits", "als", "sondern", "ich finde", "ich schlage vor", "wie wäre es"];
const commonVerbs = "habe|hast|hat|haben|bin|bist|ist|sind|kann|kannst|können|muss|musst|müssen|will|willst|wollen|möchte|möchtest|gehe|gehst|geht|arbeite|arbeitet|lerne|lernt|wohne|wohnt|mache|macht|finde|findet|spiele|spielt";
function analyze(text: string) {
const lower = text.toLowerCase();
const words = lower.split(/\s+/).filter(Boolean).length;
const used = connectorList.filter((c) => new RegExp(`(^|[^a-zäöüß])${c}([^a-zäöüß]|$)`).test(lower));
const wordOrder = new RegExp(`\\b(weil|dass|wenn|obwohl|ob)\\s+(ich|du|er|sie|es|wir|ihr|man)\\s+(${commonVerbs})\\b(?![.,!?]?\\s*$)`).exec(lower);
let score = words >= 25 ? 4 : words >= 14 ? 3 : words >= 7 ? 2 : 1;
if (used.length) score++;
if (wordOrder) score--;
score = Math.max(1, Math.min(5, score));
const tips: { de: string; ar: string }[] = [];
if (words < 7) tips.push({ de: "Etwas kurz! Versuch 2–3 Sätze und eine Begründung.", ar: "قصيرة قليلاً! حاول أن تقول 2–3 جمل مع تعليل." });
if (wordOrder)
tips.push({
de: `Achtung Wortstellung: Nach „${wordOrder[1]}“ steht das Verb am Ende (z. B. „${wordOrder[1]} ${wordOrder[2]} … ${wordOrder[3]}“).`,
ar: `انتبه لترتيب الكلمات: بعد «${wordOrder[1]}» يأتي الفعل في آخر الجملة.`,
});
if (used.length) tips.push({ de: `Toll, du benutzt: ${used.slice(0, 3).join(", ")} 👏`, ar: "ممتاز! استخدمت أدوات الربط." });
else if (words >= 7) tips.push({ de: "Tipp: Verbinde deine Sätze mit „weil“, „deshalb“ oder „außerdem“.", ar: "نصيحة: اربط جملك بـ weil أو deshalb أو außerdem." });
return { score, tips, words };
}
interface AiReply {
reply: string;
replyAr: string;
correction: string;
tipAr: string;
score: number;
}
function SessionView({ session, onBack }: { session: Session; onBack: () => void }) {
const [msgs, setMsgs] = useState<Msg[]>([]);
const [step, setStep] = useState(0);
const [input, setInput] = useState("");
const [listening, setListening] = useState(false);
const [typing, setTyping] = useState(false);
const [autoSpeak, setAutoSpeak] = useState(true);
const [scores, setScores] = useState<number[]>([]);
const [done, setDone] = useState(false);
const [aiAvailable, setAiAvailable] = useState(false);
const [useAi, setUseAi] = useState(false);
const [aiChecked, setAiChecked] = useState(false);
const [slide, setSlide] = useState(session.slides ? 0 : -1);
const [slideNotes, setSlideNotes] = useState<string[]>(() => (session.slides ?? []).map(() => ""));
const [elapsed, setElapsed] = useState(0);
const stopRef = useRef<(() => void) | null>(null);
const endRef = useRef<HTMLDivElement>(null);
const started = useRef(false);
const maxAiTurns = 8;
const inPresentation = slide >= 0 && session.slides !== undefined && slide < session.slides.length;
useEffect(() => {
fetch("/api/coach")
.then((r) => r.json())
.then((d: { enabled: boolean }) => {
setAiAvailable(d.enabled);
setUseAi(d.enabled);
})
.catch(() => {})
.finally(() => setAiChecked(true));
const id = setInterval(() => setElapsed((e) => e + 1), 1000);
return () => {
clearInterval(id);
stopSpeaking();
stopRef.current?.();
};
}, []);
useEffect(() => {
endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, [msgs, typing]);
const say = (m: Msg) => {
setMsgs((x) => [...x, m]);
if (m.from === "bot" && autoSpeak) speak(m.de, { gender: "m", rate: 0.95 });
};
const botAsk = (i: number) => {
const pr = session.prompts[i];
if (!pr) return;
setTyping(true);
setTimeout(() => {
setTyping(false);
say({ from: "bot", de: pr.de, ar: pr.ar, sample: pr.sample });
}, 700);
};
const aiTurn = async (history: Msg[]) => {
setTyping(true);
try {
const r = await fetch("/api/coach", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
mode: "chat",
topic: session.title.replace(/^\S+\s/, ""),
context: [session.context, session.prompts.map((p) => p.de).join(" / ")].filter(Boolean).join("\nMögliche Fragen: "),
history: history.filter((m) => m.from !== "tip").map((m) => ({ role: m.from === "bot" ? "assistant" : "user", content: m.de })),
}),
});
if (!r.ok) throw new Error();
const d = (await r.json()) as AiReply;
setTyping(false);
if (d.correction || d.tipAr) setMsgs((x) => [...x, { from: "tip", de: d.correction ? `✏️ Besser: ${d.correction}` : "👍 Gut gesagt!", ar: d.tipAr || undefined }]);
if (d.score) setScores((s) => [...s, d.score]);
say({ from: "bot", de: d.reply, ar: d.replyAr });
} catch {
setTyping(false);
setUseAi(false);
setMsgs((x) => [...x, { from: "tip", de: "KI nicht erreichbar – ich mache offline weiter.", ar: "الذكاء الاصطناعي غير متاح – سأكمل بدون إنترنت." }]);
botAsk(step);
}
};
// Start
useEffect(() => {
if (started.current || inPresentation || !aiChecked) return;
started.current = true;
if (session.intro) setMsgs([{ from: "tip", de: `📋 ${session.intro.de}`, ar: session.intro.ar }]);
if (useAi) void aiTurn([]);
else botAsk(0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [inPresentation, aiChecked]);
const send = (textRaw?: string) => {
const text = (textRaw ?? input).trim();
if (!text || done) return;
stopSpeaking();
setInput("");
const mine: Msg = { from: "me", de: text };
const history = [...msgs, mine];
setMsgs(history);
const userTurns = history.filter((m) => m.from === "me").length;
if (useAi) {
const a = analyze(text);
recordResult(session.id, "sprechen", a.score * 20, 3 + a.score);
if (userTurns >= maxAiTurns) return finish([...scores, a.score]);
void aiTurn(history);
return;
}
const a = analyze(text);
const newScores = [...scores, a.score];
setScores(newScores);
recordResult(session.id, "sprechen", a.score * 20, 3 + a.score);
if (a.score >= 4) sfx.correct();
const prev = session.prompts[step];
setTimeout(() => {
setMsgs((x) => [...x, { from: "tip", de: `${"⭐".repeat(a.score)} ${a.tips.map((t) => t.de).join(" ")}`, ar: a.tips.map((t) => t.ar).join(" "), sample: prev?.sample }]);
const next = step + 1;
if (next >= session.prompts.length) {
finish(newScores);
return;
}
setStep(next);
const r = reactions[Math.floor(Math.random() * reactions.length)];
const pr = session.prompts[next];
setTyping(true);
setTimeout(() => {
setTyping(false);
say({ from: "bot", de: `${r.de} ${pr.de}`, ar: `${r.ar} ${pr.ar}`, sample: pr.sample });
}, 900);
}, 400);
};
const finish = (all: number[]) => {
setDone(true);
const avg = all.length ? all.reduce((a, b) => a + b, 0) / all.length : 0;
const closing = { from: "bot" as const, de: "Vielen Dank, das war ein schönes Gespräch! Du machst große Fortschritte. 👏", ar: "شكراً جزيلاً، كانت محادثة جميلة! أنت تتقدّم كثيراً." };
setTimeout(() => say(closing), 600);
if (avg >= 3.5) {
fireConfetti();
sfx.win();
}
};
const toggleMic = () => {
if (listening) {
stopRef.current?.();
return;
}
stopSpeaking();
const base = input ? input + " " : "";
const stop = startListening(
(t) => setInput(base + t),
() => {
setListening(false);
stopRef.current = null;
},
);
if (stop) {
stopRef.current = stop;
setListening(true);
}
};
const avg = scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : 0;
const mm = String(Math.floor(elapsed / 60)).padStart(2, "0");
const ss = String(elapsed % 60).padStart(2, "0");
// ---------- Präsentationsmodus (Folien) ----------
if (inPresentation && session.slides) {
const s = session.slides[slide];
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>📊 {session.title}</h1>
<div className="row">
<span className="pill purple">
Folie {slide + 1} / {session.slides.length}
</span>
<span className="pill yellow timer">⏱ {mm}:{ss}</span>
<span className="small muted">Ziel: ca. 3–4 Minuten</span>
</div>
<div className="bar" style={{ marginTop: 10 }}>
<div style={{ width: `${((slide + 1) / session.slides.length) * 100}%` }} />
</div>
<div className="slide" style={{ marginTop: 14, fontSize: 18 }}>
<b>{s.de}</b>
<Ar block>{s.ar}</Ar>
</div>
<p className="small muted">Sprich laut (Mikrofon) oder schreib Stichpunkte. • تحدّث بصوت عالٍ أو اكتب نقاطاً.</p>
<div className="row" style={{ alignItems: "flex-end" }}>
<textarea
rows={5}
value={slideNotes[slide]}
onChange={(e) => setSlideNotes((n) => n.map((x, i) => (i === slide ? e.target.value : x)))}
placeholder="Was sagst du zu dieser Folie? …"
style={{ flex: 1 }}
/>
{sttSupported() && (
<button
className={`mic ${listening ? "on" : ""}`}
onClick={() => {
if (listening) return stopRef.current?.();
const base = slideNotes[slide] ? slideNotes[slide] + " " : "";
const stop = startListening(
(t) => setSlideNotes((n) => n.map((x, i) => (i === slide ? base + t : x))),
() => setListening(false),
);
if (stop) {
stopRef.current = stop;
setListening(true);
}
}}
aria-label="Mikrofon"
>
{listening ? "⏹" : "🎤"}
</button>
)}
</div>
<div className="row" style={{ marginTop: 14 }}>
<button className="btn secondary" disabled={slide === 0} onClick={() => setSlide((x) => x - 1)}>
← Zurück
</button>
<span className="spacer" />
<button
className="btn purple"
onClick={() => {
stopRef.current?.();
const a = analyze(slideNotes[slide] || "");
recordResult(session.id, "sprechen", a.score * 20, 2 + a.score);
setSlide((x) => x + 1);
}}
>
{slide === session.slides.length - 1 ? "Fertig → Fragen 🎤" : "Nächste Folie →"}
</button>
</div>
</div>
);
}
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<div className="row" style={{ marginTop: 8 }}>
<h1 style={{ fontSize: 22, margin: 0 }}>{session.title}</h1>
<span className="spacer" />
<span className="pill yellow timer">⏱ {mm}:{ss}</span>
</div>
<div className="ar muted">{session.titleAr}</div>
<div className="row small" style={{ marginTop: 8 }}>
<label className="row" style={{ gap: 6 }}>
<input type="checkbox" checked={autoSpeak} onChange={(e) => setAutoSpeak(e.target.checked)} style={{ width: 18, height: 18 }} /> 🔊 Vorlesen
</label>
{aiAvailable && (
<label className="row" style={{ gap: 6 }}>
<input type="checkbox" checked={useAi} onChange={(e) => setUseAi(e.target.checked)} style={{ width: 18, height: 18 }} /> 🤖 KI-Partner
</label>
)}
<span className="spacer" />
{scores.length > 0 && <span className="pill green">Ø {avg.toFixed(1)} ⭐</span>}
</div>
{session.points && (
<div className="card small" style={{ marginTop: 10 }}>
<b>Punkte zum Besprechen:</b>{" "}
{session.points.map((pt, i) => (
<span key={i} className="pill" style={{ margin: 2 }}>
{pt.de}
</span>
))}
</div>
)}
<div className="chat" style={{ marginTop: 14 }}>
{msgs.map((m, i) => (
<Bubble key={i} m={m} />
))}
{typing && (
<div className="bubble bot typing" aria-label="schreibt">
<span />
<span />
<span />
</div>
)}
<div ref={endRef} />
</div>
{done ? (
<div className="card fade-in" style={{ marginTop: 16, textAlign: "center" }}>
<div style={{ fontSize: 48 }}>{avg >= 4 ? "🏆" : avg >= 3 ? "🌟" : "💪"}</div>
<div style={{ fontSize: 22, fontWeight: 900 }}>Gespräch beendet!</div>
<div className="muted">
Durchschnitt: {avg.toFixed(1)} / 5 ⭐ • {scores.length} Antworten • {mm}:{ss} Min.
</div>
<div className="ar">{avg >= 3.5 ? "أداء رائع! استمر هكذا." : "جيد! تدرّب أكثر وحاول أن تقول جملاً أطول."}</div>
<div className="row" style={{ justifyContent: "center", marginTop: 12 }}>
<button className="btn" onClick={onBack}>
Neues Thema
</button>
</div>
</div>
) : (
<div className="composer">
<div className="row" style={{ alignItems: "flex-end", flexWrap: "nowrap" }}>
{sttSupported() && (
<button className={`mic ${listening ? "on" : ""}`} onClick={toggleMic} aria-label="Mikrofon">
{listening ? "⏹" : "🎤"}
</button>
)}
<textarea
rows={2}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send();
}
}}
placeholder={listening ? "Ich höre zu … 👂" : "Antworte auf Deutsch … • أجب بالألمانية"}
style={{ flex: 1 }}
/>
<button className="btn blue" onClick={() => send()} disabled={!input.trim() || typing}>
➤
</button>
</div>
{!sttSupported() && <div className="small muted" style={{ marginTop: 4 }}>🎤 Spracherkennung: in Chrome oder Edge verfügbar.</div>}
</div>
)}
</div>
);
}
function Bubble({ m }: { m: Msg }) {
const [showSample, setShowSample] = useState(false);
if (m.from === "me") return <div className="bubble me">{m.de}</div>;
if (m.from === "tip")
return (
<div className="bubble tip">
<div>{m.de}</div>
{m.ar && (
<Ar block>
<span className="small">{m.ar}</span>
</Ar>
)}
{m.sample && (
<div style={{ marginTop: 6 }}>
{showSample ? (
<div>
<b>💬 Beispielantwort:</b> {m.sample}{" "}
<button className="btn secondary small" onClick={() => speak(m.sample!)}>
🔊
</button>
</div>
) : (
<button className="btn secondary small" onClick={() => setShowSample(true)}>
💬 Beispielantwort zeigen
</button>
)}
</div>
)}
</div>
);
return (
<div className="bubble bot">
<div className="row" style={{ flexWrap: "nowrap", alignItems: "flex-start" }}>
<span style={{ fontSize: 22 }}>👨‍🏫</span>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 700 }}>{m.de}</div>
{m.ar && (
<Ar block>
<span className="small muted">{m.ar}</span>
</Ar>
)}
</div>
<button className="btn secondary small" onClick={() => speak(m.de, { gender: "m" })} aria-label="Nochmal hören">
🔊
</button>
</div>
</div>
);
}