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 && (
} onClick={() => begin(missed)}>
Redo the {missed.length} missed
)}
} onClick={() => begin()}>
Take it again
>
}
/>
);
}
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.
}
} onClick={() => setRunning(true)}>
Resume
)}
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 && (
setPrefs((p) => ({ ...p, minutes: Math.max(1, Math.min(600, Math.round(Number(e.target.value)) || 1)) }))} className="w-24" aria-label="Minutes" />
minutes
)}
>
)}
} onClick={() => begin()}>
{inProgress ? 'Start over' : 'Start'}
)}
);
}
/* ------------------------------ 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 && (
} onClick={() => setRunning(true)}>
Continue ({seen}/{state.order.length})
)}
0 && seen < state.order.length ? 'secondary' : 'primary'}
size="lg"
icon={ }
onClick={() => {
setSaved(freshCramState(deck.cards, false));
setRunning(true);
}}
>
Study in order
{
setSaved(freshCramState(deck.cards, true));
setRunning(true);
}}
>
Shuffle
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 && (
q.fetchNextPage()}>
Show more
)}
);
}
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')}` : ''}
} className="ml-auto">
Download
{view === 'text' || !hasOriginal ? (
) : doc.docKind === 'image' ? (
) : (
// Office previews are self-contained HTML that the server sandboxes with its Content-Security-Policy.
)}
);
}
/** Quizzes and decks added in the last two hours are marked "New". */
const NEW_FOR_MS = 2 * 3_600_000;
const ITEM_ICON = { quiz: , deck: , note: , document: };
/** The same order and names as the owner's class page; a type with nothing in it is left out. */
const KIND_ORDER = ['quiz', 'deck', 'note', 'document'] as const;
const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', note: 'Notes', document: 'Class Materials' } as const;
function SharedCollection({ data, token }: { data: PublicCollection & { ai?: ShareAi }; token: string }) {
// One section per exam, the latest first; material outside any exam comes last.
const groups = [...[...data.folders].reverse(), { id: null as string | null, name: 'Other' }].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0);
return (
{data.subtitle || 'Shared collection'}
{data.title}
{data.description &&
{data.description}
}
{data.ai?.generate && }
{groups.length === 0 ? (
Nothing has been added here yet.
) : (
groups.map((g) => (
{g.name && groups.length > 1 && {g.name} }
{KIND_ORDER.filter((k) => g.items.some((i) => i.kind === k)).map((k, n) => {
const items = g.items.filter((i) => i.kind === k);
return (
svg]:size-3.5', n > 0 && 'border-t')}>
{ITEM_ICON[k]}
{KIND_HEADING[k]}
{items.length}
{items.map((i) => (
svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : i.kind === 'document' ? 'bg-sunken text-ink-2' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}
{i.title}
{i.createdAt && Date.now() - i.createdAt < NEW_FOR_MS && New }
{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : i.kind === 'document' ? (i.count ? plural(i.count, 'page') : 'File') : 'Note'}
))}
);
})}
))
)}
);
}
/* ------------------------------ page ------------------------------ */
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(nested ? `/api/public/${token}/items/${kind}/${itemId}` : `/api/public/${token}`, signal),
retry: (count, error) => !(error instanceof ApiError && error.status === 404) && count < 2,
staleTime: 60_000,
});
const data = q.data;
useDocumentTitle(data?.title);
useEffect(() => {
// A nested URL whose parent is not a collection makes no sense; send it to the root link.
if (q.isError && nested && q.error instanceof ApiError && q.error.status === 404) navigate(`/s/${token}`, { replace: true });
}, [q.isError, q.error, nested, navigate, token]);
if (q.isLoading) return ;
if (q.isError || !data) {
if (q.error instanceof ApiError && q.error.status !== 404) {
return (
q.refetch()}>Try again}>
Check your connection and try again.
);
}
return ;
}
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 ? : null;
const page = (() => {
switch (data.kind) {
case 'quiz':
return ;
case 'deck':
return ;
case 'note':
return ;
case 'document':
return ;
case 'collection':
return ;
}
})();
return (
<>
{page}
{assistant}
>
);
}