Add the V2 web app: design system, shell, study flows, AI, settings, sharing

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:53:01 -07:00
parent eae109c166
commit 74a98ac1f1
52 changed files with 11976 additions and 1 deletions

View file

@ -0,0 +1,51 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { MessageSquare, Trash2 } from 'lucide-react';
import { useNavigate, useParams } from 'react-router';
import AssistantPanel from '@/features/AssistantPanel';
import { api } from '@/lib/api';
import { cx, timeAgo, useDocumentTitle } from '@/lib/util';
import { IconButton, useConfirm } from '@/ui';
export default function AssistantPage() {
useDocumentTitle('Assistant');
const { conversationId } = useParams();
const navigate = useNavigate();
const qc = useQueryClient();
const confirm = useConfirm();
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: { id: string; title: string; updatedAt: number }[] }>('/api/ai/conversations').then((r) => r.conversations) });
const remove = async (id: string) => {
if (!(await confirm({ title: 'Delete this conversation?', confirmLabel: 'Delete', danger: true, message: 'The messages are removed. Drafts and anything you saved are kept.' }))) return;
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
await qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
if (id === conversationId) navigate('/assistant');
};
return (
<div className="-mx-4 -mt-6 -mb-28 flex h-[calc(100dvh-52px-56px)] sm:-mx-8 lg:mx-0 lg:-mt-10 lg:-mb-16 lg:h-dvh lg:gap-6">
<aside className="hidden w-60 shrink-0 flex-col border-r border-line py-6 pr-3 lg:flex">
<div className="eyebrow mb-2 px-2">Conversations</div>
<div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto">
{(history.data ?? []).length === 0 && <p className="px-2 text-[13px] text-ink-3">Your conversations will be listed here.</p>}
{(history.data ?? []).map((c) => (
<div key={c.id} className={cx('group flex items-center rounded-[9px]', c.id === conversationId ? 'bg-ink/8' : 'hover:bg-ink/5')}>
<button type="button" onClick={() => navigate(`/assistant/${c.id}`)} className="min-w-0 flex-1 px-2.5 py-2 text-left">
<span className="flex items-center gap-2">
<MessageSquare className="size-3.5 shrink-0 text-ink-3" />
<span className="truncate text-sm">{c.title}</span>
</span>
<span className="pl-[22px] text-[11px] text-ink-3">{timeAgo(c.updatedAt)}</span>
</button>
<IconButton label="Delete conversation" size="sm" className="mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100" onClick={() => remove(c.id)}>
<Trash2 />
</IconButton>
</div>
))}
</div>
</aside>
<div className="flex min-w-0 flex-1 flex-col">
<AssistantPanel variant="page" conversationId={conversationId} onConversationChange={(id) => navigate(id ? `/assistant/${id}` : '/assistant', { replace: true })} />
</div>
</div>
);
}

125
web/src/pages/Auth.tsx Normal file
View file

@ -0,0 +1,125 @@
import { useQueryClient } from '@tanstack/react-query';
import { KeyRound, LockKeyhole } from 'lucide-react';
import { useState, type FormEvent } from 'react';
import { api, errorMessage } from '@/lib/api';
import { qk } from '@/lib/queries';
import { useDocumentTitle } from '@/lib/util';
import { Button, Callout, Field, Input } from '@/ui';
export function Brand({ size = 'md' }: { size?: 'md' | 'lg' }) {
return (
<div className="flex items-center gap-2.5">
<img src="/icon.svg" alt="" className={size === 'lg' ? 'size-11 rounded-[12px]' : 'size-8 rounded-[9px]'} />
<span className={size === 'lg' ? 'display text-[28px]' : 'display text-[21px]'}>Study Desk</span>
</div>
);
}
function AuthFrame({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
return (
<main className="grid min-h-dvh place-items-center px-5 py-10">
<div className="w-full max-w-[400px] animate-in">
<div className="mb-8 flex justify-center">
<Brand size="lg" />
</div>
<div className="card p-6 sm:p-7">
<h1 className="display text-2xl">{title}</h1>
<p className="mt-1.5 mb-6 text-sm text-ink-2">{subtitle}</p>
{children}
</div>
</div>
</main>
);
}
export function LoginPage() {
useDocumentTitle('Sign in');
const qc = useQueryClient();
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const submit = async (e: FormEvent) => {
e.preventDefault();
if (!password) return;
setBusy(true);
setError('');
try {
await api.post('/api/auth/login', { password });
qc.clear();
await qc.invalidateQueries({ queryKey: qk.auth });
} catch (err) {
setError(errorMessage(err));
setPassword('');
} finally {
setBusy(false);
}
};
return (
<AuthFrame title="Welcome back" subtitle="Enter your password to open your study desk.">
<form onSubmit={submit} className="space-y-4">
<Field label="Password" error={error || undefined}>
<Input type="password" autoFocus autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} aria-invalid={Boolean(error)} />
</Field>
<Button type="submit" variant="primary" size="lg" block loading={busy} icon={<LockKeyhole />}>
Sign in
</Button>
</form>
</AuthFrame>
);
}
export function SetupPage() {
useDocumentTitle('Set up');
const qc = useQueryClient();
const [code, setCode] = useState('');
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const mismatch = confirm.length > 0 && password !== confirm;
const submit = async (e: FormEvent) => {
e.preventDefault();
if (password.length < 8) return setError('Use at least 8 characters.');
if (password !== confirm) return setError('The passwords do not match.');
setBusy(true);
setError('');
try {
await api.post('/api/auth/setup', { code, password });
await qc.invalidateQueries({ queryKey: qk.auth });
} catch (err) {
setError(errorMessage(err));
} finally {
setBusy(false);
}
};
return (
<AuthFrame title="Set up Study Desk" subtitle="Create the administrator password. You are the only account on this desk.">
<form onSubmit={submit} className="space-y-4">
<Callout tone="accent" icon={<KeyRound />}>
Find the one-time <strong>setup code</strong> in the container log, or in <code className="num text-[12px]">setup-code.txt</code> inside the data folder.
</Callout>
<Field label="Setup code">
<Input autoFocus value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="XXXXX-XXXXX" autoComplete="off" spellCheck={false} className="num tracking-widest" required />
</Field>
<Field label="Password" hint="At least 8 characters. A short sentence works well.">
<Input type="password" autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
</Field>
<Field label="Confirm password" error={mismatch ? 'The passwords do not match.' : undefined}>
<Input type="password" autoComplete="new-password" value={confirm} onChange={(e) => setConfirm(e.target.value)} required aria-invalid={mismatch} />
</Field>
{error && (
<Callout tone="bad" className="py-2.5">
{error}
</Callout>
)}
<Button type="submit" variant="primary" size="lg" block loading={busy}>
Create password and continue
</Button>
</form>
</AuthFrame>
);
}

729
web/src/pages/ClassPage.tsx Normal file
View file

@ -0,0 +1,729 @@
import {
Archive,
ArrowDownAZ,
BookOpen,
ChevronDown,
Clock,
Copy,
Download,
FileImage,
FileText,
FileUp,
Folder as FolderIcon,
FolderInput,
FolderPlus,
Layers,
MoreHorizontal,
NotebookPen,
Pencil,
Play,
Plus,
Presentation,
Search,
Share2,
Sparkles,
Trash2,
TriangleAlert,
Upload,
X,
} from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { toast } from 'sonner';
import { ClassDialog } from '@/app/Shell';
import { MoveDialog, NewItemDialog, RenameDialog, ShareDialog, type EditableKind, type ShareKind } from '@/features/dialogs';
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { ImportDialog } from '@/features/ImportDialog';
import { useStartSession } from '@/features/study';
import { api, errorMessage, uploadWithProgress } from '@/lib/api';
import { assistant, useAssistantContext } from '@/lib/assistantStore';
import { useClass, useRefresh } from '@/lib/queries';
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', document: 'documents', note: 'notes' } as const;
function DocIcon({ kind }: { kind: string }) {
if (kind === 'pptx') return <Presentation />;
if (kind === 'image') return <FileImage />;
return <FileText />;
}
function KindIcon({ item }: { item: Item }) {
const tone = { quiz: 'bg-accent-soft text-accent', deck: 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker', document: 'bg-sunken text-ink-2', note: 'bg-good-soft text-good' }[item.kind];
return (
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', tone)}>
{item.kind === 'quiz' ? <BookOpen /> : item.kind === 'deck' ? <Layers /> : item.kind === 'note' ? <NotebookPen /> : <DocIcon kind={(item as DocumentItem).docKind} />}
</span>
);
}
function itemMeta(item: Item): ReactNode {
if (item.kind === 'quiz') {
const q = item as QuizItem;
return (
<>
<span>{plural(q.questionCount, 'question')}</span>
{q.lastPercent !== null && (
<span className={cx('num font-medium', { good: 'text-good', warn: 'text-warn', bad: 'text-bad', none: '' }[gradeTone(q.lastPercent)])}>Last {q.lastPercent}%</span>
)}
{q.lastStudiedAt && <span>{timeAgo(q.lastStudiedAt)}</span>}
</>
);
}
if (item.kind === 'deck') {
const d = item as DeckItem;
return (
<>
<span>{plural(d.cardCount, 'card')}</span>
{d.cardCount > 0 && <span>{d.learnedCount} learned</span>}
</>
);
}
if (item.kind === 'document') {
const d = item as DocumentItem;
return (
<>
<span className="uppercase">{d.docKind === 'markdown' ? 'MD' : d.docKind}</span>
{d.pageCount ? <span>{plural(d.pageCount, d.docKind === 'pptx' ? 'slide' : 'page')}</span> : null}
<span>{formatBytes(d.size)}</span>
</>
);
}
return <span className="truncate">{item.description || 'Empty note'}</span>;
}
interface Uploading {
id: number;
name: string;
progress: number;
error?: string;
}
export default function ClassPage() {
const { classId = '' } = useParams();
const navigate = useNavigate();
const refresh = useRefresh();
const confirm = useConfirm();
const { start } = useStartSession();
const [polling, setPolling] = useState(false);
const q = useClass(classId, polling ? 1500 : false);
const data = q.data;
useDocumentTitle(data?.class.name);
useAssistantContext(classId, data?.class.name);
const [filter, setFilter] = useState<Filter>('all');
const [query, setQuery] = useState('');
const [sort, setSort] = useLocalStorage<'recent' | 'title'>('sd.classSort', 'recent');
const [collapsed, setCollapsed] = useLocalStorage<Record<string, boolean>>(`sd.folders.${classId}`, {});
const [newKind, setNewKind] = useState<{ kind: 'quiz' | 'deck' | 'note' | 'folder'; folderId?: string | null } | null>(null);
const [rename, setRename] = useState<Parameters<typeof RenameDialog>[0]['target']>(null);
const [move, setMove] = useState<Parameters<typeof MoveDialog>[0]['target']>(null);
const [share, setShare] = useState<{ kind: ShareKind; id: string; title: string } | null>(null);
const [importOpen, setImportOpen] = useState(false);
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
const [editClass, setEditClass] = useState(false);
const [pasteOpen, setPasteOpen] = useState(false);
const [uploads, setUploads] = useState<Uploading[]>([]);
const [dragging, setDragging] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const dragDepth = useRef(0);
useEffect(() => {
setPolling(Boolean(data?.items.some((i) => i.kind === 'document' && (i.status === 'pending' || i.status === 'processing'))));
}, [data]);
useEffect(() => {
setFilter('all');
setQuery('');
}, [classId]);
const upload = async (files: File[]) => {
for (const file of files) {
const id = Date.now() + Math.random();
setUploads((u) => [...u, { id, name: file.name, progress: 0 }]);
const form = new FormData();
form.append('classId', classId);
form.append('file', file);
try {
await uploadWithProgress('/api/documents', form, (p) => setUploads((u) => u.map((x) => (x.id === id ? { ...x, progress: p } : x))));
setUploads((u) => u.filter((x) => x.id !== id));
await refresh();
} catch (e) {
setUploads((u) => u.map((x) => (x.id === id ? { ...x, error: errorMessage(e) } : x)));
}
}
};
const counts = useMemo(() => {
const c = { all: 0, quiz: 0, deck: 0, document: 0, note: 0 };
for (const i of data?.items ?? []) {
c.all += 1;
c[i.kind] += 1;
}
return c;
}, [data]);
const visible = useMemo(() => {
const needle = query.trim().toLowerCase();
const list = (data?.items ?? []).filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
return list.sort((a, b) => (sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : b.updatedAt - a.updatedAt));
}, [data, filter, query, sort]);
if (q.isError) return <ErrorState title="Class not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!data) {
return (
<div className="space-y-4">
<Skeleton className="h-10 w-72" />
<Skeleton className="h-11 w-full" />
{[0, 1, 2, 3].map((i) => (
<Skeleton key={i} className="h-16" />
))}
</div>
);
}
const cls = data.class;
const remove = async (item: Item) => {
const noun = item.kind === 'deck' ? 'deck' : item.kind;
const extra = item.kind === 'quiz' ? ' Its attempt history stays in your statistics.' : item.kind === 'deck' ? ' Review progress for its cards will be lost.' : item.kind === 'document' ? ' The uploaded file is removed from the server.' : '';
if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${item.title}" will be permanently deleted.${extra}`, confirmLabel: 'Delete', danger: true }))) return;
try {
await api.del(`/api/${ITEM_URL[item.kind]}/${item.id}`);
await refresh();
toast.success('Deleted');
} catch (e) {
toast.error(errorMessage(e));
}
};
const duplicate = async (item: Item) => {
try {
await api.post(`/api/${ITEM_URL[item.kind]}/${item.id}/duplicate`, {});
await refresh();
toast.success('Duplicated');
} catch (e) {
toast.error(errorMessage(e));
}
};
const removeFolder = async (f: Folder) => {
if (!(await confirm({ title: 'Delete this folder?', message: `"${f.name}" will be removed. Everything inside it stays in the class.`, confirmLabel: 'Delete folder', danger: true }))) return;
await api.del(`/api/folders/${f.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const deleteClass = async () => {
if (!(await confirm({ title: `Delete ${cls.name}?`, message: `This permanently deletes the class and everything in it: ${plural(counts.quiz, 'quiz', 'quizzes')}, ${plural(counts.deck, 'deck')}, ${plural(counts.document, 'document')} and ${plural(counts.note, 'note')}. Export it first if you might want it back.`, confirmLabel: 'Delete class', danger: true })))
return;
try {
await api.del(`/api/classes/${cls.id}`);
await refresh();
navigate('/');
toast.success('Class deleted');
} catch (e) {
toast.error(errorMessage(e));
}
};
const primaryAction = (item: Item): ReactNode => {
if (item.kind === 'quiz') {
const z = item as QuizItem;
if (z.activeAttemptId)
return (
<Link to={`/session/${z.activeAttemptId}`}>
<Button size="sm" variant="marker" icon={<Play className="fill-current" />}>
Resume
</Button>
</Link>
);
if (z.questionCount > 0)
return (
<Link to={`/quizzes/${z.id}?start=1`}>
<Button size="sm" icon={<Play className="fill-current" />}>
Start
</Button>
</Link>
);
return null;
}
if (item.kind === 'deck') {
const d = item as DeckItem;
if (d.dueCount + Math.min(d.newCount, 20) > 0 && d.cardCount > 0)
return (
<Link to={`/review?deckId=${d.id}`}>
<Button size="sm" variant={d.dueCount > 0 ? 'marker' : 'secondary'} icon={<Play className="fill-current" />}>
{d.dueCount > 0 ? `Review ${d.dueCount}` : 'Learn'}
</Button>
</Link>
);
if (d.cardCount > 0)
return (
<Link to={`/decks/${d.id}/cram`}>
<Button size="sm">Browse</Button>
</Link>
);
}
return null;
};
const row = (item: Item) => {
const doc = item.kind === 'document' ? (item as DocumentItem) : null;
const busy = doc && (doc.status === 'pending' || doc.status === 'processing');
return (
<li key={`${item.kind}:${item.id}`} className="group relative flex items-center gap-3 px-3 py-2.5 hover:bg-ink/[0.035] sm:px-4">
<KindIcon item={item} />
<div className="min-w-0 flex-1">
<Link to={`/${ITEM_URL[item.kind]}/${item.id}`} className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0">
{item.title}
</Link>
<div className="mt-0.5 flex items-center gap-x-2.5 overflow-hidden text-xs whitespace-nowrap text-ink-3">
{busy ? (
<>
<span>{doc.status === 'pending' ? 'Waiting to be read' : 'Reading…'}</span>
<ProgressBar value={doc.progress} className="w-24" />
</>
) : doc?.status === 'failed' ? (
<span className="flex items-center gap-1 truncate text-bad">
<TriangleAlert className="size-3.5 shrink-0" />
<span className="truncate">{doc.error || 'Could not be read'}</span>
</span>
) : (
itemMeta(item)
)}
{doc?.needsOcr && doc.status === 'ready' && <Badge tone="warn">Needs AI reading</Badge>}
{item.shared && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
</div>
<div className="relative z-10 flex shrink-0 items-center gap-1">
<span className="hidden sm:block">{primaryAction(item)}</span>
<Menu
trigger={
<IconButton label={`Actions for ${item.title}`} size="sm" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
{item.kind === 'quiz' && (item as QuizItem).questionCount > 0 && (
<>
<MenuItem icon={<Play />} onSelect={() => start({ source: { type: 'quiz', quizId: item.id } })}>
Quick practice
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', quizId: item.id, sourceLabel: item.title })}>
Make flashcards from this
</MenuItem>
</>
)}
{item.kind === 'deck' && (item as DeckItem).cardCount > 0 && (
<>
<MenuItem icon={<Layers />} onSelect={() => navigate(`/decks/${item.id}/cram`)}>
Browse all cards
</MenuItem>
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', deckId: item.id, sourceLabel: item.title })}>
Make a quiz from this
</MenuItem>
</>
)}
{item.kind === 'document' && doc?.status === 'ready' && (
<>
<MenuItem icon={<Sparkles />} onSelect={() => setGenerate({ documentIds: [item.id] })}>
Generate from this
</MenuItem>
<MenuItem icon={<Sparkles />} onSelect={() => assistant.open({ documentIds: [item.id], classId, newChat: true })}>
Ask about this
</MenuItem>
</>
)}
{item.kind === 'note' && (
<MenuItem icon={<Sparkles />} onSelect={() => setGenerate({ noteId: item.id, sourceLabel: item.title })}>
Generate from this
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Pencil />} onSelect={() => setRename({ kind: item.kind as EditableKind, id: item.id, title: item.title, description: item.kind === 'quiz' || item.kind === 'deck' ? item.description : undefined })}>
Rename
</MenuItem>
<MenuItem icon={<FolderInput />} onSelect={() => setMove({ kind: item.kind as EditableKind, id: item.id, title: item.title, classId, folderId: item.folderId })}>
Move
</MenuItem>
{(item.kind === 'quiz' || item.kind === 'deck') && (
<MenuItem icon={<Copy />} onSelect={() => duplicate(item)}>
Duplicate
</MenuItem>
)}
<MenuItem icon={<Share2 />} onSelect={() => setShare({ kind: item.kind, id: item.id, title: item.title })}>
Share
</MenuItem>
{(item.kind === 'quiz' || item.kind === 'deck') && (
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/${ITEM_URL[item.kind]}/${item.id}/export`)}>
Export JSON
</MenuItem>
)}
{item.kind === 'document' && (
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/documents/${item.id}/file?download=1`)}>
Download original
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => remove(item)}>
Delete
</MenuItem>
</Menu>
</div>
</li>
);
};
const loose = visible.filter((i) => !i.folderId || !data.folders.some((f) => f.id === i.folderId));
const searching = query.trim().length > 0 || filter !== 'all';
const isEmpty = data.items.length === 0 && uploads.length === 0;
const addMenu = (
<Menu
trigger={
<Button variant="primary" icon={<Plus />}>
Add
</Button>
}
>
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz' })}>
New quiz
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck' })}>
New flashcard deck
</MenuItem>
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note' })}>
New note
</MenuItem>
<MenuItem icon={<FolderPlus />} onSelect={() => setNewKind({ kind: 'folder' })}>
New folder
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Upload />} onSelect={() => fileRef.current?.click()}>
Upload documents
</MenuItem>
<MenuItem icon={<FileText />} onSelect={() => setPasteOpen(true)}>
Paste text as a document
</MenuItem>
<MenuItem icon={<FileUp />} onSelect={() => setImportOpen(true)}>
Import quizzes or cards
</MenuItem>
</Menu>
);
return (
<div
className={cx('animate-in', `tab-${cls.color}`)}
onDragEnter={(e) => {
if (!e.dataTransfer.types.includes('Files')) return;
dragDepth.current += 1;
setDragging(true);
}}
onDragLeave={() => {
dragDepth.current = Math.max(0, dragDepth.current - 1);
if (dragDepth.current === 0) setDragging(false);
}}
onDragOver={(e) => e.dataTransfer.types.includes('Files') && e.preventDefault()}
onDrop={(e) => {
if (!e.dataTransfer.files.length) return;
e.preventDefault();
dragDepth.current = 0;
setDragging(false);
void upload([...e.dataTransfer.files]);
}}
>
<input ref={fileRef} type="file" multiple hidden accept=".pdf,.docx,.pptx,.txt,.md,.markdown,.csv,.png,.jpg,.jpeg,.webp,.gif" onChange={(e) => (e.target.files && upload([...e.target.files]), (e.target.value = ''))} />
<header className="mb-6">
<div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
<div className="min-w-0 border-l-[5px] border-tab pl-4">
<div className="eyebrow mb-1 flex items-center gap-2">
{cls.code || 'Class'}
{cls.archived && <Badge>Archived</Badge>}
{data.share?.enabled && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
<h1 className="display text-[30px] sm:text-[38px]">{cls.name}</h1>
{cls.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{cls.description}</p>}
</div>
<div className="flex flex-wrap items-center gap-2">
{data.due.total > 0 && (
<Link to={`/review?classId=${cls.id}`}>
<Button variant="marker" icon={<Play className="fill-current" />}>
Review {data.due.total}
</Button>
</Link>
)}
<Button icon={<Sparkles />} onClick={() => setGenerate({})}>
Generate
</Button>
{addMenu}
<Menu
trigger={
<IconButton label="Class options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<Pencil />} onSelect={() => setEditClass(true)}>
Edit class
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare({ kind: 'class', id: cls.id, title: cls.name })}>
Share whole class
</MenuItem>
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/export/class/${cls.id}`)}>
Export class (JSON)
</MenuItem>
<MenuItem
icon={<Archive />}
onSelect={async () => {
await api.patch(`/api/classes/${cls.id}`, { archived: !cls.archived }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
>
{cls.archived ? 'Unarchive' : 'Archive'}
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={deleteClass}>
Delete class
</MenuItem>
</Menu>
</div>
</div>
</header>
{isEmpty ? (
<div className="card border-dashed">
<EmptyState
icon={<Upload />}
title="Fill this class with material"
action={
<>
<Button variant="primary" icon={<Upload />} onClick={() => fileRef.current?.click()}>
Upload documents
</Button>
<Button icon={<FileUp />} onClick={() => setImportOpen(true)}>
Import
</Button>
<Button icon={<BookOpen />} onClick={() => setNewKind({ kind: 'quiz' })}>
New quiz
</Button>
<Button icon={<Layers />} onClick={() => setNewKind({ kind: 'deck' })}>
New deck
</Button>
</>
}
>
Drop lecture slides, PDFs or notes anywhere on this page, import existing quizzes and flashcards, or write your own.
</EmptyState>
</div>
) : (
<>
<div className="mb-4 flex flex-wrap items-center gap-2">
<div className="-mx-1 flex max-w-full gap-1 overflow-x-auto px-1 pb-1">
{(
[
['all', 'All'],
['quiz', 'Quizzes'],
['deck', 'Flashcards'],
['document', 'Documents'],
['note', 'Notes'],
] as const
).map(([v, label]) => (
<button
key={v}
type="button"
aria-pressed={filter === v}
onClick={() => setFilter(v)}
className={cx('flex h-9 shrink-0 items-center gap-1.5 rounded-full border px-3.5 text-sm font-medium transition-colors', filter === v ? 'border-ink bg-ink text-paper' : 'border-line-strong bg-surface text-ink-2 hover:border-ink-3 hover:text-ink')}
>
{label}
<span className={cx('num text-xs', filter === v ? 'text-paper/65' : 'text-ink-3')}>{counts[v]}</span>
</button>
))}
</div>
<div className="ml-auto flex items-center gap-1.5">
<div className="relative">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter" aria-label="Filter this class" className="h-9 w-36 pl-8 sm:w-48" />
</div>
<Segmented
size="sm"
label="Sort"
value={sort}
onChange={setSort}
options={[
{ value: 'recent', label: <span className="sr-only">Recent</span>, icon: <Clock /> },
{ value: 'title', label: <span className="sr-only">A to Z</span>, icon: <ArrowDownAZ /> },
]}
/>
</div>
</div>
{uploads.length > 0 && (
<ul className="card mb-4 divide-y divide-line">
{uploads.map((u) => (
<li key={u.id} className="flex items-center gap-3 px-4 py-2.5">
<Upload className={cx('size-4 shrink-0', u.error ? 'text-bad' : 'text-ink-3')} />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">{u.name}</div>
{u.error ? <div className="text-[13px] text-bad">{u.error}</div> : <ProgressBar value={u.progress} className="mt-1.5" label={`Uploading ${u.name}`} />}
</div>
{u.error && (
<IconButton label="Dismiss" size="sm" onClick={() => setUploads((x) => x.filter((y) => y.id !== u.id))}>
<X />
</IconButton>
)}
</li>
))}
</ul>
)}
{visible.length === 0 ? (
<div className="card">
<EmptyState title={searching ? 'Nothing matches' : 'Nothing here yet'} icon={<Search />}>
{query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'}
</EmptyState>
</div>
) : (
<div className="space-y-4">
{loose.length > 0 && <ul className="card divide-y divide-line overflow-hidden">{loose.map(row)}</ul>}
{data.folders.map((f) => {
const items = visible.filter((i) => i.folderId === f.id);
if (items.length === 0 && searching) return null;
const isCollapsed = collapsed[f.id] && !searching;
return (
<section key={f.id} aria-label={f.name}>
<div className="mb-1.5 flex items-center gap-1">
<button type="button" aria-expanded={!isCollapsed} onClick={() => setCollapsed((c) => ({ ...c, [f.id]: !c[f.id] }))} className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-lg px-1.5 text-left hover:bg-ink/5">
<ChevronDown className={cx('size-4 shrink-0 text-ink-3 transition-transform', isCollapsed && '-rotate-90')} />
<FolderIcon className="size-4 shrink-0 text-tab" />
<span className="truncate text-sm font-semibold">{f.name}</span>
<span className="num text-xs text-ink-3">{items.length}</span>
{f.shared && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</button>
<Menu
trigger={
<IconButton label={`Folder options for ${f.name}`} size="sm" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz', folderId: f.id })}>
New quiz here
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck', folderId: f.id })}>
New deck here
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Pencil />} onSelect={() => setRename({ kind: 'folder', id: f.id, title: f.name })}>
Rename
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare({ kind: 'folder', id: f.id, title: f.name })}>
Share folder
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => removeFolder(f)}>
Delete folder
</MenuItem>
</Menu>
</div>
{!isCollapsed &&
(items.length > 0 ? (
<ul className="card divide-y divide-line overflow-hidden">{items.map(row)}</ul>
) : (
<div className="rounded-[14px] border border-dashed border-line-strong px-4 py-4 text-[13px] text-ink-3">Empty. Use "Move" on any item to put it here.</div>
))}
</section>
);
})}
</div>
)}
</>
)}
{dragging && (
<div className="pointer-events-none fixed inset-0 z-40 grid place-items-center bg-paper/85 backdrop-blur-sm">
<div className="rounded-3xl border-2 border-dashed border-accent bg-surface px-12 py-10 text-center shadow-3">
<Upload className="mx-auto mb-3 size-9 text-accent" />
<div className="display text-2xl">Drop to add to {cls.name}</div>
<div className="mt-1 text-sm text-ink-2">PDF, Word, PowerPoint, text, Markdown and images</div>
</div>
</div>
)}
<NewItemDialog kind={newKind?.kind ?? null} classId={classId} folderId={newKind?.folderId} onClose={() => setNewKind(null)} />
<RenameDialog target={rename} onClose={() => setRename(null)} />
<MoveDialog target={move} onClose={() => setMove(null)} />
<ShareDialog target={share} onClose={() => setShare(null)} />
<ImportDialog open={importOpen} onClose={() => setImportOpen(false)} classId={classId} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} preset={generate ?? undefined} />
<ClassDialog open={editClass} onOpenChange={setEditClass} existing={cls} />
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} />
</div>
);
}
function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: () => void; classId: string }) {
const refresh = useRefresh();
const [title, setTitle] = useState('');
const [text, setText] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (open) {
setTitle('');
setText('');
}
}, [open]);
const save = async () => {
setBusy(true);
try {
await api.post('/api/documents/text', { classId, title, text });
await refresh();
toast.success('Added as a document');
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Paste text as a document"
description="Pasted notes become a searchable document that AI can read and cite."
size="lg"
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!title.trim() || text.trim().length < 2} onClick={save}>
Add document
</Button>
</>
}
>
<div className="space-y-4">
<Field label="Title">
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Week 4 lecture notes" maxLength={200} />
</Field>
<Field label="Text" hint="Markdown headings (#, ##) are used as section titles.">
<Textarea rows={12} value={text} onChange={(e) => setText(e.target.value)} />
</Field>
</div>
</Dialog>
);
}

