Add the V2 web app: design system, shell, study flows, AI, settings, sharing
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
eae109c166
commit
74a98ac1f1
52 changed files with 11976 additions and 1 deletions
402
web/src/pages/SharedPage.tsx
Normal file
402
web/src/pages/SharedPage.tsx
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun } 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 { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
|
||||
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 { Markdown } from '@/ui/Markdown';
|
||||
import { Button, EmptyState, IconButton, PageLoading, Switch } from '@/ui';
|
||||
|
||||
/* ------------------------------ frame ------------------------------ */
|
||||
|
||||
function Frame({ children, back }: { children: ReactNode; back?: { to: string; label: string } }) {
|
||||
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">
|
||||
{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="mx-auto max-w-3xl animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8">{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>
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, 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;
|
||||
});
|
||||
return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false };
|
||||
}
|
||||
|
||||
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
|
||||
const [state, setState] = useLocalStorage<QuizState | null>(storageKey, null);
|
||||
const [prefs, setPrefs] = useLocalStorage('sd.pub.prefs', { mode: 'practice' as 'practice' | 'exam', shuffleQ: true, shuffleO: true });
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
|
||||
const questions = useMemo<SnapshotQuestion[]>(() => {
|
||||
if (!state) return [];
|
||||
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 begin = (only?: string[]) => {
|
||||
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, 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"
|
||||
footnote="This result is stored in your browser only. The person who shared the quiz cannot see it."
|
||||
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={null}
|
||||
sataScoring="partial"
|
||||
exitLabel="Pause"
|
||||
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
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="primary" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
|
||||
Resume
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
|
||||
{(
|
||||
[
|
||||
{ v: 'practice', t: 'Practice', b: 'See the answer and rationale after each question.' },
|
||||
{ v: 'exam', t: 'Exam', b: 'Answers and score are shown at the end.' },
|
||||
] 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', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}>
|
||||
<div className="font-semibold">{m.t}</div>
|
||||
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.b}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<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" />
|
||||
</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 }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: 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" />;
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
function SharedDocument({ doc, token }: { doc: PublicDocument; token: string }) {
|
||||
const url = `/api/public/${token}/file`;
|
||||
const inline = doc.docKind === 'pdf' || doc.docKind === 'image';
|
||||
return (
|
||||
<Frame>
|
||||
<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>
|
||||
<a href={url} download={inline ? undefined : doc.filename} target={inline ? '_blank' : undefined} rel="noreferrer" className="mt-5 inline-block">
|
||||
<Button variant="primary" size="lg" icon={<Download />}>
|
||||
{inline ? 'Open file' : 'Download'}
|
||||
</Button>
|
||||
</a>
|
||||
{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" />}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||
|
||||
function SharedCollection({ data, token }: { data: PublicCollection; token: string }) {
|
||||
const groups = [{ id: null as string | null, name: '' }, ...data.folders].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>
|
||||
{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">
|
||||
{g.name && <h2 className="eyebrow mb-2.5">{g.name}</h2>}
|
||||
<ul className="card divide-y divide-line overflow-hidden">
|
||||
{g.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' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[15px] font-medium">{i.title}</span>
|
||||
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : 'Note'}</span>
|
||||
</span>
|
||||
<ChevronRight className="size-4 text-ink-3" />
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ page ------------------------------ */
|
||||
|
||||
export default function SharedPage() {
|
||||
const { token = '', kind, itemId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const nested = Boolean(kind && itemId);
|
||||
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 : ''}`;
|
||||
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} />;
|
||||
case 'collection':
|
||||
return <SharedCollection data={data} token={token} />;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue