Second revision: MCP servers, shared-link AI, flashcard modes, document previews
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s

Generation
- Every quiz is NCLEX style; "Practice exam" writes 50 questions.
- Calculation questions only when the material involves calculations (max 5 per exam).
- Broad topics: the class's topics are listed in the prompt, a quick grouping call maps
  narrow labels onto broad ones, and leftover variants are merged.
- Exact select-all count per batch; option order shuffled.
- Python check: at most 3 runs, fixed problems count as passed, cosmetic remarks ignored.

Assistant
- Text, tool steps and cards appear in the order they happen, with paragraph breaks
  between steps.
- Optional thinking box: fixed height, follows the newest text, can be scrolled back.
- "+" opens a material picker listing recent items; items can be dragged in from class
  pages; shorter placeholder.

MCP servers
- Streamable HTTP client; encrypted headers.
- Per-server instructions and switches for chat, Explain, generation and the quiz check.
- Settings UI.

Share links
- Optional "Explain this" and "Ask about this material" per link, off by default.
- Items are loaded on the server and checked against the share; no tools; rate-limited.
- Migration 4 stores the switches.

Study and documents
- Standard flashcard mode (optionally repeat missed cards until known) next to spaced
  repetition.
- Streak visuals restyled in the app palette.
- Side by side / Original document views, with sandboxed previews of Word and PowerPoint
  files.

Other
- Built-in embedding model baked into the image; sharp stubbed if it cannot load; real
  load error shown in Settings.
- Python runner blocks network and process modules in JavaScript too.
- "View questions and answers" removed from the quiz start screen.
- Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 15:48:54 -07:00
parent 5ea61c882c
commit 031f7bec31
45 changed files with 2918 additions and 397 deletions

View file

