Add drag reordering, exam deadlines, frozen shared quizzes, batched OCR and semantic search
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 33s

- Drag-to-reorder for class materials, folders, quiz questions and deck cards. Pointer-based
  so touch works, plus keyboard (arrows/Home/End) with screen-reader announcements.
- Timed exams get a wall-clock deadline. The server refuses late answers, submits overdue
  exams with what was saved, and the countdown keeps running while the page is closed.
- Shared quiz sessions keep a frozen copy of their questions and flag later owner edits.
- Scanned PDFs are read in cached 8-page batches with real page numbers (pdf-lib), removing
  the 30 MB whole-file limit. Compatible providers now receive PDFs as file parts.
- Semantic search: embeddings for OpenAI, Gemini, Ollama and compatible servers, background
  indexing into chunk_vectors (migration 2), hybrid keyword + vector ranking for search, the
  assistant and focused generation, and a Settings -> AI section.

181 tests pass locally and in the Docker test stage on Node 24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-12 11:48:20 -07:00
parent 3046e46d1c
commit ccdad9728b
39 changed files with 1772 additions and 121 deletions

View file

@ -177,7 +177,7 @@ function CommandPalette({ open, onOpenChange, onNewClass }: { open: boolean; onO
key: `${h.kind}:${h.id}`,
icon: HIT_ICON[h.kind],
title: h.title,
meta: HIT_LABEL[h.kind],
meta: h.semantic ? 'Related passage' : HIT_LABEL[h.kind],
sub: [h.snippet, h.kind !== 'class' ? h.className : ''].filter(Boolean).join(' · '),
color: h.classColor,
run: go(hitUrl(h)),

View file

@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk } from '@/lib/queries';
import { SemanticSettings } from './SemanticSettings';
import type { AdapterMeta, AiModel, AiStatus, Provider, ProviderKind, TaskConfig, TaskName, TaskSettings } from '@/lib/types';
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui';
@ -698,6 +699,8 @@ export default function AiSettings() {
</Section>
)}
{providers.data.length > 0 && <SemanticSettings providers={providers.data} />}
{providers.data.length > 0 && <Usage />}
<ProviderDialog open={dialog.open} onClose={() => setDialog((d) => ({ ...d, open: false }))} adapters={meta.data.adapters} existing={dialog.existing} onSaved={afterSave} />

View file

