Share-link generation and med math on request
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 34s

- Visitors of class and exam links can generate NCLEX-style quizzes (default
  and maximum 50 questions, 25% select-all, Python-checked, optional 5 med
  math questions) and flashcard sets from chosen class materials, once the
  owner turns it on for the link.
- 4 quizzes and 2 flashcard sets per link per day; failed attempts do not
  count; "Reset limits" in the share dialog gives a fresh allowance.
- Sets are drafts tied to the link (migration 7): listed for every visitor,
  explainable, kept off the owner's drafts list, and reviewable or savable
  from the share dialog.
- Generate gains "Include med math" with a count (default 5): exactly that
  many dosage calculation questions at the chosen difficulty, spread through
  the quiz, even when the material has none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 22:04:08 -07:00
parent 25bc03ea75
commit e945f589ce
16 changed files with 807 additions and 44 deletions

View file

@ -0,0 +1,239 @@
/**
* Generating on a share link: visitors of a shared class or exam make their own NCLEX-style
* quiz or flashcard set from its class materials, with only the choices that matter (how many,
* how hard, which materials, med math). The owner's link allows a few sets a day.
*/
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { BookOpen, ChevronRight, CircleAlert, FileText, Layers, Sparkles } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link } from 'react-router';
import { api, errorMessage } from '@/lib/api';
import type { PublicCollection, SharedGenerated } from '@/lib/types';
import { cx, plural } from '@/lib/util';
import { Button, Callout, Dialog, Field, Input, ProgressBar, Segmented, Select, Switch } from '@/ui';
type Kind = 'quiz' | 'deck';
export function SharedGenerate({ token, data }: { token: string; data: PublicCollection }) {
const qc = useQueryClient();
const key = ['public', token, 'generated'];
const q = useQuery({
queryKey: key,
queryFn: ({ signal }) => api.pub<SharedGenerated>(`/api/public/${token}/generated`, signal),
// While a set is being written, check on it every few seconds.
refetchInterval: (query) => (query.state.data?.sets.some((s) => s.status === 'generating') ? 3000 : false),
});
const [open, setOpen] = useState(false);
const info = q.data;
if (!info) return null;
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
const quizzes = info.sets.filter((s) => s.kind === 'quiz');
const decks = info.sets.filter((s) => s.kind === 'deck');
return (
<section className="mt-7" aria-label="Practice made with AI">
<div className="mb-2.5 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="text-[17px] font-semibold">Make your own practice</h2>
<p className="text-[13px] text-ink-3">
NCLEX-style quizzes and flashcards from these class materials. Left today: {plural(left('quiz'), 'quiz', 'quizzes')}, {plural(left('deck'), 'flashcard set')}.
</p>
</div>
<Button variant="primary" onClick={() => setOpen(true)} disabled={left('quiz') + left('deck') === 0}>
Generate
</Button>
</div>
{info.sets.length > 0 && (
<div className="card overflow-hidden">
{[
['quiz', 'Quizzes', quizzes] as const,
['deck', 'Flashcards', decks] as const,
]
.filter(([, , list]) => list.length > 0)
.map(([kind, heading, list], n) => (
<section key={kind} aria-label={`AI-made ${heading.toLowerCase()}`}>
<h3 className={cx('eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5', n > 0 && 'border-t')}>
{kind === 'quiz' ? <BookOpen /> : <Layers />}
{heading} made with AI
<span className="num font-normal">{list.length}</span>
</h3>
<ul className="divide-y divide-line">
{list.map((s) => {
const icon = (
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', s.status === 'failed' ? 'bg-bad-soft text-bad' : kind === 'quiz' ? 'bg-accent-soft text-accent' : 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker')}>
{s.status === 'failed' ? <CircleAlert /> : s.status === 'generating' ? <Sparkles className="animate-pulse" /> : kind === 'quiz' ? <BookOpen /> : <Layers />}
</span>
);
if (s.status !== 'ready') {
return (
<li key={s.id} className="flex items-center gap-3 px-4 py-3.5">
{icon}
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{s.title}</span>
<span className={cx('text-xs', s.status === 'failed' ? 'text-bad' : 'text-ink-3')}>{s.status === 'failed' ? s.error : s.progressLabel || 'Starting…'}</span>
{s.status === 'generating' && <ProgressBar value={Math.max(0.04, s.progress)} className="mt-1.5 h-1" label={`Making ${s.title}`} />}
</span>
</li>
);
}
return (
<li key={s.id}>
<Link to={`/s/${token}/ai/${s.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
{icon}
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{s.title}</span>
<span className="text-xs text-ink-3">{plural(s.count, kind === 'quiz' ? 'question' : 'card')}</span>
</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
</li>
);
})}
</ul>
</section>
))}
</div>
)}
<GenerateDialog
open={open}
onClose={() => setOpen(false)}
token={token}
info={info}
documents={data.items.filter((i) => i.kind === 'document')}
onStarted={(next) => qc.setQueryData(key, next)}
/>
</section>
);
}
function GenerateDialog({
open,
onClose,
token,
info,
documents,
onStarted,
}: {
open: boolean;
onClose: () => void;
token: string;
info: SharedGenerated;
documents: PublicCollection['items'];
onStarted: (next: SharedGenerated) => void;
}) {
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
const [kind, setKind] = useState<Kind>('quiz');
const [count, setCount] = useState(info.limits.quizMax);
const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed');
const [docIds, setDocIds] = useState<string[]>([]);
const [math, setMath] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const max = kind === 'quiz' ? info.limits.quizMax : info.limits.deckMax;
useEffect(() => {
if (!open) return;
const k: Kind = left('quiz') > 0 || left('deck') === 0 ? 'quiz' : 'deck';
setKind(k);
setCount(k === 'quiz' ? info.limits.quizMax : 30);
setDocIds(documents.map((d) => d.id));
setError('');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const submit = async () => {
setBusy(true);
setError('');
try {
const res = await api.pubPost<{ set: SharedGenerated['sets'][number]; usage: SharedGenerated['usage'] }>(`/api/public/${token}/generate`, {
kind,
count,
difficulty,
documentIds: docIds.length === documents.length ? [] : docIds,
math: kind === 'quiz' && math,
});
onStarted({ ...info, sets: [res.set, ...info.sets], usage: res.usage });
onClose();
} catch (e) {
setError(errorMessage(e));
} finally {
setBusy(false);
}
};
const none = left(kind) === 0;
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Make your own practice"
description="Written by AI from this link's class materials. It takes a minute or two; you can keep studying meanwhile."
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={none || docIds.length === 0} onClick={() => void submit()}>
Generate
</Button>
</>
}
>
<div className="space-y-4">
<Segmented
label="What to make"
value={kind}
onChange={(k) => {
setKind(k);
setCount(k === 'quiz' ? info.limits.quizMax : 30);
}}
options={[
{ value: 'quiz', label: `Quiz (${left('quiz')} left today)`, icon: <BookOpen /> },
{ value: 'deck', label: `Flashcards (${left('deck')} left)`, icon: <Layers /> },
]}
className="w-full"
/>
{none && <Callout tone="warn">This link has made all its {kind === 'quiz' ? 'quizzes' : 'flashcard sets'} for today. Try again tomorrow.</Callout>}
<div className="grid gap-4 sm:grid-cols-2">
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'} hint={`Up to ${max}.`}>
<Input type="number" min={1} max={max} value={count} onChange={(e) => setCount(Math.max(1, Math.min(max, Number(e.target.value) || 1)))} />
</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>
</div>
<div>
<div className="mb-1.5 flex items-baseline justify-between text-[13px] font-medium">
<span>Class materials to use</span>
<button type="button" className="text-xs font-medium text-accent hover:underline" onClick={() => setDocIds(docIds.length === documents.length ? [] : documents.map((d) => d.id))}>
{docIds.length === documents.length ? 'Clear' : 'Select all'}
</button>
</div>
<div className="max-h-48 divide-y divide-line overflow-y-auto rounded-xl border border-line">
{documents.map((d) => (
<label key={d.id} className="flex cursor-pointer items-center gap-2.5 px-3 py-2.5 hover:bg-ink/3">
<input type="checkbox" className="size-4 accent-[var(--accent)]" checked={docIds.includes(d.id)} onChange={(e) => setDocIds(e.target.checked ? [...docIds, d.id] : docIds.filter((x) => x !== d.id))} />
<FileText className="size-4 shrink-0 text-ink-3" />
<span className="min-w-0 flex-1 truncate text-sm">{d.title}</span>
</label>
))}
</div>
</div>
{kind === 'quiz' && (
<Switch checked={math} onChange={setMath} label="Include med math" description={`Adds ${info.limits.mathQuestions} dosage calculation questions at this difficulty, even if the materials have none.`} />
)}
<p className="text-xs text-ink-3">{kind === 'quiz' ? 'NCLEX style with about 25% select-all-that-apply, double-checked with Python.' : 'One fact per card.'} AI can make mistakes: check anything important against the class materials.</p>
{error && (
<Callout tone="bad" className="py-2">
{error}
</Callout>
)}
</div>
</Dialog>
);
}