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,706 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Brain, Check, CircleAlert, Eye, ExternalLink, KeyRound, MoreHorizontal, Pencil, Plus, RefreshCw, Search, Server, Trash2, Wrench, Zap } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk } from '@/lib/queries';
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';
interface Meta {
adapters: AdapterMeta[];
tasks: Record<TaskName, { label: string; description: string }>;
catalogUpdated: string;
}
const KIND_BLURB: Record<ProviderKind, string> = {
openai: 'GPT models with an OpenAI API key.',
anthropic: 'Claude models with an Anthropic API key.',
gemini: 'Gemini models with a Google AI Studio key.',
openai_compatible: 'OpenRouter, Groq, Together, LM Studio, vLLM and other compatible servers.',
ollama: 'Models running on your own machine or server.',
};
function useAiData() {
const qc = useQueryClient();
const meta = useQuery({ queryKey: ['ai', 'meta'], queryFn: () => api.get<Meta>('/api/ai/meta'), staleTime: Infinity });
const providers = useQuery({ queryKey: qk.aiProviders, queryFn: () => api.get<{ providers: Provider[] }>('/api/ai/providers').then((r) => r.providers) });
const models = useQuery({ queryKey: qk.aiModels, queryFn: () => api.get<{ models: AiModel[] }>('/api/ai/models').then((r) => r.models) });
const tasks = useQuery({ queryKey: ['ai', 'tasks'], queryFn: () => api.get<{ tasks: TaskSettings }>('/api/ai/tasks').then((r) => r.tasks) });
const status = useQuery({ queryKey: qk.aiStatus, queryFn: () => api.get<AiStatus>('/api/ai/status') });
const reload = () => qc.invalidateQueries({ queryKey: ['ai'] });
return { meta, providers, models, tasks, status, reload };
}
/* ------------------------------ provider dialog ------------------------------ */
function ProviderDialog({ open, onClose, adapters, existing, onSaved }: { open: boolean; onClose: () => void; adapters: AdapterMeta[]; existing: Provider | null; onSaved: (p: Provider, isNew: boolean) => void }) {
const [kind, setKind] = useState<ProviderKind | null>(null);
const [name, setName] = useState('');
const [apiKey, setApiKey] = useState('');
const [baseUrl, setBaseUrl] = useState('');
const [headers, setHeaders] = useState('');
const [busy, setBusy] = useState(false);
const adapter = adapters.find((a) => a.kind === kind);
useEffect(() => {
if (!open) return;
setKind(existing?.kind ?? null);
setName(existing?.name ?? '');
setApiKey('');
setBaseUrl(existing?.baseUrl ?? '');
setHeaders('');
}, [open, existing]);
const pick = (k: ProviderKind) => {
const a = adapters.find((x) => x.kind === k)!;
setKind(k);
setName(k === 'openai_compatible' ? '' : a.label);
setBaseUrl(k === 'ollama' ? (a.defaultBaseUrl ?? '') : '');
};
const save = async () => {
if (!kind || !adapter) return;
setBusy(true);
try {
const parsedHeaders: Record<string, string> = {};
for (const line of headers.split('\n')) {
const at = line.indexOf(':');
if (at > 0) parsedHeaders[line.slice(0, at).trim()] = line.slice(at + 1).trim();
}
const body = {
name: name.trim() || adapter.label,
kind,
baseUrl: baseUrl.trim() || null,
apiKey: apiKey.trim() ? apiKey.trim() : existing ? undefined : null,
headers: headers.trim() ? parsedHeaders : existing ? undefined : {},
};
const res = existing ? await api.patch<{ provider: Provider }>(`/api/ai/providers/${existing.id}`, body) : await api.post<{ provider: Provider }>('/api/ai/providers', body);
onSaved(res.provider, !existing);
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
const needsUrl = adapter?.requiresBaseUrl;
const canSave = Boolean(kind) && (!needsUrl || baseUrl.trim()) && (!adapter?.requiresApiKey || apiKey.trim() || existing?.hasKey);
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title={existing ? `Edit ${existing.name}` : kind ? `Connect ${adapter?.label}` : 'Add an AI provider'}
description={!kind ? 'Keys are encrypted and stay on your server. They are never sent to the browser.' : undefined}
footer={
kind ? (
<>
{!existing && (
<Button variant="ghost" className="mr-auto" onClick={() => setKind(null)}>
Back
</Button>
)}
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!canSave} onClick={save}>
{existing ? 'Save' : 'Connect'}
</Button>
</>
) : undefined
}
>
{!kind ? (
<div className="grid gap-2">
{adapters.map((a) => (
<button key={a.kind} type="button" onClick={() => pick(a.kind)} className="flex items-center gap-3 rounded-xl border border-line-strong p-3.5 text-left hover:border-ink-3 hover:bg-ink/3">
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-sunken text-ink-2">{a.kind === 'ollama' || a.kind === 'openai_compatible' ? <Server className="size-[18px]" /> : <Brain className="size-[18px]" />}</span>
<span className="min-w-0 flex-1">
<span className="block font-semibold">{a.label}</span>
<span className="block text-[13px] text-ink-2">{KIND_BLURB[a.kind]}</span>
</span>
</button>
))}
</div>
) : (
adapter && (
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
if (canSave) void save();
}}
>
<Field label="Name" hint="Shown in model pickers. Useful when you connect the same service with two keys.">
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder={adapter.kind === 'openai_compatible' ? 'OpenRouter' : adapter.label} maxLength={80} />
</Field>
{(needsUrl || adapter.kind === 'ollama') && (
<Field label="Server URL" hint={adapter.kind === 'ollama' ? 'From inside Docker, "localhost" is the container. Use your server address, for example http://192.168.1.10:11434.' : 'The API root, for example https://openrouter.ai/api/v1 or http://192.168.1.10:1234/v1.'}>
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={adapter.defaultBaseUrl ?? 'https://…/v1'} inputMode="url" spellCheck={false} className="num text-[13px]" />
</Field>
)}
<Field
label="API key"
optional={!adapter.requiresApiKey}
hint={
<>
{existing?.hasKey ? `Stored key: ${existing.keyPreview}. Leave blank to keep it. ` : ''}
{adapter.requiresApiKey && (
<a href={adapter.docsUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 font-medium text-accent hover:underline">
Get a key <ExternalLink className="size-3" />
</a>
)}
</>
}
>
<Input type="password" value={apiKey} onChange={(e) => setApiKey(e.target.value)} placeholder={existing?.hasKey ? '••••••••' : adapter.keyHint} autoComplete="off" spellCheck={false} className="num text-[13px]" />
</Field>
<details className="rounded-xl border border-line">
<summary className="px-3.5 py-2.5 text-sm font-medium text-ink-2 hover:text-ink">Advanced</summary>
<div className="space-y-4 border-t border-line p-3.5">
{!needsUrl && adapter.kind !== 'ollama' && (
<Field label="Custom endpoint" optional hint="Only for proxies and gateways. Leave blank for the official API.">
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={adapter.defaultBaseUrl ?? ''} spellCheck={false} className="num text-[13px]" />
</Field>
)}
<Field label="Extra HTTP headers" optional hint={existing?.headerNames.length ? `Stored: ${existing.headerNames.join(', ')}. Entering anything here replaces them.` : 'One per line, as Name: value.'}>
<Textarea rows={2} value={headers} onChange={(e) => setHeaders(e.target.value)} placeholder="HTTP-Referer: https://study.example.com" spellCheck={false} className="num text-[13px]" />
</Field>
</div>
</details>
<button type="submit" hidden />
</form>
)
)}
</Dialog>
);
}
/* ------------------------------ model dialog ------------------------------ */
function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClose: () => void; onSaved: () => void }) {
const [label, setLabel] = useState('');
const [caps, setCaps] = useState(model?.capabilities ?? { tools: true, vision: false, pdf: false, reasoning: false, temperature: true });
const [ctx, setCtx] = useState('');
const [maxOut, setMaxOut] = useState('');
const [priceIn, setPriceIn] = useState('');
const [priceOut, setPriceOut] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!model) return;
setLabel(model.label);
setCaps(model.capabilities);
setCtx(model.contextWindow?.toString() ?? '');
setMaxOut(model.maxOutput?.toString() ?? '');
setPriceIn(model.priceIn?.toString() ?? '');
setPriceOut(model.priceOut?.toString() ?? '');
}, [model]);
const num = (s: string) => (s.trim() === '' ? null : Number(s));
const save = async () => {
if (!model) return;
setBusy(true);
try {
await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut) });
onSaved();
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={model !== null}
onOpenChange={(o) => !o && onClose()}
title="Model details"
description={model?.model}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} onClick={save}>
Save
</Button>
</>
}
>
<div className="space-y-4">
<Field label="Display name">
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} />
</Field>
<div className="space-y-3.5 rounded-xl border border-line p-4">
<Switch checked={caps.tools} onChange={(v) => setCaps({ ...caps, tools: v })} label="Tool calling" description="Needed for the assistant to act on your library. Generation falls back to plain JSON without it." />
<Switch checked={caps.vision} onChange={(v) => setCaps({ ...caps, vision: v })} label="Reads images" />
<Switch checked={caps.pdf} onChange={(v) => setCaps({ ...caps, pdf: v })} label="Reads PDF files directly" description="Used to transcribe scanned PDFs." />
<Switch checked={caps.reasoning} onChange={(v) => setCaps({ ...caps, reasoning: v })} label="Adjustable reasoning effort" />
<Switch checked={caps.temperature} onChange={(v) => setCaps({ ...caps, temperature: v })} label="Accepts a temperature" description="Turn off for models that reject it." />
</div>
<div className="grid grid-cols-2 gap-4">
<Field label="Context window" hint="Tokens">
<Input type="number" min={0} value={ctx} onChange={(e) => setCtx(e.target.value)} placeholder="Unknown" />
</Field>
<Field label="Max output" hint="Tokens">
<Input type="number" min={0} value={maxOut} onChange={(e) => setMaxOut(e.target.value)} placeholder="Unknown" />
</Field>
<Field label="Input price" hint="USD per million tokens">
<Input type="number" min={0} step="0.01" value={priceIn} onChange={(e) => setPriceIn(e.target.value)} placeholder="Unknown" />
</Field>
<Field label="Output price" hint="USD per million tokens">
<Input type="number" min={0} step="0.01" value={priceOut} onChange={(e) => setPriceOut(e.target.value)} placeholder="Unknown" />
</Field>
</div>
</div>
</Dialog>
);
}
/* ------------------------------ provider card ------------------------------ */
function ProviderCard({ provider, models, adapter, onEdit, reload }: { provider: Provider; models: AiModel[]; adapter?: AdapterMeta; onEdit: () => void; reload: () => void }) {
const confirm = useConfirm();
const [busy, setBusy] = useState<'test' | 'discover' | null>(null);
const [showAll, setShowAll] = useState(false);
const [filter, setFilter] = useState('');
const [manual, setManual] = useState('');
const [editing, setEditing] = useState<AiModel | null>(null);
const enabled = models.filter((m) => m.enabled);
const needle = filter.trim().toLowerCase();
const list = (showAll || enabled.length === 0 ? models : enabled).filter((m) => !needle || m.model.toLowerCase().includes(needle) || m.label.toLowerCase().includes(needle));
const test = async () => {
setBusy('test');
try {
const res = await api.post<{ result: { ok: boolean; message: string } }>(`/api/ai/providers/${provider.id}/test`);
if (res.result.ok) toast.success(res.result.message);
else toast.error(res.result.message);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
reload();
}
};
const discover = async () => {
setBusy('discover');
try {
const res = await api.post<{ added: number; total: number }>(`/api/ai/providers/${provider.id}/discover`);
toast.success(res.added > 0 ? `Found ${plural(res.added, 'new model')}` : `Model list is up to date (${res.total})`);
if (enabled.length === 0) setShowAll(true);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
reload();
}
};
const toggleModel = async (m: AiModel, on: boolean) => {
await api.patch(`/api/ai/models/${m.id}`, { enabled: on }).catch((e) => toast.error(errorMessage(e)));
reload();
};
const addManual = async () => {
if (!manual.trim()) return;
try {
await api.post('/api/ai/models', { providerId: provider.id, model: manual.trim() });
setManual('');
reload();
} catch (e) {
toast.error(errorMessage(e));
}
};
const remove = async () => {
if (!(await confirm({ title: `Remove ${provider.name}?`, message: 'Its key and model list are deleted. Tasks that used its models fall back to your default model.', confirmLabel: 'Remove', danger: true }))) return;
await api.del(`/api/ai/providers/${provider.id}`).catch((e) => toast.error(errorMessage(e)));
reload();
};
return (
<div className={cx('card overflow-hidden', !provider.enabled && 'opacity-70')}>
<div className="flex flex-wrap items-center gap-3 px-4 py-3.5">
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-sunken text-ink-2">{provider.kind === 'ollama' || provider.kind === 'openai_compatible' ? <Server className="size-[18px]" /> : <Brain className="size-[18px]" />}</span>
<div className="min-w-0 flex-1 basis-40">
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold">{provider.name}</span>
<Badge>{adapter?.label ?? provider.kind}</Badge>
{!provider.enabled && <Badge tone="warn">Off</Badge>}
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2.5 text-xs text-ink-3">
{provider.hasKey && (
<span className="num flex items-center gap-1">
<KeyRound className="size-3" /> {provider.keyPreview}
</span>
)}
{provider.baseUrl && <span className="num truncate">{provider.baseUrl}</span>}
{provider.lastTestOk !== null && (
<span className={cx('flex items-center gap-1', provider.lastTestOk ? 'text-good' : 'text-bad')}>
{provider.lastTestOk ? <Check className="size-3" /> : <CircleAlert className="size-3" />}
{provider.lastTestOk ? 'Connected' : provider.lastTestMessage} · {timeAgo(provider.lastTestAt)}
</span>
)}
</div>
</div>
<div className="flex items-center gap-1.5">
<Button size="sm" loading={busy === 'test'} disabled={busy !== null} onClick={test} icon={<Zap />}>
Test
</Button>
<Button size="sm" loading={busy === 'discover'} disabled={busy !== null} onClick={discover} icon={<RefreshCw />}>
Find models
</Button>
<Menu
trigger={
<IconButton label="Provider options" size="sm" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<Pencil />} onSelect={onEdit}>
Edit connection
</MenuItem>
<MenuItem
icon={<Zap />}
onSelect={async () => {
await api.patch(`/api/ai/providers/${provider.id}`, { name: provider.name, kind: provider.kind, baseUrl: provider.baseUrl, enabled: !provider.enabled }).catch((e) => toast.error(errorMessage(e)));
reload();
}}
>
{provider.enabled ? 'Turn off' : 'Turn on'}
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
Remove
</MenuItem>
</Menu>
</div>
</div>
<div className="border-t border-line bg-paper/50">
{models.length === 0 ? (
<p className="px-4 py-4 text-[13px] text-ink-2">No models yet. Use "Find models" to load the list, or add a model id below.</p>
) : (
<>
<div className="flex flex-wrap items-center gap-2 px-4 pt-3 pb-1.5">
<span className="eyebrow">
{enabled.length} of {models.length} models on
</span>
{models.length > 8 && (showAll || enabled.length === 0) && (
<div className="relative ml-auto">
<Search className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-ink-3" />
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter models" aria-label="Filter models" className="h-8 w-44 pl-7 text-[13px]" />
</div>
)}
{enabled.length > 0 && enabled.length < models.length && (
<button type="button" className={cx('text-xs font-medium text-accent hover:underline', !(models.length > 8 && showAll) && 'ml-auto')} onClick={() => setShowAll(!showAll)}>
{showAll ? 'Show only models that are on' : `Show all ${models.length}`}
</button>
)}
</div>
<ul className="max-h-80 divide-y divide-line overflow-y-auto">
{list.map((m) => (
<li key={m.id} className="flex items-center gap-3 px-4 py-2">
<input type="checkbox" role="switch" aria-label={`Use ${m.label}`} checked={m.enabled} onChange={(e) => toggleModel(m, e.target.checked)} className="size-4 shrink-0 accent-[var(--accent)]" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">{m.label}</div>
<div className="num truncate text-[11px] text-ink-3">{m.model}</div>
</div>
<div className="hidden shrink-0 items-center gap-1 sm:flex">
{m.capabilities.tools && (
<Tooltip label="Tool calling">
<span className="grid size-6 place-items-center rounded-md bg-sunken text-ink-3">
<Wrench className="size-3.5" />
</span>
</Tooltip>
)}
{m.capabilities.vision && (
<Tooltip label={m.capabilities.pdf ? 'Reads images and PDFs' : 'Reads images'}>
<span className="grid size-6 place-items-center rounded-md bg-sunken text-ink-3">
<Eye className="size-3.5" />
</span>
</Tooltip>
)}
{m.capabilities.reasoning && (
<Tooltip label="Adjustable reasoning">
<span className="grid size-6 place-items-center rounded-md bg-sunken text-ink-3">
<Brain className="size-3.5" />
</span>
</Tooltip>
)}
</div>
<span className="num hidden w-28 shrink-0 text-right text-[11px] text-ink-3 md:block">{m.priceIn !== null && m.priceOut !== null ? `$${m.priceIn} / $${m.priceOut}` : 'price unknown'}</span>
<IconButton label={`Edit ${m.label}`} size="sm" onClick={() => setEditing(m)}>
<Pencil />
</IconButton>
</li>
))}
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">No models match.</li>}
</ul>
</>
)}
<form
className="flex gap-2 border-t border-line px-4 py-3"
onSubmit={(e) => {
e.preventDefault();
void addManual();
}}
>
<Input value={manual} onChange={(e) => setManual(e.target.value)} placeholder="Add a model id manually" aria-label="Model id" spellCheck={false} className="num h-9 text-[13px]" />
<Button type="submit" size="sm" className="h-9" icon={<Plus />} disabled={!manual.trim()}>
Add
</Button>
</form>
</div>
<ModelDialog model={editing} onClose={() => setEditing(null)} onSaved={reload} />
</div>
);
}
/* ------------------------------ tasks ------------------------------ */
function TaskRow({ name, label, description, config, models, resolved, onChange }: { name: TaskName | 'default'; label: string; description: string; config: TaskConfig; models: AiModel[]; resolved?: string; onChange: (c: TaskConfig) => void }) {
const model = models.find((m) => m.id === config.modelId);
const hasOverrides = config.temperature !== null || config.reasoningEffort !== null || config.maxOutputTokens !== null;
const byProvider = useMemo(() => {
const map = new Map<string, AiModel[]>();
for (const m of models) map.set(m.providerName, [...(map.get(m.providerName) ?? []), m]);
return [...map.entries()];
}, [models]);
return (
<div className="px-4 py-3.5">
<div className="grid items-center gap-x-4 gap-y-2 sm:grid-cols-[1fr_280px]">
<div>
<div className="text-sm font-semibold">{label}</div>
<div className="text-[13px] text-ink-2">{description}</div>
</div>
<Select value={config.modelId ?? ''} onChange={(e) => onChange({ ...config, modelId: e.target.value || null })} aria-label={`Model for ${label}`}>
<option value="">{name === 'default' ? 'First available model' : `Same as default${resolved ? ` (${resolved})` : ''}`}</option>
{byProvider.map(([provider, list]) => (
<optgroup key={provider} label={provider}>
{list.map((m) => (
<option key={m.id} value={m.id} disabled={name === 'vision' && !m.capabilities.vision}>
{m.label}
{name === 'vision' && !m.capabilities.vision ? ' (no vision)' : ''}
</option>
))}
</optgroup>
))}
</Select>
</div>
<details className="mt-2" open={hasOverrides}>
<summary className="w-fit text-xs font-medium text-ink-3 hover:text-ink-2">Parameters{hasOverrides ? ' (customised)' : ''}</summary>
<div className="mt-2.5 grid gap-3 sm:grid-cols-3">
<Field label="Reasoning effort" hint={model && !model.capabilities.reasoning ? 'Not supported by this model' : undefined}>
<Select value={config.reasoningEffort ?? ''} onChange={(e) => onChange({ ...config, reasoningEffort: (e.target.value || null) as TaskConfig['reasoningEffort'] })}>
<option value="">Model default</option>
<option value="none">Off / minimal</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</Select>
</Field>
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
<Input type="number" min={0} max={2} step={0.1} value={config.temperature ?? ''} placeholder="Model default" onChange={(e) => onChange({ ...config, temperature: e.target.value === '' ? null : Math.max(0, Math.min(2, Number(e.target.value))) })} />
</Field>
<Field label="Output limit" hint="Tokens per response">
<Input type="number" min={256} step={256} value={config.maxOutputTokens ?? ''} placeholder="Automatic" onChange={(e) => onChange({ ...config, maxOutputTokens: e.target.value === '' ? null : Math.max(256, Math.round(Number(e.target.value))) })} />
</Field>
</div>
</details>
</div>
);
}
/* ------------------------------ usage ------------------------------ */
function Usage() {
const [days, setDays] = useState(30);
const q = useQuery({ queryKey: ['ai', 'usage', days], queryFn: () => api.get<any>(`/api/ai/usage?days=${days}`) });
const u = q.data;
return (
<Section
title="Usage"
action={
<Select value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label="Period" className="h-8 w-32 text-[13px]">
<option value={7}>Last 7 days</option>
<option value={30}>Last 30 days</option>
<option value={90}>Last 90 days</option>
</Select>
}
>
{!u ? (
<Skeleton className="h-28" />
) : u.total.calls === 0 ? (
<div className="card px-4 py-5 text-sm text-ink-2">No AI requests in this period.</div>
) : (
<div className="card overflow-hidden">
<div className="grid grid-cols-3 divide-x divide-line border-b border-line">
{[
['Estimated cost', formatCost(u.total.cost)],
['Requests', u.total.calls.toLocaleString()],
['Tokens in / out', `${formatTokens(u.total.input)} / ${formatTokens(u.total.output)}`],
].map(([k, v]) => (
<div key={k} className="px-4 py-3">
<div className="eyebrow">{k}</div>
<div className="num mt-1 text-lg font-semibold">{v}</div>
</div>
))}
</div>
<div className="overflow-x-auto">
<table className="w-full text-[13px]">
<thead>
<tr className="text-left text-ink-3">
<th className="px-4 py-2 font-medium">Model</th>
<th className="px-3 py-2 text-right font-medium">Requests</th>
<th className="px-3 py-2 text-right font-medium">In</th>
<th className="px-3 py-2 text-right font-medium">Out</th>
<th className="px-4 py-2 text-right font-medium">Cost</th>
</tr>
</thead>
<tbody className="divide-y divide-line border-t border-line">
{u.byModel.map((m: any) => (
<tr key={`${m.provider}:${m.model}`}>
<td className="px-4 py-2">
<div className="font-medium">{m.model}</div>
<div className="text-xs text-ink-3">
{m.provider}
{m.errors > 0 ? ` · ${plural(m.errors, 'failed request')}` : ''}
</div>
</td>
<td className="num px-3 py-2 text-right">{m.calls}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.input)}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.output)}</td>
<td className="num px-4 py-2 text-right">{m.unpriced > 0 && !m.cost ? 'no price set' : formatCost(m.cost)}</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 border-t border-line px-4 py-2.5 text-xs text-ink-3">
{u.byTask.map((t: any) => (
<span key={t.task}>
{t.task}: <span className="num text-ink-2">{formatCost(t.cost)}</span> ({t.calls})
</span>
))}
</div>
{u.recentErrors.length > 0 && (
<details className="border-t border-line">
<summary className="px-4 py-2.5 text-[13px] font-medium text-bad">Recent errors ({u.recentErrors.length})</summary>
<ul className="space-y-1.5 px-4 pb-3 text-[13px]">
{u.recentErrors.map((e: any, i: number) => (
<li key={i} className="text-ink-2">
<span className="text-ink-3">{timeAgo(e.at)} · {e.model}:</span> {e.error}
</li>
))}
</ul>
</details>
)}
</div>
)}
<p className="mt-2 text-xs text-ink-3">Costs are estimates from token counts and the list prices on each model (editable). Your provider's bill is the source of truth.</p>
</Section>
);
}
/* ------------------------------ page section ------------------------------ */
export default function AiSettings() {
const { meta, providers, models, tasks, status, reload } = useAiData();
const [dialog, setDialog] = useState<{ open: boolean; existing: Provider | null }>({ open: false, existing: null });
const usable = (models.data ?? []).filter((m) => m.available);
const afterSave = async (p: Provider, isNew: boolean) => {
await reload();
// A new connection is tested and its models loaded straight away.
try {
const test = await api.post<{ result: { ok: boolean; message: string } }>(`/api/ai/providers/${p.id}/test`);
if (!test.result.ok) {
toast.error(test.result.message);
} else {
const found = await api.post<{ added: number; total: number }>(`/api/ai/providers/${p.id}/discover`).catch(() => null);
toast.success(isNew ? `${p.name} connected${found ? `: ${plural(found.total, 'model')} found. Switch on the ones you want.` : ''}` : test.result.message);
}
} catch (e) {
toast.error(errorMessage(e));
}
await reload();
};
const saveTask = async (name: TaskName | 'default', config: TaskConfig) => {
try {
await api.put('/api/ai/tasks', { [name]: config });
await reload();
} catch (e) {
toast.error(errorMessage(e));
}
};
if (!meta.data || !providers.data || !models.data || !tasks.data) {
return (
<div className="space-y-4">
<Skeleton className="h-24" />
<Skeleton className="h-48" />
</div>
);
}
return (
<div>
{providers.data.length > 0 && usable.length === 0 && (
<Callout tone="warn" icon={<CircleAlert />} title="No models are switched on" className="mb-5">
Use "Find models" on a provider, then tick the models you want to use.
</Callout>
)}
<Section
title="Providers and models"
action={
<Button size="sm" variant="primary" icon={<Plus />} onClick={() => setDialog({ open: true, existing: null })}>
Add provider
</Button>
}
>
{providers.data.length === 0 ? (
<div className="card border-dashed">
<EmptyState
icon={<Brain />}
title="Connect an AI model"
action={
<Button variant="primary" icon={<Plus />} onClick={() => setDialog({ open: true, existing: null })}>
Add provider
</Button>
}
>
Study Desk works without AI. Connecting a model adds question and flashcard generation from your documents, explanations, and the assistant. You can connect several providers and use different models for different jobs.
</EmptyState>
</div>
) : (
<div className="space-y-3">
{providers.data.map((p) => (
<ProviderCard key={p.id} provider={p} models={models.data!.filter((m) => m.providerId === p.id)} adapter={meta.data!.adapters.find((a) => a.kind === p.kind)} onEdit={() => setDialog({ open: true, existing: p })} reload={reload} />
))}
</div>
)}
<p className="mt-2.5 text-xs text-ink-3">
API keys are encrypted on the server and never sent back to the browser. A ChatGPT, Claude or Gemini app subscription is separate from API access and cannot be used here: each provider bills API usage on its own.
</p>
</Section>
{usable.length > 0 && (
<Section title="Which model does what">
<div className="card divide-y divide-line">
<TaskRow name="default" label="Default model" description="Used for everything that has no model of its own below." config={tasks.data.default} models={usable} onChange={(c) => saveTask('default', c)} />
{(Object.keys(meta.data.tasks) as TaskName[]).map((t) => (
<TaskRow key={t} name={t} label={meta.data!.tasks[t].label} description={meta.data!.tasks[t].description} config={tasks.data![t]} models={usable} resolved={status.data?.resolved[t]?.label} onChange={(c) => saveTask(t, c)} />
))}
</div>
<p className="mt-2.5 text-xs text-ink-3">You can also pick a different model for a single draft from "More options" when generating.</p>
</Section>
)}
{providers.data.length > 0 && <Usage />}
<ProviderDialog open={dialog.open} onClose={() => setDialog((d) => ({ ...d, open: false }))} adapters={meta.data.adapters} existing={dialog.existing} onSaved={afterSave} />
</div>
);
}