@ -0,0 +1,180 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { CircleAlert, RefreshCw, Sparkles, Zap } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import type { Provider, ProviderKind } from '@/lib/types';
import { plural } from '@/lib/util';
import { Badge, Button, Callout, Field, Input, ProgressBar, Section, Select, useConfirm } from '@/ui';
interface EmbeddingStatus {
settings: { providerId: string | null; model: string; dimensions: number | null };
configured: boolean;
indexed: number;
total: number;
running: boolean;
lastError: string;
defaults: Record<ProviderKind, string | null>;
}
const KEY = ['ai', 'embeddings'];
/**
* Semantic search settings: which provider and embedding model turn document passages into
* vectors, and how far indexing has got.
*/
export function SemanticSettings({ providers }: { providers: Provider[] }) {
const qc = useQueryClient();
const confirm = useConfirm();
const q = useQuery({
queryKey: KEY,
queryFn: () => api.get<EmbeddingStatus>('/api/ai/embeddings'),
// Poll while indexing so the progress bar moves.
refetchInterval: (query) => (query.state.data?.running ? 1500 : false),
});
const data = q.data;
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.enabled);
const [providerId, setProviderId] = useState('');
const [model, setModel] = useState('');
const [dimensions, setDimensions] = useState('');
const [busy, setBusy] = useState<'save' | 'test' | 'rebuild' | null>(null);
useEffect(() => {
if (!data) return;
setProviderId(data.settings.providerId ?? '');
setModel(data.settings.model);
setDimensions(data.settings.dimensions ? String(data.settings.dimensions) : '');
}, [data]);
if (!data) return null;
const chosen = providers.find((p) => p.id === providerId);
const suggested = chosen ? data.defaults[chosen.kind] : null;
const dirty = providerId !== (data.settings.providerId ?? '') || model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : '');
const reload = () => qc.invalidateQueries({ queryKey: KEY });
const save = async () => {
if (data.configured && data.indexed > 0 && providerId && (providerId !== data.settings.providerId || model.trim() !== data.settings.model)) {
const ok = await confirm({ title: 'Switch embedding model?', message: `Vectors from different models cannot be mixed, so all ${plural(data.indexed, 'passage')} will be indexed again with the new model.`, confirmLabel: 'Switch and re-index' });
if (!ok) return;
}
setBusy('save');
try {
await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId ? model.trim() : '', dimensions: dimensions ? Number(dimensions) : null });
toast.success(providerId ? 'Semantic search is on. Indexing your documents…' : 'Semantic search is off');
await reload();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
}
};
const test = async () => {
setBusy('test');
try {
const r = await api.post<{ dimensions: number; latencyMs: number }>('/api/ai/embeddings/test');
toast.success(`Working: ${r.dimensions}-dimension vectors in ${r.latencyMs} ms`);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
}
};
const act = async (path: 'rebuild' | 'resume') => {
if (path === 'rebuild' && !(await confirm({ title: 'Rebuild the index?', message: 'Every passage is embedded again. This repeats the embedding cost.', confirmLabel: 'Rebuild' }))) return;
setBusy('rebuild');
try {
await api.post(`/api/ai/embeddings/${path}`);
await reload();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
}
};
const pct = data.total > 0 ? data.indexed / data.total : 0;
return (
<Section
title="Semantic search"
action={data.configured ? <Badge tone={data.indexed >= data.total ? 'good' : 'accent'}>{data.indexed >= data.total ? 'On' : 'Indexing'}</Badge> : <Badge>Off</Badge>}
>
<div className="card p-4 sm:p-5">
<p className="text-sm text-ink-2">
Finds passages by meaning as well as by words, so "why do patients on Lasix need bananas?" finds the section on furosemide and potassium. Used by search, the assistant and
focused generation. Keyword search keeps working without it.
</p>
{eligible.length === 0 ? (
<Callout tone="accent" icon={<Sparkles />} className="mt-4" title="Needs an embeddings provider">
Connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic does not offer embeddings.
</Callout>
) : (
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
<Field label="Provider">
<Select
value={providerId}
onChange={(e) => {
const next = providers.find((p) => p.id === e.target.value);
setProviderId(e.target.value);
if (next && (!model || !dirty)) setModel(data.defaults[next.kind] ?? '');
}}
>
<option value="">Off (keywords only)</option>
{eligible.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</Select>
</Field>
<Field label="Embedding model" hint={suggested ? `Suggested: ${suggested}` : chosen ? 'The model id your server uses for embeddings' : undefined}>
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId} />
</Field>
<Field label="Size" hint="Optional">
<Input type="number" min={64} max={4096} step={64} value={dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId} className="sm:w-28" />
</Field>
</div>
)}
{eligible.length > 0 && (
<div className="mt-3 flex flex-wrap gap-2">
<Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !model.trim())} loading={busy === 'save'} onClick={save}>
Save
</Button>
{data.configured && !dirty && (
<Button size="sm" icon={<Zap />} loading={busy === 'test'} onClick={test}>
Test
</Button>
)}
</div>
)}
{data.configured && (
<div className="mt-5 border-t border-line pt-4">
<div className="flex items-center justify-between gap-3 text-[13px]">
<span className="text-ink-2">
<span className="num font-medium text-ink">{data.indexed.toLocaleString()}</span> of <span className="num">{data.total.toLocaleString()}</span> passages indexed
{data.running ? ' · working…' : ''}
</span>
<span className="flex gap-1">
{!data.running && data.indexed < data.total && (
<Button size="sm" variant="ghost" loading={busy === 'rebuild'} onClick={() => act('resume')}>
Continue
</Button>
)}
<Button size="sm" variant="ghost" icon={<RefreshCw />} disabled={data.running} loading={busy === 'rebuild'} onClick={() => act('rebuild')}>
Rebuild
</Button>
</span>
</div>
<ProgressBar value={pct} className="mt-2" label="Indexing progress" />
{data.lastError && (
<Callout tone="warn" icon={<CircleAlert />} className="mt-3" title="Indexing paused">
{data.lastError}
</Callout>
)}
</div>
)}
</div>
<p className="mt-2 text-xs text-ink-3">Embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage. Local Ollama models are free.</p>
</Section>
);
}

View file

