/** * 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). Finished sets join the link's regular lists (marked * "New" for a while); this section only shows sets still being written, and failed ones until * the visitor dismisses them. The owner's link allows a few sets a day. */ import { useQuery, useQueryClient } from '@tanstack/react-query'; import { BookOpen, CircleAlert, FileText, Layers, Sparkles, X } from 'lucide-react'; import { useEffect, useState } from 'react'; import { api, errorMessage } from '@/lib/api'; import type { PublicCollection, SharedGenerated } from '@/lib/types'; import { cx } from '@/lib/util'; import { Button, Callout, Dialog, Field, IconButton, 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(`/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; // A set that just finished is now part of the class: reload the link's materials. const readyKey = (info?.sets ?? []).filter((s) => s.status === 'ready').map((s) => s.id).join(','); useEffect(() => { if (readyKey) void qc.invalidateQueries({ queryKey: ['public', token, '', ''] }); }, [readyKey, qc, token]); if (!info) return null; const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used); // Finished sets are listed with the rest of the link; here only what is still being written (or failed). const pending = info.sets.filter((s) => s.status === 'generating' || s.status === 'failed'); const dismiss = async (id: string) => { qc.setQueryData(key, (old) => (old ? { ...old, sets: old.sets.filter((s) => s.id !== id) } : old)); await api.pubPost(`/api/public/${token}/generated/${id}/dismiss`, {}).catch(() => undefined); }; return (

Make your own practice

{pending.length > 0 && (

In progress {pending.filter((s) => s.status === 'generating').length || ''}

    {pending.map((s) => (
  • svg]:size-[18px]', s.status === 'failed' ? 'bg-bad-soft text-bad' : s.kind === 'quiz' ? 'bg-accent-soft text-accent' : 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker')}> {s.status === 'failed' ? : s.kind === 'quiz' ? : } {s.status === 'generating' ? (s.kind === 'quiz' ? 'New quiz' : 'New flashcards') : s.title} {s.status === 'generating' ? s.progressLabel || 'Starting…' : s.error} {s.status === 'generating' && } {s.status === 'failed' && ( void dismiss(s.id)}> )}
  • ))}
)} setOpen(false)} token={token} info={info} allDocuments={data.items.filter((i) => i.kind === 'document')} exams={data.folders} onStarted={(next) => qc.setQueryData(key, next)} />
); } function GenerateDialog({ open, onClose, token, info, allDocuments, exams, onStarted, }: { open: boolean; onClose: () => void; token: string; info: SharedGenerated; allDocuments: PublicCollection['items']; /** A class link's exams (empty on an exam link, which is one exam already). */ exams: PublicCollection['folders']; onStarted: (next: SharedGenerated) => void; }) { const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used); // On a class link the visitor picks the exam: its materials are offered, and the set is saved into it. const inExam = (examId: string) => allDocuments.filter((d) => (examId ? d.folderId === examId : !d.folderId || !exams.some((e) => e.id === d.folderId))); const looseCount = exams.length ? inExam('').length : 0; const [examId, setExamId] = useState(''); const documents = exams.length ? inExam(examId) : allDocuments; const [kind, setKind] = useState('quiz'); const [count, setCount] = useState(info.limits.quizMax); const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed'); const [docIds, setDocIds] = useState([]); 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); // Start on the latest exam that has materials. const start = exams.length ? ([...exams].reverse().find((e) => inExam(e.id).length > 0)?.id ?? '') : ''; setExamId(start); setDocIds((exams.length ? inExam(start) : allDocuments).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, ...(exams.length ? { examId: examId || null } : {}), 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 ( !o && onClose()} title="Make your own practice" footer={ <> } >
{ setKind(k); setCount(k === 'quiz' ? info.limits.quizMax : 30); }} options={[ { value: 'quiz', label: `Quiz (${left('quiz')} left today)`, icon: }, { value: 'deck', label: `Flashcards (${left('deck')} left)`, icon: }, ]} className="w-full" /> {none && This link has made all its {kind === 'quiz' ? 'quizzes' : 'flashcard sets'} for today. Try again tomorrow.} {exams.length > 0 && ( )}
setCount(Math.max(1, Math.min(max, Number(e.target.value) || 1)))} />
Class materials to use
{documents.map((d) => ( ))}
{kind === 'quiz' && ( )} {error && ( {error} )}
); }