"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { BookOpenText, Loader2, PencilLine, Sparkles, Square, Star, Volume2, X, } from "lucide-react"; import { useTranslation } from "react-i18next"; import { fetchAuthStatus } from "@/lib/auth"; import { randomUuid } from "@/lib/random-uuid"; import { getOwnLearnerProfile } from "@/lib/profile-api"; import { primaryReadingActionRank, readingActionClass, resolveReadingAgeMode, type ReadingAgeMode, } from "@/lib/reading-age-presentation"; import { listReadingExtensions, runReadingExtension, submitReadingQuizAnswers, type ReadingExtensionManifest, type ReadingExtensionResult, type ReadingQuizReward, } from "@/lib/reading-api"; import { useReadingActions } from "./reading-actions-context"; import { useReadAloudSpeech } from "./use-read-aloud-speech"; import Tooltip from "@/shared/ui/Tooltip"; type VocabularyTerm = { term: string; meaning: string; usage: string; }; export type QuizHelpContext = { selection?: string; locator?: number; actions: Array<{ extension: ReadingExtensionManifest; action: ReadingExtensionManifest["actions"][number]; }>; }; type QuizQuestion = { id?: string; prompt: string; choices: string[]; can_answer?: boolean; }; type TranslationResult = { translation: string; alternatives: string[]; note: string; }; const PRIMARY_ACTION_ICONS = [Volume2, BookOpenText, PencilLine] as const; type ReadingExtensionBarProps = { materialId: string; locator: number; /** * The unit the selection was made in, when there is one. * * `locator` is the *viewport* locator and drifts as the reader scrolls. The * server verifies the quote against the text of the unit it is told about * and 400s when they disagree, so a selection has to travel with its own. */ selectionLocator?: number; selection?: string; sessionId?: string | null; onError: (message: string) => void; }; /** * The strip of action buttons above the page. * * Inside a reading workspace an adult reader does not get it: the same * actions live where they are needed — on the selection popover, in the * companion's tools menu and on the header's read-aloud button — and their * results land in the companion column. A strip of chips that were greyed * out until something was selected, with a result slot of its own between * the toolbar and the page, was a third place to look. Younger learners keep * it: three big coloured buttons are the whole point of their layout. */ export function ReadingExtensionBar(props: ReadingExtensionBarProps) { const shared = useReadingActions(); if (shared && shared.ageMode === "default") return null; return ; } function ExtensionToolbar({ materialId, locator, selectionLocator, selection, sessionId, onError, }: ReadingExtensionBarProps) { const { i18n, t } = useTranslation(); const [extensions, setExtensions] = useState([]); const [busy, setBusy] = useState(""); const [result, setResult] = useState(null); const [resultLocator, setResultLocator] = useState(locator); const [ageMode, setAgeMode] = useState("default"); const { speak, speaking, stop: stopSpeaking } = useReadAloudSpeech(); useEffect(() => { let active = true; void listReadingExtensions() .then((rows) => { if (active) setExtensions(rows); }) .catch((error) => { if (active) onError(error instanceof Error ? error.message : String(error)); }); return () => { active = false; }; }, [onError]); useEffect(() => { let active = true; void fetchAuthStatus().then(async (status) => { const learnerMode = status?.preset === "learner" || Boolean(status?.learning_policy); if (!learnerMode) { if (active) setAgeMode("default"); return; } const profile = await getOwnLearnerProfile().catch(() => null); if (active) { setAgeMode( resolveReadingAgeMode({ learnerMode, profileAge: profile?.age, policyAgeBand: status?.learning_policy?.age_band, }), ); } }); return () => { active = false; }; }, []); // Two effects, because the two things they clean up move on different // clocks. A result belongs to the document: keyed on `locator` as well, an // ordinary scroll erased a card the reader was still reading, since // `locator` is the scroll-derived *viewport* locator. useEffect(() => { setResult(null); }, [materialId]); // Speech, on the other hand, must stop the moment the reader navigates // away from the passage being read aloud — so this one keeps both keys. useEffect(() => stopSpeaking, [locator, materialId, stopSpeaking]); const actions = useMemo( () => extensions .flatMap((extension) => extension.actions.map((action) => ({ extension, action }))) .sort((left, right) => { const leftRank = primaryReadingActionRank(`${left.extension.id}:${left.action.id}`); const rightRank = primaryReadingActionRank(`${right.extension.id}:${right.action.id}`); return (leftRank < 0 ? 3 : leftRank) - (rightRank < 0 ? 3 : rightRank); }), [extensions], ); async function run( extension: ReadingExtensionManifest, action: ReadingExtensionManifest["actions"][number], ) { const key = `${extension.id}:${action.id}`; const requestedLocator = selection?.trim() ? (selectionLocator ?? locator) : locator; setBusy(key); try { const next = await runReadingExtension(materialId, extension.id, action.id, { locator: requestedLocator, selection: selection || "", locale: i18n.language, }); setResult(next); setResultLocator(requestedLocator); if (next.type === "browser_speech") { const text = String(next.payload.text || ""); const played = await speak({ materialId, locator: requestedLocator, locale: String(next.payload.locale || i18n.language), fallbackText: text, }); if (!played) { onError(t("No speech voice is available in this browser.")); } } } catch (error) { onError(error instanceof Error ? error.message : String(error)); } finally { setBusy(""); } } if (actions.length === 0) return null; return ( <>
{actions.map(({ extension, action }) => { const key = `${extension.id}:${action.id}`; const needsSelection = action.requires.includes("selection") && !selection?.trim(); // `busy === key`, not `Boolean(busy)`: an action can take the full // server timeout, and disabling all six meanwhile is // indistinguishable from the toolbar being broken. const disabled = busy === key || needsSelection; const builtInLabel = builtInActionLabel(extension.id, action.id); const primaryRank = primaryReadingActionRank(key); const shortLabel = ageMode === "early" ? primaryRank === 0 ? "Listen" : primaryRank === 1 ? "Look up word" : primaryRank === 2 ? "Quiz" : null : null; const Icon = (ageMode !== "default" ? PRIMARY_ACTION_ICONS[primaryRank] : null) ?? Sparkles; const iconSize = primaryRank >= 0 && ageMode === "early" ? 18 : 14; const button = ( ); if (!needsSelection) return button; return ( span]:w-full [&>span>button]:w-full" : "inline-flex w-max flex-none max-sm:min-w-0 max-sm:w-0 max-sm:flex-1 [&>span]:w-full [&>span>button]:w-full" } > {button} ); })}
{speaking ? (
{t("Reading aloud")}
) : null} {result && result.type !== "browser_speech" ? ( setResult(null)} onError={onError} /> ) : null} ); } export function builtInActionLabel(extensionId: string, actionId: string) { if (extensionId === "read_aloud" && actionId === "read") { return "Read aloud"; } if (extensionId === "guided_learning" && actionId === "guide") { return "Guide me"; } if (extensionId === "vocabulary" && actionId === "explain") { return "Explain vocabulary"; } if (extensionId === "quiz" && actionId === "start") { return "Quiz me"; } if (extensionId === "translation" && actionId === "translate_en") { return "Translate to English"; } if (extensionId === "translation" && actionId === "translate_zh") { return "Translate to Chinese"; } return ""; } export function ExtensionResult({ result, materialId, locator, sessionId, closeLabel, onClose, onError, variant = "strip", helpContext, }: { result: ReadingExtensionResult; materialId: string; locator: number; sessionId?: string | null; closeLabel: string; onClose: () => void; onError: (message: string) => void; /** * `strip` is the band under the toolbar, with its own title and close * button. `card` is the body of a companion card, whose header already * carries both. */ variant?: "strip" | "card"; helpContext?: QuizHelpContext; }) { const questions = Array.isArray(result.payload.questions) ? (result.payload.questions as QuizQuestion[]) : []; const items = Array.isArray(result.payload.items) ? result.payload.items.map(String) : []; const steps = Array.isArray(result.payload.steps) ? result.payload.steps.map(String) : []; const terms: VocabularyTerm[] = Array.isArray(result.payload.terms) ? result.payload.terms .map((row) => { if (typeof row !== "object" || row === null) return null; const term = row as Partial; return { term: String(term.term || ""), meaning: String(term.meaning || ""), usage: String(term.usage || ""), }; }) .filter((row): row is VocabularyTerm => row !== null) : []; const translation: TranslationResult = { translation: String(result.payload.translation || ""), alternatives: Array.isArray(result.payload.alternatives) ? result.payload.alternatives.map(String) : [], note: String(result.payload.note || ""), }; const body = String(result.payload.body || result.payload.overview || ""); const card = variant === "card"; return (
*:first-child]:mt-0" : "relative mx-3 mb-2 shrink-0 rounded-xl bg-[var(--card)] px-3 py-3 text-xs text-[var(--foreground)] shadow-[var(--dt-shadow-xs,0_0_0_1px_rgba(0,0,0,.06))]" } > {card ? null : ( <>

{result.title}

)} {result.message ? (

{result.message}

) : null} {body ?

{body}

: null} {translation.translation ? (

{translation.translation}

) : null} {translation.note ? (

{translation.note}

) : null} {translation.alternatives.length ? (
    {translation.alternatives.map((alternative, index) => (
  • {alternative}
  • ))}
) : null} {items.length ? (
    {items.map((item, index) => (
  • {item}
  • ))}
) : null} {steps.length ? (
    {steps.map((step, index) => (
  1. {step}
  2. ))}
) : null} {terms.length ? (
{terms.map((term, index) => (
{term.term}
{term.meaning}
{term.usage}
))}
) : null} {questions.length ? ( question.id)])} helpContext={helpContext} questions={questions} materialId={materialId} locator={locator} sessionId={sessionId} onError={onError} /> ) : null}
); } function QuizQuestions({ questions, materialId, locator, sessionId, onError, helpContext, }: { questions: QuizQuestion[]; materialId: string; locator: number; sessionId?: string | null; onError: (message: string) => void; helpContext?: QuizHelpContext; }) { const { t } = useTranslation(); const [answers, setAnswers] = useState>({}); const [verdicts, setVerdicts] = useState>({}); const [reward, setReward] = useState(null); const [saving, setSaving] = useState>({}); const [helping, setHelping] = useState>({}); const pendingSubmissions = useRef>({}); async function persistAnswer(question: QuizQuestion, index: number, choiceIndex: number) { const questionId = question.id || `q_${index + 1}`; const key = question.id || String(index); const pending = pendingSubmissions.current[key]; const submissionId = pending?.selected === choiceIndex ? pending.id : randomUuid(); pendingSubmissions.current[key] = { selected: choiceIndex, id: submissionId }; setSaving((current) => ({ ...current, [key]: true })); try { const results = await submitReadingQuizAnswers(materialId, { locator, session_id: sessionId || "", submission_id: submissionId, answers: [{ question_id: questionId, selected_index: choiceIndex }], }); const verdict = results.answers.find((item) => item.question_id === questionId); if (!verdict) throw new Error(t("Failed to save answer. Please try again.")); setAnswers((current) => ({ ...current, [key]: choiceIndex })); setVerdicts((current) => ({ ...current, [key]: verdict.is_correct })); setReward(results.reward ?? null); delete pendingSubmissions.current[key]; } catch (error) { onError(error instanceof Error ? error.message : String(error)); } finally { setSaving((current) => ({ ...current, [key]: false })); } } return ( <> {questions.map((question, index) => { const key = question.id || String(index); const selected = answers[key]; if (question.can_answer !== true) { return (

{question.prompt}

    {question.choices.map((choice) => (
  1. {choice}
  2. ))}
); } return (
{question.prompt}
{question.choices.map((choice, choiceIndex) => ( ))}
{question.id && helpContext ? ( setHelping((current) => ({ ...current, [key]: busy }))} onError={onError} /> ) : null} {selected !== undefined ? (

{verdicts[key] ? t("Correct") : t("Incorrect")}

) : null}
); })} {reward ? (

) : null} ); } function QuestionHelp({ questionId, materialId, locator, context, disabled, onBusyChange, onError, }: { questionId: string; materialId: string; locator: number; context: QuizHelpContext; disabled: boolean; onBusyChange: (busy: boolean) => void; onError: (message: string) => void; }) { const { t, i18n } = useTranslation(); const [result, setResult] = useState(null); const [count, setCount] = useState(0); const [busy, setBusy] = useState(false); const busyRef = useRef(false); const active = useRef(true); const requests = useRef(new Map()); useEffect(() => { active.current = true; return () => { active.current = false; }; }, []); const actions = context.actions.filter(({ extension, action }) => (extension.id === "guided_learning" && action.id === "guide") || (extension.id === "vocabulary" && action.id === "explain"), ); if (!actions.length) return null; const hasSelection = Boolean(context.selection?.trim()) && context.locator === locator; async function requestHelp(entry: QuizHelpContext["actions"][number]) { if (busyRef.current || disabled || !hasSelection) return; const selection = context.selection || ""; const locale = i18n.language; const requestKey = JSON.stringify([entry.extension.id, entry.action.id, selection, locale]); const requestId = requests.current.get(requestKey) || randomUuid(); requests.current.set(requestKey, requestId); busyRef.current = true; setBusy(true); onBusyChange(true); try { const next = await runReadingExtension(materialId, entry.extension.id, entry.action.id, { locator, selection, locale, question_id: questionId, help_request_id: requestId, }); if (!active.current) return; const receipt = next.quiz_help; if (!receipt || receipt.question_id !== questionId || !Number.isInteger(receipt.hints_used) || receipt.hints_used < 1 || (next.type !== "card" && next.type !== "feedback")) { throw new Error(t("Failed to record help. Please try again.")); } requests.current.delete(requestKey); setCount((previous) => Math.max(previous, receipt.hints_used)); setResult(next); } catch (error) { if (active.current) onError(error instanceof Error ? error.message : String(error)); } finally { if (active.current) { busyRef.current = false; setBusy(false); onBusyChange(false); } } } return (
{actions.map((entry) => ( ))}
{!hasSelection ?

{t("Select text from this question's reading section first.")}

: null} {busy ?

{t("Working on it…")}

: null} {count > 0 ?

{t("Recorded help: {{count}}", { count })}

: null} {result ? ( setResult(null)} onError={onError} /> ) : null}
); }