All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s
Providers and pricing - Add a DeepSeek provider: thinking mode with low/high/max effort, reasoning_content replayed between tool steps, cache-hit usage, /models discovery and catalog prices. - Fix "does not support tool calling": a rejected forced tool_choice (DeepSeek thinking mode) now asks for the call in the prompt; only a genuine no-tools 400 is "unsupported". - Seven reasoning-effort levels (Off to Max) mapped per adapter. - Cached-input price per model, cache-write and DeepSeek off-peak aware cost estimates. - Built-in bge-small embedding model (transformers.js) as the semantic search default. Quizzes - Numeric (type-the-answer) questions: units ignored, optional ± tolerance; editor, runner, importer, templates and generation prompts. - Quiz start screen instead of showing answers; navigator ring no longer clipped and key legend removed; clock only for timed exams; 7-point letter grades. Assistant and generation - Assistant turns run on the server independently of the browser, with re-attach and an explicit stop; drafts tray shows generations in progress. - Per-chat model switcher, @-tagging of class materials, full-width assistant page and a smaller assistant button. - Editable generation instructions and built-in presets, separate from the chatbot import instructions. Other - Dialog footer padding, keyboard hints removed, copy buttons work over plain HTTP, class and folder shares include documents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
330 lines
13 KiB
TypeScript
330 lines
13 KiB
TypeScript
import { useQuery } from '@tanstack/react-query';
|
|
import { CircleCheck, EyeOff, MoreHorizontal, Pencil, Undo2 } from 'lucide-react';
|
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
import { useNavigate, useSearchParams } from 'react-router';
|
|
import { toast } from 'sonner';
|
|
import { CardEditor } from '@/features/editors';
|
|
import { Explain } from '@/features/Explain';
|
|
import { FlipCard, StreakChip, StudyFooter, StudyTopBar, useStreak } from '@/features/flashcards';
|
|
import { api, errorMessage } from '@/lib/api';
|
|
import { useAiStatus, useRefresh } from '@/lib/queries';
|
|
import type { DueCounts, QueueCard } from '@/lib/types';
|
|
import { cx, formatMinutes, plural, useDocumentTitle, useHotkeys } from '@/lib/util';
|
|
import { Badge, Button, ClassDot, Dialog, ErrorState, IconButton, Menu, MenuItem, PageLoading } from '@/ui';
|
|
|
|
interface QueueResponse {
|
|
cards: QueueCard[];
|
|
counts: DueCounts;
|
|
}
|
|
|
|
const LEARN_AHEAD_MS = 20 * 60_000;
|
|
const RATING_STYLE: Record<number, string> = {
|
|
1: 'border-bad/40 text-bad hover:bg-bad-soft',
|
|
2: 'border-warn/40 text-warn hover:bg-warn-soft',
|
|
3: 'border-good/40 text-good hover:bg-good-soft',
|
|
4: 'border-accent/40 text-accent hover:bg-accent-soft',
|
|
};
|
|
|
|
/** Spaced-repetition review: due cards first, graded Again / Hard / Good / Easy and rescheduled by FSRS. */
|
|
export default function ReviewPage() {
|
|
const [params] = useSearchParams();
|
|
const deckId = params.get('deckId') ?? '';
|
|
const classId = params.get('classId') ?? '';
|
|
const navigate = useNavigate();
|
|
const refresh = useRefresh();
|
|
const ai = useAiStatus();
|
|
useDocumentTitle('Review');
|
|
|
|
const scope = deckId ? `deckId=${deckId}` : classId ? `classId=${classId}` : '';
|
|
const query = useQuery({
|
|
queryKey: ['review', scope],
|
|
queryFn: () => api.get<QueueResponse>(`/api/review/queue?${scope}`),
|
|
staleTime: Infinity,
|
|
gcTime: 0,
|
|
refetchOnWindowFocus: false,
|
|
});
|
|
|
|
const [queue, setQueue] = useState<QueueCard[] | null>(null);
|
|
const [flipped, setFlipped] = useState(false);
|
|
const [seenAnswer, setSeenAnswer] = useState(false);
|
|
const [leaving, setLeaving] = useState<'left' | 'right' | null>(null);
|
|
const { streak, burst, record, reset: resetStreak, hot } = useStreak();
|
|
const [busy, setBusy] = useState(false);
|
|
const [done, setDone] = useState({ reviewed: 0, again: 0 });
|
|
const [last, setLast] = useState<{ cardId: string; snapshot: QueueCard[]; wasAgain: boolean; streakBefore: number } | null>(null);
|
|
const [editing, setEditing] = useState<QueueCard | null>(null);
|
|
const [draft, setDraft] = useState({ front: '', back: '', hint: '', tags: [] as string[] });
|
|
const startedAt = useRef(Date.now());
|
|
const scopeTitle = useRef('');
|
|
|
|
useEffect(() => {
|
|
if (query.data && queue === null) {
|
|
setQueue(query.data.cards);
|
|
const first = query.data.cards[0];
|
|
scopeTitle.current = deckId ? (first?.deckTitle ?? 'Deck') : classId ? (first?.className ?? 'Class') : 'All classes';
|
|
}
|
|
}, [query.data, queue, deckId, classId]);
|
|
|
|
const current = queue?.[0];
|
|
useEffect(() => {
|
|
setFlipped(false);
|
|
setSeenAnswer(false);
|
|
setLeaving(null);
|
|
}, [current?.card.id, current?.card.reps]);
|
|
|
|
const flip = useCallback(() => {
|
|
if (!current || busy) return;
|
|
setFlipped((f) => !f);
|
|
setSeenAnswer(true);
|
|
}, [current, busy]);
|
|
|
|
const rate = useCallback(
|
|
async (rating: 1 | 2 | 3 | 4) => {
|
|
if (!current || !queue || busy || !seenAnswer) return;
|
|
setBusy(true);
|
|
const snapshot = queue;
|
|
const streakBefore = streak;
|
|
// The card swipes away while the new schedule is being saved.
|
|
setLeaving(rating === 1 ? 'left' : 'right');
|
|
try {
|
|
const [res] = await Promise.all([api.post<{ result: QueueCard }>('/api/review/answer', { cardId: current.card.id, rating }), new Promise((r) => setTimeout(r, 230))]);
|
|
record(rating > 1);
|
|
const updated = res.result;
|
|
const rest = queue.slice(1);
|
|
const dueSoon = (updated.card.state === 1 || updated.card.state === 3) && (updated.card.due ?? 0) - Date.now() < LEARN_AHEAD_MS;
|
|
if (dueSoon) {
|
|
// Bring a learning card back after a few others, so it is not seen twice in a row.
|
|
const at = Math.min(rest.length, rating === 1 ? 3 : 6);
|
|
rest.splice(at, 0, updated);
|
|
}
|
|
setQueue(rest);
|
|
setDone((d) => ({ reviewed: d.reviewed + 1, again: d.again + (rating === 1 ? 1 : 0) }));
|
|
setLast({ cardId: current.card.id, snapshot, wasAgain: rating === 1, streakBefore });
|
|
if (rest.length === 0) {
|
|
// The first load is capped; fetch anything that is still due.
|
|
const more = await api.get<QueueResponse>(`/api/review/queue?${scope}`).catch(() => null);
|
|
if (more && more.cards.length > 0) setQueue(more.cards);
|
|
}
|
|
} catch (e) {
|
|
setLeaving(null);
|
|
toast.error(errorMessage(e));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
},
|
|
[current, queue, busy, scope, seenAnswer, streak, record],
|
|
);
|
|
|
|
const undo = useCallback(async () => {
|
|
if (!last || busy) return;
|
|
setBusy(true);
|
|
try {
|
|
const res = await api.post<{ result: QueueCard }>('/api/review/undo', { cardId: last.cardId });
|
|
setQueue(last.snapshot.map((c) => (c.card.id === last.cardId ? res.result : c)));
|
|
setDone((d) => ({ reviewed: Math.max(0, d.reviewed - 1), again: Math.max(0, d.again - (last.wasAgain ? 1 : 0)) }));
|
|
resetStreak(last.streakBefore);
|
|
setLast(null);
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}, [last, busy, resetStreak]);
|
|
|
|
const suspend = async () => {
|
|
if (!current || !queue) return;
|
|
await api.patch(`/api/cards/${current.card.id}`, { suspended: true }).catch((e) => toast.error(errorMessage(e)));
|
|
setQueue(queue.slice(1));
|
|
toast('Card suspended. Unsuspend it from the deck page.');
|
|
};
|
|
|
|
const saveEdit = async () => {
|
|
if (!editing || !queue) return;
|
|
try {
|
|
await api.patch(`/api/cards/${editing.card.id}`, draft);
|
|
setQueue(queue.map((c) => (c.card.id === editing.card.id ? { ...c, card: { ...c.card, ...draft } } : c)));
|
|
setEditing(null);
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
}
|
|
};
|
|
|
|
const exit = () => {
|
|
void refresh();
|
|
navigate(deckId ? `/decks/${deckId}` : classId ? `/classes/${classId}` : '/');
|
|
};
|
|
|
|
useHotkeys({
|
|
space: (e) => (e.preventDefault(), flip()),
|
|
Enter: flip,
|
|
ArrowUp: (e) => (e.preventDefault(), flip()),
|
|
ArrowDown: (e) => (e.preventDefault(), flip()),
|
|
// Left = missed it, right = got it. The number keys give the finer four-way rating.
|
|
ArrowLeft: () => void rate(1),
|
|
ArrowRight: () => void rate(3),
|
|
'1': () => void rate(1),
|
|
'2': () => void rate(2),
|
|
'3': () => void rate(3),
|
|
'4': () => void rate(4),
|
|
u: () => void undo(),
|
|
'mod+z': (e) => {
|
|
e.preventDefault();
|
|
void undo();
|
|
},
|
|
e: () => {
|
|
if (current) {
|
|
setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags });
|
|
setEditing(current);
|
|
}
|
|
},
|
|
});
|
|
|
|
if (query.isError) return <ErrorState message={errorMessage(query.error)} onRetry={() => query.refetch()} className="pt-24" />;
|
|
if (!queue) return <PageLoading />;
|
|
|
|
const remaining = queue.length;
|
|
const counts = {
|
|
learning: queue.filter((c) => c.card.state === 1 || c.card.state === 3).length,
|
|
review: queue.filter((c) => c.card.state === 2).length,
|
|
fresh: queue.filter((c) => c.card.state === 0).length,
|
|
};
|
|
const totalPlanned = done.reviewed + remaining;
|
|
|
|
return (
|
|
<div className="flex min-h-dvh flex-col bg-paper">
|
|
<StudyTopBar
|
|
title="Review"
|
|
subtitle={scopeTitle.current}
|
|
onExit={exit}
|
|
progress={totalPlanned ? done.reviewed / totalPlanned : 1}
|
|
hot={hot}
|
|
right={
|
|
<>
|
|
<StreakChip streak={streak} />
|
|
<div className="hidden items-center gap-1 sm:flex" aria-label="Cards remaining by type">
|
|
<Badge tone="accent">{counts.fresh} new</Badge>
|
|
<Badge tone="warn">{counts.learning} learning</Badge>
|
|
<Badge tone="good">{counts.review} due</Badge>
|
|
</div>
|
|
<span className="num text-[13px] font-medium text-ink-2 sm:hidden">{remaining} left</span>
|
|
<IconButton label="Undo last rating" onClick={undo} disabled={!last || busy}>
|
|
<Undo2 />
|
|
</IconButton>
|
|
{current && (
|
|
<Menu
|
|
trigger={
|
|
<IconButton label="Card options" tooltip={false}>
|
|
<MoreHorizontal />
|
|
</IconButton>
|
|
}
|
|
>
|
|
<MenuItem
|
|
icon={<Pencil />}
|
|
onSelect={() => {
|
|
setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags });
|
|
setEditing(current);
|
|
}}
|
|
>
|
|
Edit card
|
|
</MenuItem>
|
|
<MenuItem icon={<EyeOff />} onSelect={suspend}>
|
|
Suspend card
|
|
</MenuItem>
|
|
</Menu>
|
|
)}
|
|
</>
|
|
}
|
|
/>
|
|
|
|
<main className="mx-auto flex w-full max-w-4xl flex-1 flex-col justify-center px-4 py-6 sm:px-6 sm:py-8">
|
|
{!current ? (
|
|
<div className="card m-auto w-full max-w-xl animate-in p-7 text-center sm:p-10">
|
|
<CircleCheck className="mx-auto mb-3 size-12 text-good" strokeWidth={1.6} />
|
|
<h1 className="display text-[30px]">{done.reviewed > 0 ? 'Review complete' : 'Nothing due right now'}</h1>
|
|
<p className="mx-auto mt-2 max-w-sm text-[15px] text-ink-2">
|
|
{done.reviewed > 0
|
|
? `You reviewed ${plural(done.reviewed, 'card')} in ${formatMinutes((Date.now() - startedAt.current) / 1000)}${done.again > 0 ? `, with ${done.again} to see again soon` : ''}.`
|
|
: 'Cards come back when you are about to forget them. Check in again later today or tomorrow.'}
|
|
</p>
|
|
<div className="mt-6 flex flex-wrap justify-center gap-2">
|
|
<Button variant="primary" size="lg" onClick={exit}>
|
|
Done
|
|
</Button>
|
|
{deckId && (
|
|
<Button size="lg" onClick={() => navigate(`/decks/${deckId}/cram`)}>
|
|
Browse the whole deck
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div className="mb-3 flex items-center gap-2 text-xs text-ink-3">
|
|
<ClassDot color={current.classColor} />
|
|
<span className="truncate">
|
|
{current.className} · {current.deckTitle}
|
|
</span>
|
|
<span className="ml-auto">{current.card.state === 0 ? <Badge tone="accent">New</Badge> : current.card.state === 2 ? <Badge tone="good">Review</Badge> : <Badge tone="warn">Learning</Badge>}</span>
|
|
</div>
|
|
<FlipCard
|
|
cardKey={`${current.card.id}:${current.card.reps}`}
|
|
front={current.card.front}
|
|
back={current.card.back}
|
|
hint={current.card.hint}
|
|
flipped={flipped}
|
|
onFlip={flip}
|
|
onSwipe={seenAnswer && !busy ? (known) => void rate(known ? 3 : 1) : undefined}
|
|
leaving={leaving}
|
|
burst={burst}
|
|
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
|
|
/>
|
|
</>
|
|
)}
|
|
</main>
|
|
|
|
{current && (
|
|
<StudyFooter>
|
|
{seenAnswer ? (
|
|
<div className="grid grid-cols-4 gap-2">
|
|
{current.previews.map((p) => (
|
|
<button
|
|
key={p.rating}
|
|
type="button"
|
|
disabled={busy}
|
|
onClick={() => rate(p.rating)}
|
|
className={cx('flex h-[60px] flex-col items-center justify-center rounded-[13px] border bg-surface shadow-1 transition-colors active:scale-[0.98] disabled:opacity-60', RATING_STYLE[p.rating])}
|
|
>
|
|
<span className="text-[15px] font-semibold">{p.label}</span>
|
|
<span className="num text-[11px] opacity-80">{p.interval}</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<Button size="lg" variant="primary" block className="h-[60px]" onClick={flip}>
|
|
Show answer
|
|
</Button>
|
|
)}
|
|
</StudyFooter>
|
|
)}
|
|
|
|
<Dialog
|
|
open={editing !== null}
|
|
onOpenChange={(o) => !o && setEditing(null)}
|
|
title="Edit card"
|
|
size="lg"
|
|
footer={
|
|
<>
|
|
<Button variant="ghost" onClick={() => setEditing(null)}>
|
|
Cancel
|
|
</Button>
|
|
<Button variant="primary" disabled={!draft.front.trim() || !draft.back.trim()} onClick={saveEdit}>
|
|
Save
|
|
</Button>
|
|
</>
|
|
}
|
|
>
|
|
<CardEditor value={draft} onChange={(c) => setDraft({ front: c.front, back: c.back, hint: c.hint ?? '', tags: c.tags })} onSubmit={saveEdit} showHint />
|
|
</Dialog>
|
|
</div>
|
|
);
|
|
}
|