View file

@ -0,0 +1,496 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowUp, BookOpen, Check, ChevronRight, CircleAlert, FileText, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Link, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api, errorMessage, streamEvents } from '@/lib/api';
import { assistant, useAssistantState } from '@/lib/assistantStore';
import { useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, ToolActivity, UiItem } from '@/lib/types';
import { cx, plural, timeAgo } from '@/lib/util';
import { citedSources, Markdown, type Citation } from '@/ui/Markdown';
import { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui';
interface Conversation {
id: string;
title: string;
classId: string | null;
updatedAt: number;
}
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const;
const DRAFT_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
/* ------------------------------ message parts ------------------------------ */
function ToolLine({ tool }: { tool: ToolActivity }) {
return (
<div className="flex items-center gap-2 text-[13px] text-ink-2">
{tool.status === 'running' ? <LoaderCircle className="size-3.5 shrink-0 animate-spin text-accent" /> : tool.status === 'error' ? <CircleAlert className="size-3.5 shrink-0 text-bad" /> : <Check className="size-3.5 shrink-0 text-good" />}
<span className="min-w-0 truncate">
{tool.label}
{tool.summary && <span className={cx('ml-1.5', tool.status === 'error' ? 'text-bad' : 'text-ink-3')}>· {tool.summary}</span>}
</span>
</div>
);
}
function DraftCard({ item, onNavigate }: { item: Extract<UiItem, { type: 'draft' }>; onNavigate: () => void }) {
const gone = item.status === 'discarded';
const saved = item.status === 'saved';
return (
<div className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1">
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-accent-soft text-accent [&>svg]:size-[18px]">{DRAFT_ICON[item.kind]}</span>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{item.title}</div>
<div className="text-xs text-ink-3">
{item.kind === 'note' ? 'Draft note' : `Draft · ${plural(item.count, item.kind === 'quiz' ? 'question' : 'card')}`}
{saved ? ' · saved' : gone ? ' · discarded' : ' · not saved yet'}
</div>
</div>
{!gone && (
<Link to={`/drafts/${item.draftId}`} onClick={onNavigate}>
<Button size="sm" variant={saved ? 'secondary' : 'primary'}>
{saved ? 'Open' : 'Review'}
</Button>
</Link>
)}
</div>
);
}
function ActionCard({ item, onResolved }: { item: Extract<UiItem, { type: 'action' }>; onResolved: (status: string, result: string) => void }) {
const [busy, setBusy] = useState<'confirm' | 'cancel' | null>(null);
const resolve = async (confirm: boolean) => {
setBusy(confirm ? 'confirm' : 'cancel');
try {
const res = await api.post<{ status: string; result: string }>(`/api/ai/actions/${item.actionId}`, { confirm });
onResolved(res.status, res.result);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
}
};
const destructive = item.changes.some((c) => c.startsWith('Delete'));
return (
<div className={cx('rounded-[14px] border bg-surface p-3.5 shadow-1', item.status === 'pending' ? 'border-warn/50' : 'border-line')}>
<div className="text-sm font-semibold">{item.status === 'pending' ? 'Approve these changes?' : 'Proposed changes'}</div>
<div className="mt-0.5 text-[13px] text-ink-2">{item.summary}</div>
<ul className="mt-2 space-y-0.5 text-[13px]">
{item.changes.map((c, i) => (
<li key={i} className="flex gap-2">
<span className="text-ink-3">•</span>
<span>{c}</span>
</li>
))}
</ul>
{item.status === 'pending' ? (
<div className="mt-3 flex gap-2">
<Button size="sm" variant={destructive ? 'danger' : 'primary'} loading={busy === 'confirm'} disabled={busy !== null} onClick={() => resolve(true)}>
Confirm
</Button>
<Button size="sm" variant="ghost" loading={busy === 'cancel'} disabled={busy !== null} onClick={() => resolve(false)}>
Cancel
</Button>
</div>
) : (
<div className={cx('mt-2.5 flex items-center gap-1.5 text-[13px] font-medium', item.status === 'confirmed' ? 'text-good' : item.status === 'failed' ? 'text-bad' : 'text-ink-3')}>
{item.status === 'confirmed' ? <Check className="size-4" /> : <X className="size-4" />}
{item.result ?? (item.status === 'confirmed' ? 'Done' : 'Cancelled')}
</div>
)}
</div>
);
}
function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void }) {
const navigate = useNavigate();
const [toolsOpen, setToolsOpen] = useState(false);
const citations = useMemo<Citation[]>(() => message.ui.flatMap((u) => (u.type === 'sources' ? u.items : [])), [message.ui]);
const cited = useMemo(() => citedSources(message.text, citations), [message.text, citations]);
const openCite = (c: Citation) => {
onNavigate();
navigate(`/documents/${c.documentId}?chunk=${c.chunkId}`);
};
const cards = message.ui.filter((u) => u.type !== 'sources');
const running = message.tools.filter((t) => t.status === 'running');
const finished = message.tools.filter((t) => t.status !== 'running');
const thinking = message.pending && !message.text && running.length === 0;
return (
<div className="space-y-2.5">
{finished.length > 0 && (
<div>
<button type="button" aria-expanded={toolsOpen} onClick={() => setToolsOpen(!toolsOpen)} className="flex items-center gap-1 text-xs font-medium text-ink-3 hover:text-ink-2">
<ChevronRight className={cx('size-3.5 transition-transform', toolsOpen && 'rotate-90')} />
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
</button>
{toolsOpen && <div className="mt-1.5 space-y-1 border-l-2 border-line pl-3">{finished.map((t) => <ToolLine key={t.id} tool={t} />)}</div>}
</div>
)}
{running.map((t) => (
<ToolLine key={t.id} tool={t} />
))}
{thinking && (
<div className="flex items-center gap-2 text-[13px] text-ink-3" role="status">
<Spinner className="size-3.5" label="Thinking" /> {message.reasoning ? 'Thinking it through' : 'Thinking'}
</div>
)}
{message.text && <Markdown citations={citations} onCite={openCite} className="text-[15px]">{message.text}</Markdown>}
{cards.map((item, i) =>
item.type === 'draft' ? (
<DraftCard key={i} item={item} onNavigate={onNavigate} />
) : item.type === 'action' ? (
<ActionCard key={i} item={item} onResolved={(status, result) => onAction(item.actionId, status, result)} />
) : item.type === 'link' ? (
<Link key={i} to={`/${ITEM_URL[item.kind]}/${item.id}`} onClick={onNavigate} className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1 hover:border-ink-3">
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-marker text-marker-ink">
<Play className="size-4 fill-current" />
</span>
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{item.title}</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
) : null,
)}
{cited.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-0.5">
{cited.map(({ n, cite }) => (
<button key={cite.ref} type="button" onClick={() => openCite(cite)} className="flex max-w-full items-center gap-1.5 rounded-full border border-line bg-surface py-1 pr-2.5 pl-1 text-xs text-ink-2 hover:border-ink-3 hover:text-ink">
<span className="num grid size-[18px] shrink-0 place-items-center rounded-full bg-accent-soft text-[10.5px] font-semibold text-accent">{n}</span>
<FileText className="size-3 shrink-0" />
<span className="truncate">{cite.label}</span>
</button>
))}
</div>
)}
{message.error && (
<Callout tone="bad" icon={<CircleAlert />} className="py-2.5">
{message.error}
</Callout>
)}
</div>
);
}
/* ------------------------------ panel ------------------------------ */
export default function AssistantPanel({
variant,
headerAction,
conversationId: routeConversationId,
onConversationChange,
}: {
variant: 'drawer' | 'page';
headerAction?: ReactNode;
conversationId?: string;
onConversationChange?: (id: string | null) => void;
}) {
const ai = useAiStatus();
const classes = useClasses();
const refresh = useRefresh();
const qc = useQueryClient();
const { seed, context } = useAssistantState();
const [conversationId, setConversationId] = useState<string | null>(routeConversationId ?? null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [loadingHistory, setLoadingHistory] = useState(false);
const [focusDocs, setFocusDocs] = useState<string[]>([]);
const abort = useRef<AbortController | null>(null);
const scroller = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const stick = useRef(true);
const handledSeed = useRef(0);
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: Conversation[] }>('/api/ai/conversations').then((r) => r.conversations), staleTime: 30_000 });
const load = useCallback(async (id: string) => {
setLoadingHistory(true);
try {
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setMessages(res.messages);
setConversationId(id);
stick.current = true;
} catch {
setConversationId(null);
setMessages([]);
} finally {
setLoadingHistory(false);
}
}, []);
useEffect(() => {
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId);
if (!routeConversationId && variant === 'page' && conversationId && !busy) {
setConversationId(null);
setMessages([]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [routeConversationId]);
const newChat = useCallback(() => {
abort.current?.abort();
setConversationId(null);
setMessages([]);
setFocusDocs([]);
onConversationChange?.(null);
setTimeout(() => inputRef.current?.focus(), 30);
}, [onConversationChange]);
const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds;
const className = classes.data?.find((c) => c.id === context.classId)?.name;
const send = useCallback(
async (text: string, opts: { conversationId?: string | null; documentIds?: string[]; classId?: string | null } = {}) => {
const message = text.trim();
if (!message || busy) return;
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationId;
setBusy(true);
setInput('');
stick.current = true;
const pendingId = `p${Date.now()}`;
setMessages((m) => [...m, { id: `u${Date.now()}`, role: 'user', text: message, tools: [], ui: [], createdAt: Date.now() }, { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
const controller = new AbortController();
abort.current = controller;
let newId: string | null = null;
try {
await streamEvents<AssistantEvent>(
'/api/ai/chat',
{ conversationId: convo, message, context: { classId: opts.classId !== undefined ? opts.classId : context.classId, documentIds: opts.documentIds ?? activeDocs } },
(e) => {
if (e.type === 'start') {
newId = e.conversationId;
patch((m) => ({ ...m, model: e.model }));
} else if (e.type === 'text') patch((m) => ({ ...m, text: m.text + e.delta }));
else if (e.type === 'reasoning') patch((m) => ({ ...m, reasoning: (m.reasoning ?? '') + e.delta }));
else if (e.type === 'tool') patch((m) => ({ ...m, tools: m.tools.some((t) => t.id === e.tool.id) ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] }));
else if (e.type === 'ui') patch((m) => ({ ...m, ui: [...m.ui, e.item] }));
else if (e.type === 'error') patch((m) => ({ ...m, error: e.message }));
},
controller.signal,
);
} catch (e) {
if ((e as Error)?.name !== 'AbortError') patch((m) => ({ ...m, error: errorMessage(e) }));
} finally {
patch((m) => ({ ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : controller.signal.aborted ? '*(Stopped.)*' : m.text) }));
setBusy(false);
if (newId && newId !== convo) {
setConversationId(newId);
onConversationChange?.(newId);
}
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
// Tools may have created drafts, classes or sessions.
void refresh();
}
},
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh],
);
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
useEffect(() => {
if (!seed || handledSeed.current === seed.id || !ai.data) return;
handledSeed.current = seed.id;
assistant.consumeSeed();
if (seed.newChat) {
abort.current?.abort();
setConversationId(null);
setMessages([]);
onConversationChange?.(null);
}
setFocusDocs(seed.documentIds ?? []);
if (seed.prompt && seed.autoSend && ai.data.ready) void send(seed.prompt, { conversationId: seed.newChat ? null : undefined, documentIds: seed.documentIds, classId: seed.classId });
else {
if (seed.prompt) setInput(seed.prompt);
setTimeout(() => inputRef.current?.focus(), 60);
}
}, [seed, ai.data, send, onConversationChange]);
// Keep the newest content in view unless the user has scrolled up to read.
useEffect(() => {
const el = scroller.current;
if (el && stick.current) el.scrollTop = el.scrollHeight;
}, [messages]);
useEffect(() => () => abort.current?.abort(), []);
const updateAction = (actionId: string, status: string, result: string) => {
setMessages((list) => list.map((m) => ({ ...m, ui: m.ui.map((u) => (u.type === 'action' && u.actionId === actionId ? { ...u, status: status as typeof u.status, result } : u)) })));
void refresh();
};
const suggestions = useMemo(() => {
if (activeDocs.length > 0) {
return ['Summarise the key points of this document', 'Make flashcards from this, focusing on medications and adverse effects', 'Write 15 NCLEX-style questions from this', 'What are the most testable concepts here?'];
}
if (className) {
return [`Create a 20-question NCLEX-style quiz using the documents in ${className}`, 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', `What should I focus on in ${className} this week?`, 'Make a study guide from all the documents in this class'];
}
return ['What should I study today?', 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', 'Explain the difference between left-sided and right-sided heart failure', 'Start a practice session with the questions I miss most'];
}, [activeDocs.length, className]);
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
return (
<div className="flex min-h-0 flex-1 flex-col">
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-0')}>
<span className="grid size-8 place-items-center rounded-[10px] bg-ink text-marker">
<Sparkles className="size-4" />
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">Assistant</div>
<div className="truncate text-xs text-ink-3">{ai.data?.resolved.chat ? ai.data.resolved.chat.label : ai.data && !ai.data.ready ? 'Not set up' : ''}</div>
</div>
<IconButton label="New chat" size="sm" onClick={newChat}>
<Plus />
</IconButton>
{variant === 'drawer' && (
<Menu
trigger={
<IconButton label="History" size="sm" tooltip={false}>
<History />
</IconButton>
}
>
<MenuLabel>Recent conversations</MenuLabel>
{(history.data ?? []).length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3">Nothing yet</div>}
{(history.data ?? []).slice(0, 12).map((c) => (
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={timeAgo(c.updatedAt)}>
{c.title}
</MenuItem>
))}
{conversationId && (
<>
<MenuSeparator />
<MenuItem
icon={<Trash2 />}
danger
onSelect={async () => {
await api.del(`/api/ai/conversations/${conversationId}`).catch(() => undefined);
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
newChat();
}}
>
Delete this conversation
</MenuItem>
</>
)}
</Menu>
)}
{headerAction}
</header>
<div
ref={scroller}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
}}
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-1')}
aria-live="polite"
>
{ai.isLoading || loadingHistory ? (
<div className="grid h-full place-items-center">
<Spinner />
</div>
) : !ai.data?.ready ? (
<div className="mx-auto max-w-sm pt-8">
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model to use the assistant">
Add a provider such as OpenAI, Anthropic, Google Gemini or a local model, then switch on a model.
<div className="mt-3">
<Link to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()}>
<Button size="sm" variant="primary">
Open AI settings
</Button>
</Link>
</div>
</Callout>
</div>
) : messages.length === 0 ? (
<div className="mx-auto flex h-full max-w-md flex-col justify-center pb-6">
<h2 className="display text-[26px]">What are we working on?</h2>
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review.</p>
<div className="mt-5 space-y-2">
{suggestions.map((s) => (
<button key={s} type="button" onClick={() => send(s)} className="group flex w-full items-center gap-3 rounded-[13px] border border-line bg-surface px-3.5 py-2.5 text-left text-sm shadow-1 hover:border-ink-3">
<span className="flex-1">{s}</span>
<ArrowUp className="size-4 shrink-0 rotate-45 text-ink-3 group-hover:text-ink" />
</button>
))}
</div>
</div>
) : (
<div className="mx-auto max-w-2xl space-y-6">
{messages.map((m) =>
m.role === 'user' ? (
<div key={m.id} className="flex justify-end">
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">{m.text}</div>
</div>
) : (
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && undefined} onAction={updateAction} />
),
)}
</div>
)}
</div>
{ai.data?.ready && (
<div className={cx('safe-bottom shrink-0 border-t border-line px-3 pt-2.5 pb-3', variant === 'page' && 'lg:px-0')}>
<div className="mx-auto max-w-2xl">
{contextLabel && (
<div className="mb-2 flex items-center gap-1.5">
<Badge tone="accent" className="max-w-full">
{activeDocs.length > 0 ? <FileText /> : <BookOpen />}
<span className="truncate">Looking at: {contextLabel}</span>
</Badge>
{focusDocs.length > 0 && (
<button type="button" className="text-xs text-ink-3 hover:text-ink" onClick={() => setFocusDocs([])}>
Clear
</button>
)}
</div>
)}
<form
className="flex items-end gap-2 rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
onSubmit={(e) => {
e.preventDefault();
if (busy) abort.current?.abort();
else void send(input);
}}
>
<textarea
ref={inputRef}
value={input}
rows={1}
onChange={(e) => {
setInput(e.target.value);
e.target.style.height = 'auto';
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
if (!busy) void send(input);
}
}}
placeholder="Ask anything, or describe what to create…"
aria-label="Message the assistant"
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3"
/>
<button
type="submit"
disabled={!busy && !input.trim()}
aria-label={busy ? 'Stop' : 'Send'}
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
>
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
</button>
</form>
<p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p>
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,110 @@
import { CornerDownLeft, Sparkles, Square } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { errorMessage, streamEvents } from '@/lib/api';
import { Markdown } from '@/ui/Markdown';
import { Button, Callout, Spinner } from '@/ui';
type ExplainBody =
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string }
| { kind: 'card'; front: string; back: string }
| { kind: 'text'; text: string };
type Event = { type: 'text'; delta: string } | { type: 'error'; message: string } | { type: 'done' };
/** "Explain with AI": streams a short explanation and accepts follow-up questions. */
export function Explain({ body, label = 'Explain with AI', className }: { body: ExplainBody; label?: string; className?: string }) {
const [open, setOpen] = useState(false);
const [turns, setTurns] = useState<{ ask?: string; text: string }[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [ask, setAsk] = useState('');
const abort = useRef<AbortController | null>(null);
const key = JSON.stringify(body);
useEffect(() => {
// A different question: start over.
abort.current?.abort();
setOpen(false);
setTurns([]);
setError('');
setAsk('');
}, [key]);
useEffect(() => () => abort.current?.abort(), []);
const run = async (question?: string) => {
setOpen(true);
setBusy(true);
setError('');
setTurns((t) => [...t, { ask: question, text: '' }]);
const controller = new AbortController();
abort.current = controller;
try {
await streamEvents<Event>(
'/api/ai/explain',
{ ...body, ask: question },
(e) => {
if (e.type === 'text') setTurns((t) => t.map((x, i) => (i === t.length - 1 ? { ...x, text: x.text + e.delta } : x)));
else if (e.type === 'error') setError(e.message);
},
controller.signal,
);
} catch (e) {
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
} finally {
setBusy(false);
}
};
if (!open) {
return (
<Button size="sm" variant="ghost" icon={<Sparkles />} className={className} onClick={() => run()}>
{label}
</Button>
);
}
return (
<div className={className}>
<div className="rounded-xl border border-accent/25 bg-accent-soft/50 p-4">
<div className="eyebrow mb-2 flex items-center gap-1.5 text-accent">
<Sparkles className="size-3.5" /> AI explanation
</div>
<div className="space-y-3">
{turns.map((t, i) => (
<div key={i}>
{t.ask && <div className="mb-1 text-[13px] font-medium text-ink-2">{t.ask}</div>}
{t.text ? <Markdown className="text-[14.5px]">{t.text}</Markdown> : busy && i === turns.length - 1 ? <Spinner className="size-4" label="Thinking" /> : null}
</div>
))}
</div>
{error && (
<Callout tone="bad" className="mt-3 py-2">
{error}
</Callout>
)}
<form
className="mt-3 flex gap-2"
onSubmit={(e) => {
e.preventDefault();
if (busy) return abort.current?.abort();
const question = ask.trim();
if (!question) return;
setAsk('');
void run(question);
}}
>
<input
value={ask}
onChange={(e) => setAsk(e.target.value)}
placeholder="Ask a follow-up…"
aria-label="Follow-up question"
className="h-9 min-w-0 flex-1 rounded-[9px] border border-line-strong bg-surface px-3 text-sm outline-none focus:border-accent"
/>
<Button type="submit" size="sm" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Ask'}>
{busy ? 'Stop' : 'Ask'}
</Button>
</form>
<p className="mt-2 text-[11px] text-ink-3">AI can be wrong. Check anything important against your course material.</p>
</div>
</div>
);
}

View file

@ -0,0 +1,321 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, FileText, Layers, NotebookPen, Sparkles, Target } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk, useAiModels, useAiStatus, useClass } from '@/lib/queries';
import type { DocumentItem, Template } from '@/lib/types';
import { cx, formatTokens } from '@/lib/util';
import { Button, Callout, Dialog, Field, Input, Segmented, Select, Textarea } from '@/ui';
export interface GeneratePreset {
kind?: 'quiz' | 'deck' | 'note';
documentIds?: string[];
deckId?: string;
quizId?: string;
noteId?: string;
weakAreas?: boolean;
focus?: string;
/** Label for a fixed source (conversion), shown instead of the source picker. */
sourceLabel?: string;
}
type SourceMode = 'documents' | 'text' | 'topic' | 'weak';
export function GenerateDialog({ open, onClose, classId, folderId, preset }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null; preset?: GeneratePreset }) {
const navigate = useNavigate();
const ai = useAiStatus();
const models = useAiModels();
const cls = useClass(open ? classId : undefined);
const templates = useQuery({ queryKey: [...qk.templates, 'generation'], queryFn: () => api.get<{ templates: Template[] }>('/api/templates?kind=generation').then((r) => r.templates), enabled: open });
const [kind, setKind] = useState<'quiz' | 'deck' | 'note'>('quiz');
const [mode, setMode] = useState<SourceMode>('documents');
const [docIds, setDocIds] = useState<string[]>([]);
const [text, setText] = useState('');
const [focus, setFocus] = useState('');
const [count, setCount] = useState(15);
const [style, setStyle] = useState<'nclex' | 'standard' | 'recall'>('nclex');
const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed');
const [sata, setSata] = useState(30);
const [cardStyle, setCardStyle] = useState<'concise' | 'detailed' | 'medication' | 'definition'>('concise');
const [noteStyle, setNoteStyle] = useState<'study_guide' | 'summary' | 'outline' | 'cheat_sheet'>('study_guide');
const [instructions, setInstructions] = useState('');
const [modelId, setModelId] = useState('');
const [templateId, setTemplateId] = useState('');
const [busy, setBusy] = useState(false);
const docs = useMemo(() => (cls.data?.items.filter((i): i is DocumentItem => i.kind === 'document') ?? []).filter((d) => d.status === 'ready' && d.tokenCount > 0), [cls.data]);
const fixedSource = Boolean(preset?.deckId || preset?.quizId || preset?.noteId);
useEffect(() => {
if (!open) return;
const k = preset?.kind ?? 'quiz';
setKind(k);
setDocIds(preset?.documentIds ?? []);
setMode(preset?.weakAreas ? 'weak' : 'documents');
setFocus(preset?.focus ?? '');
setText('');
setInstructions('');
setTemplateId('');
setModelId('');
setCount(k === 'deck' ? 30 : 15);
setStyle('nclex');
setDifficulty('mixed');
setSata(30);
setCardStyle('concise');
setNoteStyle('study_guide');
}, [open, preset]);
// With no usable documents, default to describing a topic.
useEffect(() => {
if (open && cls.isSuccess && docs.length === 0 && mode === 'documents' && !fixedSource) setMode('topic');
}, [open, cls.isSuccess, docs.length, mode, fixedSource]);
const applyTemplate = (id: string) => {
setTemplateId(id);
const t = templates.data?.find((x) => x.id === id);
if (!t) return;
const p = t.payload;
if (p.kind && !preset?.kind) setKind(p.kind);
if (typeof p.count === 'number') setCount(p.count);
if (p.style) setStyle(p.style);
if (p.difficulty) setDifficulty(p.difficulty);
if (typeof p.sataShare === 'number') setSata(Math.round(p.sataShare * 100));
if (p.cardStyle) setCardStyle(p.cardStyle);
if (p.noteStyle) setNoteStyle(p.noteStyle);
setInstructions(typeof p.instructions === 'string' ? p.instructions : '');
};
const selectedTokens = docs.filter((d) => docIds.includes(d.id)).reduce((n, d) => n + d.tokenCount, 0);
const canSubmit =
fixedSource || (mode === 'documents' && docIds.length > 0) || (mode === 'text' && text.trim().length > 20) || (mode === 'topic' && focus.trim().length > 2) || mode === 'weak';
const submit = async () => {
setBusy(true);
try {
const source: Record<string, unknown> = {};
if (preset?.deckId) source.deckId = preset.deckId;
else if (preset?.quizId) source.quizId = preset.quizId;
else if (preset?.noteId) source.noteId = preset.noteId;
else if (mode === 'documents') source.documentIds = docIds;
else if (mode === 'text') source.text = text;
else if (mode === 'weak') source.weakAreas = true;
const body: Record<string, unknown> = { kind, classId, folderId: folderId ?? null, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
if (kind === 'quiz') Object.assign(body, { count, style, difficulty, sataShare: sata / 100 });
else if (kind === 'deck') Object.assign(body, { count, cardStyle });
else Object.assign(body, { noteStyle });
if (fixedSource && kind !== 'note') delete body.count;
const res = await api.post<{ draftId: string }>('/api/ai/generate', body);
onClose();
navigate(`/drafts/${res.draftId}`);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
const kinds = [
{ value: 'quiz' as const, label: 'Quiz', icon: <BookOpen /> },
{ value: 'deck' as const, label: 'Flashcards', icon: <Layers /> },
{ value: 'note' as const, label: 'Study guide', icon: <NotebookPen /> },
];
const usable = (models.data ?? []).filter((m) => m.available);
const defaultModel = ai.data?.resolved.generate;
const relevantTemplates = (templates.data ?? []).filter((t) => t.payload.kind === kind);
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Generate with AI"
description="You will get a draft to review and edit. Nothing is saved until you say so."
size="lg"
footer={
ai.data?.ready ? (
<>
<span className="mr-auto hidden text-xs text-ink-3 sm:block">{defaultModel && !modelId ? `Using ${defaultModel.label}` : ''}</span>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Sparkles />} loading={busy} disabled={!canSubmit} onClick={submit}>
Generate draft
</Button>
</>
) : undefined
}
>
{ai.isLoading ? null : !ai.data?.ready ? (
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model first">
Add a provider (OpenAI, Anthropic, Gemini, or a local model) and switch on at least one model.
<div className="mt-3">
<Link to="/settings/ai" onClick={onClose}>
<Button variant="primary" size="sm">
Open AI settings
</Button>
</Link>
</div>
</Callout>
) : (
<div className="space-y-5">
{!preset?.kind && <Segmented label="What to create" value={kind} onChange={(k) => (setKind(k), setCount(k === 'deck' ? 30 : 15), setTemplateId(''))} options={kinds} className="w-full" />}
{fixedSource ? (
<Callout icon={preset?.deckId ? <Layers /> : preset?.quizId ? <BookOpen /> : <NotebookPen />}>
Source: <strong className="text-ink">{preset?.sourceLabel}</strong>
</Callout>
) : (
<div>
<div className="mb-2 text-[13px] font-medium">Based on</div>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
{(
[
{ v: 'documents', label: 'Documents', icon: <FileText />, hint: docs.length ? `${docs.length} ready` : 'None yet' },
{ v: 'text', label: 'Pasted notes', icon: <NotebookPen />, hint: 'Paste text' },
{ v: 'topic', label: 'A topic', icon: <Sparkles />, hint: 'No source' },
{ v: 'weak', label: 'Weak areas', icon: <Target />, hint: 'From results' },
] as const
).map((o) => (
<button
key={o.v}
type="button"
disabled={o.v === 'documents' && docs.length === 0}
aria-pressed={mode === o.v}
onClick={() => setMode(o.v)}
className={cx(
'rounded-xl border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-45',
mode === o.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3',
)}
>
<span className={cx('mb-1 block [&>svg]:size-4', mode === o.v ? 'text-accent' : 'text-ink-3')}>{o.icon}</span>
<span className="block text-sm font-medium">{o.label}</span>
<span className="block text-xs text-ink-3">{o.hint}</span>
</button>
))}
</div>
{mode === 'documents' && (
<div className="mt-3">
<div className="max-h-44 overflow-y-auto rounded-xl border border-line">
{docs.map((d) => (
<label key={d.id} className="flex cursor-pointer items-center gap-3 border-b border-line px-3 py-2 last:border-0 hover:bg-ink/4">
<input type="checkbox" className="size-4 accent-[var(--accent)]" checked={docIds.includes(d.id)} onChange={(e) => setDocIds((ids) => (e.target.checked ? [...ids, d.id] : ids.filter((x) => x !== d.id)))} />
<span className="min-w-0 flex-1 truncate text-sm">{d.title}</span>
<span className="num shrink-0 text-xs text-ink-3">{d.pageCount ? `${d.pageCount} p · ` : ''}~{formatTokens(d.tokenCount)} tokens</span>
</label>
))}
</div>
<div className="mt-1.5 flex items-center justify-between text-xs text-ink-3">
<button type="button" className="font-medium text-accent hover:underline" onClick={() => setDocIds(docIds.length === docs.length ? [] : docs.map((d) => d.id))}>
{docIds.length === docs.length ? 'Clear selection' : 'Select all'}
</button>
{selectedTokens > 0 && <span>~{formatTokens(selectedTokens)} tokens selected. Long material is read in parts automatically.</span>}
</div>
</div>
)}
{mode === 'text' && <Textarea className="mt-3" rows={6} value={text} onChange={(e) => setText(e.target.value)} placeholder="Paste lecture notes, a chapter summary, or anything you want turned into study material." aria-label="Pasted notes" />}
{mode === 'weak' && (
<Callout className="mt-3" icon={<Target />}>
Uses the questions you have missed most in this class, plus matching passages from its documents, to write new {kind === 'deck' ? 'cards' : kind === 'note' ? 'review notes' : 'questions'} on the same concepts.
</Callout>
)}
</div>
)}
<Field label={mode === 'topic' && !fixedSource ? 'Topic' : 'Focus'} optional={!(mode === 'topic' && !fixedSource)} hint={mode === 'documents' && !fixedSource ? 'Narrows a long document to the relevant sections.' : undefined}>
<Input value={focus} onChange={(e) => setFocus(e.target.value)} placeholder={kind === 'deck' ? 'Medications and adverse effects' : 'Pediatric respiratory disorders'} maxLength={600} />
</Field>
{relevantTemplates.length > 0 && (
<Field label="Preset" optional hint={relevantTemplates.find((t) => t.id === templateId)?.description}>
<Select value={templateId} onChange={(e) => applyTemplate(e.target.value)}>
<option value="">Custom</option>
{relevantTemplates.map((t) => (
<option key={t.id} value={t.id}>
{t.name}
</option>
))}
</Select>
</Field>
)}
{kind === 'quiz' && (
<div className="grid gap-4 sm:grid-cols-2">
{!fixedSource && (
<Field label="Questions">
<Input type="number" min={1} max={100} value={count} onChange={(e) => setCount(Math.max(1, Math.min(100, Number(e.target.value) || 1)))} />
</Field>
)}
<Field label="Style">
<Select value={style} onChange={(e) => setStyle(e.target.value as typeof style)}>
<option value="nclex">NCLEX-style (clinical judgment)</option>
<option value="standard">Standard exam questions</option>
<option value="recall">Quick recall</option>
</Select>
</Field>
<Field label="Difficulty">
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>
<option value="mixed">Mixed</option>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</Select>
</Field>
<Field label={`Select-all-that-apply: ${sata}%`}>
<input type="range" min={0} max={100} step={10} value={sata} onChange={(e) => setSata(Number(e.target.value))} className="mt-2.5 w-full accent-[var(--accent)]" />
</Field>
</div>
)}
{kind === 'deck' && (
<div className="grid gap-4 sm:grid-cols-2">
{!fixedSource && (
<Field label="Cards">
<Input type="number" min={1} max={200} value={count} onChange={(e) => setCount(Math.max(1, Math.min(200, Number(e.target.value) || 1)))} />
</Field>
)}
<Field label="Card style">
<Select value={cardStyle} onChange={(e) => setCardStyle(e.target.value as typeof cardStyle)}>
<option value="concise">Concise (one fact per card)</option>
<option value="detailed">Detailed (short bullet lists)</option>
<option value="medication">Medication cards</option>
<option value="definition">Terms and definitions</option>
</Select>
</Field>
</div>
)}
{kind === 'note' && (
<Field label="Format">
<Select value={noteStyle} onChange={(e) => setNoteStyle(e.target.value as typeof noteStyle)}>
<option value="study_guide">Study guide</option>
<option value="summary">Summary</option>
<option value="outline">Outline</option>
<option value="cheat_sheet">Cheat sheet</option>
</Select>
</Field>
)}
<details className="group rounded-xl border border-line">
<summary className="px-3.5 py-2.5 text-sm font-medium text-ink-2 hover:text-ink">More options</summary>
<div className="space-y-4 border-t border-line p-3.5">
<Field label="Extra instructions" optional>
<Textarea rows={2} value={instructions} onChange={(e) => setInstructions(e.target.value)} placeholder="Emphasise prioritisation. Include lab values with units." maxLength={4000} />
</Field>
<Field label="Model" hint="Overrides the model chosen for content generation in Settings, for this draft only.">
<Select value={modelId} onChange={(e) => setModelId(e.target.value)}>
<option value="">Default{defaultModel ? ` (${defaultModel.label})` : ''}</option>
{usable.map((m) => (
<option key={m.id} value={m.id}>
{m.label} · {m.providerName}
</option>
))}
</Select>
</Field>
</div>
</details>
</div>
)}
</Dialog>
);
}

View file

@ -0,0 +1,242 @@
import { BookOpen, CircleAlert, CircleCheck, FileUp, Layers, NotebookPen, TriangleAlert } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import { toast } from 'sonner';
import type { ContentDraft } from '@shared/content';
import { DECK_JSON_TEMPLATE, parseImport, QUIZ_JSON_TEMPLATE, summarizeIssues, TEXT_CARDS_TEMPLATE, TEXT_QUIZ_TEMPLATE } from '@shared/importer';
import { api, errorMessage } from '@/lib/api';
import { useRefresh } from '@/lib/queries';
import type { Draft } from '@/lib/types';
import { cx, downloadText, plural, useDebounced } from '@/lib/util';
import { Badge, Button, Callout, Dialog, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Textarea } from '@/ui';
const KIND_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
const DETECTED = { json: 'JSON', 'text-quiz': 'Question blocks', 'text-cards': 'Term and definition list', none: '' };
export function ImportDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
const navigate = useNavigate();
const refresh = useRefresh();
const [text, setText] = useState('');
const [filename, setFilename] = useState('');
const [titles, setTitles] = useState<Record<number, string>>({});
const [busy, setBusy] = useState(false);
const [dragging, setDragging] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const debounced = useDebounced(text, 250);
useEffect(() => {
if (open) {
setText('');
setFilename('');
setTitles({});
}
}, [open]);
const parsed = useMemo(() => {
if (!debounced.trim()) return null;
const fallbackTitle = filename ? filename.replace(/\.[^.]+$/, '').replace(/[._-]+/g, ' ') : undefined;
return parseImport(debounced, { fallbackTitle });
}, [debounced, filename]);
const items = useMemo(
() =>
(parsed?.items ?? []).map((raw, i) => {
const draft = { ...raw, title: titles[i] ?? raw.title } as ContentDraft;
const summary = summarizeIssues(draft);
const count = draft.kind === 'quiz' ? draft.questions.length : draft.kind === 'deck' ? draft.cards.length : 1;
const badItems = new Set(summary.issues.filter((x) => x.level === 'error' && x.index !== undefined).map((x) => x.index)).size;
return { draft, summary, count, badItems, titleMissing: !draft.title.trim() };
}),
[parsed, titles],
);
const importable = items.filter((x) => x.summary.errors === 0);
const blocked = items.length - importable.length;
const readFile = async (file: File) => {
if (file.size > 20 * 1024 * 1024) return toast.error('That file is larger than 20 MB.');
setFilename(file.name);
setText(await file.text());
setTitles({});
};
const review = async (draft: ContentDraft) => {
setBusy(true);
try {
const res = await api.post<{ draft: Draft }>('/api/drafts', { payload: draft, classId, folderId });
onClose();
navigate(`/drafts/${res.draft.id}`);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
const importAll = async () => {
setBusy(true);
try {
const res = await api.post<{ created: { kind: string; id: string; title: string }[] }>('/api/import', { classId, folderId, items: importable.map((x) => x.draft) });
await refresh();
toast.success(`Imported ${plural(res.created.length, 'item')}`);
onClose();
if (res.created.length === 1) {
const c = res.created[0];
navigate(`/${c.kind === 'quiz' ? 'quizzes' : c.kind === 'deck' ? 'decks' : 'notes'}/${c.id}`);
}
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
const insertTemplate = (t: string) => {
setText(t);
setFilename('');
setTitles({});
};
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Import"
description="Paste content or drop a file. You will see exactly what was understood before anything is saved."
size="lg"
footer={
<>
<Menu
align="start"
side="top"
trigger={
<Button variant="ghost" className="mr-auto">
Templates
</Button>
}
>
<MenuLabel>Insert an example</MenuLabel>
<MenuItem onSelect={() => insertTemplate(QUIZ_JSON_TEMPLATE)}>Quiz (JSON)</MenuItem>
<MenuItem onSelect={() => insertTemplate(DECK_JSON_TEMPLATE)}>Flashcards (JSON)</MenuItem>
<MenuItem onSelect={() => insertTemplate(TEXT_QUIZ_TEMPLATE)}>Questions (plain text)</MenuItem>
<MenuItem onSelect={() => insertTemplate(TEXT_CARDS_TEMPLATE)}>Flashcards (tab separated)</MenuItem>
<MenuSeparator />
<MenuLabel>Download</MenuLabel>
<MenuItem onSelect={() => downloadText('quiz-template.json', QUIZ_JSON_TEMPLATE)}>quiz-template.json</MenuItem>
<MenuItem onSelect={() => downloadText('flashcards-template.json', DECK_JSON_TEMPLATE)}>flashcards-template.json</MenuItem>
</Menu>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={importable.length === 0 || importable.some((x) => x.titleMissing)} onClick={importAll}>
{importable.length > 0 ? `Import ${plural(importable.length, 'item')}` : 'Import'}
</Button>
</>
}
>
<div
className={cx('relative rounded-xl', dragging && 'ring-2 ring-accent ring-offset-2 ring-offset-surface')}
onDragOver={(e) => {
e.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={(e) => {
e.preventDefault();
setDragging(false);
const f = e.dataTransfer.files[0];
if (f) void readFile(f);
}}
>
<Textarea
value={text}
onChange={(e) => {
setText(e.target.value);
setTitles({});
}}
rows={9}
spellCheck={false}
aria-label="Content to import"
placeholder={'Paste JSON, question blocks, or a term/definition list…\n\n1. Which finding needs immediate action?\nA. Heart rate 88\n*B. Oxygen saturation 84%\nRationale: …'}
className="num min-h-44 text-[13px] leading-relaxed"
/>
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-ink-3">
<input ref={fileRef} type="file" accept=".json,.txt,.md,.csv,.tsv,application/json,text/*" hidden onChange={(e) => e.target.files?.[0] && readFile(e.target.files[0]).then(() => (e.target.value = ''))} />
<Button size="sm" icon={<FileUp />} onClick={() => fileRef.current?.click()}>
Choose file
</Button>
<span>{filename ? filename : 'or drop a .json, .txt or .csv file here. Study Desk V1 exports work too.'}</span>
</div>
</div>
{parsed && (
<div className="mt-5 space-y-3" aria-live="polite">
{parsed.notices.map((n, i) => (
<Callout key={i} tone={n.level === 'error' ? 'bad' : 'warn'} icon={n.level === 'error' ? <CircleAlert /> : <TriangleAlert />} className="py-2.5">
{n.message}
</Callout>
))}
{items.length > 0 && (
<>
<div className="flex items-center justify-between">
<span className="eyebrow">
Found {plural(items.length, 'item')}
{parsed.detected !== 'none' ? ` · ${DETECTED[parsed.detected]}` : ''}
</span>
{blocked > 0 && <span className="text-xs text-bad">{plural(blocked, 'item')} need fixing</span>}
</div>
<ul className="divide-y divide-line rounded-xl border border-line">
{items.map((it, i) => (
<li key={i} className="p-3">
<div className="flex items-center gap-3">
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-sunken text-ink-2 [&>svg]:size-4">{KIND_ICON[it.draft.kind]}</span>
<div className="min-w-0 flex-1">
<Input
value={it.draft.title}
onChange={(e) => setTitles((t) => ({ ...t, [i]: e.target.value }))}
placeholder="Give this a title"
aria-label="Title"
aria-invalid={it.titleMissing}
className="h-8 border-transparent bg-transparent px-1.5 font-medium shadow-none hover:border-line-strong focus:bg-surface"
/>
<div className="mt-0.5 flex flex-wrap items-center gap-1.5 px-1.5 text-xs text-ink-3">
<span>{it.draft.kind === 'quiz' ? plural(it.count, 'question') : it.draft.kind === 'deck' ? plural(it.count, 'card') : 'Note'}</span>
{it.summary.errors === 0 ? (
<Badge tone="good">
<CircleCheck /> Ready
</Badge>
) : (
<Badge tone="bad">
<CircleAlert /> {it.badItems > 0 ? `${it.badItems} with problems` : plural(it.summary.errors, 'problem')}
</Badge>
)}
{it.summary.warnings > 0 && <Badge tone="warn">{plural(it.summary.warnings, 'note')}</Badge>}
</div>
</div>
<Button size="sm" variant={it.summary.errors > 0 ? 'primary' : 'secondary'} onClick={() => review(it.draft)} disabled={busy}>
{it.summary.errors > 0 ? 'Fix' : 'Review'}
</Button>
</div>
{it.summary.errors > 0 && (
<ul className="mt-2 space-y-0.5 pl-12 text-[13px] text-bad">
{it.summary.issues
.filter((x) => x.level === 'error')
.slice(0, 4)
.map((x, k) => (
<li key={k}>
{x.index !== undefined ? `${it.draft.kind === 'quiz' ? 'Question' : 'Card'} ${x.index + 1}: ` : ''}
{x.message}
</li>
))}
{it.summary.errors > 4 && <li className="text-ink-3">and {it.summary.errors - 4} more. Open "Fix" to correct them.</li>}
</ul>
)}
</li>
))}
</ul>
</>
)}
</div>
)}
</Dialog>
);
}

162
web/src/features/charts.tsx Normal file
View file

@ -0,0 +1,162 @@
import { useMemo } from 'react';
import type { DayActivity } from '@/lib/types';
import { cx } from '@/lib/util';
import { Tooltip } from '@/ui';
/** GitHub-style activity grid. Weeks run left to right, days top to bottom (Sunday first). */
export function Heatmap({ days, goal, weeks = 26, className }: { days: DayActivity[]; goal: number; weeks?: number; className?: string }) {
const { columns, months } = useMemo(() => {
const recent = days.slice(-weeks * 7 - 6);
// Pad the front so the first column starts on a Sunday.
const first = recent[0] ? new Date(`${recent[0].date}T12:00:00Z`).getUTCDay() : 0;
const cells: (DayActivity | null)[] = [...Array<null>(first).fill(null), ...recent];
const cols: (DayActivity | null)[][] = [];
for (let i = 0; i < cells.length; i += 7) cols.push(cells.slice(i, i + 7));
const trimmed = cols.slice(-weeks);
const labels: { index: number; label: string }[] = [];
let last = -1;
trimmed.forEach((col, i) => {
const d = col.find(Boolean);
if (!d) return;
const month = Number(d.date.slice(5, 7));
if (month !== last) {
last = month;
if (i < trimmed.length - 1) labels.push({ index: i, label: new Date(`${d.date}T12:00:00Z`).toLocaleDateString(undefined, { month: 'short', timeZone: 'UTC' }) });
}
});
return { columns: trimmed, months: labels };
}, [days, weeks]);
const level = (total: number) => (total === 0 ? 0 : total < goal * 0.5 ? 1 : total < goal ? 2 : total < goal * 2.5 ? 3 : 4);
const shade = ['bg-ink/6', 'bg-accent/25', 'bg-accent/45', 'bg-accent/75', 'bg-accent'];
return (
<div className={cx('overflow-x-auto', className)}>
<div className="inline-block min-w-full">
<div className="relative mb-1 h-4 text-[10px] text-ink-3" aria-hidden>
{months.map((m) => (
<span key={m.index} className="absolute" style={{ left: `calc(${m.index} * (100% / ${columns.length}))` }}>
{m.label}
</span>
))}
</div>
<div className="grid gap-[3px]" style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(9px, 1fr))` }} role="img" aria-label={`Study activity for the last ${weeks} weeks`}>
{columns.map((col, ci) => (
<div key={ci} className="grid grid-rows-7 gap-[3px]">
{Array.from({ length: 7 }, (_, ri) => {
const d = col[ri];
if (!d) return <span key={ri} className="aspect-square" />;
const label = `${new Date(`${d.date}T12:00:00Z`).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' })}: ${d.total === 0 ? 'no study' : `${d.cards} cards, ${d.questions} questions`}`;
return (
<Tooltip key={ri} label={label} side="top">
<span className={cx('aspect-square rounded-[3px]', shade[level(d.total)])} />
</Tooltip>
);
})}
</div>
))}
</div>
</div>
</div>
);
}
/** Circular progress with content in the middle. */
export function Ring({ value, size = 64, stroke = 6, children, tone = 'accent' }: { value: number; size?: number; stroke?: number; children?: React.ReactNode; tone?: 'accent' | 'good' | 'warn' | 'bad' | 'marker' }) {
const r = (size - stroke) / 2;
const c = 2 * Math.PI * r;
const v = Math.max(0, Math.min(1, value));
const color = { accent: 'var(--accent)', good: 'var(--good)', warn: 'var(--warn)', bad: 'var(--bad)', marker: 'var(--marker)' }[tone];
return (
<div className="relative shrink-0" style={{ width: size, height: size }}>
<svg width={size} height={size} className="-rotate-90" aria-hidden>
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke} />
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - v)} className="transition-[stroke-dashoffset] duration-500" />
</svg>
<div className="absolute inset-0 grid place-items-center">{children}</div>
</div>
);
}
/** Daily accuracy as a line with dots; days without answers leave a gap. */
export function AccuracyChart({ points, height = 150 }: { points: { date: string; answered: number; accuracy: number | null }[]; height?: number }) {
const w = 600;
const pad = { l: 30, r: 8, t: 10, b: 20 };
const innerW = w - pad.l - pad.r;
const innerH = height - pad.t - pad.b;
const x = (i: number) => pad.l + (points.length <= 1 ? innerW / 2 : (i / (points.length - 1)) * innerW);
const y = (v: number) => pad.t + (1 - v) * innerH;
const segments: string[] = [];
let cur = '';
points.forEach((p, i) => {
if (p.accuracy === null) {
if (cur) segments.push(cur);
cur = '';
} else cur += `${cur ? 'L' : 'M'}${x(i).toFixed(1)},${y(p.accuracy).toFixed(1)} `;
});
if (cur) segments.push(cur);
const has = points.some((p) => p.accuracy !== null);
const ticks = [0, 0.5, 1];
const labelEvery = Math.max(1, Math.round(points.length / 6));
return (
<svg viewBox={`0 0 ${w} ${height}`} className="w-full" role="img" aria-label="Accuracy over time">
{ticks.map((t) => (
<g key={t}>
<line x1={pad.l} x2={w - pad.r} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeDasharray={t === 0 ? undefined : '3 4'} />
<text x={pad.l - 6} y={y(t) + 3.5} textAnchor="end" fontSize="10" fill="var(--ink-3)" fontFamily="var(--font-mono)">
{t * 100}
</text>
</g>
))}
{points.map((p, i) =>
i % labelEvery === 0 ? (
<text key={p.date} x={x(i)} y={height - 4} textAnchor="middle" fontSize="10" fill="var(--ink-3)">
{new Date(`${p.date}T12:00:00Z`).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' })}
</text>
) : null,
)}
{segments.map((d, i) => (
<path key={i} d={d} fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
))}
{points.map((p, i) => (p.accuracy === null ? null : <circle key={p.date} cx={x(i)} cy={y(p.accuracy)} r={points.length > 45 ? 1.8 : 3} fill="var(--surface)" stroke="var(--accent)" strokeWidth="2"><title>{`${p.date}: ${Math.round(p.accuracy * 100)}% of ${p.answered}`}</title></circle>))}
{!has && (
<text x={w / 2} y={height / 2} textAnchor="middle" fontSize="13" fill="var(--ink-3)">
No questions answered in this period
</text>
)}
</svg>
);
}
/** Small bar chart: flashcard reviews coming due per day. */
export function ForecastBars({ values, className }: { values: number[]; className?: string }) {
const max = Math.max(1, ...values);
const day = (i: number) => (i === 0 ? 'Today' : i === 1 ? 'Tomorrow' : new Date(Date.now() + i * 86_400_000).toLocaleDateString(undefined, { weekday: 'short' }));
return (
<div className={cx('flex h-28 items-end gap-1.5', className)} role="img" aria-label="Upcoming flashcard reviews by day">
{values.map((v, i) => (
<Tooltip key={i} label={`${day(i)}: ${v} due`} side="top">
<div className="flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-1">
<span className="num text-[10px] text-ink-3">{v || ''}</span>
<div className={cx('w-full rounded-t-[4px]', i === 0 ? 'bg-accent' : 'bg-accent/35')} style={{ height: `${Math.max(v ? 6 : 2, (v / max) * 100)}%`, maxHeight: 'calc(100% - 30px)', minHeight: 2 }} />
<span className="w-full truncate text-center text-[10px] text-ink-3">{i === 0 ? 'Today' : day(i).slice(0, 2)}</span>
</div>
</Tooltip>
))}
</div>
);
}
/** Horizontal accuracy bar with the percentage. */
export function AccuracyBar({ value, className }: { value: number; className?: string }) {
const p = Math.round(value * 100);
const tone = p >= 80 ? 'bg-good' : p >= 60 ? 'bg-warn' : 'bg-bad';
return (
<div className={cx('flex items-center gap-2', className)}>
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink/8">
<div className={cx('h-full rounded-full', tone)} style={{ width: `${Math.max(3, p)}%` }} />
</div>
<span className="num w-9 text-right text-xs text-ink-2">{p}%</span>
</div>
);
}

View file

@ -0,0 +1,372 @@
import { useQuery } from '@tanstack/react-query';
import { Check, Copy, ExternalLink, Globe, Link2Off, RefreshCw } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk, useClasses, useRefresh } from '@/lib/queries';
import type { ClassDetail, Share, Template } from '@/lib/types';
import { copyText, plural, timeAgo } from '@/lib/util';
import { Button, Callout, Dialog, Field, Input, Select, Spinner, Switch, Textarea } from '@/ui';
const ENDPOINT = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents' } as const;
export type EditableKind = keyof typeof ENDPOINT;
const NOUN = { quiz: 'quiz', deck: 'deck', note: 'note', document: 'document', folder: 'folder', class: 'class' } as const;
/* ------------------------------ rename ------------------------------ */
export function RenameDialog({
target,
onClose,
}: {
target: { kind: EditableKind | 'folder'; id: string; title: string; description?: string } | null;
onClose: () => void;
}) {
const refresh = useRefresh();
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (target) {
setTitle(target.title);
setDescription(target.description ?? '');
}
}, [target]);
const withDescription = target?.kind === 'quiz' || target?.kind === 'deck';
const save = async () => {
if (!target || !title.trim()) return;
setBusy(true);
try {
if (target.kind === 'folder') await api.patch(`/api/folders/${target.id}`, { name: title });
else await api.patch(`/api/${ENDPOINT[target.kind]}/${target.id}`, withDescription ? { title, description } : { title });
await refresh();
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={target !== null}
onOpenChange={(o) => !o && onClose()}
title={`Rename ${target ? NOUN[target.kind] : ''}`}
size="sm"
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!title.trim()} onClick={save}>
Save
</Button>
</>
}
>
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
void save();
}}
>
<Field label={target?.kind === 'folder' ? 'Name' : 'Title'}>
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} maxLength={200} onFocus={(e) => e.target.select()} />
</Field>
{withDescription && (
<Field label="Description" optional>
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={3} maxLength={4000} />
</Field>
)}
<button type="submit" hidden />
</form>
</Dialog>
);
}
/* ------------------------------ move ------------------------------ */
export function MoveDialog({ target, onClose }: { target: { kind: EditableKind; id: string; title: string; classId: string; folderId: string | null } | null; onClose: () => void }) {
const refresh = useRefresh();
const classes = useClasses();
const [classId, setClassId] = useState('');
const [folderId, setFolderId] = useState('');
const [busy, setBusy] = useState(false);
const detail = useQuery({ queryKey: qk.class(classId), queryFn: () => api.get<ClassDetail>(`/api/classes/${classId}`), enabled: Boolean(classId) && target !== null });
useEffect(() => {
if (target) {
setClassId(target.classId);
setFolderId(target.folderId ?? '');
}
}, [target]);
const save = async () => {
if (!target) return;
setBusy(true);
try {
await api.post('/api/items/move', { items: [{ kind: target.kind, id: target.id }], classId, folderId: folderId || null });
await refresh();
toast.success('Moved');
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={target !== null}
onOpenChange={(o) => !o && onClose()}
title="Move"
description={target ? `Choose where "${target.title}" should live.` : undefined}
size="sm"
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} onClick={save}>
Move here
</Button>
</>
}
>
<div className="space-y-4">
<Field label="Class">
<Select
value={classId}
onChange={(e) => {
setClassId(e.target.value);
setFolderId('');
}}
>
{(classes.data ?? []).map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</Select>
</Field>
<Field label="Folder">
<Select value={folderId} onChange={(e) => setFolderId(e.target.value)} disabled={detail.isLoading}>
<option value="">No folder</option>
{(detail.data?.folders ?? []).map((f) => (
<option key={f.id} value={f.id}>
{f.name}
</option>
))}
</Select>
</Field>
</div>
</Dialog>
);
}
/* ------------------------------ new item ------------------------------ */
export function NewItemDialog({ kind, classId, folderId, onClose }: { kind: 'quiz' | 'deck' | 'note' | 'folder' | null; classId: string; folderId?: string | null; onClose: () => void }) {
const refresh = useRefresh();
const navigate = useNavigate();
const [title, setTitle] = useState('');
const [templateId, setTemplateId] = useState('');
const [busy, setBusy] = useState(false);
const templates = useQuery({
queryKey: [...qk.templates, kind],
queryFn: () => api.get<{ templates: Template[] }>(`/api/templates?kind=${kind}`).then((r) => r.templates),
enabled: kind === 'quiz' || kind === 'deck',
});
useEffect(() => {
if (kind) {
setTitle('');
setTemplateId('');
}
}, [kind]);
const create = async () => {
if (!kind || !title.trim()) return;
setBusy(true);
try {
if (kind === 'folder') {
await api.post(`/api/classes/${classId}/folders`, { name: title });
await refresh();
} else if (templateId) {
const res = await api.post<{ created: { kind: string; id: string } }>(`/api/templates/${templateId}/use`, { classId, folderId, title });
await refresh();
navigate(`/${res.created.kind === 'quiz' ? 'quizzes' : 'decks'}/${res.created.id}`);
} else if (kind === 'quiz') {
const res = await api.post<{ quiz: { id: string } }>('/api/quizzes', { classId, folderId, title });
await refresh();
navigate(`/quizzes/${res.quiz.id}?edit=1`);
} else if (kind === 'deck') {
const res = await api.post<{ deck: { id: string } }>('/api/decks', { classId, folderId, title });
await refresh();
navigate(`/decks/${res.deck.id}?edit=1`);
} else {
const res = await api.post<{ note: { id: string } }>('/api/notes', { classId, folderId, title });
await refresh();
navigate(`/notes/${res.note.id}?edit=1`);
}
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
const labels = { quiz: 'New quiz', deck: 'New flashcard deck', note: 'New note', folder: 'New folder' };
const placeholders = { quiz: 'Cardiac medications', deck: 'Lab values', note: 'Exam 2 review', folder: 'Unit 3' };
return (
<Dialog
open={kind !== null}
onOpenChange={(o) => !o && onClose()}
title={kind ? labels[kind] : ''}
size="sm"
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!title.trim()} onClick={create}>
Create
</Button>
</>
}
>
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
void create();
}}
>
<Field label={kind === 'folder' ? 'Name' : 'Title'}>
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} placeholder={kind ? placeholders[kind] : ''} maxLength={200} />
</Field>
{(kind === 'quiz' || kind === 'deck') && (templates.data?.length ?? 0) > 0 && (
<Field label="Start from" hint={templates.data?.find((t) => t.id === templateId)?.description}>
<Select value={templateId} onChange={(e) => setTemplateId(e.target.value)}>
<option value="">Blank {kind}</option>
{templates.data!.map((t) => (
<option key={t.id} value={t.id}>
{t.name}
{t.builtin ? '' : ' (yours)'}
</option>
))}
</Select>
</Field>
)}
<button type="submit" hidden />
</form>
</Dialog>
);
}
/* ------------------------------ share ------------------------------ */
export type ShareKind = 'quiz' | 'deck' | 'folder' | 'class' | 'note' | 'document';
export function shareUrl(token: string): string {
return `${window.location.origin}/s/${token}`;
}
const SHARE_BLURB: Record<ShareKind, string> = {
quiz: 'Anyone with the link can take this quiz and see answers, rationales and their score. They cannot change it.',
deck: 'Anyone with the link can study these flashcards. They cannot change them.',
note: 'Anyone with the link can read this note.',
document: 'Anyone with the link can view and download this file.',
folder: 'Anyone with the link can study the quizzes, decks and notes in this folder. Uploaded documents are not included.',
class: 'Anyone with the link can study every quiz, deck and note in this class. Uploaded documents are not included.',
};
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
const refresh = useRefresh();
const [share, setShare] = useState<Share | null>(null);
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
useEffect(() => {
if (!target) return;
setShare(null);
setCopied(false);
setLoading(true);
api
.get<{ shares: (Share & { kind: string; targetId: string })[] }>('/api/shares')
.then((r) => setShare(r.shares.find((s) => s.kind === target.kind && s.targetId === target.id) ?? null))
.catch(() => undefined)
.finally(() => setLoading(false));
}, [target]);
const act = async (fn: () => Promise<{ share: Share } | void>) => {
try {
const res = await fn();
if (res && 'share' in res) setShare(res.share);
await refresh();
} catch (e) {
toast.error(errorMessage(e));
}
};
const toggle = (on: boolean) => {
if (!target) return;
void act(() => (share ? api.patch<{ share: Share }>(`/api/shares/${share.id}`, { enabled: on }) : api.post<{ share: Share }>('/api/shares', { kind: target.kind, targetId: target.id })));
};
const url = share ? shareUrl(share.token) : '';
const copy = async () => {
if (await copyText(url)) {
setCopied(true);
toast.success('Link copied');
setTimeout(() => setCopied(false), 2000);
}
};
const on = Boolean(share?.enabled);
return (
<Dialog open={target !== null} onOpenChange={(o) => !o && onClose()} title="Share" description={target?.title}>
{loading ? (
<div className="grid h-32 place-items-center">
<Spinner />
</div>
) : (
target && (
<div className="space-y-4">
<div className="rounded-xl border border-line bg-paper p-4">
<Switch checked={on} onChange={toggle} label="Public link" description={SHARE_BLURB[target.kind]} />
</div>
{on && share ? (
<>
<div className="flex gap-2">
<Input readOnly value={url} onFocus={(e) => e.target.select()} aria-label="Share link" className="num text-[13px]" />
<Button variant="primary" icon={copied ? <Check /> : <Copy />} onClick={copy}>
{copied ? 'Copied' : 'Copy'}
</Button>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-[13px] text-ink-3">
<span className="flex items-center gap-1.5">
<Globe className="size-3.5" />
{share.viewCount > 0 ? `Opened ${plural(share.viewCount, 'time')}, last ${timeAgo(share.lastViewedAt)}` : 'Not opened yet'}
</span>
<span className="flex gap-1">
<a href={url} target="_blank" rel="noreferrer" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6">
<ExternalLink className="size-3.5" /> Preview
</a>
<button type="button" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6" onClick={() => act(() => api.post<{ share: Share }>(`/api/shares/${share.id}/rotate`))}>
<RefreshCw className="size-3.5" /> New link
</button>
</span>
</div>
<p className="text-[13px] text-ink-3">"New link" replaces the address, so the old one stops working. Visitors study on their own; nothing they do touches your progress.</p>
</>
) : (
<Callout icon={<Link2Off />}>{share ? 'The link is off. Anyone who has it sees a "no longer available" page.' : 'Sharing is off. Nobody else can see this.'}</Callout>
)}
</div>
)
)}
</Dialog>
);
}