@ -110,6 +110,11 @@ export interface RunnerProps {
index: number;
elapsedSec: number;
timeLimitSec: number | null;
/**
* Fixed end time on this device's clock. When set, the countdown follows the wall clock
* and keeps running while the page is hidden or closed. Without it the clock pauses.
*/
deadlineAt?: number | null;
sataScoring: SataScoring;
onAnswer: (questionId: string, selected: string[], checked: boolean) => void;
onFlags: (flags: string[]) => void;
@ -131,7 +136,6 @@ export function QuizRunner(p: RunnerProps) {
const topRef = useRef<HTMLDivElement>(null);
const tick = useLatest(p.onTick);
const finish = useLatest(p.onFinish);
const elapsedRef = useLatest(elapsed);
const autoSubmitted = useRef(false);
const total = p.questions.length;
@ -156,24 +160,36 @@ export function QuizRunner(p: RunnerProps) {
}
return n > 0 ? { n, points, percent: Math.round((points / n) * 100) } : null;
}, [p.mode, p.questions, p.answers, p.sataScoring]);
const remaining = p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
const [wallNow, setWallNow] = useState(() => Date.now());
const deadline = p.deadlineAt && p.timeLimitSec !== null ? p.deadlineAt : null;
const remaining = deadline !== null ? Math.max(0, Math.ceil((deadline - wallNow) / 1000)) : p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
// Time used: wall clock for deadline exams, otherwise the active-study clock.
const clock = deadline !== null && p.timeLimitSec !== null ? Math.max(elapsed, p.timeLimitSec - (remaining ?? 0)) : elapsed;
const clockRef = useLatest(clock);
// Session clock: pauses while the tab is hidden.
useEffect(() => {
const timer = setInterval(() => {
setWallNow(Date.now());
// The untimed/legacy clock pauses while the tab is hidden.
if (document.visibilityState === 'visible') setElapsed((e) => e + 1);
}, 1000);
return () => clearInterval(timer);
// Catch up immediately when returning to a deadline exam.
const onVisible = () => document.visibilityState === 'visible' && setWallNow(Date.now());
document.addEventListener('visibilitychange', onVisible);
return () => {
clearInterval(timer);
document.removeEventListener('visibilitychange', onVisible);
};
}, []);
useEffect(() => {
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(elapsed);
}, [elapsed, tick]);
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(clockRef.current);
}, [elapsed, tick, clockRef]);
useEffect(() => {
if (remaining === 0 && !p.finishing && !autoSubmitted.current) {
autoSubmitted.current = true;
finish.current(elapsedRef.current);
finish.current(clockRef.current);
}
}, [remaining, p.finishing, finish, elapsedRef]);
}, [remaining, p.finishing, finish, clockRef]);
useEffect(() => {
topRef.current?.scrollIntoView({ block: 'start' });
}, [index]);
@ -197,7 +213,7 @@ export function QuizRunner(p: RunnerProps) {
);
if (!ok) return;
}
p.onFinish(elapsed);
p.onFinish(clock);
};
const primary = () => {
@ -248,7 +264,7 @@ export function QuizRunner(p: RunnerProps) {
)}
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}>
<Clock className="size-3.5" />
{formatDuration(remaining ?? elapsed)}
{formatDuration(remaining ?? clock)}
</div>
<button type="button" onClick={() => setNavOpen(true)} className="num flex h-9 items-center gap-1.5 rounded-[9px] border border-line-strong bg-surface px-2.5 text-[13px] font-medium shadow-1 hover:border-ink-3" aria-label="Question navigator">
<LayoutGrid className="size-3.5 text-ink-3" />

View file

