All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
- Malformed model JSON is sent back for repair, then retried; a failed job starts over once before it fails. Visitors can dismiss failed sets. - Generated sets get a short distinct name and description; flashcards are atomic and have no hints; standard study shows known/learning counts. - Share links: "In progress" list, finished sets join the normal lists with a "New" tag, plain progress steps, newest exam first. - Share-link AI expires after a week, can be limited to the US or Arizona (DB-IP Lite or Cloudflare headers) and is locked by abuse protection (migration 8). - The assistant never answers from general knowledge; MCP and web search tools load without a manual test. - Plain-text copy, no question count in exam mode, filler text removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
598 lines
27 KiB
TypeScript
598 lines
27 KiB
TypeScript
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 (
|
|
<div className="min-h-dvh">
|
|
<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}
|
|
</Link>
|
|
) : (
|
|
<div className="flex items-center gap-2">
|
|
<img src="/icon.svg" alt="" className="size-7 rounded-lg" />
|
|
<span className="display text-[18px]">Study Desk</span>
|
|
</div>
|
|
)}
|
|
<div className="flex-1" />
|
|
<IconButton label={dark ? 'Switch to light theme' : 'Switch to dark theme'} onClick={() => setTheme(dark ? 'light' : 'dark')}>
|
|
{dark ? <Sun /> : <Moon />}
|
|
</IconButton>
|
|
</header>
|
|
<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</footer>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Unavailable() {
|
|
return (
|
|
<div className="grid min-h-dvh place-items-center px-6">
|
|
<EmptyState icon={<Link2Off />} title="This link is no longer available">
|
|
The owner may have turned sharing off or replaced the link. Ask them for a new one.
|
|
</EmptyState>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ quiz ------------------------------ */
|
|
|
|
interface QuizState {
|
|
mode: 'practice' | 'exam';
|
|
order: string[];
|
|
optionOrder: Record<string, string[]>;
|
|
answers: Record<string, AnswerState>;
|
|
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<string, string[]> = {};
|
|
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[]) => <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));
|
|
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<SnapshotQuestion[]>(() => {
|
|
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 (
|
|
<QuizResults
|
|
title={quiz.title}
|
|
mode={state.mode}
|
|
questions={questions}
|
|
answers={state.answers}
|
|
flags={state.flags}
|
|
elapsedSec={state.elapsed}
|
|
sataScoring="partial"
|
|
onExit={() => (setState(null), setRunning(false))}
|
|
exitLabel="Back to start"
|
|
renderExtra={renderExtra}
|
|
actions={
|
|
<>
|
|
{missed.length > 0 && (
|
|
<Button variant="primary" icon={<RotateCcw />} onClick={() => begin(missed)}>
|
|
Redo the {missed.length} missed
|
|
</Button>
|
|
)}
|
|
<Button icon={<RotateCcw />} onClick={() => begin()}>
|
|
Take it again
|
|
</Button>
|
|
</>
|
|
}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (state && questions.length > 0 && running) {
|
|
return (
|
|
<QuizRunner
|
|
title={quiz.title}
|
|
mode={state.mode}
|
|
questions={questions}
|
|
answers={state.answers}
|
|
flags={state.flags}
|
|
index={state.index}
|
|
elapsedSec={state.elapsed}
|
|
timeLimitSec={state.timeLimitSec ?? null}
|
|
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))}
|
|
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 (
|
|
<Frame back={back}>
|
|
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
|
<BookOpen className="size-3.5" /> Shared quiz
|
|
</div>
|
|
<h1 className="display text-[32px] sm:text-[40px]">{quiz.title}</h1>
|
|
{quiz.description && <p className="mt-2 text-[15px] text-ink-2">{quiz.description}</p>}
|
|
<p className="mt-2 text-sm text-ink-3">{plural(quiz.questions.length, 'question')}</p>
|
|
|
|
{quiz.questions.length === 0 ? (
|
|
<div className="card mt-6 p-6 text-sm text-ink-2">This quiz has no questions yet.</div>
|
|
) : (
|
|
<div className="card mt-6 p-5 sm:p-6">
|
|
{inProgress && (
|
|
<div className="mb-5 flex flex-wrap items-center gap-3 rounded-xl bg-accent-soft p-3.5">
|
|
<div className="min-w-0 flex-1">
|
|
<div className="text-sm font-semibold">You have a session in progress</div>
|
|
<div className="text-[13px] text-ink-2">
|
|
{answered} of {questions.length} answered
|
|
{state.deadlineAt ? ` · ${Math.max(0, Math.ceil((state.deadlineAt - Date.now()) / 60000))} min left` : ''}
|
|
</div>
|
|
{changed && <div className="mt-1 text-[13px] text-ink-2">This quiz has been updated since you started. Your session keeps the version you began with; start over for the latest.</div>}
|
|
</div>
|
|
<Button variant="primary" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
|
|
Resume
|
|
</Button>
|
|
</div>
|
|
)}
|
|
<Segmented
|
|
label="Mode"
|
|
value={prefs.mode}
|
|
onChange={(mode) => setPrefs((p) => ({ ...p, mode }))}
|
|
options={[
|
|
{ value: 'practice', label: 'Practice' },
|
|
{ value: 'exam', label: 'Exam' },
|
|
]}
|
|
className="w-full"
|
|
/>
|
|
<div className="mt-4 space-y-3.5">
|
|
<Switch checked={prefs.shuffleQ} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQ: v }))} label="Shuffle questions" />
|
|
<Switch checked={prefs.shuffleO} onChange={(v) => setPrefs((p) => ({ ...p, shuffleO: v }))} label="Shuffle answer choices" />
|
|
{prefs.mode === 'exam' && (
|
|
<>
|
|
<Switch checked={prefs.timed} onChange={(v) => setPrefs((p) => ({ ...p, timed: v }))} label="Time limit" />
|
|
{prefs.timed && (
|
|
<label className="flex items-center gap-2 text-sm text-ink-2">
|
|
<Timer className="size-4 text-ink-3" />
|
|
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setPrefs((p) => ({ ...p, minutes: Math.max(1, Math.min(600, Math.round(Number(e.target.value)) || 1)) }))} className="w-24" aria-label="Minutes" />
|
|
minutes
|
|
</label>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
<Button variant={inProgress ? 'secondary' : 'primary'} size="lg" block className="mt-5" icon={<Play className="fill-current" />} onClick={() => begin()}>
|
|
{inProgress ? 'Start over' : 'Start'}
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</Frame>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ 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<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) {
|
|
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 (
|
|
<Frame back={back}>
|
|
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
|
<Layers className="size-3.5" /> Shared flashcards
|
|
</div>
|
|
<h1 className="display text-[32px] sm:text-[40px]">{deck.title}</h1>
|
|
{deck.description && <p className="mt-2 text-[15px] text-ink-2">{deck.description}</p>}
|
|
<p className="mt-2 text-sm text-ink-3">{plural(deck.cards.length, 'card')}</p>
|
|
{deck.cards.length === 0 ? (
|
|
<div className="card mt-6 p-6 text-sm text-ink-2">This deck has no cards yet.</div>
|
|
) : (
|
|
<>
|
|
<div className="mt-6 flex flex-wrap gap-2">
|
|
{state && seen > 0 && seen < state.order.length && (
|
|
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
|
|
Continue ({seen}/{state.order.length})
|
|
</Button>
|
|
)}
|
|
<Button
|
|
variant={state && seen > 0 && seen < state.order.length ? 'secondary' : 'primary'}
|
|
size="lg"
|
|
icon={<Play className="fill-current" />}
|
|
onClick={() => {
|
|
setSaved(freshCramState(deck.cards, false));
|
|
setRunning(true);
|
|
}}
|
|
>
|
|
Study in order
|
|
</Button>
|
|
<Button
|
|
size="lg"
|
|
onClick={() => {
|
|
setSaved(freshCramState(deck.cards, true));
|
|
setRunning(true);
|
|
}}
|
|
>
|
|
Shuffle
|
|
</Button>
|
|
</div>
|
|
<h2 className="eyebrow mt-8 mb-2.5">All cards</h2>
|
|
<ul className="card divide-y divide-line">
|
|
{deck.cards.map((c) => (
|
|
<li key={c.id} className="grid gap-x-5 gap-y-1 px-4 py-3 sm:grid-cols-2">
|
|
<Markdown className="text-[14.5px] font-medium">{c.front}</Markdown>
|
|
<Markdown className="text-[14.5px] text-ink-2">{c.back}</Markdown>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</>
|
|
)}
|
|
</Frame>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ note, document, collection ------------------------------ */
|
|
|
|
function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; label: string } }) {
|
|
return (
|
|
<Frame back={back}>
|
|
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
|
<NotebookPen className="size-3.5" /> Shared note
|
|
</div>
|
|
<h1 className="display mb-6 text-[32px] sm:text-[40px]">{note.title}</h1>
|
|
<article className="card px-5 py-6 sm:px-10 sm:py-9">
|
|
<Markdown serif>{note.content || '*This note is empty.*'}</Markdown>
|
|
</article>
|
|
</Frame>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<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>
|
|
<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>
|
|
);
|
|
}
|
|
|
|
/** Quizzes and decks added in the last two hours are marked "New". */
|
|
const NEW_FOR_MS = 2 * 3_600_000;
|
|
|
|
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText /> };
|
|
|
|
/** 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 (
|
|
<Frame>
|
|
<div className={cx('border-l-[5px] border-tab pl-4', `tab-${data.color}`)}>
|
|
<div className="eyebrow mb-1">{data.subtitle || 'Shared collection'}</div>
|
|
<h1 className="display text-[32px] sm:text-[40px]">{data.title}</h1>
|
|
{data.description && <p className="mt-2 text-[15px] text-ink-2">{data.description}</p>}
|
|
</div>
|
|
{data.ai?.generate && <SharedGenerate token={token} data={data} />}
|
|
{groups.length === 0 ? (
|
|
<div className="card mt-8 p-6 text-sm text-ink-2">Nothing has been added here yet.</div>
|
|
) : (
|
|
groups.map((g) => (
|
|
<section key={g.id ?? 'none'} className="mt-7" aria-label={g.name || undefined}>
|
|
{g.name && groups.length > 1 && <h2 className="mb-2.5 text-[17px] font-semibold">{g.name}</h2>}
|
|
<div className="card overflow-hidden">
|
|
{KIND_ORDER.filter((k) => g.items.some((i) => i.kind === k)).map((k, n) => {
|
|
const items = g.items.filter((i) => i.kind === k);
|
|
return (
|
|
<section key={k} aria-label={KIND_HEADING[k]}>
|
|
<h3 className={cx('eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5', n > 0 && 'border-t')}>
|
|
{ITEM_ICON[k]}
|
|
{KIND_HEADING[k]}
|
|
<span className="num font-normal">{items.length}</span>
|
|
</h3>
|
|
<ul className="divide-y divide-line">
|
|
{items.map((i) => (
|
|
<li key={`${i.kind}:${i.id}`}>
|
|
<Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
|
|
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>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]}</span>
|
|
<span className="min-w-0 flex-1">
|
|
<span className="flex min-w-0 items-center gap-2">
|
|
<span className="truncate text-[15px] font-medium">{i.title}</span>
|
|
{i.createdAt && Date.now() - i.createdAt < NEW_FOR_MS && <Badge tone="accent">New</Badge>}
|
|
</span>
|
|
<span className="text-xs text-ink-3">{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'}</span>
|
|
</span>
|
|
<ChevronRight className="size-4 text-ink-3" />
|
|
</Link>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</section>
|
|
);
|
|
})}
|
|
</div>
|
|
</section>
|
|
))
|
|
)}
|
|
</Frame>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ 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<PublicPayload>(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 <PageLoading />;
|
|
if (q.isError || !data) {
|
|
if (q.error instanceof ApiError && q.error.status !== 404) {
|
|
return (
|
|
<div className="grid min-h-dvh place-items-center px-6">
|
|
<EmptyState title="Could not load this page" action={<Button onClick={() => q.refetch()}>Try again</Button>}>
|
|
Check your connection and try again.
|
|
</EmptyState>
|
|
</div>
|
|
);
|
|
}
|
|
return <Unavailable />;
|
|
}
|
|
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} 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} onImmersive={setImmersive} />;
|
|
case 'deck':
|
|
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} onImmersive={setImmersive} />;
|
|
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}
|
|
</>
|
|
);
|
|
}
|