View file

@ -0,0 +1,311 @@
import { Check, ImagePlus, MessageSquareText, Plus, Trash2 } from 'lucide-react';
import { useRef, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { DIFFICULTIES, LIMITS, optionLetter, type DraftCard, type DraftQuestion, type Issue, type QuestionType } from '@shared/content';
import { api, errorMessage } from '@/lib/api';
import { cx } from '@/lib/util';
import { IconButton, Input, Segmented, Select, Textarea } from '@/ui';
/* ------------------------------ markdown textarea with image paste ------------------------------ */
export function MarkdownArea({
value,
onChange,
placeholder,
rows = 2,
label,
className,
autoFocus,
serif,
invalid,
images = true,
onKeyDown,
}: {
value: string;
onChange: (v: string) => void;
placeholder?: string;
rows?: number;
label: string;
className?: string;
autoFocus?: boolean;
serif?: boolean;
invalid?: boolean;
images?: boolean;
onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
}) {
const ref = useRef<HTMLTextAreaElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const insert = (snippet: string) => {
const el = ref.current;
const start = el?.selectionStart ?? value.length;
const end = el?.selectionEnd ?? value.length;
const before = value.slice(0, start);
const pad = before && !before.endsWith('\n') ? '\n\n' : '';
onChange(`${before}${pad}${snippet}\n${value.slice(end)}`);
};
const uploadImage = async (file: File) => {
if (!file.type.startsWith('image/')) return;
setUploading(true);
try {
const form = new FormData();
form.append('file', file);
const res = await api.upload<{ markdown: string }>('/api/media', form);
insert(res.markdown);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setUploading(false);
}
};
return (
<div className={cx('group/md relative', className)}>
<Textarea
ref={ref}
autoGrow
rows={rows}
value={value}
autoFocus={autoFocus}
aria-label={label}
aria-invalid={invalid}
placeholder={placeholder}
onChange={(e) => onChange(e.target.value)}
onKeyDown={onKeyDown}
onPaste={(e) => {
if (!images) return;
const file = [...e.clipboardData.files].find((f) => f.type.startsWith('image/'));
if (file) {
e.preventDefault();
void uploadImage(file);
}
}}
onDrop={(e) => {
if (!images) return;
const file = [...e.dataTransfer.files].find((f) => f.type.startsWith('image/'));
if (file) {
e.preventDefault();
e.stopPropagation();
void uploadImage(file);
}
}}
className={cx(serif && 'font-serif text-[16.5px] leading-normal', images && 'pr-10')}
/>
{images && (
<>
<input ref={fileRef} type="file" accept="image/png,image/jpeg,image/gif,image/webp" hidden onChange={(e) => (e.target.files?.[0] && uploadImage(e.target.files[0]), (e.target.value = ''))} />
<IconButton label={uploading ? 'Uploading image' : 'Add image'} size="sm" disabled={uploading} onClick={() => fileRef.current?.click()} className="absolute top-1 right-1 opacity-50 group-focus-within/md:opacity-100 hover:opacity-100">
<ImagePlus className={uploading ? 'animate-pulse' : undefined} />
</IconButton>
</>
)}
</div>
);
}
function FieldLabel({ children, action }: { children: ReactNode; action?: ReactNode }) {
return (
<div className="mb-1.5 flex items-center justify-between">
<span className="eyebrow">{children}</span>
{action}
</div>
);
}
export function IssueList({ issues }: { issues: Issue[] }) {
if (issues.length === 0) return null;
return (
<ul className="space-y-0.5 text-[13px]">
{issues.map((i, k) => (
<li key={k} className={i.level === 'error' ? 'text-bad' : 'text-warn'}>
{i.level === 'error' ? '• ' : '• '}
{i.message}
</li>
))}
</ul>
);
}
/* ------------------------------ question ------------------------------ */
export function QuestionEditor({
value,
onChange,
issues = [],
topics = [],
autoFocus,
onSubmit,
}: {
value: DraftQuestion;
onChange: (q: DraftQuestion) => void;
issues?: Issue[];
topics?: string[];
autoFocus?: boolean;
/** Ctrl/Cmd+Enter inside any field. */
onSubmit?: () => void;
}) {
const [whyOpen, setWhyOpen] = useState<Record<number, boolean>>({});
const set = (patch: Partial<DraftQuestion>) => onChange({ ...value, ...patch });
const has = (field: string) => issues.some((i) => i.field === field && i.level === 'error');
const submitKey = (e: React.KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
onSubmit?.();
}
};
const setType = (type: QuestionType) => {
if (type === 'single') {
// Keep only the first marked answer so the question stays valid.
let seen = false;
set({ type, options: value.options.map((o) => ({ ...o, correct: o.correct && !seen ? (seen = true) : false })) });
} else set({ type });
};
const setOption = (i: number, patch: Partial<DraftQuestion['options'][number]>) => set({ options: value.options.map((o, k) => (k === i ? { ...o, ...patch } : o)) });
const toggleCorrect = (i: number) => {
if (value.type === 'single') set({ options: value.options.map((o, k) => ({ ...o, correct: k === i })) });
else setOption(i, { correct: !value.options[i].correct });
};
const listId = `topics-${topics.length}`;
return (
<div className="space-y-5" onKeyDown={submitKey}>
<div className="flex flex-wrap items-center gap-3">
<Segmented
size="sm"
label="Question type"
value={value.type}
onChange={setType}
options={[
{ value: 'single', label: 'Multiple choice' },
{ value: 'multi', label: 'Select all that apply' },
]}
/>
</div>
<div>
<FieldLabel>Question</FieldLabel>
<MarkdownArea label="Question text" value={value.stem} onChange={(stem) => set({ stem })} placeholder="A client with heart failure reports…" rows={2} serif autoFocus={autoFocus} invalid={has('stem')} />
</div>
<div>
<FieldLabel>{value.type === 'single' ? 'Answer choices · mark the correct one' : 'Answer choices · mark every correct one'}</FieldLabel>
<ul className="space-y-2">
{value.options.map((o, i) => (
<li key={i}>
<div className="flex items-start gap-2">
<button
type="button"
role={value.type === 'single' ? 'radio' : 'checkbox'}
aria-checked={o.correct}
aria-label={`Mark choice ${optionLetter(i)} as ${o.correct ? 'incorrect' : 'correct'}`}
onClick={() => toggleCorrect(i)}
className={cx(
'num mt-1 grid size-8 shrink-0 place-items-center border text-[13px] font-semibold transition-colors',
value.type === 'single' ? 'rounded-full' : 'rounded-[9px]',
o.correct ? 'border-good bg-good text-white dark:text-[#10241a]' : 'border-line-strong bg-surface text-ink-3 hover:border-good hover:text-good',
)}
>
{o.correct ? <Check className="size-4" strokeWidth={3} /> : optionLetter(i)}
</button>
<Textarea autoGrow rows={1} value={o.text} onChange={(e) => setOption(i, { text: e.target.value })} aria-label={`Choice ${optionLetter(i)}`} placeholder={`Choice ${optionLetter(i)}`} className="min-h-10 flex-1" />
<IconButton label={`Explain choice ${optionLetter(i)}`} size="sm" className="mt-1" active={Boolean(whyOpen[i] || o.why)} onClick={() => setWhyOpen((w) => ({ ...w, [i]: !(w[i] ?? Boolean(o.why)) }))}>
<MessageSquareText />
</IconButton>
<IconButton label={`Remove choice ${optionLetter(i)}`} size="sm" className="mt-1" disabled={value.options.length <= 2} onClick={() => set({ options: value.options.filter((_, k) => k !== i) })}>
<Trash2 />
</IconButton>
</div>
{(whyOpen[i] ?? Boolean(o.why)) && (
<Textarea autoGrow rows={1} value={o.why ?? ''} onChange={(e) => setOption(i, { why: e.target.value })} aria-label={`Why choice ${optionLetter(i)} is ${o.correct ? 'correct' : 'incorrect'}`} placeholder={`Why this is ${o.correct ? 'correct' : 'incorrect'} (optional)`} className="mt-1.5 ml-10 w-[calc(100%-2.5rem)] bg-sunken text-[13px]" />
)}
</li>
))}
</ul>
{value.options.length < LIMITS.options && (
<button type="button" onClick={() => set({ options: [...value.options, { text: '', correct: false, why: '' }] })} className="mt-2 ml-10 inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium text-accent hover:bg-accent-soft">
<Plus className="size-4" /> Add choice
</button>
)}
</div>
<div>
<FieldLabel>Rationale</FieldLabel>
<MarkdownArea label="Rationale" value={value.rationale} onChange={(rationale) => set({ rationale })} placeholder="Why the correct answer is correct. Shown after answering." rows={2} />
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_160px]">
<div>
<FieldLabel>Topic</FieldLabel>
<Input value={value.topic} onChange={(e) => set({ topic: e.target.value })} placeholder="Heart failure" maxLength={LIMITS.topic} list={listId} aria-label="Topic" />
<datalist id={listId}>
{topics.map((t) => (
<option key={t} value={t} />
))}
</datalist>
</div>
<div>
<FieldLabel>Difficulty</FieldLabel>
<Select value={value.difficulty} onChange={(e) => set({ difficulty: e.target.value as DraftQuestion['difficulty'] })} aria-label="Difficulty">
{DIFFICULTIES.map((d) => (
<option key={d} value={d}>
{d[0].toUpperCase() + d.slice(1)}
</option>
))}
</Select>
</div>
</div>
<IssueList issues={issues} />
</div>
);
}
/* ------------------------------ card ------------------------------ */
export function CardEditor({ value, onChange, issues = [], autoFocus, onSubmit, showHint }: { value: DraftCard; onChange: (c: DraftCard) => void; issues?: Issue[]; autoFocus?: boolean; onSubmit?: () => void; showHint?: boolean }) {
const [hintOpen, setHintOpen] = useState(Boolean(value.hint) || Boolean(showHint));
const set = (patch: Partial<DraftCard>) => onChange({ ...value, ...patch });
const has = (field: string) => issues.some((i) => i.field === field && i.level === 'error');
return (
<div
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
onSubmit?.();
}
}}
>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<FieldLabel>Front</FieldLabel>
<MarkdownArea label="Front" value={value.front} onChange={(front) => set({ front })} rows={3} autoFocus={autoFocus} invalid={has('front')} placeholder="Term or question" />
</div>
<div>
<FieldLabel
action={
!hintOpen ? (
<button type="button" className="text-xs font-medium text-accent hover:underline" onClick={() => setHintOpen(true)}>
Add hint
</button>
) : undefined
}
>
Back
</FieldLabel>
<MarkdownArea label="Back" value={value.back} onChange={(back) => set({ back })} rows={3} invalid={has('back')} placeholder="Answer" />
</div>
</div>
{hintOpen && (
<div className="mt-3">
<FieldLabel>Hint</FieldLabel>
<Input value={value.hint ?? ''} onChange={(e) => set({ hint: e.target.value })} placeholder="A mnemonic or nudge shown on request" aria-label="Hint" />
</div>
)}
<div className="mt-2">
<IssueList issues={issues} />
</div>
</div>
);
}