@ -31,6 +31,7 @@ interface ItemBase {
title: string;
description: string;
folderId: string | null;
sortOrder: number;
createdAt: number;
updatedAt: number;
shared: boolean;
@ -147,7 +148,9 @@ export interface Attempt {
mode: 'practice' | 'exam';
kind: string;
status: 'active' | 'completed';
settings: { shuffleQuestions: boolean; shuffleOptions: boolean; timeLimitSec: number | null; sataScoring: 'partial' | 'strict' };
settings: { shuffleQuestions: boolean; shuffleOptions: boolean; timeLimitSec: number | null; sataScoring: 'partial' | 'strict'; deadlineAt?: number | null };
/** Server clock (epoch ms) when this was produced. */
serverNow: number;
questions: SnapshotQuestion[];
answers: Record<string, AnswerState>;
flags: string[];
@ -321,6 +324,8 @@ export interface SearchHit {
classColor: ClassColor;
parentId?: string;
page?: number | null;
/** Found by meaning (semantic search) rather than by matching words. */
semantic?: boolean;
}
export interface ShareListItem extends Share {

View file

@ -12,6 +12,7 @@ import {
Folder as FolderIcon,
FolderInput,
FolderPlus,
GripVertical,
Layers,
MoreHorizontal,
NotebookPen,
@ -40,6 +41,7 @@ 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 { SortableList, type SortableRenderProps } from '@/ui/Sortable';
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';
@ -117,7 +119,7 @@ export default function ClassPage() {
const [filter, setFilter] = useState<Filter>('all');
const [query, setQuery] = useState('');
const [sort, setSort] = useLocalStorage<'recent' | 'title'>('sd.classSort', 'recent');
const [sort, setSort] = useLocalStorage<'manual' | 'recent' | 'title'>('sd.classSort', 'manual');
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);
@ -169,7 +171,9 @@ export default function ClassPage() {
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));
return list.sort((a, b) =>
sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : sort === 'recent' ? b.updatedAt - a.updatedAt : a.sortOrder - b.sortOrder || a.createdAt - b.createdAt,
);
}, [data, filter, query, sort]);
if (q.isError) return <ErrorState title="Class not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
@ -258,11 +262,17 @@ export default function ClassPage() {
return null;
};
const row = (item: Item) => {
const row = (item: Item, sortable?: SortableRenderProps) => {
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">
<li
key={`${item.kind}:${item.id}`}
ref={sortable?.ref}
style={sortable?.style}
className={cx('group relative flex items-center gap-3 bg-surface px-3 py-2.5 hover:bg-ink/[0.035] sm:px-4', sortable && 'pl-1 sm:pl-1.5', sortable?.dragging && 'shadow-3')}
>
{sortable?.handle}
<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">
@ -373,20 +383,51 @@ export default function ClassPage() {
const KIND_ORDER = ['quiz', 'deck', 'document', 'note'] as const;
const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', document: 'Documents', note: 'Notes' } as const;
const KIND_HEADING_ICON = { quiz: <BookOpen />, deck: <Layers />, document: <FileText />, note: <NotebookPen /> } as const;
const canSort = sort === 'manual' && !query.trim();
const persistOrder = (kind: Item['kind']) => async (ids: string[]) => {
// Keys within one folder group; keep the rest of this kind in their current relative order.
const all = (data?.items ?? []).filter((i) => i.kind === kind).sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt - b.createdAt).map((i) => i.id);
const moved = new Set(ids);
let k = 0;
const merged = all.map((id) => (moved.has(id) ? ids[k++] : id));
try {
await api.post(`/api/classes/${classId}/items/reorder`, { kind, ids: merged });
await refresh();
} catch (e) {
toast.error(errorMessage(e));
await refresh();
}
};
const list = (items: Item[]) =>
canSort && items.length > 1 ? (
<SortableList
items={items}
getKey={(i) => i.id}
getLabel={(i) => i.title}
noun={items[0].kind === 'deck' ? 'deck' : items[0].kind}
onReorder={(ids) => void persistOrder(items[0].kind)(ids)}
render={(item, props) => row(item, props)}
/>
) : (
items.map((i) => row(i))
);
const section = (items: Item[]) => {
if (filter !== 'all') return <ul className="card divide-y divide-line overflow-hidden">{items.map(row)}</ul>;
if (filter !== 'all') {
// One kind only; group by kind anyway so ordering stays within a kind.
return <ul className="card divide-y divide-line overflow-hidden">{list(items)}</ul>;
}
return (
<div className="card overflow-hidden">
{KIND_ORDER.filter((k) => items.some((i) => i.kind === k)).map((k, n) => {
const list = items.filter((i) => i.kind === k);
const group = items.filter((i) => i.kind === k);
return (
<section key={k} aria-label={KIND_HEADING[k]}>
<h3 className={cx('eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5', n > 0 && 'border-t')}>
{KIND_HEADING_ICON[k]}
{KIND_HEADING[k]}
<span className="num font-normal">{list.length}</span>
<span className="num font-normal">{group.length}</span>
</h3>
<ul className="divide-y divide-line">{list.map(row)}</ul>
<ul className="divide-y divide-line">{list(group)}</ul>
</section>
);
})}
@ -574,6 +615,7 @@ export default function ClassPage() {
value={sort}
onChange={setSort}
options={[
{ value: 'manual', label: <span className="sr-only">Your order (drag to rearrange)</span>, icon: <GripVertical /> },
{ value: 'recent', label: <span className="sr-only">Recent</span>, icon: <Clock /> },
{ value: 'title', label: <span className="sr-only">A to Z</span>, icon: <ArrowDownAZ /> },
]}
@ -609,13 +651,25 @@ export default function ClassPage() {
) : (
<div className="space-y-4">
{loose.length > 0 && section(loose)}
{data.folders.map((f) => {
<SortableList
items={data.folders}
getKey={(f) => f.id}
getLabel={(f) => f.name}
noun="folder"
liveAs="div"
disabled={!canSort || searching || data.folders.length < 2}
onReorder={async (ids) => {
await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
render={(f, sortable) => {
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}>
<section key={f.id} aria-label={f.name} ref={sortable.ref} style={sortable.style} className={cx(sortable.dragging && 'rounded-[14px] bg-paper shadow-3')}>
<div className="mb-1.5 flex items-center gap-1">
{sortable.handle}
<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" />
@ -661,7 +715,8 @@ export default function ClassPage() {
))}
</section>
);
})}
}}
/>
</div>
)}
</>

View file

@ -11,6 +11,7 @@ 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 { SortableList } from '@/ui/Sortable';
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Tooltip, useConfirm } from '@/ui';
import { BulkAddDialog } from './QuizPage';
@ -263,10 +264,17 @@ export default function DeckPage() {
</div>
) : (
<ul className="card mb-3 divide-y divide-line overflow-hidden">
{shown.map((card) => {
<SortableList
items={shown}
getKey={(c) => c.id}
getLabel={(c) => `card "${c.front.replace(/[#*_`>]/g, '').slice(0, 40)}"`}
noun="card"
disabled={shown.length < 2 || shown.length !== cards.length || editing !== null}
onReorder={(ids) => act(() => api.post(`/api/decks/${deck.id}/cards/reorder`, { ids }))}
render={(card, sortable) => {
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')}>
<li key={card.id} id={`card-${card.id}`} ref={sortable.ref} style={sortable.style} className={cx('scroll-mt-24 bg-surface', params.get('card') === card.id && 'bg-marker/20', sortable.dragging && 'shadow-3')}>
{editing === card.id ? (
<div className="p-4">
<CardEditor value={draft} onChange={setDraft} autoFocus onSubmit={saveEdit} />
@ -280,7 +288,8 @@ export default function DeckPage() {
</div>
</div>
) : (
<div className={cx('flex items-start gap-3 px-4 py-3', card.suspended && 'opacity-55')}>
<div className={cx('flex items-start gap-3 px-4 py-3', sortable.handle && 'pl-1.5', card.suspended && 'opacity-55')}>
{sortable.handle && <div className="-my-1">{sortable.handle}</div>}
<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>
@ -322,7 +331,8 @@ export default function DeckPage() {
)}
</li>
);
})}
}}
/>
{shown.length === 0 && <li className="px-4 py-8 text-center text-sm text-ink-3">No cards match "{filter}".</li>}
</ul>
)}