View file

@ -0,0 +1,69 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { Explain } from '@/features/Explain';
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
import { api, errorMessage } from '@/lib/api';
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
import { useDocumentTitle } from '@/lib/util';
import { Button, EmptyState, ErrorState, PageLoading } from '@/ui';
/** Browse every card in a deck, self-graded. Does not affect the spaced-repetition schedule. */
export default function CramPage() {
const { deckId = '' } = useParams();
const navigate = useNavigate();
const refresh = useRefresh();
const ai = useAiStatus();
const q = useDeck(deckId);
const data = q.data;
useDocumentTitle(data ? `Browse · ${data.deck.title}` : undefined);
const [state, setState] = useState<CramState | null>(null);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const latest = useRef<CramState | null>(null);
useEffect(() => {
if (!data || state) return;
setState(reconcileCramState(data.session?.state as CramState | null, data.cards) ?? freshCramState(data.cards, false));
}, [data, state]);
const persist = (next: CramState) => {
setState(next);
latest.current = next;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => {
void api.put(`/api/decks/${deckId}/session`, { state: next }).catch(() => undefined);
}, 600);
};
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
if (latest.current) void api.put(`/api/decks/${deckId}/session`, { state: latest.current }).catch(() => undefined);
},
[deckId],
);
if (q.isError) return <ErrorState title="Deck not found" message={errorMessage(q.error)} className="pt-24" />;
if (!data || !state) return <PageLoading />;
const exit = () => {
void refresh();
navigate(`/decks/${deckId}`);
};
if (data.cards.length === 0) {
return (
<div className="pt-24">
<EmptyState title="This deck has no cards yet" action={<Button onClick={exit}>Back to deck</Button>} />
</div>
);
}
return (
<CramSession
title={data.deck.title}
cards={data.cards}
state={state}
onState={persist}
onExit={exit}
exitLabel="Save and exit"
onGrade={(cardId, known) => void api.post('/api/review/cram', { cardId, known }).catch(() => undefined)}
renderExtra={ai.data?.ready ? (card) => <Explain body={{ kind: 'card', front: card.front, back: card.back }} /> : undefined}
/>
);
}

354
web/src/pages/DeckPage.tsx Normal file
View file