@ -37,7 +37,7 @@ import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { ImportDialog } from '@/features/ImportDialog';
import { useStartSession } from '@/features/study';
import { api, errorMessage, uploadWithProgress } from '@/lib/api';
import { assistant, useAssistantContext } from '@/lib/assistantStore';
import { assistant, ITEM_DRAG_TYPE, useAssistantContext } from '@/lib/assistantStore';
import { useClass, useRefresh } from '@/lib/queries';
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
@ -276,7 +276,15 @@ export default function ClassPage() {
{sortable?.handle}
<KindIcon item={item} />
<div className="min-w-0 flex-1">
<Link to={`/${ITEM_URL[item.kind]}/${item.id}`} className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0">
<Link
to={`/${ITEM_URL[item.kind]}/${item.id}`}
className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0"
onDragStart={(e) => {
// Dropping this onto the assistant adds it to the chat.
e.dataTransfer.setData(ITEM_DRAG_TYPE, JSON.stringify({ kind: item.kind, id: item.id, title: item.title }));
e.dataTransfer.effectAllowed = 'copyLink';
}}
>
{item.title}
</Link>
<div className="mt-0.5 flex items-center gap-x-2.5 overflow-hidden text-xs whitespace-nowrap text-ink-3">

View file

@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { useNavigate, useParams, useSearchParams } from 'react-router';
import { Explain } from '@/features/Explain';
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
import { api, errorMessage } from '@/lib/api';
@ -7,23 +7,33 @@ import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
import { useDocumentTitle } from '@/lib/util';
import { Button, EmptyState, ErrorState, PageLoading } from '@/ui';
/** Browse every card in a deck, self-graded. Does not affect the spaced-repetition schedule. */
/** Standard study: every card in a deck, self-graded. Does not affect the spaced-repetition schedule. */
export default function CramPage() {
const { deckId = '' } = useParams();
const [params, setParams] = useSearchParams();
const navigate = useNavigate();
const refresh = useRefresh();
const ai = useAiStatus();
const q = useDeck(deckId);
const data = q.data;
useDocumentTitle(data ? `Browse · ${data.deck.title}` : undefined);
useDocumentTitle(data ? `Study · ${data.deck.title}` : undefined);
const [state, setState] = useState<CramState | null>(null);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const latest = useRef<CramState | null>(null);
useEffect(() => {
if (!data || state) return;
// ?new=1 starts a fresh session with the options chosen on the deck page; otherwise resume.
if (params.get('new')) {
const next = freshCramState(data.cards, params.get('shuffle') === '1', 1, params.get('repeat') === '1');
setState(next);
latest.current = next;
void api.put(`/api/decks/${deckId}/session`, { state: next }).catch(() => undefined);
setParams({}, { replace: true });
return;
}
setState(reconcileCramState(data.session?.state as CramState | null, data.cards) ?? freshCramState(data.cards, false));
}, [data, state]);
}, [data, state, params, setParams, deckId]);
const persist = (next: CramState) => {
setState(next);

View file

@ -9,10 +9,10 @@ import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { api, errorMessage } from '@/lib/api';
import { useAssistantContext } from '@/lib/assistantStore';
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
import { cx, downloadFile, plural, useDocumentTitle } from '@/lib/util';
import { cx, downloadFile, plural, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { SortableList } from '@/ui/Sortable';
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Tooltip, useConfirm } from '@/ui';
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Switch, Tooltip, useConfirm } from '@/ui';
import { BulkAddDialog } from './QuizPage';
function dueLabel(card: Card): { text: string; tone: 'neutral' | 'accent' | 'good' | 'warn' } {
@ -24,6 +24,87 @@ function dueLabel(card: Card): { text: string; tone: 'neutral' | 'accent' | 'goo
return { text: days === 1 ? 'Tomorrow' : days < 31 ? `${days} days` : days < 365 ? `${Math.round(days / 30)} mo` : `${(days / 365).toFixed(1)} y`, tone: 'good' };
}
interface DeckStudyPrefs {
mode: 'standard' | 'srs';
/** Standard mode: missed cards come round again until they are known. */
repeatMissed: boolean;
shuffle: boolean;
}
/** Pick how to study the deck: a standard pass (know it / still learning) or spaced repetition. */
function StudyPanel({ deckId, cardCount, due, hasSession }: { deckId: string; cardCount: number; due: number; hasSession: boolean }) {
const navigate = useNavigate();
const [prefs, setPrefs] = useLocalStorage<DeckStudyPrefs>('sd.deckStudyPrefs', { mode: 'standard', repeatMissed: true, shuffle: true });
if (cardCount === 0) return null;
const srs = prefs.mode === 'srs';
const start = () => navigate(srs ? `/review?deckId=${deckId}` : `/decks/${deckId}/cram?new=1&repeat=${prefs.repeatMissed ? 1 : 0}&shuffle=${prefs.shuffle ? 1 : 0}`);
return (
<section className="card mb-6 p-5 sm:p-6" aria-label="Study this deck">
{hasSession && !srs && (
<Callout
tone="warn"
icon={<Play />}
className="mb-5"
title="You have a session in progress"
action={
<Button to={`/decks/${deckId}/cram`} variant="marker" size="sm">
Resume
</Button>
}
>
Pick up where you left off, or start a new one below.
</Callout>
)}
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Study mode">
{(
[
{ v: 'standard', title: 'Standard', body: 'Go through the cards and mark each one known or still learning. Your review schedule is not changed.' },
{ v: 'srs', title: 'Spaced repetition', body: 'Review the cards that are due. How well you remember each one sets when it comes back.' },
] as const
).map((m) => (
<button
key={m.v}
type="button"
role="radio"
aria-checked={prefs.mode === m.v}
onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))}
className={cx('rounded-xl border p-3.5 text-left transition-colors', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}
>
<div className="font-semibold">{m.title}</div>
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.body}</div>
</button>
))}
</div>
{srs ? (
<p className="mt-4 text-[13px] text-ink-2">
{due > 0 ? (
<>
<strong className="marker num text-ink">{due}</strong> {due === 1 ? 'card is' : 'cards are'} due now, including new cards for today.
</>
) : (
'Nothing is due right now. Cards come back when they are due; use Standard to go through them any time.'
)}
</p>
) : (
<div className="mt-4 space-y-4 rounded-xl border border-line p-4">
<Switch
checked={prefs.repeatMissed}
onChange={(v) => setPrefs((p) => ({ ...p, repeatMissed: v }))}
label="Repeat missed cards until I know them"
description={prefs.repeatMissed ? 'A card you miss goes to the back of the pile and comes round again.' : 'Go through the deck once, then choose whether to study the missed cards.'}
/>
<Switch checked={prefs.shuffle} onChange={(v) => setPrefs((p) => ({ ...p, shuffle: v }))} label="Shuffle cards" />
</div>
)}
<div className="mt-5 flex flex-wrap items-center gap-2 border-t border-line pt-5">
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} onClick={start} disabled={srs && due === 0} className="min-w-40">
{srs ? (due > 0 ? `Review ${due}` : 'Nothing due') : hasSession ? 'Start new session' : 'Start'}
</Button>
</div>
</section>
);
}
export default function DeckPage() {
const { deckId = '' } = useParams();
const [params, setParams] = useSearchParams();
@ -123,7 +204,6 @@ export default function DeckPage() {
{ label: 'Young', n: stats.young, cls: 'bg-good/55' },
{ label: 'Mature', n: stats.mature, cls: 'bg-good' },
];
const canStudy = due.total > 0;
return (
<div className={cx('animate-in', `tab-${data.class.color}`)}>
@ -155,12 +235,6 @@ export default function DeckPage() {
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button to={`/review?deckId=${deck.id}`} variant={canStudy ? 'primary' : 'secondary'} size="lg" icon={<Play className="fill-current" />} disabled={!canStudy}>
{canStudy ? `Review ${due.total}` : 'Nothing due'}
</Button>
<Button to={`/decks/${deck.id}/cram`} size="lg" icon={<Layers />} disabled={cards.length === 0}>
{data.session ? 'Continue browsing' : 'Browse all'}
</Button>
<Menu
trigger={
<IconButton label="Deck options" tooltip={false}>
@ -215,6 +289,8 @@ export default function DeckPage() {
</div>
</header>
<StudyPanel deckId={deck.id} cardCount={cards.length} due={due.total} hasSession={Boolean(data.session)} />
{stats.total > 0 && (
<div className="card mb-6 p-4">
<div className="flex h-2.5 overflow-hidden rounded-full bg-ink/8" role="img" aria-label={segments.map((s) => `${s.n} ${s.label.toLowerCase()}`).join(', ')}>

View file

@ -1,5 +1,5 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { BookOpen, ChevronRight, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
import { BookOpen, ChevronRight, Columns2, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
@ -9,7 +9,7 @@ import { api, errorMessage } from '@/lib/api';
import { assistant, useAssistantContext } from '@/lib/assistantStore';
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
import type { ClassInfo, DocChunk, DocumentInfo, Share } from '@/lib/types';
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle } from '@/lib/util';
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Spinner, useConfirm } from '@/ui';
@ -36,7 +36,7 @@ export default function DocumentPage() {
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const [view, setView] = useState<'text' | 'original'>('text');
const [view, setView] = useLocalStorage<'text' | 'side' | 'original'>('sd.documentView', 'text');
const [rename, setRename] = useState(false);
const [move, setMove] = useState(false);
const [share, setShare] = useState(false);
@ -77,7 +77,7 @@ export default function DocumentPage() {
}
const cls = q.data.class;
const busy = doc.status === 'pending' || doc.status === 'processing';
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image';
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image' || doc.docKind === 'docx' || doc.docKind === 'pptx';
const fileUrl = `/api/documents/${doc.id}/file`;
const reprocess = async (ocr: boolean) => {
@ -99,6 +99,65 @@ export default function DocumentPage() {
}
};
const all = chunks.data?.pages.flatMap((p) => p.chunks) ?? [];
const office = doc.docKind === 'docx' || doc.docKind === 'pptx';
const originalView = (height: string) =>
doc.docKind === 'image' ? (
<div className="card grid place-items-center p-4">
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
</div>
) : (
// Office previews are self-contained HTML; the server sandboxes them with its Content-Security-Policy.
<iframe src={office ? `/api/documents/${doc.id}/preview` : fileUrl} title={`${doc.title} (original)`} className={cx('card w-full bg-surface', height)} />
);
const noText = !ready ? null : doc.chunkCount === 0 ? (
<div className="card">
<EmptyState icon={<FileText />} title="No text to show">
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
</EmptyState>
</div>
) : null;
const articleView = (
<div className="min-w-0">
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
<article className="card divide-y divide-line">
{chunks.isLoading && (
<div className="space-y-3 p-6">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4" />
<Skeleton className="h-4 w-5/6" />
</div>
)}
{all.map((ch, i) => {
const prev = all[i - 1];
const showHeading = ch.heading && ch.heading !== prev?.heading;
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
return (
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
{(showHeading || showPage) && (
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
{showPage && (
<span className="num text-[11px] text-ink-3">
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
</span>
)}
</div>
)}
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
</section>
);
})}
</article>
{chunks.hasNextPage && (
<div className="mt-4 flex justify-center">
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
Show more
</Button>
</div>
)}
</div>
);
return (
<div className={cx('animate-in', `tab-${cls.color}`)}>
@ -239,6 +298,7 @@ export default function DocumentPage() {
onChange={setView}
options={[
{ value: 'text', label: 'Extracted text', icon: <FileText /> },
{ value: 'side', label: 'Side by side', icon: <Columns2 /> },
{ value: 'original', label: 'Original', icon: <ScanText /> },
]}
/>
@ -246,94 +306,50 @@ export default function DocumentPage() {
)}
{view === 'original' && hasOriginal ? (
doc.docKind === 'image' ? (
<div className="card grid place-items-center p-4">
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
</div>
) : (
<iframe src={fileUrl} title={doc.title} className="card h-[82vh] w-full" />
)
) : !ready ? null : doc.chunkCount === 0 ? (
<div className="card">
<EmptyState icon={<FileText />} title="No text to show">
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
</EmptyState>
originalView('h-[82vh]')
) : view === 'side' && hasOriginal ? (
<div className="grid items-start gap-4 lg:grid-cols-2">
<div className="lg:sticky lg:top-4">{originalView('h-[60vh] lg:h-[calc(100dvh-2rem)]')}</div>
<div className="min-w-0">{ready ? (noText ?? articleView) : null}</div>
</div>
) : (
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
<div className="min-w-0">
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
<article className="card divide-y divide-line">
{chunks.isLoading && (
<div className="space-y-3 p-6">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4" />
<Skeleton className="h-4 w-5/6" />
) : !ready ? null : (
noText ?? (
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
{articleView}
{q.data.outline.length > 1 && (
<aside className="hidden lg:block">
<div className="sticky top-8">
<div className="eyebrow mb-2">Outline</div>
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
{q.data.outline.map((o) => (
<li key={o.seq}>
<button
type="button"
onClick={async () => {
// Load forward until the section is on the page, then scroll to it.
let pages = chunks.data?.pages ?? [];
let guard = 0;
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
const res = await chunks.fetchNextPage();
pages = res.data?.pages ?? [];
guard += 1;
}
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
}}
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
title={o.heading}
>
{o.heading}
</button>
</li>
))}
</ul>
</div>
)}
{all.map((ch, i) => {
const prev = all[i - 1];
const showHeading = ch.heading && ch.heading !== prev?.heading;
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
return (
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
{(showHeading || showPage) && (
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
{showPage && (
<span className="num text-[11px] text-ink-3">
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
</span>
)}
</div>
)}
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
</section>
);
})}
</article>
{chunks.hasNextPage && (
<div className="mt-4 flex justify-center">
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
Show more
</Button>
</div>
</aside>
)}
</div>
{q.data.outline.length > 1 && (
<aside className="hidden lg:block">
<div className="sticky top-8">
<div className="eyebrow mb-2">Outline</div>
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
{q.data.outline.map((o) => (
<li key={o.seq}>
<button
type="button"
onClick={async () => {
// Load forward until the section is on the page, then scroll to it.
let pages = chunks.data?.pages ?? [];
let guard = 0;
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
const res = await chunks.fetchNextPage();
pages = res.data?.pages ?? [];
guard += 1;
}
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
}}
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
title={o.heading}
>
{o.heading}
</button>
</li>
))}
</ul>
</div>
</aside>
)}
</div>
)
)}
<RenameDialog target={rename ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setRename(false)} />

View file

@ -154,9 +154,6 @@ function StartPanel({ quizId, total, resume, onShowQuestions }: { quizId: string
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go} className="min-w-40">
{resume ? 'Start new session' : 'Start'}
</Button>
<Button variant="ghost" size="lg" icon={<ClipboardList />} onClick={onShowQuestions} className="ml-auto">
View questions and answers
</Button>
</div>
</section>
);

View file

@ -3,7 +3,9 @@ import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
import { Explain } from '@/features/Explain';
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
import { SharedAssistant } from '@/features/SharedAssistant';
import { QuizResults, QuizRunner } from '@/features/quiz';
import { api, ApiError } from '@/lib/api';
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
@ -116,7 +118,8 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
};
}
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
const renderExtra = explainUrl ? (q: SnapshotQuestion, selected: string[]) => <Explain url={explainUrl} body={{ kind: 'question', quizId: quiz.id, questionId: q.id, selected }} /> : undefined;
const [state, setState] = useLocalStorage<QuizState | null>(storageKey, null);
const [prefs, setPrefs] = useLocalStorage('sd.pub.prefs2', { mode: 'practice' as 'practice' | 'exam', shuffleQ: true, shuffleO: true, timed: false, minutes: 0 });
const minutes = prefs.minutes > 0 ? prefs.minutes : Math.max(5, Math.round(quiz.questions.length * 1.2));
@ -169,6 +172,7 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
onExit={() => (setState(null), setRunning(false))}
exitLabel="Back to start"
footnote="This result is stored in your browser only. The person who shared the quiz cannot see it."
renderExtra={renderExtra}
actions={
<>
{missed.length > 0 && (
@ -199,6 +203,7 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
deadlineAt={state.deadlineAt ?? null}
sataScoring="partial"
exitLabel={state.deadlineAt ? 'Leave (the clock keeps running)' : 'Pause'}
renderExtra={renderExtra}
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
onFlags={(flags) => setState((s) => (s ? { ...s, flags } : s))}
onIndex={(index) => setState((s) => (s ? { ...s, index } : s))}
@ -283,13 +288,24 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
/* ------------------------------ deck ------------------------------ */
function SharedDeck({ deck, storageKey, back }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string } }) {
function SharedDeck({ deck, storageKey, back, explainUrl }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
const [saved, setSaved] = useLocalStorage<CramState | null>(storageKey, null);
const [running, setRunning] = useState(false);
const state = useMemo(() => reconcileCramState(saved, deck.cards), [saved, deck.cards]);
if (running && state) {
return <CramSession title={deck.title} subtitle="Shared flashcards" cards={deck.cards} state={state} onState={setSaved} onExit={() => setRunning(false)} exitLabel="Pause" />;
return (
<CramSession
title={deck.title}
subtitle="Shared flashcards"
cards={deck.cards}
state={state}
onState={setSaved}
onExit={() => setRunning(false)}
exitLabel="Pause"
renderExtra={explainUrl ? (card) => <Explain url={explainUrl} body={{ kind: 'card', deckId: deck.id, cardId: card.id }} /> : undefined}
/>
);
}
const seen = state ? Math.min(state.index, state.order.length) : 0;
return (
@ -456,16 +472,26 @@ export default function SharedPage() {
}
const back = nested ? { to: `/s/${token}`, label: 'All materials' } : undefined;
const key = `sd.pub.${token.slice(0, 12)}.${data.kind}.${'id' in data ? data.id : ''}`;
switch (data.kind) {
case 'quiz':
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} />;
case 'deck':
return <SharedDeck key={key} deck={data} storageKey={key} back={back} />;
case 'note':
return <SharedNote note={data} back={back} />;
case 'document':
return <SharedDocument doc={data} token={token} nested={nested} back={back} />;
case 'collection':
return <SharedCollection data={data} token={token} />;
}
const explainUrl = data.ai?.explain ? `/api/public/${token}/explain` : undefined;
const assistant = data.ai?.assistant ? <SharedAssistant token={token} title={data.title} item={nested && data.kind !== 'collection' ? { kind: data.kind, id: data.id } : undefined} /> : null;
const page = (() => {
switch (data.kind) {
case 'quiz':
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} explainUrl={explainUrl} />;
case 'deck':
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} />;
case 'note':
return <SharedNote note={data} back={back} />;
case 'document':
return <SharedDocument doc={data} token={token} nested={nested} back={back} />;
case 'collection':
return <SharedCollection data={data} token={token} />;
}
})();
return (
<>
{page}
{assistant}
</>
);
}