Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s

- Built-in Parallel web search (keyless; optional sign-in for higher limits and research)
  with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any
  MCP server, with token refresh and pre-registered client support
- Friendly tool steps (icon, name, status; details on click) and ids stripped from results;
  per-chat tool switches; taller thinking box
- Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only
  material for generation; class setting for what the groups are called
- Assistant can ask clarifying questions in an inline form before generating
- OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats
- Explain beside the quiz on wide screens, grounded in the cited source pages
- Quiz results: percentage ring coloured by score band, rainbow at 100
- Share links: assistant button like the owner's, hidden during quizzes; documents readable
  in the browser
- Live draft and library updates over server-sent events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 20:30:00 -07:00
parent 60cf2322f7
commit c595e0ff2c
54 changed files with 4710 additions and 387 deletions

View file

@ -1,6 +1,8 @@
import {
Archive,
ArrowDownAZ,
ArrowLeft,
ArrowRight,
BookOpen,
ChevronDown,
Clock,
@ -42,7 +44,7 @@ import { useClass, useRefresh } from '@/lib/queries';
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { SortableList, type SortableRenderProps } from '@/ui/Sortable';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
import { letterGrade } from '@shared/content';
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
@ -116,7 +118,18 @@ export default function ClassPage() {
const q = useClass(classId, polling ? 1500 : false);
const data = q.data;
useDocumentTitle(data?.class.name);
useAssistantContext(classId, data?.class.name);
/**
* The exam (folder) in view: a class is divided into exams, each with its own material.
* 'all' shows everything, 'none' what is in no exam. Remembered per class; new visitors start
* on the latest exam.
*/
const [examChoice, setExamChoice] = useLocalStorage<string>(`sd.exam.${classId}`, '');
const exams = data?.folders ?? [];
const examView = examChoice === 'all' || examChoice === 'none' || exams.some((f) => f.id === examChoice) ? examChoice : exams.length ? exams[exams.length - 1].id : 'all';
const currentExam = exams.find((f) => f.id === examView) ?? null;
const groupLabel = data?.class.groupLabel ?? 'Exam';
useAssistantContext(classId, currentExam ? `${data?.class.name} · ${currentExam.name}` : data?.class.name, [], currentExam?.id ?? null);
const [filter, setFilter] = useState<Filter>('all');
const [query, setQuery] = useState('');
@ -149,6 +162,7 @@ export default function ClassPage() {
setUploads((u) => [...u, { id, name: file.name, progress: 0 }]);
const form = new FormData();
form.append('classId', classId);
if (currentExam) form.append('folderId', currentExam.id);
form.append('file', file);
try {
await uploadWithProgress('/api/documents', form, (p) => setUploads((u) => u.map((x) => (x.id === id ? { ...x, progress: p } : x))));
@ -160,22 +174,35 @@ export default function ClassPage() {
}
};
/** Items of the exam in view. */
const scoped = useMemo(() => {
const items = data?.items ?? [];
const known = new Set((data?.folders ?? []).map((f) => f.id));
if (examView === 'all') return items;
if (examView === 'none') return items.filter((i) => !i.folderId || !known.has(i.folderId));
return items.filter((i) => i.folderId === examView);
}, [data, examView]);
const looseCount = useMemo(() => {
const known = new Set((data?.folders ?? []).map((f) => f.id));
return (data?.items ?? []).filter((i) => !i.folderId || !known.has(i.folderId)).length;
}, [data]);
const counts = useMemo(() => {
const c = { all: 0, quiz: 0, deck: 0, document: 0, note: 0 };
for (const i of data?.items ?? []) {
for (const i of scoped) {
c.all += 1;
c[i.kind] += 1;
}
return c;
}, [data]);
}, [scoped]);
const visible = useMemo(() => {
const needle = query.trim().toLowerCase();
const list = (data?.items ?? []).filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
const list = scoped.filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
return list.sort((a, b) =>
sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : sort === 'recent' ? b.updatedAt - a.updatedAt : a.sortOrder - b.sortOrder || a.createdAt - b.createdAt,
);
}, [data, filter, query, sort]);
}, [scoped, filter, query, sort]);
if (q.isError) return <ErrorState title="Class not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!data) {
@ -213,8 +240,10 @@ export default function ClassPage() {
}
};
const removeFolder = async (f: Folder) => {
if (!(await confirm({ title: 'Delete this folder?', message: `"${f.name}" will be removed. Everything inside it stays in the class.`, confirmLabel: 'Delete folder', danger: true }))) return;
const noun = groupLabel.toLowerCase();
if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${f.name}" will be removed. Everything in it stays in the class, outside any ${noun}.`, confirmLabel: `Delete ${noun}`, danger: true }))) return;
await api.del(`/api/folders/${f.id}`).catch((e) => toast.error(errorMessage(e)));
if (examChoice === f.id) setExamChoice('');
await refresh();
};
const deleteClass = async () => {
@ -456,17 +485,18 @@ export default function ClassPage() {
</Button>
}
>
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz' })}>
{currentExam && <MenuLabel>Adding to {currentExam.name}</MenuLabel>}
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz', folderId: currentExam?.id ?? null })}>
New quiz
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck' })}>
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck', folderId: currentExam?.id ?? null })}>
New flashcard deck
</MenuItem>
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note' })}>
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note', folderId: currentExam?.id ?? null })}>
New note
</MenuItem>
<MenuItem icon={<FolderPlus />} onSelect={() => setNewKind({ kind: 'folder' })}>
New folder
New {groupLabel.toLowerCase()}
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Upload />} onSelect={() => fileRef.current?.click()}>
@ -590,6 +620,22 @@ export default function ClassPage() {
</div>
) : (
<>
<ExamTabs
exams={exams}
items={data.items}
looseCount={looseCount}
view={examView}
label={groupLabel}
onView={setExamChoice}
onNew={() => setNewKind({ kind: 'folder' })}
onRename={(f) => setRename({ kind: 'folder', id: f.id, title: f.name })}
onShare={(f) => setShare({ kind: 'folder', id: f.id, title: f.name })}
onDelete={removeFolder}
onReorder={async (ids) => {
await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
/>
<div className="mb-4 flex flex-wrap items-center gap-2">
<div className="-mx-1 flex max-w-full gap-1 overflow-x-auto px-1 pb-1">
{(
@ -653,10 +699,31 @@ export default function ClassPage() {
{visible.length === 0 ? (
<div className="card">
<EmptyState title={searching ? 'Nothing matches' : 'Nothing here yet'} icon={<Search />}>
{query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'}
</EmptyState>
{currentExam && !searching ? (
<EmptyState
title={`Nothing in ${currentExam.name} yet`}
icon={<FolderIcon />}
action={
<>
<Button variant="primary" icon={<Upload />} onClick={() => fileRef.current?.click()}>
Upload documents
</Button>
<Button icon={<Sparkles />} onClick={() => setGenerate({})}>
Generate
</Button>
</>
}
>
Add this {groupLabel.toLowerCase()}'s slides and notes, then generate quizzes and flashcards from them. Use Move on anything already in the class to bring it here.
</EmptyState>
) : (
<EmptyState title={searching ? 'Nothing matches' : 'Nothing here yet'} icon={<Search />}>
{query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'}
</EmptyState>
)}
</div>
) : examView !== 'all' ? (
section(visible)
) : (
<div className="space-y-4">
{loose.length > 0 && section(loose)}
@ -741,19 +808,19 @@ export default function ClassPage() {
</div>
)}
<NewItemDialog kind={newKind?.kind ?? null} classId={classId} folderId={newKind?.folderId} onClose={() => setNewKind(null)} />
<NewItemDialog kind={newKind?.kind ?? null} classId={classId} folderId={newKind?.folderId} groupLabel={groupLabel} onClose={() => setNewKind(null)} />
<RenameDialog target={rename} onClose={() => setRename(null)} />
<MoveDialog target={move} onClose={() => setMove(null)} />
<ShareDialog target={share} onClose={() => setShare(null)} />
<ImportDialog open={importOpen} onClose={() => setImportOpen(false)} classId={classId} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} preset={generate ?? undefined} />
<ImportDialog open={importOpen} onClose={() => setImportOpen(false)} classId={classId} folderId={currentExam?.id ?? null} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} folderId={currentExam?.id ?? null} preset={generate ?? undefined} />
<ClassDialog open={editClass} onOpenChange={setEditClass} existing={cls} />
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} />
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} folderId={currentExam?.id ?? null} />
</div>
);
}
function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: () => void; classId: string }) {
function PasteTextDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
const refresh = useRefresh();
const [title, setTitle] = useState('');
const [text, setText] = useState('');
@ -767,7 +834,7 @@ function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: (
const save = async () => {
setBusy(true);
try {
await api.post('/api/documents/text', { classId, title, text });
await api.post('/api/documents/text', { classId, folderId: folderId ?? null, title, text });
await refresh();
toast.success('Added as a document');
onClose();
@ -806,3 +873,116 @@ function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: (
</Dialog>
);
}
/* ------------------------------ exams ------------------------------ */
/**
* The second level of a class: one tab per exam (or unit, module… as the class calls them),
* plus "All" and, when anything is outside every exam, "Not in an exam".
*/
function ExamTabs({
exams,
items,
looseCount,
view,
label,
onView,
onNew,
onRename,
onShare,
onDelete,
onReorder,
}: {
exams: Folder[];
items: Item[];
looseCount: number;
view: string;
label: string;
onView: (v: string) => void;
onNew: () => void;
onRename: (f: Folder) => void;
onShare: (f: Folder) => void;
onDelete: (f: Folder) => void;
onReorder: (ids: string[]) => void;
}) {
const noun = label.toLowerCase();
const count = (id: string) => items.filter((i) => i.folderId === id).length;
const move = (index: number, by: number) => {
const ids = exams.map((f) => f.id);
const [id] = ids.splice(index, 1);
ids.splice(Math.max(0, Math.min(ids.length, index + by)), 0, id);
onReorder(ids);
};
if (exams.length === 0) {
return (
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-[14px] border border-dashed border-line-strong px-4 py-3 text-[13.5px] text-ink-2">
<FolderIcon className="size-4 shrink-0 text-tab" />
<span className="min-w-0 flex-1">Divide this class into {noun}s so each keeps its own documents, quizzes and flashcards, and generating uses only that {noun}'s material.</span>
<Button size="sm" icon={<Plus />} onClick={onNew}>
New {noun}
</Button>
</div>
);
}
const tab = (key: string, text: ReactNode, n: number, extra?: ReactNode) => (
<div key={key} className={cx('flex shrink-0 items-center rounded-[11px] border transition-colors', view === key ? 'border-tab bg-surface shadow-1' : 'border-transparent hover:bg-ink/5')}>
<button type="button" role="tab" aria-selected={view === key} onClick={() => onView(key)} className={cx('flex h-10 items-center gap-2 pr-2 pl-3.5 text-sm', view === key ? 'font-semibold text-ink' : 'font-medium text-ink-2')}>
{text}
<span className="num text-xs font-normal text-ink-3">{n}</span>
</button>
{extra}
</div>
);
return (
<div className="mb-4 border-b border-line pb-3">
<div role="tablist" aria-label={`${label}s`} className="-mx-1 flex items-center gap-1 overflow-x-auto px-1 pb-1">
{exams.map((f, index) =>
tab(
f.id,
<>
<FolderIcon className="size-4 text-tab" />
<span className="max-w-48 truncate">{f.name}</span>
{f.shared && <Share2 className="size-3.5 text-accent" aria-label="Shared" />}
</>,
count(f.id),
view === f.id ? (
<Menu
trigger={
<IconButton label={`${label} options for ${f.name}`} size="sm" tooltip={false} className="mr-1">
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<Pencil />} onSelect={() => onRename(f)}>
Rename
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => onShare(f)}>
Share this {noun}
</MenuItem>
{index > 0 && (
<MenuItem icon={<ArrowLeft />} onSelect={() => move(index, -1)}>
Move earlier
</MenuItem>
)}
{index < exams.length - 1 && (
<MenuItem icon={<ArrowRight />} onSelect={() => move(index, 1)}>
Move later
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => onDelete(f)}>
Delete {noun}
</MenuItem>
</Menu>
) : null,
),
)}
{looseCount > 0 && tab('none', <span className="text-ink-2">Not in a{/^[aeiou]/i.test(noun) ? 'n' : ''} {noun}</span>, looseCount)}
{tab('all', <span>All</span>, items.length)}
<button type="button" onClick={onNew} className="ml-1 flex h-10 shrink-0 items-center gap-1.5 rounded-[11px] px-3 text-sm font-medium text-ink-3 hover:bg-ink/5 hover:text-ink">
<Plus className="size-4" /> New {noun}
</button>
</div>
</div>
);
}

View file

@ -136,7 +136,7 @@ export default function SessionPage() {
navigate(back);
};
const renderExtra = ai.data?.ready
? (q: SnapshotQuestion, selected: string[]) => <Explain body={{ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected, rationale: q.rationale }} />
? (q: SnapshotQuestion, selected: string[]) => <Explain body={{ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected, rationale: q.rationale, quizId: q.quizId ?? undefined }} />
: undefined;
if (attempt.status === 'completed') {

View file

@ -1,10 +1,11 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Brain, Check, Copy, Database, Download, ExternalLink, FileUp, GraduationCap, HardDriveDownload, Layers, Link2, Lock, NotebookPen, RefreshCw, Share2, SlidersHorizontal, Sparkles, Stamp, Trash2, Upload } from 'lucide-react';
import { BookOpen, Brain, Globe, Check, Copy, Database, Download, ExternalLink, FileUp, GraduationCap, HardDriveDownload, Layers, Link2, Lock, NotebookPen, RefreshCw, Share2, SlidersHorizontal, Sparkles, Stamp, Trash2, Upload } from 'lucide-react';
import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'react';
import { NavLink, useNavigate, useParams } from 'react-router';
import { NavLink, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { shareUrl } from '@/features/dialogs';
import { TemplateSettings } from '@/features/TemplateSettings';
import { WebSearchSettings } from '@/features/WebSearchSettings';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { AppSettings, ShareListItem, Template } from '@/lib/types';
@ -16,6 +17,7 @@ const AiSettings = lazy(() => import('@/features/AiSettings'));
const TABS = [
{ id: 'study', label: 'Study', icon: <SlidersHorizontal /> },
{ id: 'ai', label: 'AI', icon: <Sparkles /> },
{ id: 'web', label: 'Web search', icon: <Globe /> },
{ id: 'sharing', label: 'Sharing', icon: <Share2 /> },
{ id: 'templates', label: 'Templates', icon: <Stamp /> },
{ id: 'data', label: 'Data and backup', icon: <Database /> },
@ -539,6 +541,16 @@ export default function SettingsPage() {
useEffect(() => {
if (tab && !TABS.some((t) => t.id === tab)) navigate('/settings', { replace: true });
}, [tab, navigate]);
// Back from an MCP or web search sign-in.
const [params, setParams] = useSearchParams();
useEffect(() => {
const outcome = params.get('mcp_oauth');
if (!outcome) return;
const message = params.get('message') || (outcome === 'ok' ? 'Signed in.' : 'The sign-in failed.');
if (outcome === 'ok') toast.success(message);
else toast.error(message);
setParams({}, { replace: true });
}, [params, setParams]);
return (
<div className="animate-in">
@ -564,6 +576,7 @@ export default function SettingsPage() {
<AiSettings />
</Suspense>
)}
{active === 'web' && <WebSearchSettings />}
{active === 'sharing' && <SharingSettings />}
{active === 'templates' && <TemplateSettings />}
{active === 'data' && <DataSettings />}

View file

@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun, Timer } from 'lucide-react';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { AlignLeft, ArrowLeft, BookOpen, Eye, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun, Timer } from 'lucide-react';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
@ -9,18 +9,18 @@ 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';
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useTheme } from '@/lib/util';
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, EmptyState, IconButton, Input, PageLoading, Switch } from '@/ui';
import { Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui';
/* ------------------------------ frame ------------------------------ */
function Frame({ children, back }: { children: ReactNode; back?: { to: string; label: string } }) {
function Frame({ children, back, wide }: { children: ReactNode; back?: { to: string; label: string }; wide?: boolean }) {
const [, setTheme] = useTheme();
const dark = document.documentElement.dataset.theme === 'dark';
return (
<div className="min-h-dvh">
<header className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-4 sm:px-5">
<header className={cx('mx-auto flex h-14 items-center gap-2 px-4 sm:px-5', wide ? 'max-w-5xl' : 'max-w-3xl')}>
{back ? (
<Link to={back.to} className="-ml-2 flex h-9 items-center gap-1.5 rounded-lg px-2 text-sm font-medium text-ink-2 hover:bg-ink/6 hover:text-ink">
<ArrowLeft className="size-4" /> {back.label}
@ -36,7 +36,7 @@ function Frame({ children, back }: { children: ReactNode; back?: { to: string; l
{dark ? <Sun /> : <Moon />}
</IconButton>
</header>
<main className="mx-auto max-w-3xl animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8">{children}</main>
<main className={cx('mx-auto animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8', wide ? 'max-w-5xl' : 'max-w-3xl')}>{children}</main>
<footer className="pb-8 text-center text-xs text-ink-3">Shared with Study Desk. Your progress is saved in this browser only.</footer>
</div>
);
@ -118,7 +118,7 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
};
}
function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string }; explainUrl?: string; onImmersive?: (on: boolean) => void }) {
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 });
@ -142,6 +142,12 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz;
}, [quiz, state]);
const changed = Boolean(state?.version && state.version !== quizVersion(quiz));
// While a quiz is being taken the assistant button steps aside.
const taking = Boolean(state && questions.length > 0 && running && !state.done);
useEffect(() => {
onImmersive?.(taking);
return () => onImmersive?.(false);
}, [taking, onImmersive]);
const expired = Boolean(state && !state.done && state.deadlineAt && Date.now() > state.deadlineAt);
// A timed exam whose deadline passed while the page was closed is submitted as it stands.
@ -288,9 +294,13 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz;
/* ------------------------------ deck ------------------------------ */
function SharedDeck({ deck, storageKey, back, explainUrl }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
function SharedDeck({ deck, storageKey, back, explainUrl, onImmersive }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string }; explainUrl?: string; onImmersive?: (on: boolean) => void }) {
const [saved, setSaved] = useLocalStorage<CramState | null>(storageKey, null);
const [running, setRunning] = useState(false);
useEffect(() => {
onImmersive?.(running);
return () => onImmersive?.(false);
}, [running, onImmersive]);
const state = useMemo(() => reconcileCramState(saved, deck.cards), [saved, deck.cards]);
if (running && state) {
@ -378,24 +388,92 @@ function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; lab
);
}
function SharedDocument({ doc, token, nested, back }: { doc: PublicDocument; token: string; nested?: boolean; back?: { to: string; label: string } }) {
const url = nested ? `/api/public/${token}/items/document/${doc.id}/file` : `/api/public/${token}/file`;
const inline = doc.docKind === 'pdf' || doc.docKind === 'image';
interface TextChunk {
id: number;
seq: number;
text: string;
heading: string;
pageStart: number | null;
pageEnd: number | null;
}
/** The document's extracted text, page by page: readable on any device, including phones. */
function SharedDocumentText({ base }: { base: string }) {
const q = useInfiniteQuery({
queryKey: ['public', 'text', base],
queryFn: ({ pageParam, signal }) => api.pub<{ chunks: TextChunk[]; nextOffset: number | null }>(`${base}/text?offset=${pageParam}&limit=30`, signal),
initialPageParam: 0,
getNextPageParam: (last) => last.nextOffset ?? undefined,
});
const chunks = q.data?.pages.flatMap((p) => p.chunks) ?? [];
if (q.isLoading) return <div className="card mt-5 h-64 animate-pulse" />;
if (chunks.length === 0) return <div className="card mt-5 p-6 text-sm text-ink-2">No readable text was found in this file. Download it to open it.</div>;
let lastPage: number | null = null;
return (
<Frame back={back}>
<article className="card mt-5 px-5 py-6 sm:px-9 sm:py-8">
{chunks.map((c) => {
const newPage = c.pageStart !== null && c.pageStart !== lastPage;
if (c.pageStart !== null) lastPage = c.pageEnd ?? c.pageStart;
return (
<section key={c.id} className="mb-5">
{newPage && <div className="eyebrow mb-2 border-t border-line pt-3 first:border-0 first:pt-0">Page {c.pageStart}</div>}
{c.heading && <h3 className="mb-1.5 text-[15px] font-semibold">{c.heading}</h3>}
<div className="reading text-[16px] leading-relaxed whitespace-pre-wrap">{c.text}</div>
</section>
);
})}
{q.hasNextPage && (
<Button variant="secondary" block loading={q.isFetchingNextPage} onClick={() => q.fetchNextPage()}>
Show more
</Button>
)}
</article>
);
}
function SharedDocument({ doc, token, nested, back }: { doc: PublicDocument; token: string; nested?: boolean; back?: { to: string; label: string } }) {
const base = nested ? `/api/public/${token}/items/document/${doc.id}` : `/api/public/${token}`;
const fileUrl = `${base}/file`;
const office = doc.docKind === 'docx' || doc.docKind === 'pptx';
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image' || office;
// Phones rarely show PDFs inside a page, so they start on the text.
const phone = useMediaQuery('(max-width: 639px)');
const [view, setView] = useState<'original' | 'text'>(hasOriginal && !(phone && doc.docKind === 'pdf') ? 'original' : 'text');
return (
<Frame back={back} wide>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<FileText className="size-3.5" /> Shared document
</div>
<h1 className="display text-[30px] sm:text-[36px]">{doc.title}</h1>
<p className="mt-2 text-sm text-ink-3">
{doc.filename} · {formatBytes(doc.size)}
{doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
</p>
<Button href={url} download={inline ? undefined : doc.filename} target={inline ? '_blank' : undefined} variant="primary" size="lg" icon={<Download />} className="mt-5">
{inline ? 'Open file' : 'Download'}
</Button>
{doc.docKind === 'image' && <img src={url} alt={doc.title} className="card mt-6 max-w-full p-2" />}
{doc.docKind === 'pdf' && <iframe src={url} title={doc.title} className="card mt-6 hidden h-[78vh] w-full sm:block" />}
<div className="mt-3 flex flex-wrap items-center gap-3">
{hasOriginal && (
<Segmented
size="sm"
label="View"
value={view}
onChange={setView}
options={[
{ value: 'original', label: 'Original', icon: <Eye /> },
{ value: 'text', label: 'Text', icon: <AlignLeft /> },
]}
/>
)}
<span className="text-sm text-ink-3">
{doc.filename} · {formatBytes(doc.size)}
{doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
</span>
<Button href={fileUrl} download={doc.filename} size="sm" variant="ghost" icon={<Download />} className="ml-auto">
Download
</Button>
</div>
{view === 'text' || !hasOriginal ? (
<SharedDocumentText base={base} />
) : doc.docKind === 'image' ? (
<img src={fileUrl} alt={doc.title} className="card mt-5 max-w-full p-2" />
) : (
// Office previews are self-contained HTML that the server sandboxes with its Content-Security-Policy.
<iframe src={office ? `${base}/preview` : fileUrl} title={doc.title} className="card mt-5 h-[80vh] w-full bg-surface" />
)}
</Frame>
);
}
@ -444,6 +522,7 @@ export default function SharedPage() {
const { token = '', kind, itemId } = useParams();
const navigate = useNavigate();
const nested = Boolean(kind && itemId);
const [immersive, setImmersive] = useState(false);
const q = useQuery({
queryKey: ['public', token, kind ?? '', itemId ?? ''],
queryFn: ({ signal }) => api.pub<PublicPayload>(nested ? `/api/public/${token}/items/${kind}/${itemId}` : `/api/public/${token}`, signal),
@ -473,13 +552,13 @@ 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 : ''}`;
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 assistant = data.ai?.assistant ? <SharedAssistant token={token} title={data.title} hidden={immersive} 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} />;
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} explainUrl={explainUrl} onImmersive={setImmersive} />;
case 'deck':
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} />;
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} onImmersive={setImmersive} />;
case 'note':
return <SharedNote note={data} back={back} />;
case 'document':