Next.js 15 app that turns photos, PDFs, DOCX/PPTX and text into a swipeable feed of AI-generated activities (flashcards, multiple choice, true/false, fill-in-the-blank, matching, ordering, short answer) using the user's own Ollama models. Highlights: - All AI calls run in server route handlers; the browser never talks to Ollama. - Bring-your-own-key mode (default): the key lives only in the browser and is sent per-request; server, local-daemon and shared-key modes also supported. - Client-side document extraction (pdf.js, mammoth, jszip) with scanned-PDF page rendering for the vision model; notes stay in their original language. - ChatGPT-style shell: collapsible sidebar / mobile drawer, neutral token-based light + dark themes, folder organisation, PWA (manifest, SW, offline page). - Strict JSON validation with zod + auto-repair, rate limiting, and request guards (cross-origin, body-size, API-key sanitising). - setup.sh bootstraps deps, .env.local and a production build. Gitignore excludes .env*, the generated pdf.js worker and local scratch files.
189 lines
6.9 KiB
TypeScript
189 lines
6.9 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
|
|
import { ApiError, gradeAnswer } from "@/lib/client-api";
|
|
import type { Activity } from "@/lib/schemas";
|
|
import { cn } from "@/lib/utils";
|
|
import { Button, Spinner } from "@/components/ui";
|
|
|
|
import {
|
|
ActivityHeader,
|
|
FeedbackPanel,
|
|
Hint,
|
|
PromptCard,
|
|
QuestionText,
|
|
type ActivityComponentProps,
|
|
} from "./shared";
|
|
|
|
type ShortAnswerActivity = Extract<Activity, { type: "short_answer" }>;
|
|
|
|
type GradeState =
|
|
| { status: "idle" }
|
|
| { status: "grading" }
|
|
| { status: "graded"; correct: boolean; feedback: string; missing: string[] }
|
|
| { status: "error"; message: string }
|
|
| { status: "self-check" };
|
|
|
|
export function ShortAnswer({ activity, active, language, onAnswered, onNext, isLast }: ActivityComponentProps<ShortAnswerActivity>) {
|
|
const [value, setValue] = useState("");
|
|
const [state, setState] = useState<GradeState>({ status: "idle" });
|
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
|
|
|
useEffect(() => {
|
|
if (active && state.status === "idle") {
|
|
const timer = window.setTimeout(() => textareaRef.current?.focus(), 350);
|
|
return () => window.clearTimeout(timer);
|
|
}
|
|
}, [active, state.status]);
|
|
|
|
const grade = async () => {
|
|
if (!value.trim() || state.status === "grading") return;
|
|
setState({ status: "grading" });
|
|
try {
|
|
const result = await gradeAnswer({
|
|
question: activity.question,
|
|
referenceAnswer: activity.referenceAnswer,
|
|
keyPoints: activity.keyPoints,
|
|
userAnswer: value.trim(),
|
|
language,
|
|
});
|
|
setState({
|
|
status: "graded",
|
|
correct: result.correct,
|
|
feedback: result.feedback,
|
|
missing: result.missing,
|
|
});
|
|
onAnswered(result.correct, { userAnswer: value.trim() });
|
|
} catch (error) {
|
|
setState({
|
|
status: "error",
|
|
message:
|
|
error instanceof ApiError
|
|
? error.message
|
|
: "Grading failed. Check that Ollama is reachable and try again.",
|
|
});
|
|
}
|
|
};
|
|
|
|
const selfCheck = (correct: boolean) => {
|
|
setState({ status: "graded", correct, feedback: "Self-checked — you judged this one yourself.", missing: [] });
|
|
onAnswered(correct, { userAnswer: value.trim() });
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<ActivityHeader type="short_answer" topic={activity.topic} />
|
|
<PromptCard>
|
|
<QuestionText>{activity.question}</QuestionText>
|
|
</PromptCard>
|
|
|
|
<label className="sr-only" htmlFor={`answer-${activity.id}`}>
|
|
Your answer
|
|
</label>
|
|
<textarea
|
|
id={`answer-${activity.id}`}
|
|
ref={textareaRef}
|
|
value={value}
|
|
onChange={(event) => setValue(event.target.value)}
|
|
onKeyDown={(event) => {
|
|
event.stopPropagation();
|
|
if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
|
|
event.preventDefault();
|
|
void grade();
|
|
}
|
|
}}
|
|
disabled={state.status === "grading" || state.status === "graded"}
|
|
rows={3}
|
|
placeholder="Type your answer in your own words…"
|
|
className="w-full resize-none rounded-2xl border-2 border-frost-200 bg-white/90 px-4 py-3 text-[15px] font-medium text-frost-950 shadow-sm outline-none transition placeholder:text-slate-400 focus:border-frost-500 disabled:opacity-70 dark:border-white/12 dark:bg-white/[0.07] dark:text-frost-50 dark:placeholder:text-slate-400"
|
|
/>
|
|
|
|
{state.status === "idle" ? (
|
|
<div className="flex items-center justify-between gap-3">
|
|
<Hint>Ctrl/⌘ + Enter to submit.</Hint>
|
|
<Button size="lg" onClick={() => void grade()} disabled={!value.trim()}>
|
|
Submit answer
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
|
|
{state.status === "grading" ? (
|
|
<div className="flex items-center gap-3 rounded-2xl border border-white/60 bg-white/50 backdrop-blur-xl px-4 py-3 text-sm font-semibold text-frost-800 dark:border-white/15 dark:bg-white/10 dark:text-frost-100">
|
|
<Spinner className="size-5" />
|
|
Grading your answer…
|
|
</div>
|
|
) : null}
|
|
|
|
{state.status === "error" ? (
|
|
<div className="rounded-2xl border-2 border-amber-300 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/10 dark:text-amber-100">
|
|
<p className="font-bold">Couldn't grade that answer</p>
|
|
<p className="mt-1">{state.message}</p>
|
|
<div className="mt-3 flex flex-wrap gap-2">
|
|
<Button size="sm" onClick={() => void grade()}>
|
|
Retry
|
|
</Button>
|
|
<Button size="sm" variant="secondary" onClick={() => setState({ status: "self-check" })}>
|
|
Show answer & self-check
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
{state.status === "self-check" ? (
|
|
<div className="card space-y-3 p-4">
|
|
<p className="text-sm font-bold text-frost-900 dark:text-frost-100">Model answer</p>
|
|
<p className="text-sm leading-relaxed text-frost-700 dark:text-frost-200">{activity.referenceAnswer}</p>
|
|
<p className="text-xs text-frost-500 dark:text-frost-400">Key points: {activity.keyPoints.join(" · ")}</p>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<Button variant="secondary" onClick={() => selfCheck(false)}>
|
|
😅 I missed it
|
|
</Button>
|
|
<Button variant="success" onClick={() => selfCheck(true)}>
|
|
🧊 I had it right
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
{state.status === "graded" ? (
|
|
<>
|
|
<div
|
|
className={cn(
|
|
"rounded-2xl border-2 p-3 text-sm font-semibold",
|
|
state.correct
|
|
? "border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-400/40 dark:bg-emerald-400/10 dark:text-emerald-100"
|
|
: "border-rose-300 bg-rose-50 text-rose-900 dark:border-rose-400/40 dark:bg-rose-400/10 dark:text-rose-100",
|
|
)}
|
|
>
|
|
<p className="font-extrabold uppercase tracking-wide">
|
|
{state.correct ? "Accepted" : "Needs work"}
|
|
</p>
|
|
<p className="mt-1 font-normal">{state.feedback}</p>
|
|
{state.missing.length ? (
|
|
<ul className="mt-2 list-inside list-disc font-normal">
|
|
{state.missing.map((item) => (
|
|
<li key={item}>{item}</li>
|
|
))}
|
|
</ul>
|
|
) : null}
|
|
{!state.correct ? (
|
|
<p className="mt-2 font-normal">
|
|
<span className="font-bold">Model answer: </span>
|
|
{activity.referenceAnswer}
|
|
</p>
|
|
) : null}
|
|
</div>
|
|
|
|
<FeedbackPanel
|
|
correct={state.correct}
|
|
explanation={activity.explanation}
|
|
xp={activity.xp}
|
|
isLast={isLast}
|
|
onNext={onNext}
|
|
/>
|
|
</>
|
|
) : null}
|
|
</>
|
|
);
|
|
}
|