View file

@ -0,0 +1,290 @@
import { ArrowLeft, ArrowRight, Check, Lightbulb, RotateCcw, Shuffle, X } from 'lucide-react';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, IconButton, Kbd, ProgressBar } from '@/ui';
import { Ring } from './charts';
/* ------------------------------ the card ------------------------------ */
export function FlipCard({
front,
back,
hint,
flipped,
onFlip,
label,
cardKey,
footer,
}: {
front: string;
back: string;
hint?: string;
flipped: boolean;
onFlip: () => void;
label?: ReactNode;
/** Changing this replays the entrance animation and resets the hint. */
cardKey: string;
footer?: ReactNode;
}) {
const [showHint, setShowHint] = useState(false);
useEffect(() => setShowHint(false), [cardKey]);
const face = 'flip-face flex min-h-[320px] flex-col rounded-[22px] border border-line bg-surface shadow-2 sm:min-h-[380px]';
// Short answers read best large and centred; long ones as normal text.
const size = (text: string) => (text.length < 60 ? 'text-[28px] sm:text-[34px] leading-tight text-center' : text.length < 220 ? 'text-[21px] sm:text-[24px] leading-snug text-center' : 'text-[17px] sm:text-[18px]');
return (
<div key={cardKey} className="flip w-full animate-in">
<div className="flip-inner" data-flipped={flipped}>
<div className={cx(face, 'flip-front')}>
<button type="button" onClick={onFlip} aria-label="Show answer" className="flex flex-1 cursor-pointer flex-col rounded-[22px] text-left">
<div className="flex items-center justify-between px-5 pt-4">
<span className="eyebrow">{label ?? 'Front'}</span>
<span className="text-xs text-ink-3">Tap to flip</span>
</div>
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
{front}
</Markdown>
</div>
</button>
{hint && (
<div className="border-t border-line px-5 py-3">
{showHint ? (
<div className="flex items-start gap-2 text-sm text-ink-2">
<Lightbulb className="mt-0.5 size-4 shrink-0 text-warn" />
<Markdown>{hint}</Markdown>
</div>
) : (
<button type="button" onClick={() => setShowHint(true)} className="flex items-center gap-1.5 text-[13px] font-medium text-ink-2 hover:text-ink">
<Lightbulb className="size-4" /> Show hint
</button>
)}
</div>
)}
</div>
<div className={cx(face, 'flip-back')}>
<button type="button" onClick={onFlip} aria-label="Show question" className="flex cursor-pointer items-center justify-between rounded-t-[22px] px-5 pt-4 text-left">
<span className="eyebrow">Back</span>
<span className="max-w-[70%] truncate text-xs text-ink-3">{front.replace(/[#*_`>]/g, '').slice(0, 80)}</span>
</button>
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10" aria-live="polite">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(back))}>
{back}
</Markdown>
</div>
{footer && <div className="border-t border-line px-5 py-3">{footer}</div>}
</div>
</div>
</div>
);
}
export function StudyTopBar({ title, subtitle, onExit, right, progress, exitLabel = 'Exit' }: { title: string; subtitle?: ReactNode; onExit: () => void; right?: ReactNode; progress?: number; exitLabel?: string }) {
return (
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-3 sm:px-5">
<IconButton label={exitLabel} onClick={onExit}>
<X />
</IconButton>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{title}</div>
{subtitle && <div className="truncate text-xs text-ink-3">{subtitle}</div>}
</div>
{right}
</div>
{progress !== undefined && <ProgressBar value={progress} tone="ink" className="h-[3px] rounded-none" label="Progress" />}
</header>
);
}
/* ------------------------------ browse / cram ------------------------------ */
export interface CramState {
order: string[];
index: number;
known: string[];
unknown: string[];
shuffled: boolean;
/** Which pass this is: 1 = whole deck, 2+ = cards still being learned. */
round: number;
}
export interface CramCard {
id: string;
front: string;
back: string;
hint?: string;
}
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1): CramState {
const ids = cards.map((c) => c.id);
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round };
}
/** Drops cards that no longer exist and clamps the position, so a saved session survives deck edits. */
export function reconcileCramState(state: CramState | null | undefined, cards: CramCard[]): CramState | null {
if (!state || !Array.isArray(state.order)) return null;
const valid = new Set(cards.map((c) => c.id));
const order = state.order.filter((id) => valid.has(id));
if (order.length === 0) return null;
return {
order,
index: Math.max(0, Math.min(state.index ?? 0, order.length)),
known: (state.known ?? []).filter((id) => valid.has(id)),
unknown: (state.unknown ?? []).filter((id) => valid.has(id)),
shuffled: Boolean(state.shuffled),
round: state.round ?? 1,
};
}
export function CramSession({
title,
subtitle,
cards,
state,
onState,
onExit,
onGrade,
exitLabel,
renderExtra,
}: {
title: string;
subtitle?: string;
cards: CramCard[];
state: CramState;
onState: (s: CramState) => void;
onExit: () => void;
/** Called when a card is graded (used for activity tracking). */
onGrade?: (cardId: string, known: boolean) => void;
exitLabel?: string;
renderExtra?: (card: CramCard) => ReactNode;
}) {
const [flipped, setFlipped] = useState(false);
const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]);
const total = state.order.length;
const done = state.index >= total;
const card = done ? undefined : byId.get(state.order[state.index]);
useEffect(() => setFlipped(false), [state.index, state.round]);
const grade = (known: boolean) => {
if (!card) return;
onGrade?.(card.id, known);
onState({
...state,
index: state.index + 1,
known: known ? [...state.known.filter((x) => x !== card.id), card.id] : state.known.filter((x) => x !== card.id),
unknown: known ? state.unknown.filter((x) => x !== card.id) : [...state.unknown.filter((x) => x !== card.id), card.id],
});
};
const move = (delta: number) => onState({ ...state, index: Math.max(0, Math.min(total, state.index + delta)) });
const restart = (shuffled = state.shuffled) => onState(freshCramState(cards, shuffled));
const studyUnknown = () => {
const pool = cards.filter((c) => state.unknown.includes(c.id));
onState({ ...freshCramState(pool, true, state.round + 1) });
};
useHotkeys({
space: (e) => {
e.preventDefault();
if (!done) setFlipped((f) => !f);
},
Enter: () => !done && setFlipped((f) => !f),
ArrowRight: () => move(1),
ArrowLeft: () => move(-1),
'1': () => flipped && grade(false),
'2': () => flipped && grade(true),
});
return (
<div className="flex min-h-dvh flex-col bg-paper">
<StudyTopBar
title={title}
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : 'Browse')}
onExit={onExit}
exitLabel={exitLabel}
progress={total ? Math.min(1, state.index / total) : 0}
right={
<>
<span className="num text-[13px] font-medium text-ink-2">
{Math.min(state.index + 1, total)}/{total}
</span>
<IconButton label={state.shuffled ? 'Shuffled. Restart in order' : 'Shuffle and restart'} active={state.shuffled} onClick={() => restart(!state.shuffled)}>
<Shuffle />
</IconButton>
</>
}
/>
<main className="mx-auto flex w-full max-w-2xl flex-1 flex-col px-4 pt-6 pb-36 sm:px-5 sm:pt-10">
{done || !card ? (
<div className="card m-auto w-full animate-in p-7 text-center sm:p-10">
<div className="mx-auto mb-4 w-fit">
<Ring value={total ? state.known.length / (state.known.length + state.unknown.length || 1) : 0} size={104} stroke={9} tone="good">
<span className="display num text-[28px]">{state.known.length}</span>
</Ring>
</div>
<h2 className="display text-[28px]">{state.unknown.length === 0 ? 'You know them all' : 'Round complete'}</h2>
<p className="mt-2 text-[15px] text-ink-2">
{state.known.length} known{state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of {plural(total, 'card')}.
</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
{state.unknown.length > 0 && (
<Button variant="primary" size="lg" icon={<RotateCcw />} onClick={studyUnknown}>
Study the {state.unknown.length} again
</Button>
)}
<Button size="lg" icon={<RotateCcw />} onClick={() => restart()}>
Start over
</Button>
<Button size="lg" variant="ghost" onClick={onExit}>
Done
</Button>
</div>
</div>
) : (
<>
<FlipCard cardKey={`${state.round}:${card.id}`} front={card.front} back={card.back} hint={card.hint} flipped={flipped} onFlip={() => setFlipped((f) => !f)} footer={renderExtra?.(card)} />
<div className="mt-4 flex justify-center gap-1.5">
{state.known.includes(card.id) && <Badge tone="good">Marked known</Badge>}
{state.unknown.includes(card.id) && <Badge tone="warn">Still learning</Badge>}
</div>
</>
)}
</main>
{!done && card && (
<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 flex h-[76px] max-w-2xl items-center gap-2 px-3 sm:px-5">
<IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0}>
<ArrowLeft />
</IconButton>
{flipped ? (
<>
<Button size="lg" className="flex-1 border-warn/40 text-warn hover:bg-warn-soft" icon={<RotateCcw />} onClick={() => grade(false)}>
Still learning
<span className="hidden sm:inline">
<Kbd>1</Kbd>
</span>
</Button>
<Button size="lg" className="flex-1 border-good/40 text-good hover:bg-good-soft" icon={<Check />} onClick={() => grade(true)}>
Know it
<span className="hidden sm:inline">
<Kbd>2</Kbd>
</span>
</Button>
</>
) : (
<Button size="lg" variant="primary" className="flex-1" onClick={() => setFlipped(true)}>
Show answer
<span className="hidden sm:inline">
<Kbd>Space</Kbd>
</span>
</Button>
)}
<IconButton label="Skip card" onClick={() => move(1)}>
<ArrowRight />
</IconButton>
</div>
</footer>
)}
</div>
);
}