View file

@ -13,6 +13,7 @@ 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 { SortableList } from '@/ui/Sortable';
import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui';
interface StartPrefs {
@ -534,8 +535,18 @@ export default function QuizPage() {
</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')}>
<SortableList
items={shown}
getKey={(x) => x.question.id}
getLabel={(x) => `question ${x.index + 1}`}
noun="question"
disabled={shown.length < 2 || shown.length !== questions.length || editing !== null}
onReorder={async (ids) => {
await api.post(`/api/quizzes/${quiz.id}/questions/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
render={({ question, index }, sortable) => (
<li key={question.id} id={`q-${question.id}`} ref={sortable.ref} style={sortable.style} className={cx('card scroll-mt-24 p-4 sm:p-5', params.get('q') === question.id && 'ring-2 ring-marker', sortable.dragging && 'shadow-3')}>
{editing === question.id ? (
<>
<QuestionEditor value={draft} onChange={setDraft} issues={editingIssues.filter((i) => draft.stem || i.field !== 'stem')} topics={topics} autoFocus onSubmit={() => save(false)} />
@ -543,6 +554,7 @@ export default function QuizPage() {
</>
) : (
<div className="flex items-start gap-2">
{sortable.handle && <div className="-mt-1 -ml-2 sm:-ml-3">{sortable.handle}</div>}
<div className="min-w-0 flex-1">
<QuestionView q={question} index={index} stat={stats[question.id]} />
</div>
@ -580,7 +592,8 @@ export default function QuizPage() {
</div>
)}
</li>
))}
)}
/>
{shown.length === 0 && questions.length > 0 && (
<li className="card">
<EmptyState icon={<Search />} title="No questions match" />

View file

@ -6,7 +6,7 @@ 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 { ApiError, 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';
@ -34,10 +34,28 @@ export default function SessionPage() {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const inflight = useRef<Promise<unknown>>(Promise.resolve());
const warned = useRef(false);
// Server deadline translated to this device's clock (corrects for clock skew).
const deadline = useRef<number | null>(null);
/** The server submitted the exam at its deadline: drop unsaved work and show the results. */
const timeUp = useCallback(async () => {
pending.current = { answers: {} };
if (timer.current) clearTimeout(timer.current);
try {
const fresh = await api.get<{ attempt: Attempt }>(`/api/attempts/${attemptId}`);
qc.setQueryData(qk.attempt(attemptId), fresh.attempt);
} catch {
/* the results load on the next visit */
}
toast.info('Time is up. Your exam was submitted with the answers saved before the deadline.');
window.scrollTo(0, 0);
}, [attemptId, qc]);
const timeUpRef = useLatest(timeUp);
useEffect(() => {
if (attempt && loaded.current !== attempt.id) {
loaded.current = attempt.id;
deadline.current = attempt.settings.deadlineAt ? attempt.settings.deadlineAt - (attempt.serverNow - Date.now()) : null;
setAnswers(attempt.answers);
setFlags(attempt.flags);
setIndex(attempt.currentIndex);
@ -57,6 +75,10 @@ export default function SessionPage() {
warned.current = false;
})
.catch((e) => {
if (e instanceof ApiError && e.code === 'time_up') {
void timeUpRef.current();
return;
}
// Put the changes back so the next save retries them.
pending.current = { ...payload, ...pending.current, answers: { ...(payload.answers ?? {}), ...pending.current.answers } };
if (!warned.current) {
@ -65,7 +87,7 @@ export default function SessionPage() {
}
});
return inflight.current;
}, [attemptId]);
}, [attemptId, timeUpRef]);
const queue = useCallback(
(patch: Partial<typeof pending.current>, immediate = false) => {
@ -177,6 +199,7 @@ export default function SessionPage() {
void refresh();
window.scrollTo(0, 0);
} catch (e) {
if (e instanceof ApiError && e.code === 'time_up') return void timeUp();
toast.error(errorMessage(e));
} finally {
setFinishing(false);
@ -193,6 +216,7 @@ export default function SessionPage() {
index={index}
elapsedSec={attempt.elapsedSec}
timeLimitSec={attempt.settings.timeLimitSec}
deadlineAt={deadline.current}
sataScoring={attempt.settings.sataScoring}
finishing={finishing}
onAnswer={(qid, selected, checked) => {

View file

@ -62,6 +62,27 @@ interface QuizState {
elapsed: number;
done: boolean;
timeLimitSec?: number | null;
/** End of a timed exam (epoch ms). The clock keeps running while the page is closed. */
deadlineAt?: number | null;
/**
* The questions exactly as they were when the session began (options in display order).
* Edits the owner makes later never change an in-progress session or a finished score.
* Sessions saved before this existed are rebuilt from the live quiz.
*/
questions?: SnapshotQuestion[];
/** Fingerprint of the quiz content at the start, to notice later edits. */
version?: string;
}
/** Short, stable fingerprint of a quiz's questions (FNV-1a over its JSON). */
function quizVersion(quiz: PublicQuiz): string {
const text = JSON.stringify(quiz.questions);
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h.toString(36);
}
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, timeLimitSec: number | null, only?: string[]): QuizState {
@ -73,7 +94,26 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
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, timeLimitSec };
const byId = new Map(quiz.questions.map((q) => [q.id, q]));
const questions = ids.map((id) => {
const q = byId.get(id)!;
const order = optionOrder[id];
return { ...q, options: order.map((oid) => q.options.find((o) => o.id === oid)!).filter(Boolean) };
});
return {
mode,
order: ids,
optionOrder,
answers: {},
flags: [],
index: 0,
elapsed: 0,
done: false,
timeLimitSec,
deadlineAt: timeLimitSec ? Date.now() + timeLimitSec * 1000 : null,
questions,
version: quizVersion(quiz),
};
}
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
@ -82,9 +122,11 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
const minutes = prefs.minutes > 0 ? prefs.minutes : Math.max(5, Math.round(quiz.questions.length * 1.2));
const [running, setRunning] = useState(false);
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
// Frozen sessions keep their own copy. Older saved sessions are rebuilt from the saved order,
// dropping anything the owner has since removed.
const questions = useMemo<SnapshotQuestion[]>(() => {
if (!state) return [];
if (state.questions?.length) return state.questions;
const byId = new Map(quiz.questions.map((q) => [q.id, q]));
return state.order
.map((id) => byId.get(id))
@ -96,6 +138,17 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
});
}, [quiz, state]);
const changed = Boolean(state?.version && state.version !== quizVersion(quiz));
const expired = Boolean(state && !state.done && state.deadlineAt && Date.now() > state.deadlineAt);
// A timed exam whose deadline passed while the page was closed is submitted as it stands.
useEffect(() => {
if (expired) {
setState((s) => (s && !s.done ? { ...s, done: true, elapsed: s.timeLimitSec ?? s.elapsed } : s));
setRunning(false);
}
}, [expired, setState]);
const begin = (only?: string[]) => {
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, prefs.mode === 'exam' && prefs.timed ? minutes * 60 : null, only));
setRunning(true);
@ -143,8 +196,9 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
index={state.index}
elapsedSec={state.elapsed}
timeLimitSec={state.timeLimitSec ?? null}
deadlineAt={state.deadlineAt ?? null}
sataScoring="partial"
exitLabel="Pause"
exitLabel={state.deadlineAt ? 'Leave (the clock keeps running)' : '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))}
@ -179,7 +233,9 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
<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
{state.deadlineAt ? ` · ${Math.max(0, Math.ceil((state.deadlineAt - Date.now()) / 60000))} min left` : ''}
</div>
{changed && <div className="mt-1 text-[13px] text-ink-2">This quiz has been updated since you started. Your session keeps the version you began with; start over for the latest.</div>}
</div>
<Button variant="primary" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
Resume

193
web/src/ui/Sortable.tsx Normal file
View file

@ -0,0 +1,193 @@
import { GripVertical } from 'lucide-react';
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import { cx } from '@/lib/util';
/**
* A pointer-driven sortable list: works with mouse, touch and pen (HTML5 drag and drop does
* not work on touch screens), plus keyboard reordering from the handle (arrow keys, Home/End).
* The list re-renders in the new order immediately; `onReorder` persists it.
*/
export interface SortableRenderProps {
/** Attach to the element that represents the item. */
ref: (el: HTMLElement | null) => void;
style: CSSProperties;
dragging: boolean;
/** The drag handle; render it wherever the row wants it. */
handle: ReactNode;
}
interface SortableListProps<T> {
items: T[];
getKey: (item: T) => string;
getLabel: (item: T) => string;
onReorder: (keys: string[], moved: T) => void;
render: (item: T, props: SortableRenderProps, index: number) => ReactNode;
disabled?: boolean;
/** Visible noun for screen-reader announcements, e.g. "question". */
noun?: string;
handleClassName?: string;
/** Element for the screen-reader live region: `li` inside a list, `div` elsewhere. */
liveAs?: 'li' | 'div';
}
interface DragState {
key: string;
pointerId: number;
startY: number;
dy: number;
from: number;
to: number;
/** Top and height of every item when the drag began, in list order. */
rects: { top: number; height: number }[];
gap: number;
}
function move<T>(list: T[], from: number, to: number): T[] {
const next = list.slice();
const [x] = next.splice(from, 1);
next.splice(to, 0, x);
return next;
}
export function SortableList<T>({ items, getKey, getLabel, onReorder, render, disabled, noun = 'item', handleClassName, liveAs = 'li' }: SortableListProps<T>) {
const [order, setOrder] = useState<T[]>(items);
const [drag, setDrag] = useState<DragState | null>(null);
const [announce, setAnnounce] = useState('');
const nodes = useRef(new Map<string, HTMLElement>());
const handles = useRef(new Map<string, HTMLButtonElement>());
const refocus = useRef<string | null>(null);
// Follow upstream data unless a drag is in progress.
useEffect(() => {
if (!drag) setOrder(items);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items]);
useLayoutEffect(() => {
if (refocus.current) {
handles.current.get(refocus.current)?.focus();
refocus.current = null;
}
});
const commit = useCallback(
(next: T[], moved: T, index: number) => {
setOrder(next);
onReorder(next.map(getKey), moved);
setAnnounce(`${getLabel(moved)} moved to position ${index + 1} of ${next.length}`);
},
[getKey, getLabel, onReorder],
);
const onPointerDown = (e: ReactPointerEvent<HTMLButtonElement>, key: string) => {
if (disabled || (e.pointerType === 'mouse' && e.button !== 0)) return;
const from = order.findIndex((x) => getKey(x) === key);
const rects = order.map((x) => {
const r = nodes.current.get(getKey(x))?.getBoundingClientRect();
return { top: r?.top ?? 0, height: r?.height ?? 0 };
});
const gap = rects.length > 1 ? Math.max(0, rects[1].top - (rects[0].top + rects[0].height)) : 0;
e.currentTarget.setPointerCapture(e.pointerId);
e.preventDefault();
setDrag({ key, pointerId: e.pointerId, startY: e.clientY, dy: 0, from, to: from, rects, gap });
};
const onPointerMove = (e: ReactPointerEvent<HTMLButtonElement>) => {
if (!drag || e.pointerId !== drag.pointerId) return;
const dy = e.clientY - drag.startY;
const me = drag.rects[drag.from];
const center = me.top + me.height / 2 + dy;
let to = 0;
drag.rects.forEach((r, i) => {
if (i !== drag.from && r.top + r.height / 2 < center) to += 1;
});
setDrag({ ...drag, dy, to });
};
const finish = (e: ReactPointerEvent<HTMLButtonElement>, cancel = false) => {
if (!drag || e.pointerId !== drag.pointerId) return;
const { from, to } = drag;
setDrag(null);
if (!cancel && from !== to) commit(move(order, from, to), order[from], to);
};
const onKeyDown = (e: KeyboardEvent<HTMLButtonElement>, index: number) => {
if (disabled) return;
const last = order.length - 1;
const target = { ArrowUp: index - 1, ArrowDown: index + 1, Home: 0, End: last }[e.key];
if (target === undefined) return;
e.preventDefault();
if (target < 0 || target > last || target === index) return;
refocus.current = getKey(order[index]);
commit(move(order, index, target), order[index], target);
};
const shiftFor = (i: number): number => {
if (!drag || i === drag.from) return 0;
const h = drag.rects[drag.from].height + drag.gap;
if (drag.from < drag.to && i > drag.from && i <= drag.to) return -h;
if (drag.from > drag.to && i >= drag.to && i < drag.from) return h;
return 0;
};
return (
<>
{order.map((item, i) => {
const key = getKey(item);
const dragging = drag?.key === key;
const style: CSSProperties = drag
? dragging
? { transform: `translateY(${drag.dy}px)`, zIndex: 20, position: 'relative', transition: 'none' }
: { transform: `translateY(${shiftFor(i)}px)`, transition: 'transform 160ms ease', position: 'relative' }
: {};
const handle = disabled ? null : (
<button
type="button"
ref={(el) => {
if (el) handles.current.set(key, el);
else handles.current.delete(key);
}}
aria-label={`Reorder ${getLabel(item)}. Position ${i + 1} of ${order.length}. Use arrow keys to move.`}
aria-roledescription={`${noun} drag handle`}
className={cx(
'relative z-10 grid size-8 shrink-0 cursor-grab touch-none place-items-center rounded-[8px] text-ink-3 hover:bg-ink/7 hover:text-ink active:cursor-grabbing [&>svg]:size-4',
dragging && 'cursor-grabbing bg-ink/8 text-ink',
handleClassName,
)}
onPointerDown={(e) => onPointerDown(e, key)}
onPointerMove={onPointerMove}
onPointerUp={(e) => finish(e)}
onPointerCancel={(e) => finish(e, true)}
onKeyDown={(e) => onKeyDown(e, i)}
onClick={(e) => e.preventDefault()}
>
<GripVertical aria-hidden />
</button>
);
return render(
item,
{
ref: (el) => {
if (el) nodes.current.set(key, el);
else nodes.current.delete(key);
},
style,
dragging,
handle,
},
i,
);
})}
{liveAs === 'li' ? (
<li className="sr-only" aria-live="polite" role="status">
{announce}
</li>
) : (
<div className="sr-only" aria-live="polite" role="status">
{announce}
</div>
)}
</>
);
}