Files
edueasy/components/child/exercise-session.tsx
T
renato97 a3360ec6e4 feat: fase 2+3 — expansion masiva multi-perfil + bug fixes + hardening
Fase 2 (expansion):
- Francesca: +6 etapas matematicas (5-10), +7 etapas lectura (3-9), +2 ortografia
- Sebastian: +8 etapas matematicas (4-11), +6 lectura, +3 historia, +3 geografia, +1 banderas
- Nuevas paginas: ortografia, lectura, geografia, matematicas
- ~900 ejercicios nuevos, paridad ~500 por perfil

Fase 3 (bug fixes + hardening):
- Fix: SessionLog auto-create en grade route
- Fix: engine cache (no borrar antes de revisar)
- Fix: FSRS cards actualizadas en flujo curriculum
- Fix: responseMs real (no hardcodeado 3000)
- Fix: options dentro de content en sebastian etapa-1
- Fix: trazo-letra consonantes crash
- Security: execFileSync anti-command-injection en TTS
- DB: 18 cascade deletes + indices + unique constraints
- APIs debug: reset, state, seed
- Docker: espeak-ng + prisma + user/group
- E2E: 23 tests nuevos (curriculum-flow.spec.ts)
- Code review: tailwind colors, middleware dev mode, eslint config

Verificado: tsc exit 0, build exit 0, 61 E2E tests pass
2026-07-25 22:07:28 -03:00

183 lines
5.1 KiB
TypeScript

"use client"
import { useState, useCallback, useEffect, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { GatoMascota } from "@/components/child/gato-mascota"
import NoChildError from "@/components/child/no-child-error"
import TemporizadorVisual from "@/components/child/temporizador-visual"
import ExerciseDispatcher from "@/components/exercises/exercise-dispatcher"
import { speak, stopSpeaking } from "@/lib/speech"
import type { Exercise } from "@/curriculum/types"
const CHILD_ID_KEY = "edueasy_child_id"
type PageState = "loading" | "ready" | "complete" | "error"
interface Props {
topic: string
loadingMessage: string
completeMessage: string
profile?: string
}
export default function ExerciseSession({ topic, loadingMessage, completeMessage, profile }: Props) {
const [pageState, setPageState] = useState<PageState>("loading")
const [exercise, setExercise] = useState<Exercise | null>(null)
const [running, setRunning] = useState(true)
const [score, setScore] = useState(0)
const [totalAttempts, setTotalAttempts] = useState(0)
const childIdRef = useRef<string>("")
const exerciseStartedAt = useRef<number>(Date.now())
const startedAtRef = useRef(new Date().toISOString())
const getChildId = useCallback(() => {
const id = localStorage.getItem(CHILD_ID_KEY) || ""
childIdRef.current = id
return id
}, [])
const fetchNext = useCallback(async () => {
const childId = getChildId()
if (!childId) {
setPageState("error")
return null
}
try {
const qs = new URLSearchParams({ childId, topic })
if (profile) qs.set("profile", profile)
const res = await fetch(`/api/curriculum/next?${qs}`)
const data = await res.json()
if (data.done || !data.id) {
setPageState("complete")
return null
}
setExercise(data)
exerciseStartedAt.current = Date.now()
setPageState("ready")
return data
} catch {
setPageState("error")
return null
}
}, [getChildId, topic, profile])
useEffect(() => {
fetchNext()
}, [fetchNext])
const gradeAttempt = useCallback(async (ex: Exercise, correct: boolean) => {
const childId = childIdRef.current
if (!childId || !ex) return
setTotalAttempts((t) => t + 1)
if (correct) setScore((s) => s + 1)
const errorType = !correct
? ex.errorType || "discriminacion-auditiva"
: null
try {
const responseMs = Date.now() - exerciseStartedAt.current
await fetch("/api/curriculum/grade", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
childId,
exerciseId: ex.id,
skillCode: ex.skillCode,
correct,
promptLevel: 0,
responseMs,
errorType,
stage: ex.stage,
}),
})
} catch {
// silent
}
}, [])
const handleComplete = useCallback(
async (correct: boolean) => {
if (!exercise) return
await gradeAttempt(exercise, correct)
stopSpeaking()
if (correct) {
await speak("¡Muy bien!")
await new Promise((r) => setTimeout(r, 800))
} else {
await speak("¡Seguí intentando!")
await new Promise((r) => setTimeout(r, 800))
}
fetchNext()
},
[exercise, gradeAttempt, fetchNext],
)
const resetSession = useCallback(() => {
setScore(0)
setTotalAttempts(0)
setRunning(true)
startedAtRef.current = new Date().toISOString()
fetchNext()
}, [fetchNext])
if (pageState === "loading") {
return (
<div className="flex-1 flex items-center justify-center">
<GatoMascota mood="coach" message={loadingMessage} size="sm" />
</div>
)
}
if (pageState === "error") {
return <NoChildError onRetry={resetSession} />
}
if (pageState === "complete") {
return (
<div className="flex-1 flex flex-col items-center justify-center p-8 gap-6">
<GatoMascota mood="celebrate" message={completeMessage} size="lg" />
<p className="text-lg font-display">
Aciertos: {score}/{totalAttempts}
</p>
<button
onClick={resetSession}
className="bg-primary text-primary-foreground touch-target-lg rounded-2xl px-8 py-4 text-xl font-display font-bold"
>
Jugar de nuevo
</button>
</div>
)
}
return (
<div className="flex-1 flex flex-col items-center justify-center p-6 gap-6">
<TemporizadorVisual
durationMinutes={10}
onComplete={() => {
setRunning(false)
setPageState("complete")
}}
running={running}
/>
<AnimatePresence mode="wait">
<motion.div
key={exercise?.id || "empty"}
initial={{ opacity: 0, x: 50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -50 }}
transition={{ duration: 0.25 }}
className="w-full max-w-md"
>
{exercise && (
<ExerciseDispatcher exercise={exercise} onComplete={handleComplete} />
)}
</motion.div>
</AnimatePresence>
</div>
)
}