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'; import { Explain } from '@/features/Explain'; import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards'; import { SharedAssistant } from '@/features/SharedAssistant'; import { SharedGenerate } from '@/features/SharedGenerate'; import { QuizResults, QuizRunner } from '@/features/quiz'; import { api, ApiError } from '@/lib/api'; import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, ShareAi, SnapshotQuestion } from '@/lib/types'; import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util'; import { Markdown } from '@/ui/Markdown'; import { Badge, Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui'; /* ------------------------------ frame ------------------------------ */ 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 (
{back ? ( {back.label} ) : (
Study Desk
)}
setTheme(dark ? 'light' : 'dark')}> {dark ? : }
{children}
); } function Unavailable() { return (
} title="This link is no longer available"> The owner may have turned sharing off or replaced the link. Ask them for a new one.
); } /* ------------------------------ quiz ------------------------------ */ interface QuizState { mode: 'practice' | 'exam'; order: string[]; optionOrder: Record; answers: Record; flags: string[]; index: number; elapsed: number; done: boolean; timeLimitSec?: number | null; /** End of a timed exam (epoch ms). The clock keeps running while the page is closed. */ deadlineAt?: number | null; /** * The questions exactly as they were when the session began (options in display order). * Edits the owner makes later never change an in-progress session or a finished score. * Sessions saved before this existed are rebuilt from the live quiz. */ questions?: SnapshotQuestion[]; /** Fingerprint of the quiz content at the start, to notice later edits. */ version?: string; } /** Short, stable fingerprint of a quiz's questions (FNV-1a over its JSON). */ function quizVersion(quiz: PublicQuiz): string { const text = JSON.stringify(quiz.questions); let h = 0x811c9dc5; for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } return h.toString(36); } function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, timeLimitSec: number | null, only?: string[]): QuizState { const seed = (Math.random() * 2 ** 32) >>> 0; let ids = quiz.questions.map((q) => q.id).filter((id) => !only || only.includes(id)); if (shuffleQ) ids = seededShuffle(ids, seed); const optionOrder: Record = {}; quiz.questions.forEach((q, i) => { const optionIds = q.options.map((o) => o.id); optionOrder[q.id] = shuffleO ? seededShuffle(optionIds, seed + i + 1) : optionIds; }); const byId = new Map(quiz.questions.map((q) => [q.id, q])); const questions = ids.map((id) => { const q = byId.get(id)!; const order = optionOrder[id]; return { ...q, options: order.map((oid) => q.options.find((o) => o.id === oid)!).filter(Boolean) }; }); return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false, timeLimitSec, deadlineAt: timeLimitSec ? Date.now() + timeLimitSec * 1000 : null, questions, version: quizVersion(quiz), }; } 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[]) => : undefined; const [state, setState] = useLocalStorage(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)); const [running, setRunning] = useState(false); // Frozen sessions keep their own copy. Older saved sessions are rebuilt from the saved order, // dropping anything the owner has since removed. const questions = useMemo(() => { if (!state) return []; if (state.questions?.length) return state.questions; const byId = new Map(quiz.questions.map((q) => [q.id, q])); return state.order .map((id) => byId.get(id)) .filter((q): q is SnapshotQuestion => Boolean(q)) .map((q) => { const order = state.optionOrder[q.id] ?? []; const sorted = [...q.options].sort((a, b) => (order.indexOf(a.id) + 1 || 99) - (order.indexOf(b.id) + 1 || 99)); return { ...q, options: sorted }; }); }, [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. useEffect(() => { if (expired) { setState((s) => (s && !s.done ? { ...s, done: true, elapsed: s.timeLimitSec ?? s.elapsed } : s)); setRunning(false); } }, [expired, setState]); const begin = (only?: string[]) => { setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, prefs.mode === 'exam' && prefs.timed ? minutes * 60 : null, only)); setRunning(true); window.scrollTo(0, 0); }; if (state && questions.length > 0 && state.done) { const missed = questions.filter((q) => !isFullyCorrect(scoreQuestion(q, state.answers[q.id]?.selected ?? [])) && (state.mode === 'exam' || (state.answers[q.id]?.selected.length ?? 0) > 0)).map((q) => q.id); return ( (setState(null), setRunning(false))} exitLabel="Back to start" renderExtra={renderExtra} actions={ <> {missed.length > 0 && ( )} } /> ); } if (state && questions.length > 0 && running) { return ( 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))} onTick={(elapsed) => setState((s) => (s ? { ...s, elapsed } : s))} onFinish={(elapsed) => { setState((s) => (s ? { ...s, elapsed, done: true } : s)); window.scrollTo(0, 0); }} onExit={() => setRunning(false)} /> ); } const inProgress = state && questions.length > 0 && !state.done; const answered = inProgress ? Object.values(state.answers).filter((a) => a.selected.length > 0).length : 0; return (
Shared quiz

{quiz.title}

{quiz.description &&

{quiz.description}

}

{plural(quiz.questions.length, 'question')}

{quiz.questions.length === 0 ? (
This quiz has no questions yet.
) : (
{inProgress && (
You have a session in progress
{answered} of {questions.length} answered {state.deadlineAt ? ` · ${Math.max(0, Math.ceil((state.deadlineAt - Date.now()) / 60000))} min left` : ''}
{changed &&
This quiz has been updated since you started. Your session keeps the version you began with; start over for the latest.
}
)} setPrefs((p) => ({ ...p, mode }))} options={[ { value: 'practice', label: 'Practice' }, { value: 'exam', label: 'Exam' }, ]} className="w-full" />
setPrefs((p) => ({ ...p, shuffleQ: v }))} label="Shuffle questions" /> setPrefs((p) => ({ ...p, shuffleO: v }))} label="Shuffle answer choices" /> {prefs.mode === 'exam' && ( <> setPrefs((p) => ({ ...p, timed: v }))} label="Time limit" /> {prefs.timed && ( )} )}
)} ); } /* ------------------------------ deck ------------------------------ */ 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(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) { return ( setRunning(false)} exitLabel="Pause" renderExtra={explainUrl ? (card) => : undefined} /> ); } const seen = state ? Math.min(state.index, state.order.length) : 0; return (
Shared flashcards

{deck.title}

{deck.description &&

{deck.description}

}

{plural(deck.cards.length, 'card')}

{deck.cards.length === 0 ? (
This deck has no cards yet.
) : ( <>
{state && seen > 0 && seen < state.order.length && ( )}

All cards

    {deck.cards.map((c) => (
  • {c.front} {c.back}
  • ))}
)} ); } /* ------------------------------ note, document, collection ------------------------------ */ function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; label: string } }) { return (
Shared note

{note.title}

{note.content || '*This note is empty.*'}
); } 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
; if (chunks.length === 0) return
No readable text was found in this file. Download it to open it.
; let lastPage: number | null = null; return (
{chunks.map((c) => { const newPage = c.pageStart !== null && c.pageStart !== lastPage; if (c.pageStart !== null) lastPage = c.pageEnd ?? c.pageStart; return (
{newPage &&
Page {c.pageStart}
} {c.heading &&

{c.heading}

}
{c.text}
); })} {q.hasNextPage && ( )}
); } 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 (
Shared document

{doc.title}

{hasOriginal && ( }, { value: 'text', label: 'Text', icon: }, ]} /> )} {doc.filename} · {formatBytes(doc.size)} {doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
{view === 'text' || !hasOriginal ? ( ) : doc.docKind === 'image' ? ( {doc.title} ) : ( // Office previews are self-contained HTML that the server sandboxes with its Content-Security-Policy.