@ -0,0 +1,354 @@
import { BookOpen, ChevronRight, Copy, Download, Eye, EyeOff, FolderInput, Layers, ListPlus, MoreHorizontal, Pencil, Play, Plus, RotateCcw, Search, Share2, Stamp, Trash2 } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { blankCard, type Card, type DraftCard } from '@shared/content';
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
import { CardEditor } from '@/features/editors';
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { api, errorMessage } from '@/lib/api';
import { useAssistantContext } from '@/lib/assistantStore';
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
import { cx, downloadFile, plural, useDocumentTitle } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Tooltip, useConfirm } from '@/ui';
import { BulkAddDialog } from './QuizPage';
function dueLabel(card: Card): { text: string; tone: 'neutral' | 'accent' | 'good' | 'warn' } {
if (card.suspended) return { text: 'Suspended', tone: 'neutral' };
if (card.state === 0) return { text: 'New', tone: 'accent' };
if (card.state === 1 || card.state === 3) return { text: 'Learning', tone: 'warn' };
const days = card.due ? Math.ceil((card.due - Date.now()) / 86_400_000) : 0;
if (days <= 0) return { text: 'Due', tone: 'warn' };
return { text: days === 1 ? 'Tomorrow' : days < 31 ? `${days} days` : days < 365 ? `${Math.round(days / 30)} mo` : `${(days / 365).toFixed(1)} y`, tone: 'good' };
}
export default function DeckPage() {
const { deckId = '' } = useParams();
const [params, setParams] = useSearchParams();
const navigate = useNavigate();
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const q = useDeck(deckId);
const data = q.data;
useDocumentTitle(data?.deck.title);
useAssistantContext(data?.deck.classId, data?.deck.title);
const [editing, setEditing] = useState<string | null>(null);
const [draft, setDraft] = useState<DraftCard>(blankCard());
const [fresh, setFresh] = useState<DraftCard>(blankCard());
const [adding, setAdding] = useState(false);
const [filter, setFilter] = useState('');
const [bulkOpen, setBulkOpen] = useState(false);
const [rename, setRename] = useState(false);
const [move, setMove] = useState(false);
const [share, setShare] = useState(false);
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
const addRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!data) return;
if (params.get('edit')) {
setTimeout(() => addRef.current?.querySelector('textarea')?.focus(), 80);
const next = new URLSearchParams(params);
next.delete('edit');
setParams(next, { replace: true });
}
const target = params.get('card');
if (target) setTimeout(() => document.getElementById(`card-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data?.deck.id]);
const shown = useMemo(() => {
const needle = filter.trim().toLowerCase();
return (data?.cards ?? []).filter((c) => !needle || c.front.toLowerCase().includes(needle) || c.back.toLowerCase().includes(needle));
}, [data, filter]);
if (q.isError) return <ErrorState title="Deck not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!data) {
return (
<div className="space-y-4">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-10 w-96 max-w-full" />
<Skeleton className="h-20" />
<Skeleton className="h-64" />
</div>
);
}
const { deck, cards, stats, due } = data;
const act = async (fn: () => Promise<unknown>, ok?: string) => {
try {
await fn();
await refresh();
if (ok) toast.success(ok);
} catch (e) {
toast.error(errorMessage(e));
}
};
const addCard = async () => {
if (!fresh.front.trim() || !fresh.back.trim()) return;
setAdding(true);
await act(() => api.post(`/api/decks/${deck.id}/cards`, { cards: [fresh] }));
setFresh(blankCard());
setAdding(false);
setTimeout(() => addRef.current?.querySelector('textarea')?.focus(), 40);
};
const saveEdit = async () => {
if (!editing || !draft.front.trim() || !draft.back.trim()) return;
await act(() => api.patch(`/api/cards/${editing}`, draft));
setEditing(null);
};
const deleteDeck = async () => {
if (!(await confirm({ title: 'Delete this deck?', message: `"${deck.title}", its ${plural(cards.length, 'card')} and their review progress will be permanently deleted.`, confirmLabel: 'Delete deck', danger: true }))) return;
try {
await api.del(`/api/decks/${deck.id}`);
await refresh();
navigate(`/classes/${deck.classId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
const resetDeck = async () => {
if (!(await confirm({ title: 'Reset review progress?', message: 'Every card in this deck goes back to "new" and its schedule is cleared. The cards themselves are kept.', confirmLabel: 'Reset progress', danger: true }))) return;
await act(() => api.post(`/api/decks/${deck.id}/reset`), 'Progress reset');
};
const active = Math.max(1, stats.total - stats.suspended);
const segments = [
{ label: 'New', n: stats.new, cls: 'bg-accent' },
{ label: 'Learning', n: stats.learning, cls: 'bg-warn' },
{ label: 'Young', n: stats.young, cls: 'bg-good/55' },
{ label: 'Mature', n: stats.mature, cls: 'bg-good' },
];
const canStudy = due.total > 0;
return (
<div className={cx('animate-in', `tab-${data.class.color}`)}>
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
<Link to={`/classes/${data.class.id}`} className="flex items-center gap-1.5 hover:text-ink">
<ClassDot color={data.class.color} />
{data.class.name}
</Link>
<ChevronRight className="size-3.5" />
<span>Flashcards</span>
</nav>
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
<div className="min-w-0">
<h1 className="display text-[30px] sm:text-[36px]">{deck.title}</h1>
{deck.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{deck.description}</p>}
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-ink-2">
<span>{plural(stats.total, 'card')}</span>
{due.total > 0 && (
<span>
<strong className="marker num text-ink">{due.total}</strong> to study now
</span>
)}
{data.share?.enabled && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<Link to={`/review?deckId=${deck.id}`} aria-disabled={!canStudy} className={cx(!canStudy && 'pointer-events-none')}>
<Button variant={canStudy ? 'primary' : 'secondary'} size="lg" icon={<Play className="fill-current" />} disabled={!canStudy}>
{canStudy ? `Review ${due.total}` : 'Nothing due'}
</Button>
</Link>
<Link to={`/decks/${deck.id}/cram`} className={cx(cards.length === 0 && 'pointer-events-none')}>
<Button size="lg" icon={<Layers />} disabled={cards.length === 0}>
{data.session ? 'Continue browsing' : 'Browse all'}
</Button>
</Link>
<Menu
trigger={
<IconButton label="Deck options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
{ai.data?.ready && cards.length > 0 && (
<>
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', deckId: deck.id, sourceLabel: deck.title })}>
Make a quiz from this
</MenuItem>
<MenuSeparator />
</>
)}
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
Rename
</MenuItem>
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
Move
</MenuItem>
<MenuItem
icon={<Copy />}
onSelect={async () => {
const res = await api.post<{ deck: { id: string } }>(`/api/decks/${deck.id}/duplicate`, {}).catch((e) => (toast.error(errorMessage(e)), null));
if (res) {
await refresh();
navigate(`/decks/${res.deck.id}`);
toast.success('Duplicated');
}
}}
>
Duplicate
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
Share
</MenuItem>
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/decks/${deck.id}/export`)}>
Export JSON
</MenuItem>
<MenuItem icon={<Stamp />} onSelect={() => act(() => api.post('/api/templates/from', { kind: 'deck', id: deck.id }), 'Saved as a template')}>
Save as template
</MenuItem>
<MenuSeparator />
<MenuItem icon={<RotateCcw />} onSelect={resetDeck}>
Reset review progress
</MenuItem>
<MenuItem icon={<Trash2 />} danger onSelect={deleteDeck}>
Delete deck
</MenuItem>
</Menu>
</div>
</header>
{stats.total > 0 && (
<div className="card mb-6 p-4">
<div className="flex h-2.5 overflow-hidden rounded-full bg-ink/8" role="img" aria-label={segments.map((s) => `${s.n} ${s.label.toLowerCase()}`).join(', ')}>
{segments.map((s) => (s.n > 0 ? <div key={s.label} className={s.cls} style={{ width: `${(s.n / active) * 100}%` }} /> : null))}
</div>
<div className="mt-3 flex flex-wrap gap-x-5 gap-y-1.5 text-[13px]">
{segments.map((s) => (
<span key={s.label} className="flex items-center gap-1.5 text-ink-2">
<span className={cx('size-2.5 rounded-[3px]', s.cls)} />
{s.label} <span className="num font-semibold text-ink">{s.n}</span>
</span>
))}
{stats.suspended > 0 && (
<span className="flex items-center gap-1.5 text-ink-3">
<EyeOff className="size-3.5" /> Suspended <span className="num font-semibold">{stats.suspended}</span>
</span>
)}
<Tooltip label="Mature cards have an interval of 21 days or more. New cards are introduced a few per day (set the limit in Settings).">
<button type="button" className="ml-auto text-xs text-ink-3 underline decoration-dotted underline-offset-2">
What do these mean?
</button>
</Tooltip>
</div>
</div>
)}
<div className="mb-3 flex items-center justify-between gap-2">
<h2 className="eyebrow">Cards</h2>
<div className="flex items-center gap-2">
{cards.length > 6 && (
<div className="relative">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Find a card" aria-label="Find a card" className="h-9 w-40 pl-8 sm:w-56" />
</div>
)}
<Button size="sm" variant="ghost" icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
Paste several
</Button>
</div>
</div>
{cards.length === 0 ? (
<div className="card mb-3 border-dashed">
<EmptyState icon={<Layers />} title="No cards yet">
Add your first card below, paste a list, or generate cards from your class documents.
</EmptyState>
</div>
) : (
<ul className="card mb-3 divide-y divide-line overflow-hidden">
{shown.map((card) => {
const label = dueLabel(card);
return (
<li key={card.id} id={`card-${card.id}`} className={cx('scroll-mt-24', params.get('card') === card.id && 'bg-marker/20')}>
{editing === card.id ? (
<div className="p-4">
<CardEditor value={draft} onChange={setDraft} autoFocus onSubmit={saveEdit} />
<div className="mt-4 flex justify-end gap-2">
<Button variant="ghost" onClick={() => setEditing(null)}>
Cancel
</Button>
<Button variant="primary" disabled={!draft.front.trim() || !draft.back.trim()} onClick={saveEdit}>
Save
</Button>
</div>
</div>
) : (
<div className={cx('flex items-start gap-3 px-4 py-3', card.suspended && 'opacity-55')}>
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-1 sm:grid-cols-2">
<Markdown className="max-h-28 overflow-hidden text-[14.5px] font-medium">{card.front}</Markdown>
<Markdown className="max-h-28 overflow-hidden text-[14.5px] text-ink-2">{card.back}</Markdown>
</div>
<Badge tone={label.tone} className="mt-0.5 hidden sm:inline-flex">
{label.text}
</Badge>
<div className="flex shrink-0">
<IconButton
label="Edit card"
size="sm"
onClick={() => {
setDraft({ front: card.front, back: card.back, hint: card.hint, tags: card.tags });
setEditing(card.id);
}}
>
<Pencil />
</IconButton>
<Menu
trigger={
<IconButton label="Card options" size="sm" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={card.suspended ? <Eye /> : <EyeOff />} onSelect={() => act(() => api.patch(`/api/cards/${card.id}`, { suspended: !card.suspended }))}>
{card.suspended ? 'Unsuspend' : 'Suspend'}
</MenuItem>
<MenuItem icon={<RotateCcw />} disabled={card.state === 0} onSelect={() => act(() => api.patch(`/api/cards/${card.id}`, { reset: true }), 'Card reset to new')}>
Reset progress
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => act(() => api.del(`/api/cards/${card.id}`))}>
Delete
</MenuItem>
</Menu>
</div>
</div>
)}
</li>
);
})}
{shown.length === 0 && <li className="px-4 py-8 text-center text-sm text-ink-3">No cards match "{filter}".</li>}
</ul>
)}
<div ref={addRef} className="card p-4">
<div className="eyebrow mb-3 flex items-center gap-1.5">
<Plus className="size-3.5" /> Add a card
</div>
<CardEditor value={fresh} onChange={setFresh} onSubmit={addCard} />
<div className="mt-4 flex items-center justify-end gap-3">
<span className="hidden text-xs text-ink-3 sm:block">Ctrl+Enter adds the card and starts the next one</span>
<Button variant="primary" icon={<Plus />} loading={adding} disabled={!fresh.front.trim() || !fresh.back.trim()} onClick={addCard}>
Add card
</Button>
</div>
</div>
<BulkAddDialog open={bulkOpen} onClose={() => setBulkOpen(false)} kind="deck" onAdd={(items) => act(() => api.post(`/api/decks/${deck.id}/cards`, { cards: items }), `Added ${plural(items.length, 'card')}`)} />
<RenameDialog target={rename ? { kind: 'deck', id: deck.id, title: deck.title, description: deck.description } : null} onClose={() => setRename(false)} />
<MoveDialog target={move ? { kind: 'deck', id: deck.id, title: deck.title, classId: deck.classId, folderId: deck.folderId } : null} onClose={() => setMove(false)} />
<ShareDialog target={share ? { kind: 'deck', id: deck.id, title: deck.title } : null} onClose={() => setShare(false)} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={deck.classId} folderId={deck.folderId} preset={generate ?? undefined} />
</div>
);
}

View file

@ -0,0 +1,347 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { BookOpen, ChevronRight, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { api, errorMessage } from '@/lib/api';
import { assistant, useAssistantContext } from '@/lib/assistantStore';
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
import type { ClassInfo, DocChunk, DocumentInfo, Share } from '@/lib/types';
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Spinner, useConfirm } from '@/ui';
interface Detail {
document: DocumentInfo;
class: ClassInfo;
outline: { seq: number; heading: string; page: number | null }[];
share: Share | null;
}
interface ChunkPage {
chunks: DocChunk[];
total: number;
offset: number;
nextOffset: number | null;
}
const KIND_LABEL: Record<string, string> = { pdf: 'PDF', docx: 'Word document', pptx: 'PowerPoint', text: 'Text', markdown: 'Markdown', image: 'Image' };
export default function DocumentPage() {
const { docId = '' } = useParams();
const [params] = useSearchParams();
const focusChunk = Number(params.get('chunk')) || null;
const navigate = useNavigate();
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const [view, setView] = useState<'text' | 'original'>('text');
const [rename, setRename] = useState(false);
const [move, setMove] = useState(false);
const [share, setShare] = useState(false);
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
const q = useQuery({
queryKey: qk.document(docId),
queryFn: () => api.get<Detail>(`/api/documents/${docId}`),
refetchInterval: (query) => (['pending', 'processing'].includes(query.state.data?.document.status ?? '') ? 1200 : false),
});
const doc = q.data?.document;
useDocumentTitle(doc?.title);
useAssistantContext(doc?.classId, doc?.title, doc ? [doc.id] : []);
const ready = doc?.status === 'ready';
const chunks = useInfiniteQuery({
queryKey: ['document-chunks', docId, focusChunk, doc?.updatedAt],
queryFn: ({ pageParam }) => api.get<ChunkPage>(`/api/documents/${docId}/chunks?limit=30&${pageParam === null && focusChunk ? `around=${focusChunk}` : `offset=${pageParam ?? 0}`}`),
initialPageParam: null as number | null,
getNextPageParam: (last) => last.nextOffset,
enabled: ready && (doc?.chunkCount ?? 0) > 0,
});
const firstOffset = chunks.data?.pages[0]?.offset ?? 0;
useEffect(() => {
if (focusChunk && chunks.data) setTimeout(() => document.getElementById(`chunk-${focusChunk}`)?.scrollIntoView({ block: 'center' }), 80);
}, [focusChunk, chunks.data?.pages.length]); // eslint-disable-line react-hooks/exhaustive-deps
if (q.isError) return <ErrorState title="Document not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!q.data || !doc) {
return (
<div className="space-y-4">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-10 w-96 max-w-full" />
<Skeleton className="h-96" />
</div>
);
}
const cls = q.data.class;
const busy = doc.status === 'pending' || doc.status === 'processing';
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image';
const fileUrl = `/api/documents/${doc.id}/file`;
const reprocess = async (ocr: boolean) => {
try {
await api.post(`/api/documents/${doc.id}/reprocess`, { ocr });
await refresh();
} catch (e) {
toast.error(errorMessage(e));
}
};
const remove = async () => {
if (!(await confirm({ title: 'Delete this document?', message: `"${doc.title}" and its uploaded file will be permanently deleted. Quizzes and cards already generated from it are kept.`, confirmLabel: 'Delete', danger: true }))) return;
try {
await api.del(`/api/documents/${doc.id}`);
await refresh();
navigate(`/classes/${doc.classId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
const all = chunks.data?.pages.flatMap((p) => p.chunks) ?? [];
return (
<div className={cx('animate-in', `tab-${cls.color}`)}>
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
<Link to={`/classes/${cls.id}`} className="flex items-center gap-1.5 hover:text-ink">
<ClassDot color={cls.color} />
{cls.name}
</Link>
<ChevronRight className="size-3.5" />
<span>Document</span>
</nav>
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
<div className="min-w-0">
<h1 className="display text-[28px] sm:text-[34px]">{doc.title}</h1>
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-ink-2">
<span>{KIND_LABEL[doc.docKind]}</span>
{doc.pageCount ? <span>{plural(doc.pageCount, doc.docKind === 'pptx' ? 'slide' : 'page')}</span> : null}
<span>{formatBytes(doc.size)}</span>
{ready && doc.tokenCount > 0 && <span>about {formatTokens(doc.tokenCount)} tokens</span>}
{q.data.share?.enabled && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button variant="primary" icon={<Sparkles />} disabled={!ready || doc.chunkCount === 0} onClick={() => setGenerate({ documentIds: [doc.id] })}>
Generate
</Button>
<Button icon={<MessageSquare />} disabled={!ready || doc.chunkCount === 0} onClick={() => assistant.open({ documentIds: [doc.id], classId: doc.classId, newChat: true })}>
Ask
</Button>
<Menu
trigger={
<IconButton label="Document options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
{ready && doc.chunkCount > 0 && (
<>
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', documentIds: [doc.id] })}>
Quiz from this
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', documentIds: [doc.id] })}>
Flashcards from this
</MenuItem>
<MenuItem icon={<NotebookPen />} onSelect={() => setGenerate({ kind: 'note', documentIds: [doc.id] })}>
Study guide from this
</MenuItem>
<MenuSeparator />
</>
)}
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
Rename
</MenuItem>
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
Move
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
Share
</MenuItem>
<MenuItem icon={<Download />} onSelect={() => downloadFile(`${fileUrl}?download=1`)}>
Download original
</MenuItem>
<MenuItem icon={<RefreshCw />} disabled={busy} onSelect={() => reprocess(false)}>
Read the file again
</MenuItem>
{(doc.docKind === 'pdf' || doc.docKind === 'image') && (
<MenuItem icon={<ScanText />} disabled={busy || !ai.data?.ready} onSelect={() => reprocess(true)}>
Read with AI vision
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
Delete
</MenuItem>
</Menu>
</div>
</header>
{busy && (
<Callout tone="accent" icon={<Spinner className="size-[18px] text-accent" />} title={doc.status === 'pending' ? 'Waiting to be read' : 'Reading the file'} className="mb-5">
Text is being extracted and indexed for search and AI. This page updates on its own.
<ProgressBar value={doc.progress} className="mt-2.5 max-w-sm" label="Processing" />
</Callout>
)}
{doc.status === 'failed' && (
<Callout
tone="bad"
icon={<TriangleAlert />}
title="This file could not be read"
className="mb-5"
action={
<Button size="sm" onClick={() => reprocess(false)}>
Try again
</Button>
}
>
{doc.error}
</Callout>
)}
{ready && doc.needsOcr && (
<Callout
tone="warn"
icon={<ScanText />}
title={doc.docKind === 'image' ? 'This image has not been read yet' : 'No selectable text was found'}
className="mb-5"
action={
ai.data?.ready ? (
<Button size="sm" variant="primary" onClick={() => reprocess(true)}>
Read with AI
</Button>
) : (
<Link to="/settings/ai">
<Button size="sm">Set up AI</Button>
</Link>
)
}
>
{doc.docKind === 'image' ? 'An AI model with vision can transcribe it so it becomes searchable and usable for generation.' : 'It looks like a scan. An AI model with vision and PDF support can transcribe it.'}
</Callout>
)}
{ready &&
doc.warnings
.filter((w) => !(doc.needsOcr && /AI model/.test(w)))
.map((w, i) => (
<Callout key={i} tone="warn" icon={<TriangleAlert />} className="mb-3 py-2.5">
{w}
</Callout>
))}
{hasOriginal && (
<div className="mb-4">
<Segmented
label="View"
value={view}
onChange={setView}
options={[
{ value: 'text', label: 'Extracted text', icon: <FileText /> },
{ value: 'original', label: 'Original', icon: <ScanText /> },
]}
/>
</div>
)}
{view === 'original' && hasOriginal ? (
doc.docKind === 'image' ? (
<div className="card grid place-items-center p-4">
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
</div>
) : (
<iframe src={fileUrl} title={doc.title} className="card h-[82vh] w-full" />
)
) : !ready ? null : doc.chunkCount === 0 ? (
<div className="card">
<EmptyState icon={<FileText />} title="No text to show">
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
</EmptyState>
</div>
) : (
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
<div className="min-w-0">
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
<article className="card divide-y divide-line">
{chunks.isLoading && (
<div className="space-y-3 p-6">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4" />
<Skeleton className="h-4 w-5/6" />
</div>
)}
{all.map((ch, i) => {
const prev = all[i - 1];
const showHeading = ch.heading && ch.heading !== prev?.heading;
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
return (
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
{(showHeading || showPage) && (
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
{showPage && (
<span className="num text-[11px] text-ink-3">
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
</span>
)}
</div>
)}
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
</section>
);
})}
</article>
{chunks.hasNextPage && (
<div className="mt-4 flex justify-center">
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
Show more
</Button>
</div>
)}
</div>
{q.data.outline.length > 1 && (
<aside className="hidden lg:block">
<div className="sticky top-8">
<div className="eyebrow mb-2">Outline</div>
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
{q.data.outline.map((o) => (
<li key={o.seq}>
<button
type="button"
onClick={async () => {
// Load forward until the section is on the page, then scroll to it.
let pages = chunks.data?.pages ?? [];
let guard = 0;
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
const res = await chunks.fetchNextPage();
pages = res.data?.pages ?? [];
guard += 1;
}
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
}}
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
title={o.heading}
>
{o.heading}
</button>
</li>
))}
</ul>
</div>
</aside>
)}
</div>
)}
<RenameDialog target={rename ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setRename(false)} />
<MoveDialog target={move ? { kind: 'document', id: doc.id, title: doc.title, classId: doc.classId, folderId: doc.folderId } : null} onClose={() => setMove(false)} />
<ShareDialog target={share ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setShare(false)} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={doc.classId} folderId={doc.folderId} preset={generate ?? undefined} />
</div>
);
}

514
web/src/pages/DraftPage.tsx Normal file
View file

@ -0,0 +1,514 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { BookOpen, Check, ChevronRight, CircleAlert, Eye, FileText, Layers, NotebookPen, Pencil, Plus, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { toast } from 'sonner';
import { blankCard, blankQuestion, optionLetter, QUESTION_TYPE_LABEL, validateDraft, validateDraftCard, validateDraftQuestion, type ContentDraft, type DraftCard, type DraftQuestion } from '@shared/content';
import { CardEditor, QuestionEditor } from '@/features/editors';
import { api, errorMessage } from '@/lib/api';
import { qk, useClass, useClasses, useQuiz, useRefresh } from '@/lib/queries';
import type { Draft } from '@/lib/types';
import { cx, plural, useDocumentTitle } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Callout, EmptyState, ErrorState, Field, IconButton, Input, PageLoading, ProgressBar, Segmented, Select, Textarea, useConfirm } from '@/ui';
const KIND = { quiz: { label: 'Quiz', icon: <BookOpen />, url: 'quizzes' }, deck: { label: 'Flashcards', icon: <Layers />, url: 'decks' }, note: { label: 'Note', icon: <NotebookPen />, url: 'notes' } } as const;
function QuestionPreview({ q }: { q: DraftQuestion }) {
return (
<>
<Markdown serif className="text-[17px]">
{q.stem || '*No question text*'}
</Markdown>
<ul className="mt-3 space-y-1.5">
{q.options.map((o, i) => (
<li key={i} className="flex items-start gap-2.5 text-[15px]">
<span className={cx('num mt-0.5 grid size-6 shrink-0 place-items-center text-xs font-semibold', q.type === 'single' ? 'rounded-full' : 'rounded-md', o.correct ? 'bg-good text-white dark:text-[#10241a]' : 'bg-sunken text-ink-3')}>
{o.correct ? <Check className="size-3.5" strokeWidth={3} /> : optionLetter(i)}
</span>
<div className="min-w-0 flex-1">
<Markdown className={o.correct ? 'font-medium' : 'text-ink-2'}>{o.text || '*empty*'}</Markdown>
{o.why && <div className="mt-0.5 text-[13px] text-ink-3">{o.why}</div>}
</div>
</li>
))}
</ul>
{q.rationale && (
<div className="mt-3 rounded-xl bg-sunken px-4 py-3">
<div className="eyebrow mb-1">Rationale</div>
<Markdown className="text-[14.5px]">{q.rationale}</Markdown>
</div>
)}
{q.source && (
<div className="mt-2 flex items-center gap-1.5 text-xs text-ink-3">
<FileText className="size-3.5" /> {q.source}
</div>
)}
</>
);
}
export default function DraftPage() {
const { draftId = '' } = useParams();
const navigate = useNavigate();
const qc = useQueryClient();
const refresh = useRefresh();
const confirm = useConfirm();
const classes = useClasses();
const query = useQuery({
queryKey: qk.draft(draftId),
queryFn: () => api.get<{ draft: Draft }>(`/api/drafts/${draftId}`).then((r) => r.draft),
refetchInterval: (q) => (q.state.data?.status === 'generating' ? 1000 : false),
refetchOnWindowFocus: false,
staleTime: Infinity,
});
const draft = query.data;
const [payload, setPayload] = useState<ContentDraft | null>(null);
const [classId, setClassId] = useState('');
const [folderId, setFolderId] = useState('');
const [mode, setMode] = useState<'new' | 'append' | 'replace'>('new');
const [targetId, setTargetId] = useState('');
const [editing, setEditing] = useState<number | null>(null);
const [preview, setPreview] = useState(true);
const [saving, setSaving] = useState(false);
const loaded = useRef('');
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const dirty = useRef(false);
const cls = useClass(classId || undefined);
const original = useQuiz(draft?.meta.origin === 'improve' ? draft.meta.targetId : undefined);
useDocumentTitle(draft ? `Review: ${draft.title || 'draft'}` : 'Draft');
// Adopt the server copy once generation has finished.
useEffect(() => {
if (!draft || draft.status === 'generating') return;
const key = `${draft.id}:${draft.status}`;
if (loaded.current === key) return;
loaded.current = key;
setPayload(draft.payload);
setClassId(draft.classId ?? '');
setFolderId(draft.folderId ?? '');
setMode(draft.meta.origin === 'improve' ? 'replace' : 'new');
setTargetId(draft.meta.targetId ?? '');
}, [draft]);
useEffect(() => {
if (!classId && classes.data?.length && draft && draft.status === 'ready') setClassId(classes.data.find((c) => !c.archived)?.id ?? classes.data[0].id);
}, [classId, classes.data, draft]);
const persist = (next: ContentDraft) => {
setPayload(next);
dirty.current = true;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => void flush(next), 900);
};
const flush = async (next: ContentDraft) => {
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = null;
if (!dirty.current) return;
dirty.current = false;
await api.put(`/api/drafts/${draftId}`, { payload: next, classId: classId || null, folderId: folderId || null }).catch(() => {
dirty.current = true;
});
};
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
},
[],
);
const issues = useMemo(() => (payload ? validateDraft(payload) : []), [payload]);
const errors = issues.filter((i) => i.level === 'error');
const badItems = new Set(errors.filter((i) => i.index !== undefined).map((i) => i.index));
const sameKindItems = (cls.data?.items ?? []).filter((i) => i.kind === draft?.kind);
if (query.isError) return <ErrorState title="Draft not found" message={errorMessage(query.error)} />;
if (!draft) return <PageLoading />;
const discard = async (ask = true) => {
if (ask && !(await confirm({ title: 'Discard this draft?', message: 'The generated content will be thrown away.', confirmLabel: 'Discard', danger: true }))) return;
await api.del(`/api/drafts/${draft.id}`).catch(() => undefined);
void refresh();
navigate(draft.classId ? `/classes/${draft.classId}` : '/');
};
/* ---------- generating ---------- */
if (draft.status === 'generating') {
const partial = draft.itemCount;
return (
<div className="mx-auto max-w-xl pt-10 text-center sm:pt-20">
<div className="mx-auto mb-5 grid size-14 animate-pulse place-items-center rounded-2xl bg-accent-soft text-accent">
<Sparkles className="size-7" />
</div>
<h1 className="display text-[30px]">Writing your {draft.kind === 'quiz' ? 'quiz' : draft.kind === 'deck' ? 'flashcards' : 'study guide'}</h1>
<p className="mt-2 text-[15px] text-ink-2" aria-live="polite">
{draft.progressLabel || 'Getting started'}
{draft.meta.model ? ` · ${draft.meta.model}` : ''}
</p>
<ProgressBar value={Math.max(0.04, draft.progress)} className="mx-auto mt-6 h-2 max-w-sm" label="Generation progress" />
{draft.kind !== 'note' && partial > 0 && <p className="mt-3 text-sm text-ink-3">{plural(partial, draft.kind === 'quiz' ? 'question' : 'card')} so far</p>}
<p className="mt-6 text-[13px] text-ink-3">You can leave this page. The draft keeps generating and will be waiting here.</p>
<Button
variant="ghost"
className="mt-4"
onClick={async () => {
await api.post(`/api/drafts/${draft.id}/cancel`).catch(() => undefined);
void query.refetch();
}}
>
Cancel
</Button>
</div>
);
}
/* ---------- failed / gone ---------- */
if (draft.status === 'failed' && draft.itemCount === 0) {
return (
<div className="mx-auto max-w-xl pt-10">
<ErrorState title="Generation did not finish" message={draft.error || 'Something went wrong.'} />
<div className="flex justify-center gap-2">
<Button variant="primary" onClick={() => navigate(draft.classId ? `/classes/${draft.classId}` : '/')}>
Back to class
</Button>
<Button variant="ghost" onClick={() => discard(false)}>
Discard
</Button>
</div>
</div>
);
}
if (draft.status === 'saved' || draft.status === 'discarded') {
return (
<EmptyState
icon={<Check />}
title={draft.status === 'saved' ? 'This draft was saved' : 'This draft was discarded'}
action={
draft.status === 'saved' && draft.savedId && draft.savedKind ? (
<Button variant="primary" onClick={() => navigate(`/${KIND[draft.savedKind as keyof typeof KIND].url}/${draft.savedId}`)}>
Open it
</Button>
) : (
<Button onClick={() => navigate('/')}>Go to Today</Button>
)
}
/>
);
}
if (!payload) return <PageLoading />;
const isImprove = draft.meta.origin === 'improve';
const save = async () => {
if (errors.length > 0) return;
setSaving(true);
try {
dirty.current = true;
await flush(payload);
const res = await api.post<{ saved: { kind: keyof typeof KIND; id: string; count: number } }>(`/api/drafts/${draft.id}/save`, {
classId: classId || undefined,
folderId: folderId || null,
mode,
targetId: mode === 'new' ? undefined : targetId || undefined,
});
await refresh();
qc.removeQueries({ queryKey: qk.draft(draft.id) });
toast.success(mode === 'replace' ? 'Revisions applied' : mode === 'append' ? 'Added' : 'Saved to your library');
navigate(`/${KIND[res.saved.kind].url}/${res.saved.id}`, { replace: true });
} catch (e) {
toast.error(errorMessage(e));
} finally {
setSaving(false);
}
};
const setQuestions = (questions: DraftQuestion[]) => payload.kind === 'quiz' && persist({ ...payload, questions });
const setCards = (cards: DraftCard[]) => payload.kind === 'deck' && persist({ ...payload, cards });
const count = payload.kind === 'quiz' ? payload.questions.length : payload.kind === 'deck' ? payload.cards.length : 0;
const noun = payload.kind === 'quiz' ? 'question' : 'card';
const removeInvalid = () => {
if (payload.kind === 'quiz') setQuestions(payload.questions.filter((_, i) => !badItems.has(i)));
else if (payload.kind === 'deck') setCards(payload.cards.filter((_, i) => !badItems.has(i)));
setEditing(null);
};
const topics = payload.kind === 'quiz' ? [...new Set(payload.questions.map((q) => q.topic).filter(Boolean))] : [];
const canSave = errors.length === 0 && (mode === 'new' ? Boolean(classId) : Boolean(targetId));
return (
<div className="animate-in pb-28">
<header className="mb-6">
<div className="eyebrow mb-2 flex flex-wrap items-center gap-2">
<span className="flex items-center gap-1.5 [&>svg]:size-3.5">
{KIND[draft.kind].icon} Draft {KIND[draft.kind].label.toLowerCase()}
</span>
{draft.meta.model && (
<Badge tone="accent">
<Sparkles /> {draft.meta.model}
</Badge>
)}
{draft.meta.origin === 'import' && <Badge>Import</Badge>}
</div>
<Input
value={payload.title}
onChange={(e) => persist({ ...payload, title: e.target.value })}
placeholder="Give it a title"
aria-label="Title"
aria-invalid={!payload.title.trim()}
className="display h-auto border-transparent bg-transparent px-0 py-1 text-[28px] shadow-none hover:border-line-strong focus:px-2 sm:text-[34px]"
readOnly={isImprove}
/>
<p className="mt-1 text-[15px] text-ink-2">
{isImprove ? 'Review the revised questions. The original quiz changes only when you apply them.' : 'Review and edit before saving. Nothing is in your library yet.'}
{draft.meta.sources?.length ? ` Based on ${draft.meta.sources.map((s) => s.title).join(', ')}.` : ''}
</p>
</header>
{draft.status === 'failed' && (
<Callout tone="warn" icon={<TriangleAlert />} title="Generation stopped early" className="mb-4">
{draft.error} What was written before that is below.
</Callout>
)}
{(draft.meta.notes ?? []).map((n, i) => (
<Callout key={i} tone="warn" icon={<TriangleAlert />} className="mb-4 py-2.5">
{n}
</Callout>
))}
{badItems.size > 0 && (
<Callout
tone="bad"
icon={<CircleAlert />}
className="mb-4"
title={`${plural(badItems.size, noun)} ${badItems.size === 1 ? 'needs' : 'need'} fixing before you can save`}
action={
<Button size="sm" onClick={removeInvalid}>
Remove {badItems.size === 1 ? 'it' : 'them'}
</Button>
}
>
They are marked below. Edit each one, or remove them.
</Callout>
)}
{/* destination */}
{!isImprove && (
<div className="card mb-6 grid gap-4 p-4 sm:grid-cols-3">
<Field label="Class">
<Select
value={classId}
onChange={(e) => {
setClassId(e.target.value);
setFolderId('');
setTargetId('');
}}
>
{!classId && <option value="">Choose a class</option>}
{(classes.data ?? []).map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</Select>
</Field>
{payload.kind !== 'note' ? (
<Field label="Save as">
<Select
value={mode === 'append' ? targetId : ''}
onChange={(e) => {
setMode(e.target.value ? 'append' : 'new');
setTargetId(e.target.value);
}}
>
<option value="">A new {payload.kind}</option>
{sameKindItems.length > 0 && (
<optgroup label={`Add to an existing ${payload.kind}`}>
{sameKindItems.map((i) => (
<option key={i.id} value={i.id}>
{i.title}
</option>
))}
</optgroup>
)}
</Select>
</Field>
) : (
<div />
)}
{mode === 'new' && (
<Field label="Folder">
<Select value={folderId} onChange={(e) => setFolderId(e.target.value)}>
<option value="">No folder</option>
{(cls.data?.folders ?? []).map((f) => (
<option key={f.id} value={f.id}>
{f.name}
</option>
))}
</Select>
</Field>
)}
</div>
)}
{/* content */}
{payload.kind === 'note' ? (
<div>
<div className="mb-3 flex justify-end">
<Segmented
size="sm"
label="View"
value={preview ? 'preview' : 'edit'}
onChange={(v) => setPreview(v === 'preview')}
options={[
{ value: 'preview', label: 'Preview', icon: <Eye /> },
{ value: 'edit', label: 'Edit', icon: <Pencil /> },
]}
/>
</div>
{preview ? (
<article className="card px-5 py-6 sm:px-10 sm:py-9">
<Markdown serif>{payload.content}</Markdown>
</article>
) : (
<Textarea value={payload.content} onChange={(e) => persist({ ...payload, content: e.target.value })} rows={28} className="num text-[13.5px] leading-relaxed" aria-label="Note content (Markdown)" />
)}
</div>
) : (
<>
<div className="mb-3 flex items-center justify-between">
<h2 className="eyebrow">{plural(count, noun)}</h2>
</div>
<ol className="space-y-3">
{payload.kind === 'quiz'
? payload.questions.map((q, i) => {
const own = validateDraftQuestion(q, i);
const bad = own.some((x) => x.level === 'error');
const before = isImprove ? original.data?.questions.find((x) => x.id === draft.meta.replaceQuestionIds?.[i]) : undefined;
return (
<li key={i} className={cx('card p-4 sm:p-5', bad && 'border-bad/60 ring-1 ring-bad/30')}>
<div className="mb-2.5 flex flex-wrap items-center gap-1.5">
<span className="num text-xs font-semibold text-ink-3">{String(i + 1).padStart(2, '0')}</span>
<Badge>{QUESTION_TYPE_LABEL[q.type]}</Badge>
{q.topic && <Badge tone="accent">{q.topic}</Badge>}
{q.difficulty !== 'medium' && <Badge>{q.difficulty}</Badge>}
{bad && (
<Badge tone="bad">
<CircleAlert /> Needs fixing
</Badge>
)}
<span className="ml-auto flex">
<IconButton label={editing === i ? 'Done editing' : 'Edit question'} size="sm" active={editing === i} onClick={() => setEditing(editing === i ? null : i)}>
{editing === i ? <Check /> : <Pencil />}
</IconButton>
<IconButton
label="Remove question"
size="sm"
onClick={() => {
setQuestions(payload.questions.filter((_, k) => k !== i));
setEditing(null);
}}
>
<Trash2 />
</IconButton>
</span>
</div>
{editing === i ? (
<QuestionEditor value={q} onChange={(next) => setQuestions(payload.questions.map((x, k) => (k === i ? next : x)))} issues={own} topics={topics} onSubmit={() => setEditing(null)} />
) : (
<>
<QuestionPreview q={q} />
{bad && <ul className="mt-3 space-y-0.5 text-[13px] text-bad">{own.filter((x) => x.level === 'error').map((x, k) => <li key={k}>• {x.message}</li>)}</ul>}
</>
)}
{before && (
<details className="mt-3 rounded-xl border border-line">
<summary className="flex items-center gap-1 px-3 py-2 text-[13px] font-medium text-ink-2 hover:text-ink">
<ChevronRight className="size-3.5" /> Original question
</summary>
<div className="border-t border-line p-3 opacity-80">
<QuestionPreview q={{ ...before, options: before.options.map((o) => ({ text: o.text, correct: o.correct, why: o.why })), source: undefined }} />
</div>
</details>
)}
</li>
);
})
: payload.cards.map((c, i) => {
const own = validateDraftCard(c, i);
const bad = own.length > 0;
return (
<li key={i} className={cx('card p-4', bad && 'border-bad/60 ring-1 ring-bad/30')}>
{editing === i ? (
<>
<CardEditor value={c} onChange={(next) => setCards(payload.cards.map((x, k) => (k === i ? next : x)))} issues={own} autoFocus onSubmit={() => setEditing(null)} />
<div className="mt-3 flex justify-end">
<Button size="sm" variant="primary" onClick={() => setEditing(null)}>
Done
</Button>
</div>
</>
) : (
<div className="flex items-start gap-3">
<span className="num mt-0.5 text-xs font-semibold text-ink-3">{String(i + 1).padStart(2, '0')}</span>
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-1.5 sm:grid-cols-2">
<Markdown className="text-[14.5px] font-medium">{c.front || '*empty*'}</Markdown>
<div>
<Markdown className="text-[14.5px] text-ink-2">{c.back || '*empty*'}</Markdown>
{c.hint && <div className="mt-1 text-xs text-ink-3">Hint: {c.hint}</div>}
</div>
</div>
<span className="flex shrink-0">
<IconButton label="Edit card" size="sm" onClick={() => setEditing(i)}>
<Pencil />
</IconButton>
<IconButton label="Remove card" size="sm" onClick={() => setCards(payload.cards.filter((_, k) => k !== i))}>
<Trash2 />
</IconButton>
</span>
</div>
)}
</li>
);
})}
</ol>
{!isImprove && (
<Button
className="mt-3"
icon={<Plus />}
onClick={() => {
if (payload.kind === 'quiz') setQuestions([...payload.questions, blankQuestion()]);
else setCards([...payload.cards, blankCard()]);
setEditing(count);
}}
>
Add {noun}
</Button>
)}
</>
)}
{/* save bar */}
<div className="safe-bottom fixed inset-x-0 bottom-14 z-30 border-t border-line bg-paper/95 backdrop-blur lg:bottom-0 lg:left-[252px]">
<div className="mx-auto flex h-16 max-w-[1080px] items-center gap-2 px-4 sm:px-8">
<div className="min-w-0 flex-1 text-[13px]" aria-live="polite">
{errors.length > 0 ? (
<span className="flex items-center gap-1.5 font-medium text-bad">
<CircleAlert className="size-4 shrink-0" />
<span className="truncate">{badItems.size > 0 ? `${plural(badItems.size, noun)} to fix` : errors[0].message}</span>
</span>
) : (
<span className="flex items-center gap-1.5 text-good">
<Check className="size-4" /> Ready to save
</span>
)}
</div>
<Button variant="ghost" onClick={() => discard()}>
Discard
</Button>
<Button variant="primary" loading={saving} disabled={!canSave} onClick={save}>
{isImprove ? `Apply ${plural(count, 'revision')}` : mode === 'append' ? `Add ${plural(count, noun)}` : payload.kind === 'note' ? 'Save note' : `Save ${plural(count, noun)}`}
</Button>
</div>
</div>
</div>
);
}

311
web/src/pages/Home.tsx Normal file
View file

@ -0,0 +1,311 @@
import { ArrowRight, BookOpen, CircleCheck, FileUp, Flame, GraduationCap, Layers, Play, Plus, RotateCcw, Sparkles, Target } from 'lucide-react';
import { useState } from 'react';
import { Link } from 'react-router';
import { ClassDialog } from '@/app/Shell';
import { AccuracyBar, Heatmap, Ring } from '@/features/charts';
import { useStartSession } from '@/features/study';
import { assistant } from '@/lib/assistantStore';
import { useAiStatus, useClasses, useOverview } from '@/lib/queries';
import type { AttemptSummary } from '@/lib/types';
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
import { Badge, Button, ClassDot, ErrorState, ProgressBar, Section, Skeleton } from '@/ui';
function greeting(): string {
const h = new Date().getHours();
if (h < 5) return 'Burning the midnight oil';
if (h < 12) return 'Good morning';
if (h < 18) return 'Good afternoon';
return 'Good evening';
}
function Onboarding({ hasClass, aiReady, onNewClass }: { hasClass: boolean; aiReady: boolean; onNewClass: () => void }) {
const steps = [
{ done: hasClass, title: 'Create a class', body: 'One for each course. Everything else lives inside it.', action: <Button size="sm" variant="primary" icon={<Plus />} onClick={onNewClass}>New class</Button> },
{ done: false, title: 'Add material', body: 'Import quizzes and flashcards, write your own, or upload lecture slides and notes.', action: hasClass ? <span className="text-[13px] text-ink-3">Open a class to add material</span> : null },
{ done: aiReady, title: 'Connect an AI model', body: 'Optional. Lets Study Desk write questions from your documents and explain answers.', action: <Link to="/settings/ai" className="text-[13px] font-medium text-accent hover:underline">Open AI settings</Link> },
];
return (
<div className="card overflow-hidden">
<div className="border-b border-line bg-sunken/60 px-5 py-4 sm:px-6">
<h2 className="display text-2xl">Set up your desk</h2>
<p className="mt-1 text-sm text-ink-2">Three steps and you are studying.</p>
</div>
<ol className="divide-y divide-line">
{steps.map((s, i) => (
<li key={s.title} className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-4 sm:px-6">
<span className={cx('num grid size-8 shrink-0 place-items-center rounded-full text-sm font-semibold', s.done ? 'bg-good-soft text-good' : 'bg-ink text-paper')}>{s.done ? <CircleCheck className="size-4" /> : i + 1}</span>
<div className="min-w-0 flex-1 basis-52">
<div className={cx('font-medium', s.done && 'text-ink-3 line-through')}>{s.title}</div>
<div className="text-[13px] text-ink-2">{s.body}</div>
</div>
{!s.done && s.action}
</li>
))}
</ol>
</div>
);
}
function ResumeRow({ a }: { a: AttemptSummary }) {
return (
<Link to={`/session/${a.id}`} className="group flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-accent-soft text-accent">
<Play className="size-4 fill-current" />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{a.title}</span>
<span className="mt-1 flex items-center gap-2">
<ProgressBar value={a.questionCount ? a.answeredCount / a.questionCount : 0} className="w-24" />
<span className="num text-xs text-ink-3">
{a.answeredCount}/{a.questionCount}
</span>
<span className="text-xs text-ink-3">· {a.mode === 'exam' ? 'Exam' : 'Practice'} · {timeAgo(a.updatedAt)}</span>
</span>
</span>
<ArrowRight className="size-4 text-ink-3 transition-transform group-hover:translate-x-0.5" />
</Link>
);
}
export default function Home() {
useDocumentTitle('Today');
const overview = useOverview();
const classes = useClasses();
const ai = useAiStatus();
const { start, starting } = useStartSession();
const [classDialog, setClassDialog] = useState(false);
if (overview.isError) return <ErrorState message="Could not load your overview." onRetry={() => overview.refetch()} />;
const o = overview.data;
const list = (classes.data ?? []).filter((c) => !c.archived);
const loading = overview.isLoading || classes.isLoading;
const hasContent = list.some((c) => c.counts.quizzes + c.counts.decks + c.counts.documents + c.counts.notes > 0);
const isNew = !loading && !hasContent;
const due = o?.due.total ?? 0;
const today = new Date().toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
return (
<div className="animate-in">
<header className="mb-7">
<div className="eyebrow mb-1.5">{today}</div>
<h1 className="display text-[32px] sm:text-[40px]">{greeting()}.</h1>
{o && !isNew && (
<p className="mt-2 text-[15px] text-ink-2">
{due > 0 ? (
<>
You have <span className="marker font-semibold text-ink">{plural(due, 'card')}</span> to review
</>
) : (
'Your flashcards are all caught up'
)}
{o.activeAttempts.length > 0 ? ` and ${plural(o.activeAttempts.length, 'session')} in progress` : ''}.
</p>
)}
</header>
{loading ? (
<div className="grid gap-4 md:grid-cols-3">
<Skeleton className="h-44 md:col-span-2" />
<Skeleton className="h-44" />
<Skeleton className="h-40 md:col-span-3" />
</div>
) : isNew ? (
<Onboarding hasClass={list.length > 0} aiReady={Boolean(ai.data?.ready)} onNewClass={() => setClassDialog(true)} />
) : (
o && (
<>
<div className="mb-8 grid gap-4 lg:grid-cols-[1.35fr_1fr]">
{/* Review */}
<div className="card relative overflow-hidden p-5 sm:p-6">
<div className="flex items-start justify-between gap-4">
<div>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<Layers className="size-3.5" /> Flashcard review
</div>
{due > 0 ? (
<>
<div className="flex items-baseline gap-2">
<span className="display num text-[56px] leading-none font-medium tracking-tight">{due}</span>
<span className="text-ink-2">due today</span>
</div>
<div className="mt-3 flex flex-wrap gap-1.5">
{o.due.learning > 0 && <Badge tone="warn">{o.due.learning} learning</Badge>}
{o.due.review > 0 && <Badge tone="good">{o.due.review} review</Badge>}
{o.due.new > 0 && <Badge tone="accent">{o.due.new} new</Badge>}
</div>
</>
) : (
<>
<div className="display mt-1 text-[28px]">All caught up</div>
<p className="mt-1 max-w-xs text-sm text-ink-2">
{o.forecast[1] > 0 ? `${plural(o.forecast[1], 'card')} come due tomorrow.` : 'Nothing is scheduled for tomorrow yet. Add cards to a deck to start building memory.'}
</p>
</>
)}
</div>
<Ring value={o.streak.goal ? o.streak.todayTotal / o.streak.goal : 0} size={76} stroke={7} tone={o.streak.todayDone ? 'good' : 'accent'}>
<div className="text-center leading-none">
<div className="num text-[17px] font-semibold">{o.streak.todayTotal}</div>
<div className="mt-0.5 text-[10px] text-ink-3">of {o.streak.goal}</div>
</div>
</Ring>
</div>
<div className="mt-5 flex flex-wrap gap-2">
{due > 0 ? (
<Link to="/review">
<Button variant="primary" size="lg" icon={<Play className="fill-current" />}>
Start review
</Button>
</Link>
) : null}
{o.missedCount > 0 && (
<Button size="lg" icon={<RotateCcw />} loading={starting} onClick={() => start({ source: { type: 'missed' }, count: Math.min(20, o.missedCount) })}>
Redo {Math.min(20, o.missedCount)} missed questions
</Button>
)}
</div>
</div>
{/* Streak */}
<div className="card flex flex-col p-5 sm:p-6">
<div className="flex items-center justify-between">
<div className="eyebrow flex items-center gap-1.5">
<Flame className="size-3.5" /> Streak
</div>
<Link to="/insights" className="text-xs font-medium text-accent hover:underline">
Insights
</Link>
</div>
<div className="mt-2 flex items-baseline gap-2">
<span className="display num text-[40px] leading-none">{o.streak.current}</span>
<span className="text-sm text-ink-2">{o.streak.current === 1 ? 'day' : 'days'}</span>
{o.streak.longest > o.streak.current && <span className="ml-auto text-xs text-ink-3">Best {o.streak.longest}</span>}
</div>
<p className="mt-1 text-[13px] text-ink-3">
{o.streak.todayDone ? 'Today counts. Nice work.' : `${Math.max(0, o.streak.goal - o.streak.todayTotal)} more ${o.streak.goal - o.streak.todayTotal === 1 ? 'item' : 'items'} today to ${o.streak.current > 0 ? 'keep it going' : 'start one'}.`}
</p>
<Heatmap days={o.activity} goal={o.streak.goal} weeks={18} className="mt-auto pt-4" />
</div>
</div>
{o.activeAttempts.length > 0 && (
<Section title="Pick up where you left off">
<div className="card divide-y divide-line overflow-hidden">
{o.activeAttempts.map((a) => (
<ResumeRow key={a.id} a={a} />
))}
</div>
</Section>
)}
<div className="grid gap-x-6 lg:grid-cols-2">
<Section
title="Needs work"
action={
ai.data?.ready && o.weakTopics.length > 0 ? (
<button type="button" className="flex items-center gap-1 text-xs font-medium text-accent hover:underline" onClick={() => assistant.open({ prompt: 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts.', autoSend: true, newChat: true })}>
<Sparkles className="size-3.5" /> New questions on these
</button>
) : undefined
}
>
{o.weakTopics.length === 0 ? (
<div className="card px-5 py-6 text-sm text-ink-2">
<Target className="mb-2 size-5 text-ink-3" />
Topics you score under 75% on will show up here once you have answered a few questions.
</div>
) : (
<div className="card divide-y divide-line">
{o.weakTopics.map((t) => (
<div key={`${t.classId}:${t.topic}`} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<ClassDot color={t.classColor} />
<span className="truncate text-sm font-medium">{t.topic}</span>
</div>
<AccuracyBar value={t.accuracy} className="mt-1.5" />
</div>
{t.classId && (
<Button size="sm" onClick={() => start({ source: { type: 'topics', classId: t.classId!, topics: [t.topic] } })}>
Practice
</Button>
)}
</div>
))}
</div>
)}
</Section>
<Section title="Recent results">
{o.recentAttempts.length === 0 ? (
<div className="card px-5 py-6 text-sm text-ink-2">
<BookOpen className="mb-2 size-5 text-ink-3" />
Finished quizzes appear here with your score.
</div>
) : (
<div className="card divide-y divide-line">
{o.recentAttempts.map((a) => {
const p = pct(a.score, a.maxScore);
const tone = gradeTone(p);
return (
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-9 w-12 shrink-0 place-items-center rounded-[10px] text-sm font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{a.title}</span>
<span className="text-xs text-ink-3">
{plural(a.questionCount, 'question')} · {timeAgo(a.completedAt)}
</span>
</span>
</Link>
);
})}
</div>
)}
</Section>
</div>
</>
)
)}
{!loading && list.length > 0 && (
<Section
title="Classes"
className="mt-2"
action={
<Button size="sm" variant="ghost" icon={<Plus />} onClick={() => setClassDialog(true)}>
New class
</Button>
}
>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{list.map((c) => (
<Link key={c.id} to={`/classes/${c.id}`} className={cx('card group relative overflow-hidden p-4 pl-5 transition-shadow hover:shadow-2', `tab-${c.color}`)}>
<span aria-hidden className="absolute inset-y-0 left-0 w-1.5 bg-tab" />
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
{c.code && <div className="num mb-0.5 text-[11px] text-ink-3">{c.code}</div>}
<div className="display truncate text-[19px]">{c.name}</div>
</div>
{c.due > 0 && <Badge tone="marker">{c.due} due</Badge>}
</div>
<div className="mt-3 flex flex-wrap gap-x-3 gap-y-1 text-xs text-ink-3">
<span className="flex items-center gap-1"><BookOpen className="size-3.5" />{c.counts.quizzes}</span>
<span className="flex items-center gap-1"><Layers className="size-3.5" />{c.counts.decks}</span>
<span className="flex items-center gap-1"><FileUp className="size-3.5" />{c.counts.documents}</span>
</div>
</Link>
))}
</div>
</Section>
)}
{!loading && list.length === 0 && !isNew && (
<div className="card p-6 text-center">
<GraduationCap className="mx-auto mb-2 size-6 text-ink-3" />
<Button variant="primary" onClick={() => setClassDialog(true)}>New class</Button>
</div>
)}
<ClassDialog open={classDialog} onOpenChange={setClassDialog} />
</div>
);
}

View file

@ -0,0 +1,203 @@
import { useQuery } from '@tanstack/react-query';
import { ChartColumn, Flame, RotateCcw, Sparkles, Target } from 'lucide-react';
import { useState } from 'react';
import { Link } from 'react-router';
import { AccuracyBar, AccuracyChart, ForecastBars, Heatmap } from '@/features/charts';
import { useStartSession } from '@/features/study';
import { api, errorMessage } from '@/lib/api';
import { assistant } from '@/lib/assistantStore';
import { useAiStatus, useClasses } from '@/lib/queries';
import type { Insights } from '@/lib/types';
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
import { Button, ClassDot, EmptyState, ErrorState, PageHeader, Section, Segmented, Select, Skeleton } from '@/ui';
function Stat({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: 'good' | 'warn' | 'bad' | 'none' }) {
return (
<div className="card p-4">
<div className="eyebrow">{label}</div>
<div className={cx('display num mt-1.5 text-[30px] leading-none', tone === 'good' && 'text-good', tone === 'warn' && 'text-warn', tone === 'bad' && 'text-bad')}>{value}</div>
{sub && <div className="mt-1.5 text-xs text-ink-3">{sub}</div>}
</div>
);
}
export default function InsightsPage() {
useDocumentTitle('Insights');
const classes = useClasses();
const ai = useAiStatus();
const { start, starting } = useStartSession();
const [classId, setClassId] = useState('');
const [days, setDays] = useState<'7' | '30' | '90'>('30');
const q = useQuery({ queryKey: ['insights', classId, days], queryFn: () => api.get<Insights>(`/api/insights?days=${days}${classId ? `&classId=${classId}` : ''}`), placeholderData: (prev) => prev });
const d = q.data;
if (q.isError) return <ErrorState message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
const acc = d?.totals.accuracy ?? null;
const accPct = acc === null ? null : Math.round(acc * 100);
const topics = (d?.topics ?? []).filter((t) => t.seen >= 2);
const empty = d && d.totals.questionsAnswered === 0 && d.totals.cardsReviewed === 0 && d.activity.every((a) => a.total === 0);
return (
<div className="animate-in">
<PageHeader
title="Insights"
description="How your studying is going, and where to spend the next hour."
actions={
<>
<Select value={classId} onChange={(e) => setClassId(e.target.value)} aria-label="Class" className="w-48">
<option value="">All classes</option>
{(classes.data ?? []).map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</Select>
<Segmented
label="Period"
value={days}
onChange={setDays}
options={[
{ value: '7', label: '7 days' },
{ value: '30', label: '30 days' },
{ value: '90', label: '90 days' },
]}
/>
</>
}
/>
{!d ? (
<div className="grid gap-4 sm:grid-cols-4">
{[0, 1, 2, 3].map((i) => (
<Skeleton key={i} className="h-24" />
))}
<Skeleton className="h-56 sm:col-span-4" />
</div>
) : empty ? (
<div className="card">
<EmptyState icon={<ChartColumn />} title="Nothing to chart yet">
Take a quiz or review some flashcards and your progress will start to appear here.
</EmptyState>
</div>
) : (
<div className={cx('transition-opacity', q.isFetching && 'opacity-70')}>
<div className="mb-8 grid grid-cols-2 gap-3 lg:grid-cols-4">
<Stat label="Accuracy" value={accPct === null ? '—' : `${accPct}%`} sub={`${plural(d.totals.questionsAnswered, 'question')} answered`} tone={gradeTone(accPct)} />
<Stat label="Card retention" value={d.totals.retention === null ? '—' : `${Math.round(d.totals.retention * 100)}%`} sub={`${plural(d.totals.cardsReviewed, 'card')} reviewed`} tone={d.totals.retention === null ? 'none' : gradeTone(Math.round(d.totals.retention * 100))} />
<Stat label="Study days" value={`${d.totals.studyDays}`} sub={`of the last ${d.range}`} />
<Stat label="Streak" value={`${d.streak.current}`} sub={`Best ${d.streak.longest} · goal ${d.streak.goal}/day`} />
</div>
<div className="grid gap-x-6 lg:grid-cols-[1.5fr_1fr]">
<Section title="Quiz accuracy by day">
<div className="card p-4">
<AccuracyChart points={d.accuracy} />
</div>
</Section>
<Section title="Reviews coming up">
<div className="card p-4">
<ForecastBars values={d.forecast} />
<p className="mt-3 text-xs text-ink-3">
{d.due.total > 0 ? (
<>
{plural(d.due.total, 'card')} ready now.{' '}
<Link to={classId ? `/review?classId=${classId}` : '/review'} className="font-medium text-accent hover:underline">
Start review
</Link>
</>
) : (
'Nothing due right now.'
)}
</p>
</div>
</Section>
</div>
<Section
title="Activity"
action={
<span className="flex items-center gap-1.5 text-xs text-ink-3">
<Flame className="size-3.5" /> A day counts toward your streak at {d.streak.goal} items
</span>
}
>
<div className="card p-4 sm:p-5">
<Heatmap days={d.activity} goal={d.streak.goal} weeks={53} />
</div>
</Section>
<Section
title="Topics, weakest first"
action={
<div className="flex gap-2">
{d.missedCount > 0 && (
<Button size="sm" icon={<RotateCcw />} loading={starting} onClick={() => start({ source: { type: 'missed', classId: classId || undefined }, count: Math.min(25, d.missedCount) })}>
Redo missed ({Math.min(25, d.missedCount)})
</Button>
)}
{ai.data?.ready && topics.length > 0 && (
<Button size="sm" icon={<Sparkles />} onClick={() => assistant.open({ prompt: 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts.', autoSend: true, newChat: true, classId: classId || null })}>
New questions on weak areas
</Button>
)}
</div>
}
>
{topics.length === 0 ? (
<div className="card px-5 py-6 text-sm text-ink-2">
<Target className="mb-2 size-5 text-ink-3" />
Give your questions a topic and answer a few of them. Accuracy by topic will show up here.
</div>
) : (
<div className="card divide-y divide-line">
{topics.map((t) => (
<div key={`${t.classId}:${t.topic}`} className="grid grid-cols-[1fr_auto] items-center gap-x-4 gap-y-1 px-4 py-3 sm:grid-cols-[1.2fr_1fr_auto]">
<div className="min-w-0">
<div className="flex items-center gap-2">
<ClassDot color={t.classColor} />
<span className="truncate text-sm font-medium">{t.topic}</span>
</div>
<div className="mt-0.5 pl-[18px] text-xs text-ink-3">
{t.className ? `${t.className} · ` : ''}
{plural(t.seen, 'answer')}
</div>
</div>
<AccuracyBar value={t.accuracy} className="col-span-2 sm:col-span-1" />
{t.classId && t.questions > 0 ? (
<Button size="sm" className="col-start-2 row-start-1 sm:col-start-3" onClick={() => start({ source: { type: 'topics', classId: t.classId!, topics: [t.topic] } })}>
Practice
</Button>
) : (
<span />
)}
</div>
))}
</div>
)}
</Section>
{d.recentAttempts.length > 0 && (
<Section title="Recent sessions">
<div className="card divide-y divide-line">
{d.recentAttempts.map((a) => {
const p = pct(a.score, a.maxScore);
const tone = gradeTone(p);
return (
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-2.5 hover:bg-ink/4">
<span className={cx('num grid h-8 w-12 shrink-0 place-items-center rounded-[9px] text-[13px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{a.title}</span>
<span className="shrink-0 text-xs text-ink-3">
{a.mode === 'exam' ? 'Exam · ' : ''}
{timeAgo(a.completedAt)}
</span>
</Link>
);
})}
</div>
</Section>
)}
</div>
)}
</div>
);
}

233
web/src/pages/NotePage.tsx Normal file
View file

@ -0,0 +1,233 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { MoveDialog, ShareDialog } from '@/features/dialogs';
import { MarkdownArea } from '@/features/editors';
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { api, errorMessage } from '@/lib/api';
import { useAssistantContext } from '@/lib/assistantStore';
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
import type { ClassInfo, NoteInfo, Share } from '@/lib/types';
import { cx, downloadText, timeAgo, useDocumentTitle } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, useConfirm } from '@/ui';
export default function NotePage() {
const { noteId = '' } = useParams();
const [params, setParams] = useSearchParams();
const navigate = useNavigate();
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const q = useQuery({ queryKey: qk.note(noteId), queryFn: () => api.get<{ note: NoteInfo; class: ClassInfo; share: Share | null }>(`/api/notes/${noteId}`), refetchOnWindowFocus: false });
const note = q.data?.note;
useDocumentTitle(note?.title);
useAssistantContext(note?.classId, note?.title);
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [status, setStatus] = useState<'saved' | 'saving' | 'dirty' | 'error'>('saved');
const [move, setMove] = useState(false);
const [share, setShare] = useState(false);
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
const loaded = useRef('');
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const latest = useRef({ title: '', content: '' });
useEffect(() => {
if (note && loaded.current !== note.id) {
loaded.current = note.id;
setTitle(note.title);
setContent(note.content);
latest.current = { title: note.title, content: note.content };
setEditing(Boolean(params.get('edit')) || note.content.trim() === '');
if (params.get('edit')) setParams({}, { replace: true });
}
}, [note, params, setParams]);
const saveNow = async () => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
setStatus('saving');
try {
await api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content });
setStatus('saved');
} catch {
setStatus('error');
}
};
const change = (patch: Partial<{ title: string; content: string }>) => {
latest.current = { ...latest.current, ...patch };
if (patch.title !== undefined) setTitle(patch.title);
if (patch.content !== undefined) setContent(patch.content);
setStatus('dirty');
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => void saveNow(), 900);
};
useEffect(
() => () => {
if (timer.current) {
clearTimeout(timer.current);
void api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }).catch(() => undefined);
}
},
[noteId],
);
if (q.isError) return <ErrorState title="Note not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!q.data || !note) {
return (
<div className="space-y-4">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-10 w-96 max-w-full" />
<Skeleton className="h-96" />
</div>
);
}
const cls = q.data.class;
const remove = async () => {
if (!(await confirm({ title: 'Delete this note?', message: `"${note.title}" will be permanently deleted.`, confirmLabel: 'Delete', danger: true }))) return;
try {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
await api.del(`/api/notes/${note.id}`);
await refresh();
navigate(`/classes/${note.classId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
return (
<div className={cx('animate-in', `tab-${cls.color}`)}>
<nav aria-label="Breadcrumb" className="no-print mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
<Link to={`/classes/${cls.id}`} className="flex items-center gap-1.5 hover:text-ink">
<ClassDot color={cls.color} />
{cls.name}
</Link>
<ChevronRight className="size-3.5" />
<span>{note.kind === 'guide' ? 'Study guide' : 'Note'}</span>
</nav>
<header className="mb-5 flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
<div className="min-w-0 flex-1 basis-80">
{editing ? (
<Input value={title} onChange={(e) => change({ title: e.target.value })} aria-label="Title" maxLength={200} className="display h-auto border-transparent bg-transparent px-0 py-1 text-[28px] shadow-none hover:border-line-strong focus:px-2 sm:text-[34px]" />
) : (
<h1 className="display text-[28px] sm:text-[34px]">{title}</h1>
)}
<div className="no-print mt-1.5 flex flex-wrap items-center gap-2 text-[13px] text-ink-3">
<span>Edited {timeAgo(note.updatedAt)}</span>
{editing && (
<span className={cx('flex items-center gap-1', status === 'error' && 'text-bad')} aria-live="polite">
{status === 'saved' ? (
<>
<Check className="size-3.5" /> Saved
</>
) : status === 'error' ? (
'Could not save. Check your connection.'
) : (
'Saving…'
)}
</span>
)}
{q.data.share?.enabled && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
</div>
<div className="no-print flex items-center gap-2">
<Segmented
label="Mode"
value={editing ? 'edit' : 'read'}
onChange={(v) => {
if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId)));
setEditing(v === 'edit');
}}
options={[
{ value: 'read', label: 'Read', icon: <Eye /> },
{ value: 'edit', label: 'Edit', icon: <Pencil /> },
]}
/>
<Menu
trigger={
<IconButton label="Note options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
{ai.data?.ready && content.trim().length > 40 && (
<>
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', noteId: note.id, sourceLabel: title })}>
Quiz from this note
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', noteId: note.id, sourceLabel: title })}>
Flashcards from this note
</MenuItem>
<MenuSeparator />
</>
)}
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
Move
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
Share
</MenuItem>
<MenuItem icon={<Download />} onSelect={() => downloadText(`${title.replace(/[^\w\- ]+/g, '').trim() || 'note'}.md`, `# ${title}\n\n${content}`, 'text/markdown')}>
Download as Markdown
</MenuItem>
<MenuItem icon={<Printer />} onSelect={() => (setEditing(false), setTimeout(() => window.print(), 150))}>
Print
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
Delete
</MenuItem>
</Menu>
</div>
</header>
{editing ? (
<div className="grid gap-4 xl:grid-cols-2">
<div>
<MarkdownArea label="Note content (Markdown)" value={content} onChange={(v) => change({ content: v })} rows={22} placeholder={'Write in Markdown.\n\n## Heading\n- bullet\n**bold**, tables, and pasted images all work.'} className="[&_textarea]:min-h-[60vh] [&_textarea]:font-mono [&_textarea]:text-[13.5px]" />
<p className="mt-1.5 text-xs text-ink-3">Markdown. Paste or drop an image to embed it. Changes save automatically.</p>
</div>
<article className="card hidden max-h-[80vh] overflow-y-auto px-7 py-6 xl:block">
<div className="eyebrow mb-3 flex items-center gap-1.5">
<Eye className="size-3.5" /> Preview
</div>
<Markdown serif>{content || '*Nothing yet.*'}</Markdown>
</article>
</div>
) : content.trim() ? (
<article className="card px-5 py-6 sm:px-12 sm:py-10 print:border-0 print:p-0 print:shadow-none">
<Markdown serif className="mx-auto max-w-[70ch]">
{content}
</Markdown>
</article>
) : (
<div className="card">
<EmptyState
icon={<Sparkles />}
title="This note is empty"
action={
<Button variant="primary" icon={<Pencil />} onClick={() => setEditing(true)}>
Start writing
</Button>
}
/>
</div>
)}
<MoveDialog target={move ? { kind: 'note', id: note.id, title, classId: note.classId, folderId: note.folderId } : null} onClose={() => setMove(false)} />
<ShareDialog target={share ? { kind: 'note', id: note.id, title } : null} onClose={() => setShare(false)} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={note.classId} folderId={note.folderId} preset={generate ?? undefined} />
</div>
);
}

679
web/src/pages/QuizPage.tsx Normal file
View file

@ -0,0 +1,679 @@
import { ArrowDown, ArrowUp, BookOpen, Check, ChevronRight, ClipboardList, Copy, Download, FolderInput, History, Layers, ListPlus, MoreHorizontal, Pencil, Play, Plus, RotateCcw, Search, Share2, Sparkles, Stamp, Timer, Trash2, WandSparkles } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { blankQuestion, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content';
import { parseImport } from '@shared/importer';
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
import { QuestionEditor } from '@/features/editors';
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { useStartSession } from '@/features/study';
import { api, errorMessage } from '@/lib/api';
import { useAssistantContext } from '@/lib/assistantStore';
import { useAiStatus, useQuiz, useRefresh } from '@/lib/queries';
import { cx, downloadFile, formatDateTime, formatMinutes, gradeTone, pct, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui';
interface StartPrefs {
mode: 'practice' | 'exam';
shuffleQuestions: boolean;
shuffleOptions: boolean;
}
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) {
const { start, starting } = useStartSession();
const [prefs, setPrefs] = useLocalStorage<StartPrefs>('sd.startPrefs', { mode: 'practice', shuffleQuestions: true, shuffleOptions: true });
const [count, setCount] = useState(total);
const [timed, setTimed] = useState(false);
const [minutes, setMinutes] = useState(30);
useEffect(() => {
if (open) {
setCount(total);
setMinutes(Math.max(5, Math.round(total * 1.2)));
setTimed(false);
}
}, [open, total]);
const go = () =>
start({
mode: prefs.mode,
source: { type: 'quiz', quizId },
shuffleQuestions: prefs.shuffleQuestions,
shuffleOptions: prefs.shuffleOptions,
count: count < total ? count : undefined,
timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null,
});
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Start a session"
description={title}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Play className="fill-current" />} loading={starting} onClick={go}>
Start
</Button>
</>
}
>
<div className="space-y-5">
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
{(
[
{ v: 'practice', title: 'Practice', body: 'Check each answer as you go and read the rationale right away.' },
{ v: 'exam', title: 'Exam', body: 'No feedback until you submit. Flag questions and come back to them.' },
] as const
).map((m) => (
<button
key={m.v}
type="button"
role="radio"
aria-checked={prefs.mode === m.v}
onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))}
className={cx('rounded-xl border p-3.5 text-left transition-colors', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}
>
<div className="font-semibold">{m.title}</div>
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.body}</div>
</button>
))}
</div>
<Field label={`Questions: ${count === total ? `all ${total}` : `${count} of ${total}`}`}>
<input type="range" min={1} max={total} value={count} onChange={(e) => setCount(Number(e.target.value))} className="mt-1 w-full accent-[var(--accent)]" disabled={total <= 1} />
</Field>
<div className="space-y-4 rounded-xl border border-line p-4">
<Switch checked={prefs.shuffleQuestions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQuestions: v }))} label="Shuffle questions" />
<Switch checked={prefs.shuffleOptions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleOptions: v }))} label="Shuffle answer choices" description='"All of the above" style choices stay last.' />
{prefs.mode === 'exam' && (
<>
<Switch checked={timed} onChange={setTimed} label="Time limit" description="The exam submits itself when time runs out." />
{timed && (
<div className="flex items-center gap-2">
<Timer className="size-4 text-ink-3" />
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setMinutes(Math.max(1, Math.min(600, Number(e.target.value) || 1)))} className="w-24" aria-label="Minutes" />
<span className="text-sm text-ink-2">minutes</span>
</div>
)}
</>
)}
</div>
</div>
</Dialog>
);
}
/** Paste several questions (or cards) as text or JSON and add them to an existing item. */
export function BulkAddDialog({ open, onClose, kind, onAdd }: { open: boolean; onClose: () => void; kind: 'quiz' | 'deck'; onAdd: (items: unknown[]) => Promise<void> }) {
const [text, setText] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (open) setText('');
}, [open]);
const parsed = useMemo(() => (text.trim() ? parseImport(text, { prefer: kind }) : null), [text, kind]);
const all: (DraftQuestion | DraftCard)[] = (parsed?.items ?? []).flatMap((it): (DraftQuestion | DraftCard)[] => (kind === 'quiz' && it.kind === 'quiz' ? it.questions : kind === 'deck' && it.kind === 'deck' ? it.cards : []));
const valid = all.filter((x) => ('stem' in x ? validateDraftQuestion(x, 0).every((i) => i.level !== 'error') : Boolean(x.front.trim() && x.back.trim())));
const noun = kind === 'quiz' ? 'question' : 'card';
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title={`Add several ${noun}s`}
size="lg"
footer={
<>
<span className="mr-auto text-[13px] text-ink-3" aria-live="polite">
{parsed ? (all.length === 0 ? `No ${noun}s recognised yet` : `${valid.length} ready${all.length > valid.length ? `, ${all.length - valid.length} with problems will be skipped` : ''}`) : ''}
</span>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button
variant="primary"
disabled={valid.length === 0}
loading={busy}
onClick={async () => {
setBusy(true);
try {
await onAdd(valid);
onClose();
} finally {
setBusy(false);
}
}}
>
Add {valid.length > 0 ? plural(valid.length, noun) : ''}
</Button>
</>
}
>
<Textarea
autoFocus
rows={14}
value={text}
onChange={(e) => setText(e.target.value)}
spellCheck={false}
className="num text-[13px]"
aria-label={`Paste ${noun}s`}
placeholder={
kind === 'quiz'
? '1. Which electrolyte imbalance causes peaked T waves?\nA. Hypokalemia\n*B. Hyperkalemia\nC. Hyponatremia\nRationale: High potassium speeds repolarisation.\nTopic: Electrolytes\n\n2. Next question…\n\nMark correct choices with * (or add a line "Answer: B, D"). JSON works too.'
: 'Furosemide\tLoop diuretic; monitor potassium\nMetoprolol\tBeta-1 blocker; hold for HR under 60\n\nOne card per line: front, a tab (or " - " or "::"), then back. JSON works too.'
}
/>
</Dialog>
);
}
function QuestionView({ q, index, stat }: { q: Question; index: number; stat?: { seen: number; correct: number; lastCorrect: boolean } }) {
const [open, setOpen] = useState(false);
const hasMore = Boolean(q.rationale) || q.options.some((o) => o.why);
return (
<div>
<div className="mb-2 flex flex-wrap items-center gap-1.5">
<span className="num text-xs font-semibold text-ink-3">{String(index + 1).padStart(2, '0')}</span>
<Badge>{QUESTION_TYPE_LABEL[q.type]}</Badge>
{q.topic && <Badge tone="accent">{q.topic}</Badge>}
{q.difficulty !== 'medium' && <Badge>{q.difficulty}</Badge>}
{stat && stat.seen > 0 && (
<Badge tone={stat.lastCorrect ? 'good' : 'bad'}>
{stat.correct}/{stat.seen} correct
</Badge>
)}
</div>
<Markdown serif className="text-[17px]">
{q.stem}
</Markdown>
<ul className="mt-3 space-y-1.5">
{q.options.map((o, i) => (
<li key={o.id} className="flex items-start gap-2.5 text-[15px]">
<span className={cx('num mt-0.5 grid size-6 shrink-0 place-items-center text-xs font-semibold', q.type === 'single' ? 'rounded-full' : 'rounded-md', o.correct ? 'bg-good text-white dark:text-[#10241a]' : 'bg-sunken text-ink-3')}>
{o.correct ? <Check className="size-3.5" strokeWidth={3} /> : optionLetter(i)}
</span>
<div className="min-w-0 flex-1">
<Markdown className={o.correct ? 'font-medium' : 'text-ink-2'}>{o.text}</Markdown>
{open && o.why && <div className="mt-0.5 text-[13px] text-ink-3">{o.why}</div>}
</div>
</li>
))}
</ul>
{hasMore && (
<>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="mt-3 flex items-center gap-1 text-[13px] font-medium text-accent hover:underline">
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
{open ? 'Hide rationale' : 'Show rationale'}
</button>
{open && q.rationale && (
<div className="mt-2 rounded-xl bg-sunken px-4 py-3">
<Markdown className="text-[14.5px]">{q.rationale}</Markdown>
</div>
)}
</>
)}
</div>
);
}
export default function QuizPage() {
const { quizId = '' } = useParams();
const [params, setParams] = useSearchParams();
const navigate = useNavigate();
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const q = useQuiz(quizId);
const data = q.data;
useDocumentTitle(data?.quiz.title);
useAssistantContext(data?.quiz.classId, data?.quiz.title);
const { start, starting } = useStartSession();
const [tab, setTab] = useState<'questions' | 'history'>('questions');
const [editing, setEditing] = useState<string | 'new' | null>(null);
const [draft, setDraft] = useState<DraftQuestion>(blankQuestion());
const [saving, setSaving] = useState(false);
const [filter, setFilter] = useState('');
const [onlyMissed, setOnlyMissed] = useState(false);
const [startOpen, setStartOpen] = useState(false);
const [bulkOpen, setBulkOpen] = useState(false);
const [rename, setRename] = useState(false);
const [move, setMove] = useState(false);
const [share, setShare] = useState(false);
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
const newRef = useRef<HTMLDivElement>(null);
// Deep links: ?start=1 opens the start dialog, ?edit=1 a blank question, ?q=<id> scrolls to a question.
useEffect(() => {
if (!data) return;
const next = new URLSearchParams(params);
if (params.get('start') && data.questions.length > 0) setStartOpen(true);
if (params.get('edit')) {
setDraft(blankQuestion());
setEditing('new');
}
const target = params.get('q');
if (target) setTimeout(() => document.getElementById(`q-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
if (params.get('start') || params.get('edit')) {
next.delete('start');
next.delete('edit');
setParams(next, { replace: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data?.quiz.id]);
const topics = useMemo(() => [...new Set((data?.questions ?? []).map((x) => x.topic).filter(Boolean))].sort(), [data]);
const stats = data?.questionStats ?? {};
const shown = useMemo(() => {
const needle = filter.trim().toLowerCase();
return (data?.questions ?? [])
.map((question, index) => ({ question, index }))
.filter(({ question }) => (!needle || question.stem.toLowerCase().includes(needle) || question.topic.toLowerCase().includes(needle)) && (!onlyMissed || stats[question.id]?.lastCorrect === false));
}, [data, filter, onlyMissed, stats]);
if (q.isError) return <ErrorState title="Quiz not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!data) {
return (
<div className="space-y-4">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-10 w-96 max-w-full" />
<Skeleton className="h-24" />
{[0, 1].map((i) => (
<Skeleton key={i} className="h-48" />
))}
</div>
);
}
const { quiz, questions, history } = data;
const full = history.filter((h) => h.kind === 'full' && h.maxScore);
const best = full.length ? Math.max(...full.map((h) => pct(h.score, h.maxScore) ?? 0)) : null;
const last = full.length ? pct(full[0].score, full[0].maxScore) : null;
const missedCount = Object.values(stats).filter((s) => !s.lastCorrect).length;
const editingIssues = editing ? validateDraftQuestion(draft, 0) : [];
const canSave = editingIssues.every((i) => i.level !== 'error');
const beginEdit = (question: Question) => {
setDraft(questionToDraft(question));
setEditing(question.id);
};
const beginNew = () => {
setDraft({ ...blankQuestion(), topic: questions[questions.length - 1]?.topic ?? '' });
setEditing('new');
setTimeout(() => newRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 60);
};
const save = async (another = false) => {
if (!canSave || !editing) return;
setSaving(true);
try {
if (editing === 'new') await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: [draft] });
else await api.patch(`/api/questions/${editing}`, draft);
await refresh();
if (another && editing === 'new') {
setDraft({ ...blankQuestion(draft.type), topic: draft.topic });
setTimeout(() => newRef.current?.querySelector('textarea')?.focus(), 60);
} else setEditing(null);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setSaving(false);
}
};
const removeQuestion = async (question: Question) => {
if (!(await confirm({ title: 'Delete this question?', message: 'It will be removed from the quiz. Past attempts keep their own copy.', confirmLabel: 'Delete', danger: true }))) return;
await api.del(`/api/questions/${question.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const moveQuestion = async (index: number, delta: number) => {
const ids = questions.map((x) => x.id);
const to = index + delta;
if (to < 0 || to >= ids.length) return;
[ids[index], ids[to]] = [ids[to], ids[index]];
await api.post(`/api/quizzes/${quiz.id}/questions/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const duplicateQuestion = async (question: Question, index: number) => {
await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: [questionToDraft(question)], index: index + 1 }).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const deleteQuiz = async () => {
if (!(await confirm({ title: 'Delete this quiz?', message: `"${quiz.title}" and its ${plural(questions.length, 'question')} will be permanently deleted.`, confirmLabel: 'Delete quiz', danger: true }))) return;
try {
await api.del(`/api/quizzes/${quiz.id}`);
await refresh();
navigate(`/classes/${quiz.classId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
const improve = async (ids?: string[]) => {
try {
const res = await api.post<{ draftId: string }>('/api/ai/improve', { quizId: quiz.id, questionIds: ids });
navigate(`/drafts/${res.draftId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
const editorFooter = (isNew: boolean) => (
<div className="mt-5 flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
<span className="mr-auto hidden text-xs text-ink-3 sm:block">Ctrl+Enter to save</span>
<Button variant="ghost" onClick={() => setEditing(null)}>
Cancel
</Button>
{isNew && (
<Button disabled={!canSave} loading={saving} onClick={() => save(true)}>
Save and add another
</Button>
)}
<Button variant="primary" disabled={!canSave} loading={saving} onClick={() => save(false)}>
Save
</Button>
</div>
);
return (
<div className={cx('animate-in', `tab-${data.class.color}`)}>
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
<Link to={`/classes/${data.class.id}`} className="flex items-center gap-1.5 hover:text-ink">
<ClassDot color={data.class.color} />
{data.class.name}
</Link>
<ChevronRight className="size-3.5" />
<span>Quiz</span>
</nav>
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
<div className="min-w-0">
<h1 className="display text-[30px] sm:text-[36px]">{quiz.title}</h1>
{quiz.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{quiz.description}</p>}
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-ink-2">
<span>{plural(questions.length, 'question')}</span>
{full.length > 0 && (
<>
<span>
Last <strong className="num text-ink">{last}%</strong>
</span>
<span>
Best <strong className="num text-ink">{best}%</strong>
</span>
<span>{plural(history.length, 'attempt')}</span>
</>
)}
{data.share?.enabled && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{data.activeAttempt ? (
<Link to={`/session/${data.activeAttempt.id}`}>
<Button variant="marker" size="lg" icon={<Play className="fill-current" />}>
Resume ({data.activeAttempt.answeredCount}/{data.activeAttempt.questionCount})
</Button>
</Link>
) : null}
<Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}>
{data.activeAttempt ? 'Start new' : 'Start'}
</Button>
<Menu
trigger={
<IconButton label="Quiz options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
{missedCount > 0 && (
<MenuItem icon={<RotateCcw />} onSelect={() => start({ source: { type: 'missed', quizId: quiz.id } })}>
Practice {missedCount} missed
</MenuItem>
)}
{ai.data?.ready && questions.length > 0 && (
<>
<MenuItem icon={<WandSparkles />} onSelect={() => improve()}>
Improve questions with AI
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', quizId: quiz.id, sourceLabel: quiz.title })}>
Make flashcards from this
</MenuItem>
</>
)}
<MenuSeparator />
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
Rename
</MenuItem>
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
Move
</MenuItem>
<MenuItem
icon={<Copy />}
onSelect={async () => {
const res = await api.post<{ quiz: { id: string } }>(`/api/quizzes/${quiz.id}/duplicate`, {}).catch((e) => (toast.error(errorMessage(e)), null));
if (res) {
await refresh();
navigate(`/quizzes/${res.quiz.id}`);
toast.success('Duplicated');
}
}}
>
Duplicate
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
Share
</MenuItem>
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/quizzes/${quiz.id}/export`)}>
Export JSON
</MenuItem>
<MenuItem
icon={<Stamp />}
onSelect={async () => {
await api.post('/api/templates/from', { kind: 'quiz', id: quiz.id }).then(() => toast.success('Saved as a template')).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
>
Save as template
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={deleteQuiz}>
Delete quiz
</MenuItem>
</Menu>
</div>
</header>
<div className="mb-4 flex flex-wrap items-center gap-2">
<Segmented
value={tab}
onChange={setTab}
label="View"
options={[
{ value: 'questions', label: `Questions`, icon: <ClipboardList /> },
{ value: 'history', label: `History${history.length ? ` (${history.length})` : ''}`, icon: <History /> },
]}
/>
{tab === 'questions' && questions.length > 0 && (
<div className="ml-auto flex flex-wrap items-center gap-2">
{missedCount > 0 && (
<button type="button" aria-pressed={onlyMissed} onClick={() => setOnlyMissed(!onlyMissed)} className={cx('h-9 rounded-full border px-3 text-[13px] font-medium', onlyMissed ? 'border-bad bg-bad-soft text-bad' : 'border-line-strong text-ink-2 hover:border-ink-3')}>
Missed ({missedCount})
</button>
)}
{questions.length > 5 && (
<div className="relative">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Find a question" aria-label="Find a question" className="h-9 w-44 pl-8 sm:w-56" />
</div>
)}
</div>
)}
</div>
{tab === 'questions' ? (
<>
{questions.length === 0 && editing !== 'new' ? (
<div className="card border-dashed">
<EmptyState
icon={<BookOpen />}
title="No questions yet"
action={
<>
<Button variant="primary" icon={<Plus />} onClick={beginNew}>
Write a question
</Button>
<Button icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
Paste several
</Button>
<Button icon={<Sparkles />} onClick={() => navigate(`/classes/${quiz.classId}`)}>
Generate from documents
</Button>
</>
}
>
Write questions one at a time, paste a batch as text, or generate them from your class documents.
</EmptyState>
</div>
) : (
<ol className="space-y-3">
{shown.map(({ question, index }) => (
<li key={question.id} id={`q-${question.id}`} className={cx('card scroll-mt-24 p-4 sm:p-5', params.get('q') === question.id && 'ring-2 ring-marker')}>
{editing === question.id ? (
<>
<QuestionEditor value={draft} onChange={setDraft} issues={editingIssues.filter((i) => draft.stem || i.field !== 'stem')} topics={topics} autoFocus onSubmit={() => save(false)} />
{editorFooter(false)}
</>
) : (
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
<QuestionView q={question} index={index} stat={stats[question.id]} />
</div>
<div className="flex shrink-0 flex-col sm:flex-row">
<IconButton label="Edit question" size="sm" onClick={() => beginEdit(question)}>
<Pencil />
</IconButton>
<Menu
trigger={
<IconButton label="Question options" size="sm" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<Copy />} onSelect={() => duplicateQuestion(question, index)}>
Duplicate
</MenuItem>
<MenuItem icon={<ArrowUp />} disabled={index === 0} onSelect={() => moveQuestion(index, -1)}>
Move up
</MenuItem>
<MenuItem icon={<ArrowDown />} disabled={index === questions.length - 1} onSelect={() => moveQuestion(index, 1)}>
Move down
</MenuItem>
{ai.data?.ready && (
<MenuItem icon={<WandSparkles />} onSelect={() => improve([question.id])}>
Improve with AI
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => removeQuestion(question)}>
Delete
</MenuItem>
</Menu>
</div>
</div>
)}
</li>
))}
{shown.length === 0 && questions.length > 0 && (
<li className="card">
<EmptyState icon={<Search />} title="No questions match" />
</li>
)}
</ol>
)}
<div ref={newRef} className="mt-3 scroll-mt-24">
{editing === 'new' ? (
<div className="card border-accent/40 p-4 ring-2 ring-accent/15 sm:p-5">
<div className="eyebrow mb-4">New question</div>
<QuestionEditor value={draft} onChange={setDraft} issues={[]} topics={topics} autoFocus onSubmit={() => save(true)} />
{!canSave && draft.stem.trim() && <div className="mt-3 text-[13px] text-ink-3">{editingIssues.find((i) => i.level === 'error')?.message}</div>}
{editorFooter(true)}
</div>
) : (
questions.length > 0 && (
<div className="flex flex-wrap gap-2">
<Button icon={<Plus />} onClick={beginNew}>
Add question
</Button>
<Button variant="ghost" icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
Paste several
</Button>
</div>
)
)}
</div>
</>
) : history.length === 0 ? (
<div className="card">
<EmptyState icon={<History />} title="No attempts yet">
Finished sessions are listed here with your score and time.
</EmptyState>
</div>
) : (
<>
{full.length >= 2 && (
<Callout className="mb-3" tone={last !== null && best !== null && last >= best ? 'good' : 'neutral'}>
{last !== null && best !== null && last >= best ? `Your latest attempt (${last}%) is your best so far.` : `Latest ${last}%, best ${best}% across ${plural(full.length, 'full attempt')}.`}
</Callout>
)}
<ul className="card divide-y divide-line">
{history.map((h) => {
const p = pct(h.score, h.maxScore);
const tone = gradeTone(p);
return (
<li key={h.id}>
<Link to={`/session/${h.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-10 w-14 shrink-0 place-items-center rounded-[10px] text-[15px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">
{h.completedAt ? formatDateTime(h.completedAt) : ''}
<span className="ml-2 font-normal text-ink-3">{timeAgo(h.completedAt)}</span>
</span>
<span className="text-xs text-ink-3">
{h.mode === 'exam' ? 'Exam' : 'Practice'}
{h.kind !== 'full' ? ' · missed only' : ''} · {h.maxScore ?? h.questionCount} scored{h.elapsedSec > 0 ? ` · ${formatMinutes(h.elapsedSec)}` : ''}
</span>
</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
</li>
);
})}
</ul>
</>
)}
<StartSessionDialog open={startOpen} onClose={() => setStartOpen(false)} quizId={quiz.id} total={questions.length} title={quiz.title} />
<BulkAddDialog
open={bulkOpen}
onClose={() => setBulkOpen(false)}
kind="quiz"
onAdd={async (items) => {
try {
await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: items });
await refresh();
toast.success(`Added ${plural(items.length, 'question')}`);
} catch (e) {
toast.error(errorMessage(e));
throw e;
}
}}
/>
<RenameDialog target={rename ? { kind: 'quiz', id: quiz.id, title: quiz.title, description: quiz.description } : null} onClose={() => setRename(false)} />
<MoveDialog target={move ? { kind: 'quiz', id: quiz.id, title: quiz.title, classId: quiz.classId, folderId: quiz.folderId } : null} onClose={() => setMove(false)} />
<ShareDialog target={share ? { kind: 'quiz', id: quiz.id, title: quiz.title } : null} onClose={() => setShare(false)} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={quiz.classId} folderId={quiz.folderId} preset={generate ?? undefined} />
{starting && <span className="sr-only" role="status">Starting session</span>}
</div>
);
}

View file

@ -0,0 +1,328 @@
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, StudyTopBar } 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, Kbd, 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 [busy, setBusy] = useState(false);
const [done, setDone] = useState({ reviewed: 0, again: 0 });
const [last, setLast] = useState<{ cardId: string; snapshot: QueueCard[]; wasAgain: boolean } | 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), [current?.card.id]);
const rate = useCallback(
async (rating: 1 | 2 | 3 | 4) => {
if (!current || !queue || busy) return;
setBusy(true);
const snapshot = queue;
try {
const res = await api.post<{ result: QueueCard }>('/api/review/answer', { cardId: current.card.id, rating });
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 });
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) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
},
[current, queue, busy, scope],
);
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)) }));
setLast(null);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
}, [last, busy]);
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();
if (current) setFlipped((f) => !f);
},
Enter: () => {
if (!current) return;
if (flipped) void rate(3);
else setFlipped(true);
},
'1': () => flipped && void rate(1),
'2': () => flipped && void rate(2),
'3': () => flipped && void rate(3),
'4': () => flipped && 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}
right={
<>
<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 (U)" onClick={undo} disabled={!last || busy}>
<Undo2 />
</IconButton>
{current && (
<Menu
trigger={
<IconButton label="Card options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem
icon={<Pencil />}
hint="E"
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-2xl flex-1 flex-col px-4 pt-6 pb-40 sm:px-5 sm:pt-10">
{!current ? (
<div className="card m-auto w-full 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={() => setFlipped((f) => !f)}
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
/>
</>
)}
</main>
{current && (
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
<div className="mx-auto max-w-2xl px-3 py-3 sm:px-5">
{flipped ? (
<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-[58px] 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-[58px]" onClick={() => setFlipped(true)}>
Show answer
<span className="hidden sm:inline">
<Kbd>Space</Kbd>
</span>
</Button>
)}
<div className="mt-2 hidden justify-center gap-4 text-[11px] text-ink-3 sm:flex">
<span>
<Kbd>1</Kbd>–<Kbd>4</Kbd> rate
</span>
<span>
<Kbd>Enter</Kbd> good
</span>
<span>
<Kbd>U</Kbd> undo
</span>
<span>
<Kbd>E</Kbd> edit
</span>
</div>
</div>
</footer>
)}
<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>
);
}

View file

@ -0,0 +1,209 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, RotateCcw, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { toast } from 'sonner';
import { Explain } from '@/features/Explain';
import { QuizResults, QuizRunner } from '@/features/quiz';
import { useStartSession } from '@/features/study';
import { api, errorMessage } from '@/lib/api';
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
import type { AnswerState, Attempt, SnapshotQuestion } from '@/lib/types';
import { useDocumentTitle, useLatest } from '@/lib/util';
import { Button, ErrorState, PageLoading, useConfirm } from '@/ui';
export default function SessionPage() {
const { attemptId = '' } = useParams();
const navigate = useNavigate();
const qc = useQueryClient();
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const { start, starting } = useStartSession();
const query = useQuery({ queryKey: qk.attempt(attemptId), queryFn: () => api.get<{ attempt: Attempt }>(`/api/attempts/${attemptId}`).then((r) => r.attempt), staleTime: Infinity, refetchOnWindowFocus: false });
const attempt = query.data;
useDocumentTitle(attempt?.title);
// Local working copy: the UI never waits for the network.
const [answers, setAnswers] = useState<Record<string, AnswerState>>({});
const [flags, setFlags] = useState<string[]>([]);
const [index, setIndex] = useState(0);
const [finishing, setFinishing] = useState(false);
const loaded = useRef('');
const pending = useRef<{ answers: Record<string, { selected: string[]; checked: boolean }>; flags?: string[]; currentIndex?: number; elapsedSec?: number }>({ answers: {} });
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const inflight = useRef<Promise<unknown>>(Promise.resolve());
const warned = useRef(false);
useEffect(() => {
if (attempt && loaded.current !== attempt.id) {
loaded.current = attempt.id;
setAnswers(attempt.answers);
setFlags(attempt.flags);
setIndex(attempt.currentIndex);
}
}, [attempt]);
const flush = useCallback((): Promise<unknown> => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
const body = pending.current;
if (Object.keys(body.answers).length === 0 && body.flags === undefined && body.currentIndex === undefined && body.elapsedSec === undefined) return inflight.current;
pending.current = { answers: {} };
const payload = { ...body, answers: Object.keys(body.answers).length ? body.answers : undefined };
inflight.current = inflight.current
.then(() => api.patch(`/api/attempts/${attemptId}`, payload))
.then(() => {
warned.current = false;
})
.catch((e) => {
// Put the changes back so the next save retries them.
pending.current = { ...payload, ...pending.current, answers: { ...(payload.answers ?? {}), ...pending.current.answers } };
if (!warned.current) {
warned.current = true;
toast.error(`Progress is not being saved: ${errorMessage(e)}`);
}
});
return inflight.current;
}, [attemptId]);
const queue = useCallback(
(patch: Partial<typeof pending.current>, immediate = false) => {
pending.current = { ...pending.current, ...patch, answers: { ...pending.current.answers, ...(patch.answers ?? {}) } };
if (timer.current) clearTimeout(timer.current);
if (immediate) void flush();
else timer.current = setTimeout(() => void flush(), 500);
},
[flush],
);
const flushRef = useLatest(flush);
useEffect(() => {
const onHide = () => {
if (document.visibilityState === 'hidden') void flushRef.current();
};
document.addEventListener('visibilitychange', onHide);
window.addEventListener('pagehide', onHide);
return () => {
document.removeEventListener('visibilitychange', onHide);
window.removeEventListener('pagehide', onHide);
void flushRef.current();
};
}, [flushRef]);
if (query.isError) {
return (
<div className="pt-20">
<ErrorState title="Session not found" message={errorMessage(query.error)} />
<div className="flex justify-center">
<Button onClick={() => navigate('/')}>Go to Today</Button>
</div>
</div>
);
}
if (!attempt || loaded.current !== attempt.id) return <PageLoading />;
const back = attempt.quizId ? `/quizzes/${attempt.quizId}` : attempt.classId ? `/classes/${attempt.classId}` : '/';
const exit = async () => {
await flush();
void refresh();
navigate(back);
};
const renderExtra = ai.data?.ready
? (q: SnapshotQuestion, selected: string[]) => <Explain body={{ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected, rationale: q.rationale }} />
: undefined;
if (attempt.status === 'completed') {
const missed = attempt.questions.filter((q) => attempt.results && !attempt.results[q.id]?.correct && (attempt.mode === 'exam' || attempt.results[q.id]?.answered)).length;
return (
<QuizResults
title={attempt.title}
mode={attempt.mode}
questions={attempt.questions}
answers={attempt.answers}
flags={attempt.flags}
elapsedSec={attempt.elapsedSec}
sataScoring={attempt.settings.sataScoring}
completedAt={attempt.completedAt}
onExit={() => navigate(back)}
renderExtra={renderExtra}
actions={
<>
{missed > 0 && (
<Button variant="primary" icon={<RotateCcw />} loading={starting} onClick={() => start({ source: { type: 'retake', attemptId: attempt.id } })}>
Redo the {missed} missed
</Button>
)}
{attempt.quizId && (
<Button icon={<RotateCcw />} onClick={() => start({ mode: attempt.mode, source: { type: 'quiz', quizId: attempt.quizId! } })}>
Take it again
</Button>
)}
<Button variant="ghost" icon={<ArrowLeft />} onClick={() => navigate(back)}>
{attempt.quizId ? 'Back to quiz' : 'Done'}
</Button>
<Button
variant="ghost"
icon={<Trash2 />}
className="sm:ml-auto"
onClick={async () => {
if (!(await confirm({ title: 'Delete this attempt?', message: 'It will be removed from your history and statistics.', confirmLabel: 'Delete', danger: true }))) return;
await api.del(`/api/attempts/${attempt.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
navigate(back);
}}
>
Delete attempt
</Button>
</>
}
/>
);
}
const finish = async (elapsedSec: number) => {
setFinishing(true);
try {
await flush();
const res = await api.post<{ attempt: Attempt }>(`/api/attempts/${attempt.id}/complete`, { elapsedSec });
qc.setQueryData(qk.attempt(attempt.id), res.attempt);
void refresh();
window.scrollTo(0, 0);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setFinishing(false);
}
};
return (
<QuizRunner
title={attempt.title}
mode={attempt.mode}
questions={attempt.questions}
answers={answers}
flags={flags}
index={index}
elapsedSec={attempt.elapsedSec}
timeLimitSec={attempt.settings.timeLimitSec}
sataScoring={attempt.settings.sataScoring}
finishing={finishing}
onAnswer={(qid, selected, checked) => {
setAnswers((a) => ({ ...a, [qid]: { selected, checked } }));
queue({ answers: { [qid]: { selected, checked } } }, checked);
}}
onFlags={(next) => {
setFlags(next);
queue({ flags: next });
}}
onIndex={(i) => {
setIndex(i);
queue({ currentIndex: i });
}}
onTick={(elapsedSec) => queue({ elapsedSec })}
onFinish={finish}
onExit={exit}
renderExtra={renderExtra}
/>
);
}

View file

@ -0,0 +1,626 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Brain, Check, Copy, Database, Download, ExternalLink, FileUp, GraduationCap, HardDriveDownload, Layers, Link2, Lock, NotebookPen, RefreshCw, Share2, SlidersHorizontal, Sparkles, Stamp, Trash2, Upload } from 'lucide-react';
import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'react';
import { NavLink, useNavigate, useParams } from 'react-router';
import { toast } from 'sonner';
import { shareUrl } from '@/features/dialogs';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { AppSettings, ShareListItem, Template } from '@/lib/types';
import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util';
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
const AiSettings = lazy(() => import('@/features/AiSettings'));
const TABS = [
{ id: 'study', label: 'Study', icon: <SlidersHorizontal /> },
{ id: 'ai', label: 'AI', icon: <Sparkles /> },
{ id: 'sharing', label: 'Sharing', icon: <Share2 /> },
{ id: 'templates', label: 'Templates', icon: <Stamp /> },
{ id: 'data', label: 'Data and backup', icon: <Database /> },
{ id: 'security', label: 'Security', icon: <Lock /> },
] as const;
type TabId = (typeof TABS)[number]['id'];
interface SettingsResponse {
settings: AppSettings;
system: {
version: string;
node: string;
dataDir: string;
databaseBytes: number;
uploadBytes: number;
maxUploadMb: number;
counts: Record<string, number>;
timezones: string[];
};
}
/* ------------------------------ study ------------------------------ */
function StudySettings() {
const refresh = useRefresh();
const [theme, setTheme] = useTheme();
const q = useQuery({ queryKey: qk.settings, queryFn: () => api.get<SettingsResponse>('/api/settings') });
const [form, setForm] = useState<AppSettings | null>(null);
const [saved, setSaved] = useState(false);
useEffect(() => {
if (q.data && !form) setForm(q.data.settings);
}, [q.data, form]);
if (!q.data || !form) return <Skeleton className="h-80" />;
const save = async (patch: Partial<AppSettings>) => {
const next = { ...form, ...patch };
setForm(next);
try {
await api.put('/api/settings', patch);
setSaved(true);
setTimeout(() => setSaved(false), 1500);
void refresh();
} catch (e) {
toast.error(errorMessage(e));
}
};
return (
<>
<Section title="Appearance">
<div className="card p-4">
<Segmented
label="Theme"
value={theme}
onChange={setTheme}
options={[
{ value: 'light', label: 'Light' },
{ value: 'dark', label: 'Dark' },
{ value: 'system', label: 'Match system' },
]}
/>
</div>
</Section>
<Section title="Flashcards" action={saved ? <span className="flex items-center gap-1 text-xs text-good"><Check className="size-3.5" /> Saved</span> : undefined}>
<div className="card divide-y divide-line">
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
<div>
<div className="text-sm font-medium">New cards per day</div>
<div className="text-[13px] text-ink-3">How many never-seen cards are introduced each day, across all decks. Reviews of cards you already know are never limited.</div>
</div>
<Input type="number" min={0} max={500} value={form.newCardsPerDay} onChange={(e) => setForm({ ...form, newCardsPerDay: Number(e.target.value) })} onBlur={() => save({ newCardsPerDay: Math.max(0, Math.min(500, Math.round(form.newCardsPerDay) || 0)) })} aria-label="New cards per day" />
</div>
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
<div>
<div className="text-sm font-medium">Target retention: {Math.round(form.desiredRetention * 100)}%</div>
<div className="text-[13px] text-ink-3">The chance of remembering a card when it comes back. Higher means more frequent reviews. 90% suits most people; try 93 to 95% before a big exam.</div>
</div>
<input type="range" min={0.8} max={0.97} step={0.01} value={form.desiredRetention} onChange={(e) => setForm({ ...form, desiredRetention: Number(e.target.value) })} onMouseUp={() => save({ desiredRetention: form.desiredRetention })} onTouchEnd={() => save({ desiredRetention: form.desiredRetention })} onKeyUp={() => save({ desiredRetention: form.desiredRetention })} className="w-full accent-[var(--accent)]" aria-label="Target retention" />
</div>
</div>
<p className="mt-2 text-xs text-ink-3">Scheduling uses FSRS, the algorithm behind modern Anki. It adapts each card's interval to how well you remember it.</p>
</Section>
<Section title="Quizzes and goals">
<div className="card divide-y divide-line">
<div className="p-4">
<Switch
checked={form.sataScoring === 'partial'}
onChange={(v) => save({ sataScoring: v ? 'partial' : 'strict' })}
label="Partial credit for select-all-that-apply"
description="On: NCLEX-style scoring, one point per correct choice and minus one per wrong choice, never below zero. Off: all or nothing. Applies to new sessions."
/>
</div>
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
<div>
<div className="text-sm font-medium">Daily goal</div>
<div className="text-[13px] text-ink-3">Cards reviewed plus questions answered that make a day count toward your streak.</div>
</div>
<Input type="number" min={1} max={1000} value={form.dailyGoal} onChange={(e) => setForm({ ...form, dailyGoal: Number(e.target.value) })} onBlur={() => save({ dailyGoal: Math.max(1, Math.min(1000, Math.round(form.dailyGoal) || 1)) })} aria-label="Daily goal" />
</div>
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_260px]">
<div>
<div className="text-sm font-medium">Timezone</div>
<div className="text-[13px] text-ink-3">Decides when a study day starts and ends.</div>
</div>
<Select value={form.timezone} onChange={(e) => save({ timezone: e.target.value })} aria-label="Timezone">
{!q.data.system.timezones.includes(form.timezone) && <option value={form.timezone}>{form.timezone}</option>}
{q.data.system.timezones.map((tz) => (
<option key={tz} value={tz}>
{tz.replace(/_/g, ' ')}
</option>
))}
</Select>
</div>
</div>
</Section>
</>
);
}
/* ------------------------------ sharing ------------------------------ */
const SHARE_ICON: Record<ShareListItem['kind'], ReactNode> = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileUp />, folder: <Link2 />, class: <GraduationCap /> };
function SharingSettings() {
const refresh = useRefresh();
const confirm = useConfirm();
const q = useQuery({ queryKey: qk.shares, queryFn: () => api.get<{ shares: ShareListItem[] }>('/api/shares').then((r) => r.shares) });
const act = async (fn: () => Promise<unknown>, ok?: string) => {
try {
await fn();
await refresh();
if (ok) toast.success(ok);
} catch (e) {
toast.error(errorMessage(e));
}
};
if (!q.data) return <Skeleton className="h-48" />;
const live = q.data.filter((s) => s.enabled).length;
return (
<Section
title={`Public links${q.data.length ? ` · ${live} active` : ''}`}
action={
live > 1 ? (
<Button
size="sm"
variant="ghost"
onClick={async () => {
if (!(await confirm({ title: 'Turn off every link?', message: `${plural(live, 'link')} will stop working until you turn them back on.`, confirmLabel: 'Turn all off', danger: true }))) return;
await act(() => Promise.all(q.data!.filter((s) => s.enabled).map((s) => api.patch(`/api/shares/${s.id}`, { enabled: false }))), 'All links are off');
}}
>
Turn all off
</Button>
) : undefined
}
>
{q.data.length === 0 ? (
<div className="card">
<EmptyState icon={<Share2 />} title="Nothing is shared">
Use "Share" on any quiz, deck, note, folder or class to create a public link. Friends can study without an account, and you can switch a link off at any time.
</EmptyState>
</div>
) : (
<ul className="card divide-y divide-line">
{q.data.map((s) => (
<li key={s.id} className={cx('flex flex-wrap items-center gap-3 px-4 py-3', !s.enabled && 'opacity-60')}>
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-sunken text-ink-2 [&>svg]:size-4">{SHARE_ICON[s.kind]}</span>
<div className="min-w-0 flex-1 basis-48">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{s.title}</span>
<Badge>{s.kind}</Badge>
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-ink-3">
{s.className && s.kind !== 'class' && (
<span className="flex items-center gap-1">
<ClassDot color={s.classColor} className="size-2" /> {s.className}
</span>
)}
<span>{s.viewCount > 0 ? `Opened ${plural(s.viewCount, 'time')}, last ${timeAgo(s.lastViewedAt)}` : 'Never opened'}</span>
</div>
</div>
<div className="flex items-center gap-1">
<IconButton label="Copy link" size="sm" disabled={!s.enabled} onClick={async () => (await copyText(shareUrl(s.token))) && toast.success('Link copied')}>
<Copy />
</IconButton>
<a href={shareUrl(s.token)} target="_blank" rel="noreferrer" aria-label="Open link" className={cx('inline-grid size-8 place-items-center rounded-[9px] text-ink-2 hover:bg-ink/7', !s.enabled && 'pointer-events-none opacity-40')}>
<ExternalLink className="size-[18px]" />
</a>
<IconButton label="Replace with a new link" size="sm" onClick={() => act(() => api.post(`/api/shares/${s.id}/rotate`), 'New link created. The old one no longer works.')}>
<RefreshCw />
</IconButton>
<IconButton label="Delete link" size="sm" onClick={() => act(() => api.del(`/api/shares/${s.id}`), 'Link deleted')}>
<Trash2 />
</IconButton>
<input type="checkbox" role="switch" aria-label={`Link for ${s.title} is ${s.enabled ? 'on' : 'off'}`} checked={s.enabled} onChange={(e) => act(() => api.patch(`/api/shares/${s.id}`, { enabled: e.target.checked }))} className="ml-1.5 size-4 accent-[var(--accent)]" />
</div>
</li>
))}
</ul>
)}
<p className="mt-2.5 text-xs text-ink-3">Visitors can only read and study what a link points to. They cannot edit anything, see other content, or affect your progress. Uploaded documents are shared only when you share the document itself.</p>
</Section>
);
}
/* ------------------------------ templates ------------------------------ */
function TemplateSettings() {
const refresh = useRefresh();
const q = useQuery({ queryKey: qk.templates, queryFn: () => api.get<{ templates: Template[] }>('/api/templates').then((r) => r.templates) });
if (!q.data) return <Skeleton className="h-48" />;
const groups: { kind: Template['kind']; title: string; blurb: string }[] = [
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI.' },
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.' },
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.' },
];
return (
<>
{groups.map((g) => {
const list = q.data!.filter((t) => t.kind === g.kind);
return (
<Section key={g.kind} title={g.title}>
<ul className="card divide-y divide-line">
{list.map((t) => (
<li key={t.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{t.name}</span>
{t.builtin ? <Badge>Built in</Badge> : <Badge tone="accent">Yours</Badge>}
</div>
{t.description && <div className="mt-0.5 line-clamp-2 text-[13px] text-ink-2">{t.description}</div>}
{t.kind !== 'generation' && <div className="mt-0.5 text-xs text-ink-3">{t.kind === 'quiz' ? plural((t.payload.questions ?? []).length, 'question') : plural((t.payload.cards ?? []).length, 'card')}</div>}
</div>
{!t.builtin && (
<IconButton
label="Delete template"
size="sm"
onClick={async () => {
await api.del(`/api/templates/${t.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
>
<Trash2 />
</IconButton>
)}
</li>
))}
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">None yet.</li>}
</ul>
<p className="mt-2 text-xs text-ink-3">{g.blurb}</p>
</Section>
);
})}
</>
);
}
/* ------------------------------ data ------------------------------ */
interface V1Summary {
classes: number;
folders: number;
decks: number;
cards: number;
quizzes: number;
questions: number;
attempts: number;
scheduledCards: number;
activityDays: number;
skipped: string[];
}
function DataSettings() {
const refresh = useRefresh();
const confirm = useConfirm();
const settings = useQuery({ queryKey: qk.settings, queryFn: () => api.get<SettingsResponse>('/api/settings') });
const backups = useQuery({ queryKey: ['backups'], queryFn: () => api.get<{ backups: { name: string; size: number; createdAt: number }[]; directory: string }>('/api/backups') });
const bundleRef = useRef<HTMLInputElement>(null);
const v1Ref = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState('');
const [v1File, setV1File] = useState<File | null>(null);
const [v1Preview, setV1Preview] = useState<V1Summary | null>(null);
const importBundle = async (file: File) => {
setBusy('bundle');
try {
const json = JSON.parse(await file.text());
const res = await api.post<{ summary: { classes: number; quizzes: number; decks: number; notes: number; skipped: string[] } }>('/api/import/bundle', json);
await refresh();
const s = res.summary;
toast.success(`Restored ${plural(s.classes, 'class', 'classes')}, ${plural(s.quizzes, 'quiz', 'quizzes')}, ${plural(s.decks, 'deck')} and ${plural(s.notes, 'note')}${s.skipped.length ? `. ${s.skipped.length} problems skipped.` : ''}`);
} catch (e) {
toast.error(e instanceof SyntaxError ? 'That file is not valid JSON.' : errorMessage(e));
} finally {
setBusy('');
}
};
const v1 = async (file: File, preview: boolean) => {
setBusy(preview ? 'v1preview' : 'v1');
try {
const form = new FormData();
form.append('file', file);
const res = await api.upload<{ summary: V1Summary }>(`/api/import/v1${preview ? '?preview=1' : ''}`, form);
if (preview) {
setV1File(file);
setV1Preview(res.summary);
} else {
await refresh();
setV1File(null);
setV1Preview(null);
toast.success(`Migrated ${plural(res.summary.classes, 'class', 'classes')} from V1`);
}
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy('');
}
};
const sys = settings.data?.system;
return (
<>
<Section title="Export">
<div className="card divide-y divide-line">
<div className="flex flex-wrap items-center gap-3 p-4">
<div className="min-w-0 flex-1 basis-64">
<div className="text-sm font-medium">Everything as JSON</div>
<div className="text-[13px] text-ink-3">All classes with their quizzes, flashcards and notes in one readable file. Portable: import it into another Study Desk. Does not include uploads or progress.</div>
</div>
<Button icon={<Download />} onClick={() => downloadFile('/api/export/all')}>
Export JSON
</Button>
</div>
<div className="flex flex-wrap items-center gap-3 p-4">
<div className="min-w-0 flex-1 basis-64">
<div className="text-sm font-medium">Full backup</div>
<div className="text-[13px] text-ink-3">A zip with the complete database (content, progress, history, settings) and every uploaded file. Use this to move servers or recover from a disaster.</div>
</div>
<Button variant="primary" icon={<HardDriveDownload />} onClick={() => downloadFile('/api/backup/download')}>
Download backup
</Button>
</div>
</div>
</Section>
<Section title="Import">
<div className="card divide-y divide-line">
<div className="flex flex-wrap items-center gap-3 p-4">
<div className="min-w-0 flex-1 basis-64">
<div className="text-sm font-medium">Restore a JSON export</div>
<div className="text-[13px] text-ink-3">Recreates the classes in an "Everything as JSON" file alongside what you already have. To import a single quiz or deck, use Add → Import inside a class.</div>
</div>
<input ref={bundleRef} type="file" accept=".json,application/json" hidden onChange={(e) => (e.target.files?.[0] && importBundle(e.target.files[0]), (e.target.value = ''))} />
<Button icon={<Upload />} loading={busy === 'bundle'} onClick={() => bundleRef.current?.click()}>
Choose file
</Button>
</div>
<div className="p-4">
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1 basis-64">
<div className="text-sm font-medium">Migrate from Study Desk V1</div>
<div className="text-[13px] text-ink-3">
Upload the V1 database file (<code className="num text-[12px]">study.db</code> from the old container's data folder). Classes, groups, decks, quizzes, attempt history, flashcard schedules and your activity are copied in. The V1 file is only read, never changed.
</div>
</div>
<input ref={v1Ref} type="file" accept=".db,.sqlite,.sqlite3,application/octet-stream" hidden onChange={(e) => (e.target.files?.[0] && v1(e.target.files[0], true), (e.target.value = ''))} />
<Button icon={<Upload />} loading={busy === 'v1preview'} onClick={() => v1Ref.current?.click()}>
Choose study.db
</Button>
</div>
{v1Preview && v1File && (
<Callout tone="accent" className="mt-3" title={`Found in ${v1File.name}`}>
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 text-[13px] sm:grid-cols-3">
<span>{plural(v1Preview.classes, 'class', 'classes')}</span>
<span>{plural(v1Preview.folders, 'group')} → folders</span>
<span>{plural(v1Preview.quizzes, 'quiz', 'quizzes')} · {plural(v1Preview.questions, 'question')}</span>
<span>{plural(v1Preview.decks, 'deck')} · {plural(v1Preview.cards, 'card')}</span>
<span>{plural(v1Preview.attempts, 'quiz attempt')}</span>
<span>{plural(v1Preview.scheduledCards, 'card schedule')}</span>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<Button
size="sm"
variant="primary"
loading={busy === 'v1'}
onClick={async () => {
if (await confirm({ title: 'Migrate this V1 data?', message: 'Everything listed is added as new classes. A snapshot of the current database is taken first. Running the migration twice creates duplicates.', confirmLabel: 'Migrate' })) void v1(v1File, false);
}}
>
Migrate now
</Button>
<Button size="sm" variant="ghost" onClick={() => (setV1Preview(null), setV1File(null))}>
Cancel
</Button>
</div>
</Callout>
)}
</div>
</div>
</Section>
<Section
title="Database snapshots"
action={
<Button
size="sm"
variant="ghost"
icon={<FileUp />}
loading={busy === 'snap'}
onClick={async () => {
setBusy('snap');
await api.post('/api/backups').then(() => toast.success('Snapshot saved')).catch((e) => toast.error(errorMessage(e)));
setBusy('');
void backups.refetch();
}}
>
Snapshot now
</Button>
}
>
<div className="card">
{!backups.data ? (
<Skeleton className="m-4 h-16" />
) : backups.data.backups.length === 0 ? (
<p className="px-4 py-4 text-[13px] text-ink-2">No snapshots yet. One is written automatically each day once you have content, and before every upgrade that changes the database.</p>
) : (
<ul className="max-h-72 divide-y divide-line overflow-y-auto">
{backups.data.backups.map((b) => (
<li key={b.name} className="flex items-center gap-3 px-4 py-2.5">
<div className="min-w-0 flex-1">
<div className="num truncate text-[13px] font-medium">{b.name}</div>
<div className="text-xs text-ink-3">
{formatDateTime(b.createdAt)} · {formatBytes(b.size)}
</div>
</div>
<IconButton label={`Download ${b.name}`} size="sm" onClick={() => downloadFile(`/api/backups/${encodeURIComponent(b.name)}`)}>
<Download />
</IconButton>
</li>
))}
</ul>
)}
</div>
<p className="mt-2 text-xs text-ink-3">
Snapshots live in <code className="num">{backups.data?.directory ?? 'data/backups'}</code> on the server. Include your data folder in your Unraid backups to keep them off the machine too.
</p>
</Section>
{sys && (
<Section title="About this installation">
<dl className="card grid grid-cols-2 gap-x-6 gap-y-3 p-4 text-[13px] sm:grid-cols-4">
{[
['Version', sys.version],
['Database', formatBytes(sys.databaseBytes)],
['Uploads', formatBytes(sys.uploadBytes)],
['Upload limit', `${sys.maxUploadMb} MB per file`],
['Classes', sys.counts.classes],
['Questions', sys.counts.questions],
['Flashcards', sys.counts.cards],
['Documents', sys.counts.documents],
].map(([k, v]) => (
<div key={k as string}>
<dt className="text-ink-3">{k}</dt>
<dd className="num mt-0.5 font-medium">{typeof v === 'number' ? v.toLocaleString() : v}</dd>
</div>
))}
</dl>
</Section>
)}
</>
);
}
/* ------------------------------ security ------------------------------ */
function SecuritySettings() {
const [current, setCurrent] = useState('');
const [next, setNext] = useState('');
const [confirmPw, setConfirmPw] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const sessions = useQuery({ queryKey: ['sessions'], queryFn: () => api.get<{ sessions: { id: string; createdAt: number; lastSeenAt: number; userAgent: string; ip: string; current: boolean }[] }>('/api/auth/sessions').then((r) => r.sessions) });
const change = async (e: React.FormEvent) => {
e.preventDefault();
if (next.length < 8) return setError('Use at least 8 characters.');
if (next !== confirmPw) return setError('The new passwords do not match.');
setBusy(true);
setError('');
try {
await api.post('/api/auth/password', { current, next });
setCurrent('');
setNext('');
setConfirmPw('');
toast.success('Password changed. Other devices were signed out.');
void sessions.refetch();
} catch (err) {
setError(errorMessage(err));
} finally {
setBusy(false);
}
};
const device = (ua: string) => {
const os = /iPhone|iPad/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'Unknown device';
const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser';
return `${browser} on ${os}`;
};
return (
<>
<Section title="Change password">
<form onSubmit={change} className="card max-w-md space-y-4 p-4">
<Field label="Current password">
<Input type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} required />
</Field>
<Field label="New password" hint="At least 8 characters.">
<Input type="password" autoComplete="new-password" value={next} onChange={(e) => setNext(e.target.value)} required minLength={8} />
</Field>
<Field label="Confirm new password" error={error || undefined}>
<Input type="password" autoComplete="new-password" value={confirmPw} onChange={(e) => setConfirmPw(e.target.value)} required />
</Field>
<Button type="submit" variant="primary" loading={busy}>
Change password
</Button>
</form>
<p className="mt-2 max-w-md text-xs text-ink-3">Forgot it? Set the RESET_ADMIN_PASSWORD environment variable on the container, restart once, then remove it.</p>
</Section>
<Section
title="Signed-in devices"
action={
(sessions.data?.length ?? 0) > 1 ? (
<Button
size="sm"
variant="ghost"
onClick={async () => {
await api.post('/api/auth/sessions/revoke-others').then(() => toast.success('Other devices signed out')).catch((e) => toast.error(errorMessage(e)));
void sessions.refetch();
}}
>
Sign out the others
</Button>
) : undefined
}
>
<ul className="card divide-y divide-line">
{(sessions.data ?? []).map((s) => (
<li key={s.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 text-sm font-medium">
{device(s.userAgent)}
{s.current && <Badge tone="good">This device</Badge>}
</div>
<div className="text-xs text-ink-3">
Active {timeAgo(s.lastSeenAt)} · signed in {timeAgo(s.createdAt)}
{s.ip && s.ip !== 'unknown' ? ` · ${s.ip}` : ''}
</div>
</div>
</li>
))}
</ul>
</Section>
</>
);
}
/* ------------------------------ page ------------------------------ */
export default function SettingsPage() {
const { tab } = useParams();
const navigate = useNavigate();
const active = (TABS.find((t) => t.id === tab)?.id ?? 'study') as TabId;
useDocumentTitle('Settings');
useEffect(() => {
if (tab && !TABS.some((t) => t.id === tab)) navigate('/settings', { replace: true });
}, [tab, navigate]);
return (
<div className="animate-in">
<PageHeader title="Settings" />
<div className="grid gap-x-10 gap-y-5 lg:grid-cols-[190px_1fr]">
<nav aria-label="Settings sections" className="-mx-4 flex gap-1 overflow-x-auto px-4 pb-1 lg:mx-0 lg:flex-col lg:overflow-visible lg:px-0">
{TABS.map((t) => (
<NavLink
key={t.id}
to={t.id === 'study' ? '/settings' : `/settings/${t.id}`}
end
className={() => cx('flex h-9 shrink-0 items-center gap-2.5 rounded-[9px] px-3 text-sm font-medium whitespace-nowrap [&>svg]:size-4', active === t.id ? 'bg-ink text-paper lg:bg-ink/8 lg:text-ink' : 'text-ink-2 hover:bg-ink/5 hover:text-ink')}
>
{t.icon}
{t.label}
</NavLink>
))}
</nav>
<div className="min-w-0">
{active === 'study' && <StudySettings />}
{active === 'ai' && (
<Suspense fallback={<PageLoading />}>
<AiSettings />
</Suspense>
)}
{active === 'sharing' && <SharingSettings />}
{active === 'templates' && <TemplateSettings />}
{active === 'data' && <DataSettings />}
{active === 'security' && <SecuritySettings />}
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,402 @@
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun } from 'lucide-react';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
import { QuizResults, QuizRunner } from '@/features/quiz';
import { api, ApiError } from '@/lib/api';
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useTheme } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, EmptyState, IconButton, PageLoading, Switch } from '@/ui';
/* ------------------------------ frame ------------------------------ */
function Frame({ children, back }: { children: ReactNode; back?: { to: string; label: string } }) {
const [, setTheme] = useTheme();
const dark = document.documentElement.dataset.theme === 'dark';
return (
<div className="min-h-dvh">
<header className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-4 sm:px-5">
{back ? (
<Link to={back.to} className="-ml-2 flex h-9 items-center gap-1.5 rounded-lg px-2 text-sm font-medium text-ink-2 hover:bg-ink/6 hover:text-ink">
<ArrowLeft className="size-4" /> {back.label}
</Link>
) : (
<div className="flex items-center gap-2">
<img src="/icon.svg" alt="" className="size-7 rounded-lg" />
<span className="display text-[18px]">Study Desk</span>
</div>
)}
<div className="flex-1" />
<IconButton label={dark ? 'Switch to light theme' : 'Switch to dark theme'} onClick={() => setTheme(dark ? 'light' : 'dark')}>
{dark ? <Sun /> : <Moon />}
</IconButton>
</header>
<main className="mx-auto max-w-3xl animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8">{children}</main>
<footer className="pb-8 text-center text-xs text-ink-3">Shared with Study Desk. Your progress is saved in this browser only.</footer>
</div>
);
}
function Unavailable() {
return (
<div className="grid min-h-dvh place-items-center px-6">
<EmptyState icon={<Link2Off />} title="This link is no longer available">
The owner may have turned sharing off or replaced the link. Ask them for a new one.
</EmptyState>
</div>
);
}
/* ------------------------------ quiz ------------------------------ */
interface QuizState {
mode: 'practice' | 'exam';
order: string[];
optionOrder: Record<string, string[]>;
answers: Record<string, AnswerState>;
flags: string[];
index: number;
elapsed: number;
done: boolean;
}
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, only?: string[]): QuizState {
const seed = (Math.random() * 2 ** 32) >>> 0;
let ids = quiz.questions.map((q) => q.id).filter((id) => !only || only.includes(id));
if (shuffleQ) ids = seededShuffle(ids, seed);
const optionOrder: Record<string, string[]> = {};
quiz.questions.forEach((q, i) => {
const optionIds = q.options.map((o) => o.id);
optionOrder[q.id] = shuffleO ? seededShuffle(optionIds, seed + i + 1) : optionIds;
});
return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false };
}
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
const [state, setState] = useLocalStorage<QuizState | null>(storageKey, null);
const [prefs, setPrefs] = useLocalStorage('sd.pub.prefs', { mode: 'practice' as 'practice' | 'exam', shuffleQ: true, shuffleO: true });
const [running, setRunning] = useState(false);
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
const questions = useMemo<SnapshotQuestion[]>(() => {
if (!state) return [];
const byId = new Map(quiz.questions.map((q) => [q.id, q]));
return state.order
.map((id) => byId.get(id))
.filter((q): q is SnapshotQuestion => Boolean(q))
.map((q) => {
const order = state.optionOrder[q.id] ?? [];
const sorted = [...q.options].sort((a, b) => (order.indexOf(a.id) + 1 || 99) - (order.indexOf(b.id) + 1 || 99));
return { ...q, options: sorted };
});
}, [quiz, state]);
const begin = (only?: string[]) => {
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, only));
setRunning(true);
window.scrollTo(0, 0);
};
if (state && questions.length > 0 && state.done) {
const missed = questions.filter((q) => !isFullyCorrect(scoreQuestion(q, state.answers[q.id]?.selected ?? [])) && (state.mode === 'exam' || (state.answers[q.id]?.selected.length ?? 0) > 0)).map((q) => q.id);
return (
<QuizResults
title={quiz.title}
mode={state.mode}
questions={questions}
answers={state.answers}
flags={state.flags}
elapsedSec={state.elapsed}
sataScoring="partial"
onExit={() => (setState(null), setRunning(false))}
exitLabel="Back to start"
footnote="This result is stored in your browser only. The person who shared the quiz cannot see it."
actions={
<>
{missed.length > 0 && (
<Button variant="primary" icon={<RotateCcw />} onClick={() => begin(missed)}>
Redo the {missed.length} missed
</Button>
)}
<Button icon={<RotateCcw />} onClick={() => begin()}>
Take it again
</Button>
</>
}
/>
);
}
if (state && questions.length > 0 && running) {
return (
<QuizRunner
title={quiz.title}
mode={state.mode}
questions={questions}
answers={state.answers}
flags={state.flags}
index={state.index}
elapsedSec={state.elapsed}
timeLimitSec={null}
sataScoring="partial"
exitLabel="Pause"
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
onFlags={(flags) => setState((s) => (s ? { ...s, flags } : s))}
onIndex={(index) => setState((s) => (s ? { ...s, index } : s))}
onTick={(elapsed) => setState((s) => (s ? { ...s, elapsed } : s))}
onFinish={(elapsed) => {
setState((s) => (s ? { ...s, elapsed, done: true } : s));
window.scrollTo(0, 0);
}}
onExit={() => setRunning(false)}
/>
);
}
const inProgress = state && questions.length > 0 && !state.done;
const answered = inProgress ? Object.values(state.answers).filter((a) => a.selected.length > 0).length : 0;
return (
<Frame back={back}>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<BookOpen className="size-3.5" /> Shared quiz
</div>
<h1 className="display text-[32px] sm:text-[40px]">{quiz.title}</h1>
{quiz.description && <p className="mt-2 text-[15px] text-ink-2">{quiz.description}</p>}
<p className="mt-2 text-sm text-ink-3">{plural(quiz.questions.length, 'question')}</p>
{quiz.questions.length === 0 ? (
<div className="card mt-6 p-6 text-sm text-ink-2">This quiz has no questions yet.</div>
) : (
<div className="card mt-6 p-5 sm:p-6">
{inProgress && (
<div className="mb-5 flex flex-wrap items-center gap-3 rounded-xl bg-accent-soft p-3.5">
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">You have a session in progress</div>
<div className="text-[13px] text-ink-2">
{answered} of {questions.length} answered
</div>
</div>
<Button variant="primary" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
Resume
</Button>
</div>
)}
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
{(
[
{ v: 'practice', t: 'Practice', b: 'See the answer and rationale after each question.' },
{ v: 'exam', t: 'Exam', b: 'Answers and score are shown at the end.' },
] as const
).map((m) => (
<button key={m.v} type="button" role="radio" aria-checked={prefs.mode === m.v} onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))} className={cx('rounded-xl border p-3.5 text-left', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}>
<div className="font-semibold">{m.t}</div>
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.b}</div>
</button>
))}
</div>
<div className="mt-4 space-y-3.5">
<Switch checked={prefs.shuffleQ} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQ: v }))} label="Shuffle questions" />
<Switch checked={prefs.shuffleO} onChange={(v) => setPrefs((p) => ({ ...p, shuffleO: v }))} label="Shuffle answer choices" />
</div>
<Button variant={inProgress ? 'secondary' : 'primary'} size="lg" block className="mt-5" icon={<Play className="fill-current" />} onClick={() => begin()}>
{inProgress ? 'Start over' : 'Start'}
</Button>
</div>
)}
</Frame>
);
}
/* ------------------------------ deck ------------------------------ */
function SharedDeck({ deck, storageKey, back }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string } }) {
const [saved, setSaved] = useLocalStorage<CramState | null>(storageKey, null);
const [running, setRunning] = useState(false);
const state = useMemo(() => reconcileCramState(saved, deck.cards), [saved, deck.cards]);
if (running && state) {
return <CramSession title={deck.title} subtitle="Shared flashcards" cards={deck.cards} state={state} onState={setSaved} onExit={() => setRunning(false)} exitLabel="Pause" />;
}
const seen = state ? Math.min(state.index, state.order.length) : 0;
return (
<Frame back={back}>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<Layers className="size-3.5" /> Shared flashcards
</div>
<h1 className="display text-[32px] sm:text-[40px]">{deck.title}</h1>
{deck.description && <p className="mt-2 text-[15px] text-ink-2">{deck.description}</p>}
<p className="mt-2 text-sm text-ink-3">{plural(deck.cards.length, 'card')}</p>
{deck.cards.length === 0 ? (
<div className="card mt-6 p-6 text-sm text-ink-2">This deck has no cards yet.</div>
) : (
<>
<div className="mt-6 flex flex-wrap gap-2">
{state && seen > 0 && seen < state.order.length && (
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
Continue ({seen}/{state.order.length})
</Button>
)}
<Button
variant={state && seen > 0 && seen < state.order.length ? 'secondary' : 'primary'}
size="lg"
icon={<Play className="fill-current" />}
onClick={() => {
setSaved(freshCramState(deck.cards, false));
setRunning(true);
}}
>
Study in order
</Button>
<Button
size="lg"
onClick={() => {
setSaved(freshCramState(deck.cards, true));
setRunning(true);
}}
>
Shuffle
</Button>
</div>
<h2 className="eyebrow mt-8 mb-2.5">All cards</h2>
<ul className="card divide-y divide-line">
{deck.cards.map((c) => (
<li key={c.id} className="grid gap-x-5 gap-y-1 px-4 py-3 sm:grid-cols-2">
<Markdown className="text-[14.5px] font-medium">{c.front}</Markdown>
<Markdown className="text-[14.5px] text-ink-2">{c.back}</Markdown>
</li>
))}
</ul>
</>
)}
</Frame>
);
}
/* ------------------------------ note, document, collection ------------------------------ */
function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; label: string } }) {
return (
<Frame back={back}>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<NotebookPen className="size-3.5" /> Shared note
</div>
<h1 className="display mb-6 text-[32px] sm:text-[40px]">{note.title}</h1>
<article className="card px-5 py-6 sm:px-10 sm:py-9">
<Markdown serif>{note.content || '*This note is empty.*'}</Markdown>
</article>
</Frame>
);
}
function SharedDocument({ doc, token }: { doc: PublicDocument; token: string }) {
const url = `/api/public/${token}/file`;
const inline = doc.docKind === 'pdf' || doc.docKind === 'image';
return (
<Frame>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<FileText className="size-3.5" /> Shared document
</div>
<h1 className="display text-[30px] sm:text-[36px]">{doc.title}</h1>
<p className="mt-2 text-sm text-ink-3">
{doc.filename} · {formatBytes(doc.size)}
{doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
</p>
<a href={url} download={inline ? undefined : doc.filename} target={inline ? '_blank' : undefined} rel="noreferrer" className="mt-5 inline-block">
<Button variant="primary" size="lg" icon={<Download />}>
{inline ? 'Open file' : 'Download'}
</Button>
</a>
{doc.docKind === 'image' && <img src={url} alt={doc.title} className="card mt-6 max-w-full p-2" />}
{doc.docKind === 'pdf' && <iframe src={url} title={doc.title} className="card mt-6 hidden h-[78vh] w-full sm:block" />}
</Frame>
);
}
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
function SharedCollection({ data, token }: { data: PublicCollection; token: string }) {
const groups = [{ id: null as string | null, name: '' }, ...data.folders].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0);
return (
<Frame>
<div className={cx('border-l-[5px] border-tab pl-4', `tab-${data.color}`)}>
<div className="eyebrow mb-1">{data.subtitle || 'Shared collection'}</div>
<h1 className="display text-[32px] sm:text-[40px]">{data.title}</h1>
{data.description && <p className="mt-2 text-[15px] text-ink-2">{data.description}</p>}
</div>
{groups.length === 0 ? (
<div className="card mt-8 p-6 text-sm text-ink-2">Nothing has been added here yet.</div>
) : (
groups.map((g) => (
<section key={g.id ?? 'none'} className="mt-7">
{g.name && <h2 className="eyebrow mb-2.5">{g.name}</h2>}
<ul className="card divide-y divide-line overflow-hidden">
{g.items.map((i) => (
<li key={`${i.kind}:${i.id}`}>
<Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{i.title}</span>
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : 'Note'}</span>
</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
</li>
))}
</ul>
</section>
))
)}
</Frame>
);
}
/* ------------------------------ page ------------------------------ */
export default function SharedPage() {
const { token = '', kind, itemId } = useParams();
const navigate = useNavigate();
const nested = Boolean(kind && itemId);
const q = useQuery({
queryKey: ['public', token, kind ?? '', itemId ?? ''],
queryFn: ({ signal }) => api.pub<PublicPayload>(nested ? `/api/public/${token}/items/${kind}/${itemId}` : `/api/public/${token}`, signal),
retry: (count, error) => !(error instanceof ApiError && error.status === 404) && count < 2,
staleTime: 60_000,
});
const data = q.data;
useDocumentTitle(data?.title);
useEffect(() => {
// A nested URL whose parent is not a collection makes no sense; send it to the root link.
if (q.isError && nested && q.error instanceof ApiError && q.error.status === 404) navigate(`/s/${token}`, { replace: true });
}, [q.isError, q.error, nested, navigate, token]);
if (q.isLoading) return <PageLoading />;
if (q.isError || !data) {
if (q.error instanceof ApiError && q.error.status !== 404) {
return (
<div className="grid min-h-dvh place-items-center px-6">
<EmptyState title="Could not load this page" action={<Button onClick={() => q.refetch()}>Try again</Button>}>
Check your connection and try again.
</EmptyState>
</div>
);
}
return <Unavailable />;
}
const back = nested ? { to: `/s/${token}`, label: 'All materials' } : undefined;
const key = `sd.pub.${token.slice(0, 12)}.${data.kind}.${'id' in data ? data.id : ''}`;
switch (data.kind) {
case 'quiz':
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} />;
case 'deck':
return <SharedDeck key={key} deck={data} storageKey={key} back={back} />;
case 'note':
return <SharedNote note={data} back={back} />;
case 'document':
return <SharedDocument doc={data} token={token} />;
case 'collection':
return <SharedCollection data={data} token={token} />;
}
}