519
web/src/features/quiz.tsx Normal file
View file

@ -0,0 +1,519 @@
import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { isFullyCorrect, optionLetter, scoreQuestion, type SataScoring } from '@shared/content';
import type { AnswerState, SnapshotQuestion } from '@/lib/types';
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Dialog, IconButton, Kbd, ProgressBar, Segmented, useConfirm } from '@/ui';
import { Ring } from './charts';
/* ------------------------------ option list ------------------------------ */
function OptionList({
question,
selected,
revealed,
onToggle,
}: {
question: SnapshotQuestion;
selected: string[];
/** Show which choices are correct (after checking in practice, or in review). */
revealed: boolean;
onToggle?: (id: string) => void;
}) {
const multi = question.type === 'multi';
return (
<ul className="space-y-2.5" role={multi ? 'group' : 'radiogroup'} aria-label="Answer choices">
{question.options.map((o, i) => {
const picked = selected.includes(o.id);
const state = !revealed ? (picked ? 'picked' : 'idle') : o.correct ? (picked ? 'right' : 'missed') : picked ? 'wrong' : 'idle';
const styles = {
idle: 'border-line-strong bg-surface',
picked: 'border-accent bg-accent-soft ring-1 ring-accent',
right: 'border-good bg-good-soft ring-1 ring-good',
missed: 'border-good/60 bg-surface border-dashed',
wrong: 'border-bad bg-bad-soft ring-1 ring-bad',
}[state];
const key = {
idle: 'border-line-strong text-ink-3 bg-surface',
picked: 'border-accent bg-accent text-accent-ink',
right: 'border-good bg-good text-white dark:text-[#10241a]',
missed: 'border-good text-good bg-surface',
wrong: 'border-bad bg-bad text-white dark:text-[#2a1210]',
}[state];
return (
<li key={o.id}>
<button
type="button"
role={multi ? 'checkbox' : 'radio'}
aria-checked={picked}
disabled={revealed || !onToggle}
onClick={() => onToggle?.(o.id)}
className={cx('flex w-full items-start gap-3 rounded-[14px] border px-3.5 py-3 text-left transition-[background,border-color,box-shadow] disabled:cursor-default', styles, !revealed && onToggle && 'hover:border-ink-3 active:scale-[0.995]')}
>
<span className={cx('num mt-px grid size-7 shrink-0 place-items-center border text-[13px] font-semibold', multi ? 'rounded-[8px]' : 'rounded-full', key)}>
{state === 'right' || state === 'missed' ? <Check className="size-4" strokeWidth={3} /> : state === 'wrong' ? <X className="size-4" strokeWidth={3} /> : optionLetter(i)}
</span>
<span className="min-w-0 flex-1">
<Markdown className="text-[16px] leading-snug">{o.text}</Markdown>
{revealed && (state === 'missed' || state === 'wrong' || state === 'right') && (
<span className={cx('mt-1 block text-[13px] font-medium', state === 'wrong' ? 'text-bad' : 'text-good')}>
{state === 'right' ? 'Correct' : state === 'missed' ? (multi ? 'Correct, not selected' : 'Correct answer') : 'Your answer'}
</span>
)}
{revealed && o.why && <span className="mt-1 block text-[13.5px] leading-snug text-ink-2">{o.why}</span>}
</span>
</button>
</li>
);
})}
</ul>
);
}
function Verdict({ score }: { score: number }) {
const full = isFullyCorrect(score);
const partial = !full && score > 0;
return (
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')} role="status">
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
</div>
);
}
/* ------------------------------ runner ------------------------------ */
export interface RunnerProps {
title: string;
mode: 'practice' | 'exam';
questions: SnapshotQuestion[];
answers: Record<string, AnswerState>;
flags: string[];
index: number;
elapsedSec: number;
timeLimitSec: number | null;
sataScoring: SataScoring;
onAnswer: (questionId: string, selected: string[], checked: boolean) => void;
onFlags: (flags: string[]) => void;
onIndex: (index: number) => void;
/** Called every few seconds with the running clock so progress can be saved. */
onTick?: (elapsedSec: number) => void;
onFinish: (elapsedSec: number) => void;
onExit: () => void;
finishing?: boolean;
/** Extra content under the rationale (AI explanation). */
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
exitLabel?: string;
}
export function QuizRunner(p: RunnerProps) {
const confirm = useConfirm();
const [elapsed, setElapsed] = useState(p.elapsedSec);
const [navOpen, setNavOpen] = useState(false);
const topRef = useRef<HTMLDivElement>(null);
const tick = useLatest(p.onTick);
const finish = useLatest(p.onFinish);
const elapsedRef = useLatest(elapsed);
const total = p.questions.length;
const index = Math.min(p.index, total - 1);
const question = p.questions[index];
const answer = p.answers[question.id];
const selected = answer?.selected ?? [];
const checked = p.mode === 'practice' && Boolean(answer?.checked);
const answeredCount = p.questions.filter((q) => (p.mode === 'practice' ? p.answers[q.id]?.checked : (p.answers[q.id]?.selected.length ?? 0) > 0)).length;
const flagged = p.flags.includes(question.id);
const isLast = index === total - 1;
const remaining = p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
// Session clock: pauses while the tab is hidden.
useEffect(() => {
const timer = setInterval(() => {
if (document.visibilityState === 'visible') setElapsed((e) => e + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
useEffect(() => {
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(elapsed);
}, [elapsed, tick]);
useEffect(() => {
if (remaining === 0 && !p.finishing) finish.current(elapsedRef.current);
}, [remaining, p.finishing, finish, elapsedRef]);
useEffect(() => {
topRef.current?.scrollIntoView({ block: 'start' });
}, [index]);
const toggle = (id: string) => {
if (checked) return;
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
p.onAnswer(question.id, next, false);
};
const check = () => selected.length > 0 && p.onAnswer(question.id, selected, true);
const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i)));
const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]);
const requestFinish = async () => {
const unanswered = total - answeredCount;
if (unanswered > 0) {
const ok = await confirm(
p.mode === 'exam'
? { title: 'Submit the exam?', message: `${plural(unanswered, 'question')} ${unanswered === 1 ? 'is' : 'are'} unanswered and will be marked wrong.`, confirmLabel: 'Submit' }
: { title: 'Finish now?', message: `You have answered ${answeredCount} of ${total}. Only answered questions are scored.`, confirmLabel: 'Finish' },
);
if (!ok) return;
}
p.onFinish(elapsed);
};
const primary = () => {
if (p.mode === 'practice' && !checked) return check();
if (isLast) return void requestFinish();
go(index + 1);
};
useHotkeys({
...Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)])),
...Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)])),
Enter: primary,
ArrowRight: () => go(index + 1),
ArrowLeft: () => go(index - 1),
// "f" doubles as choice F on six-option questions; the flag keeps a dedicated key too.
...(question.options.length < 6 ? { f: toggleFlag } : {}),
m: toggleFlag,
});
const score = checked ? scoreQuestion(question, selected, p.sataScoring) : 0;
const statusOf = (q: SnapshotQuestion) => {
const a = p.answers[q.id];
if (p.mode === 'practice' && a?.checked) return isFullyCorrect(scoreQuestion(q, a.selected, p.sataScoring)) ? 'right' : 'wrong';
return (a?.selected.length ?? 0) > 0 ? 'answered' : 'blank';
};
return (
<div className="flex min-h-dvh flex-col bg-paper">
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-3 sm:px-5">
<IconButton label={p.exitLabel ?? 'Save and exit'} onClick={p.onExit}>
<X />
</IconButton>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{p.title}</div>
<div className="text-xs text-ink-3">{p.mode === 'exam' ? 'Exam' : 'Practice'}</div>
</div>
<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)}
</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" />
{index + 1}/{total}
</button>
</div>
<ProgressBar value={answeredCount / total} tone="ink" className="h-[3px] rounded-none" label="Progress" />
</header>
<main className="mx-auto w-full max-w-3xl flex-1 px-4 pt-6 pb-32 sm:px-5 sm:pt-9">
<div ref={topRef} className="scroll-mt-20" />
<div key={question.id} className="animate-in">
<div className="mb-3 flex flex-wrap items-center gap-2">
<span className="eyebrow">Question {index + 1}</span>
{question.topic && <Badge tone="accent">{question.topic}</Badge>}
{flagged && (
<Badge tone="marker">
<Flag /> Flagged
</Badge>
)}
</div>
<Markdown serif className="text-[20px] leading-[1.45] sm:text-[22px]">
{question.stem}
</Markdown>
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : 'Choose one answer.'}</p>
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
{checked && (
<div className="mt-5 animate-in space-y-4">
<Verdict score={score} />
{question.rationale && (
<div className="rounded-[14px] border border-line bg-surface p-4">
<div className="eyebrow mb-1.5">Rationale</div>
<Markdown className="text-[15px]">{question.rationale}</Markdown>
</div>
)}
{p.renderExtra?.(
question,
question.options.filter((o) => selected.includes(o.id)).map((o) => o.text),
)}
</div>
)}
</div>
</main>
<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 flex h-[68px] max-w-3xl items-center gap-2 px-3 sm:px-5">
<Button size="lg" variant="ghost" icon={<ArrowLeft />} onClick={() => go(index - 1)} disabled={index === 0} aria-label="Previous question">
<span className="hidden sm:inline">Back</span>
</Button>
<Button size="lg" variant={flagged ? 'marker' : 'ghost'} icon={<Flag className={flagged ? 'fill-current' : undefined} />} onClick={toggleFlag} aria-pressed={flagged}>
<span className="hidden sm:inline">{flagged ? 'Flagged' : 'Flag'}</span>
</Button>
<div className="flex-1" />
{p.mode === 'practice' && !checked ? (
<>
<Button size="lg" variant="ghost" onClick={() => (isLast ? requestFinish() : go(index + 1))}>
{isLast ? 'Finish' : 'Skip'}
</Button>
<Button size="lg" variant="primary" disabled={selected.length === 0} onClick={check} className="min-w-32">
Check
<span className="hidden sm:inline">
<Kbd>↵</Kbd>
</span>
</Button>
</>
) : isLast ? (
<Button size="lg" variant="primary" loading={p.finishing} onClick={requestFinish} className="min-w-32">
{p.mode === 'exam' ? 'Submit exam' : 'See results'}
</Button>
) : (
<>
{p.mode === 'exam' && answeredCount === total && (
<Button size="lg" variant="ghost" loading={p.finishing} onClick={requestFinish}>
Submit
</Button>
)}
<Button size="lg" variant="primary" onClick={() => go(index + 1)} className="min-w-32">
Next <ArrowRight className="size-4" />
</Button>
</>
)}
</div>
</footer>
<Dialog
open={navOpen}
onOpenChange={setNavOpen}
title="Questions"
description={`${answeredCount} of ${total} answered${p.flags.length ? `, ${p.flags.length} flagged` : ''}`}
footer={
<Button variant="primary" loading={p.finishing} onClick={() => (setNavOpen(false), void requestFinish())}>
{p.mode === 'exam' ? 'Submit exam' : 'Finish'}
</Button>
}
>
<div className="grid grid-cols-6 gap-2 sm:grid-cols-8">
{p.questions.map((q, i) => {
const s = statusOf(q);
return (
<button
key={q.id}
type="button"
aria-label={`Question ${i + 1}, ${s === 'blank' ? 'not answered' : s === 'answered' ? 'answered' : s === 'right' ? 'correct' : 'incorrect'}${p.flags.includes(q.id) ? ', flagged' : ''}`}
aria-current={i === index}
onClick={() => (go(i), setNavOpen(false))}
className={cx(
'num relative grid aspect-square place-items-center rounded-[10px] border text-sm font-semibold',
s === 'right' ? 'border-good bg-good-soft text-good' : s === 'wrong' ? 'border-bad bg-bad-soft text-bad' : s === 'answered' ? 'border-ink bg-ink text-paper' : 'border-line-strong text-ink-2 hover:border-ink-3',
i === index && 'ring-2 ring-accent ring-offset-2 ring-offset-surface',
)}
>
{i + 1}
{p.flags.includes(q.id) && <span className="absolute -top-1 -right-1 size-3 rounded-full bg-marker ring-2 ring-surface" />}
</button>
);
})}
</div>
<div className="mt-5 hidden flex-wrap gap-x-4 gap-y-2 text-xs text-ink-3 sm:flex">
<span className="flex items-center gap-1.5">
<Kbd>1</Kbd>–<Kbd>9</Kbd> or <Kbd>A</Kbd>–<Kbd>E</Kbd> choose
</span>
<span className="flex items-center gap-1.5">
<Kbd>Enter</Kbd> check / next
</span>
<span className="flex items-center gap-1.5">
<Kbd>←</Kbd>
<Kbd>→</Kbd> move
</span>
<span className="flex items-center gap-1.5">
<Kbd>M</Kbd> flag
</span>
</div>
</Dialog>
</div>
);
}
/* ------------------------------ results ------------------------------ */
export interface ResultsProps {
title: string;
mode: 'practice' | 'exam';
questions: SnapshotQuestion[];
answers: Record<string, AnswerState>;
flags: string[];
elapsedSec: number;
sataScoring: SataScoring;
completedAt?: number | null;
actions: ReactNode;
onExit: () => void;
exitLabel?: string;
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
footnote?: ReactNode;
}
export function QuizResults(p: ResultsProps) {
const [filter, setFilter] = useState<'all' | 'wrong' | 'flagged'>('all');
const rows = useMemo(
() =>
p.questions.map((q, i) => {
const selected = p.answers[q.id]?.selected ?? [];
const answered = selected.length > 0;
const score = scoreQuestion(q, selected, p.sataScoring);
return { q, i, selected, answered, score, correct: isFullyCorrect(score), scored: p.mode === 'exam' || answered };
}),
[p.questions, p.answers, p.sataScoring, p.mode],
);
const scored = rows.filter((r) => r.scored);
const points = scored.reduce((n, r) => n + r.score, 0);
const percent = scored.length ? Math.round((points / scored.length) * 100) : 0;
const right = scored.filter((r) => r.correct).length;
const partial = scored.filter((r) => !r.correct && r.score > 0).length;
const wrong = scored.length - right - partial;
const skipped = rows.length - scored.length;
const tone = percent >= 80 ? 'good' : percent >= 60 ? 'warn' : 'bad';
const topics = useMemo(() => {
const map = new Map<string, { n: number; s: number }>();
for (const r of scored) {
const key = r.q.topic || 'General';
const cur = map.get(key) ?? { n: 0, s: 0 };
cur.n += 1;
cur.s += r.score;
map.set(key, cur);
}
return [...map.entries()].map(([topic, v]) => ({ topic, n: v.n, accuracy: v.s / v.n })).sort((a, b) => a.accuracy - b.accuracy);
}, [scored]);
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
const headline = percent >= 90 ? 'Excellent work' : percent >= 80 ? 'Strong result' : percent >= 60 ? 'Getting there' : 'Worth another pass';
return (
<div className="min-h-dvh bg-paper">
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-3 sm:px-5">
<IconButton label={p.exitLabel ?? 'Close'} onClick={p.onExit}>
<X />
</IconButton>
<div className="min-w-0 flex-1 truncate text-sm font-semibold">{p.title}</div>
</div>
</header>
<main className="mx-auto max-w-3xl animate-in px-4 pt-8 pb-24 sm:px-5">
<section className="card p-6 sm:p-8">
<div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-left">
<Ring value={percent / 100} size={128} stroke={11} tone={tone}>
<div className="leading-none">
<span className="display num text-[38px] font-medium">{percent}</span>
<span className="text-lg text-ink-3">%</span>
</div>
</Ring>
<div className="min-w-0 flex-1">
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
<h1 className="display text-[30px]">{headline}</h1>
<p className="mt-1.5 text-[15px] text-ink-2">
<span className="num font-semibold text-ink">{Number.isInteger(points) ? points : points.toFixed(1)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
{p.elapsedSec > 0 ? ` in ${formatMinutes(p.elapsedSec)}` : ''}
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
</p>
<div className="mt-3 flex flex-wrap justify-center gap-1.5 sm:justify-start">
<Badge tone="good">{right} correct</Badge>
{partial > 0 && <Badge tone="warn">{partial} partly</Badge>}
{wrong > 0 && <Badge tone="bad">{wrong} incorrect</Badge>}
</div>
</div>
</div>
<div className="mt-6 flex flex-wrap justify-center gap-2 border-t border-line pt-5 sm:justify-start">{p.actions}</div>
{p.footnote && <div className="mt-4 text-[13px] text-ink-3">{p.footnote}</div>}
</section>
{topics.length > 1 && (
<section className="mt-6">
<h2 className="eyebrow mb-2.5">By topic</h2>
<div className="card divide-y divide-line">
{topics.map((t) => {
const pc = Math.round(t.accuracy * 100);
return (
<div key={t.topic} className="flex items-center gap-3 px-4 py-2.5">
<span className="min-w-0 flex-1 truncate text-sm font-medium">{t.topic}</span>
<span className="text-xs text-ink-3">{plural(t.n, 'question')}</span>
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-ink/8 sm:w-36">
<div className={cx('h-full rounded-full', pc >= 80 ? 'bg-good' : pc >= 60 ? 'bg-warn' : 'bg-bad')} style={{ width: `${Math.max(4, pc)}%` }} />
</div>
<span className="num w-10 text-right text-[13px] font-medium">{pc}%</span>
</div>
);
})}
</div>
</section>
)}
<section className="mt-8">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<h2 className="eyebrow">Review</h2>
<Segmented
size="sm"
label="Filter questions"
value={filter}
onChange={setFilter}
options={[
{ value: 'all', label: `All ${rows.length}` },
{ value: 'wrong', label: `Missed ${scored.length - right}` },
...(p.flags.length > 0 ? [{ value: 'flagged' as const, label: `Flagged ${p.flags.length}` }] : []),
]}
/>
</div>
{visible.length === 0 ? (
<div className="card px-5 py-8 text-center text-sm text-ink-2">{filter === 'wrong' ? 'Nothing missed. Every scored question was correct.' : 'No questions here.'}</div>
) : (
<ol className="space-y-3">
{visible.map((r) => (
<li key={r.q.id} className="card p-4 sm:p-5">
<div className="mb-2.5 flex flex-wrap items-center gap-2">
<span className="num text-xs font-semibold text-ink-3">{String(r.i + 1).padStart(2, '0')}</span>
{!r.scored ? <Badge>Skipped</Badge> : r.correct ? <Badge tone="good">Correct</Badge> : r.score > 0 ? <Badge tone="warn">Partly correct</Badge> : <Badge tone="bad">{r.answered ? 'Incorrect' : 'Not answered'}</Badge>}
{r.q.topic && <Badge tone="accent">{r.q.topic}</Badge>}
{p.flags.includes(r.q.id) && (
<Badge tone="marker">
<Flag /> Flagged
</Badge>
)}
</div>
<Markdown serif className="mb-3.5 text-[17px]">
{r.q.stem}
</Markdown>
<OptionList question={r.q} selected={r.selected} revealed />
{r.q.rationale && (
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
<div className="eyebrow mb-1">Rationale</div>
<Markdown className="text-[14.5px]">{r.q.rationale}</Markdown>
</div>
)}
{p.renderExtra && (
<div className="mt-3">
{p.renderExtra(
r.q,
r.q.options.filter((o) => r.selected.includes(o.id)).map((o) => o.text),
)}
</div>
)}
</li>
))}
</ol>
)}
</section>
</main>
</div>
);
}
export function RetakeIcon() {
return <RotateCcw />;
}

42
web/src/features/study.ts Normal file
View file

@ -0,0 +1,42 @@
import { useState } from 'react';
import { useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { useRefresh } from '@/lib/queries';
import type { Attempt } from '@/lib/types';
export type AttemptSource =
| { type: 'quiz'; quizId: string }
| { type: 'retake'; attemptId: string }
| { type: 'missed'; classId?: string; quizId?: string }
| { type: 'topics'; classId: string; topics: string[] }
| { type: 'questions'; questionIds: string[]; title?: string };
export interface StartOptions {
mode?: 'practice' | 'exam';
source: AttemptSource;
shuffleQuestions?: boolean;
shuffleOptions?: boolean;
count?: number;
timeLimitMin?: number | null;
}
/** Starts a quiz session and opens it. */
export function useStartSession() {
const navigate = useNavigate();
const refresh = useRefresh();
const [starting, setStarting] = useState(false);
const start = async (opts: StartOptions) => {
setStarting(true);
try {
const res = await api.post<{ attempt: Attempt }>('/api/attempts', { mode: 'practice', ...opts });
void refresh();
navigate(`/session/${res.attempt.id}`);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setStarting(false);
}
};
return { start, starting };
}