Study/web/src/features/flashcards.tsx
Elijah aed14cd04f Address first round of feedback
- Flashcards: whole card flips on click (both sides), 3D turn, swipe-away on grading,
  streak chip and flame bursts, bigger cards on desktop, arrow keys for everything
- Review and browse keep the sidebar on desktop
- Quizzes: live practice score, partial-credit explanation, time limit for shared exams
- Class page: items grouped by type inside each folder
- Import: copyable, editable instructions for outside chatbots
- Assistant: reads notes and links to library items

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 18:30:07 -07:00

431 lines
18 KiB
TypeScript

import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, IconButton, Kbd, ProgressBar } from '@/ui';
import { Ring } from './charts';
/* ------------------------------ streaks ------------------------------ */
export type StreakTier = 1 | 2 | 3;
/** A run this long turns the progress bar and counter to flame. */
export const STREAK_HOT = 5;
/** Celebrations at 5, then every 10. */
export const isStreakMilestone = (n: number) => n === 5 || (n >= 10 && n % 10 === 0);
export const streakTier = (n: number): StreakTier => (n >= 20 ? 3 : n >= 10 ? 2 : 1);
const BURST_MS: Record<StreakTier, number> = { 1: 1600, 2: 1900, 3: 2400 };
const BURST_COPY: Record<StreakTier, string> = { 1: 'On fire', 2: 'Blazing', 3: 'Unstoppable' };
export function FlameIcon({ className }: { className?: string }) {
const id = `flame-${useId().replace(/[^a-zA-Z0-9]/g, '')}`;
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden focusable="false">
<defs>
<linearGradient id={id} x1="0" y1="1" x2="0" y2="0">
<stop offset="0%" stopColor="#ea580c" />
<stop offset="55%" stopColor="#fb923c" />
<stop offset="100%" stopColor="#fbbf24" />
</linearGradient>
</defs>
<path
fill={`url(#${id})`}
fillRule="evenodd"
clipRule="evenodd"
d="M12.963 2.286a.75.75 0 0 0-1.071-.136 9.742 9.742 0 0 0-3.539 6.177A7.547 7.547 0 0 1 6.648 6.61a.75.75 0 0 0-1.152-.082A9 9 0 1 0 15.68 4.534a7.46 7.46 0 0 1-2.717-2.248ZM15.75 14.25a3.75 3.75 0 1 1-7.313-1.172c.628.465 1.35.81 2.133 1a5.99 5.99 0 0 1 1.925-3.547 3.75 3.75 0 0 1 3.255 3.719Z"
/>
</svg>
);
}
export function StreakChip({ streak }: { streak: number }) {
if (streak < 2) return null;
const hot = streak >= STREAK_HOT;
return (
<span key={hot ? 'hot' : 'warm'} className={cx('streak-chip inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-xs font-bold whitespace-nowrap', hot ? 'streak-chip-hot' : 'bg-ink/7 text-ink-2')}>
{hot && <FlameIcon className="size-3.5 shrink-0" />}
{streak} in a row
</span>
);
}
function StreakBurst({ streak, tier }: { streak: number; tier: StreakTier }) {
const flame = { 1: 'size-16', 2: 'size-24', 3: 'size-36 md:size-44' }[tier];
const heading = { 1: 'text-lg', 2: 'text-2xl', 3: 'text-4xl md:text-5xl' }[tier];
return (
<div className="streak-scrim pointer-events-none absolute inset-0 z-30 flex items-center justify-center rounded-[24px]" style={{ '--streak-ms': `${BURST_MS[tier]}ms` } as CSSProperties} role="status" aria-live="polite">
<div className="streak-pop flex flex-col items-center">
<FlameIcon className={cx('streak-flame', flame)} />
<span className={cx('streak-heading mt-1 font-black tracking-wide uppercase', heading)}>{BURST_COPY[tier]}</span>
<span className="mt-1 text-sm font-semibold text-ink">{streak} in a row</span>
</div>
</div>
);
}
/** Tracks a run of correct answers and fires a short celebration at milestones. */
export function useStreak() {
const [streak, setStreak] = useState(0);
const [burst, setBurst] = useState<{ streak: number; tier: StreakTier; id: number } | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);
const record = useCallback((correct: boolean) => {
setStreak((prev) => {
const next = correct ? prev + 1 : 0;
if (correct && isStreakMilestone(next)) {
const tier = streakTier(next);
setBurst({ streak: next, tier, id: Date.now() });
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => setBurst(null), BURST_MS[tier]);
}
return next;
});
}, []);
const reset = useCallback((to = 0) => setStreak(to), []);
return { streak, burst, record, reset, hot: streak >= STREAK_HOT };
}
/* ------------------------------ the card ------------------------------ */
const stop = (e: { stopPropagation: () => void }) => e.stopPropagation();
export function FlipCard({
front,
back,
hint,
flipped,
onFlip,
label,
cardKey,
footer,
leaving,
burst,
}: {
front: string;
back: string;
hint?: string;
flipped: boolean;
onFlip: () => void;
label?: ReactNode;
/** Changing this replays the entrance animation and resets the hint. */
cardKey: string;
/** Extra content under the answer (kept clickable without flipping the card). */
footer?: ReactNode;
/** Plays the swipe-away animation used when a card is graded. */
leaving?: 'left' | 'right' | null;
burst?: { streak: number; tier: StreakTier; id: number } | null;
}) {
const [showHint, setShowHint] = useState(false);
useEffect(() => setShowHint(false), [cardKey]);
const face = 'flip-face flex min-h-[max(320px,min(60vh,680px))] flex-col rounded-[24px] border border-line bg-surface shadow-2';
// Short answers read best large and centred; long ones as normal text.
const size = (text: string) =>
text.length < 60 ? 'text-[30px] sm:text-[38px] lg:text-[46px] leading-tight text-center' : text.length < 220 ? 'text-[22px] sm:text-[26px] lg:text-[30px] leading-snug text-center' : 'text-[17px] sm:text-[19px] lg:text-[21px]';
return (
<div key={cardKey} className={cx('flip-scene relative w-full animate-in', leaving === 'left' && 'swipe-left', leaving === 'right' && 'swipe-right')}>
{/* The whole card is the flip target, on both sides. Space, Enter and the arrow keys do the same. */}
<div
className="flip-card rounded-[24px] outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-4 focus-visible:ring-offset-paper"
data-flipped={flipped}
role="button"
tabIndex={0}
aria-label={flipped ? 'Flashcard, answer side. Activate to show the question.' : 'Flashcard, question side. Activate to show the answer.'}
onClick={onFlip}
>
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
<div className="flex items-center justify-between px-6 pt-5">
<span className="eyebrow">{label ?? 'Question'}</span>
<span className="text-xs text-ink-3">Click or press Space to flip</span>
</div>
<div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
{front}
</Markdown>
</div>
{hint && (
<div className="border-t border-line px-6 py-3" onClick={stop}>
{showHint ? (
<div className="flex items-start gap-2 text-sm text-ink-2">
<Lightbulb className="mt-0.5 size-4 shrink-0 text-warn" />
<Markdown>{hint}</Markdown>
</div>
) : (
<button type="button" onClick={() => setShowHint(true)} className="flex items-center gap-1.5 text-[13px] font-medium text-ink-2 hover:text-ink">
<Lightbulb className="size-4" /> Show hint
</button>
)}
</div>
)}
</div>
<div className={cx(face, 'flip-back border-accent/30')} inert={flipped ? undefined : true}>
<div className="flex items-center justify-between gap-4 px-6 pt-5">
<span className="eyebrow text-accent">Answer</span>
<span className="max-w-[70%] truncate text-xs text-ink-3">{front.replace(/[#*_`>]/g, '').slice(0, 90)}</span>
</div>
<div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16" aria-live="polite">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(back))}>
{back}
</Markdown>
</div>
{footer && (
<div className="cursor-auto border-t border-line px-6 py-3" onClick={stop} onKeyDown={stop}>
{footer}
</div>
)}
</div>
</div>
{burst && <StreakBurst key={burst.id} streak={burst.streak} tier={burst.tier} />}
</div>
);
}
export function StudyTopBar({ title, subtitle, onExit, right, progress, exitLabel = 'Exit', hot }: { title: string; subtitle?: ReactNode; onExit: () => void; right?: ReactNode; progress?: number; exitLabel?: string; hot?: boolean }) {
return (
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-14 max-w-4xl items-center gap-2 px-3 sm:px-6">
<IconButton label={exitLabel} onClick={onExit}>
<X />
</IconButton>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{title}</div>
{subtitle && <div className="truncate text-xs text-ink-3">{subtitle}</div>}
</div>
{right}
</div>
{progress !== undefined && (
<div role="progressbar" aria-label="Progress" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(progress * 100)} className="h-[3px] bg-ink/8">
<div className={cx('h-full transition-[width] duration-300', hot ? 'streak-bar' : 'bg-ink')} style={{ width: `${Math.max(0, Math.min(1, progress)) * 100}%` }} />
</div>
)}
</header>
);
}
/** Footer that stays at the bottom of the study column, in or out of the app shell. */
export function StudyFooter({ children }: { children: ReactNode }) {
return (
<footer className="safe-bottom sticky bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
<div className="mx-auto max-w-4xl px-3 py-3 sm:px-6">{children}</div>
</footer>
);
}
export function KeyHints({ items }: { items: [ReactNode, string][] }) {
return (
<div className="mt-2 hidden flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] text-ink-3 md:flex">
{items.map(([keys, label]) => (
<span key={label} className="flex items-center gap-1">
{keys} {label}
</span>
))}
</div>
);
}
const SWIPE_MS = 230;
/* ------------------------------ browse / cram ------------------------------ */
export interface CramState {
order: string[];
index: number;
known: string[];
unknown: string[];
shuffled: boolean;
/** Which pass this is: 1 = whole deck, 2+ = cards still being learned. */
round: number;
}
export interface CramCard {
id: string;
front: string;
back: string;
hint?: string;
}
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1): CramState {
const ids = cards.map((c) => c.id);
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round };
}
/** Drops cards that no longer exist and clamps the position, so a saved session survives deck edits. */
export function reconcileCramState(state: CramState | null | undefined, cards: CramCard[]): CramState | null {
if (!state || !Array.isArray(state.order)) return null;
const valid = new Set(cards.map((c) => c.id));
const order = state.order.filter((id) => valid.has(id));
if (order.length === 0) return null;
return {
order,
index: Math.max(0, Math.min(state.index ?? 0, order.length)),
known: (state.known ?? []).filter((id) => valid.has(id)),
unknown: (state.unknown ?? []).filter((id) => valid.has(id)),
shuffled: Boolean(state.shuffled),
round: state.round ?? 1,
};
}
export function CramSession({
title,
subtitle,
cards,
state,
onState,
onExit,
onGrade,
exitLabel,
renderExtra,
}: {
title: string;
subtitle?: string;
cards: CramCard[];
state: CramState;
onState: (s: CramState) => void;
onExit: () => void;
/** Called when a card is graded (used for activity tracking). */
onGrade?: (cardId: string, known: boolean) => void;
exitLabel?: string;
renderExtra?: (card: CramCard) => ReactNode;
}) {
const [flipped, setFlipped] = useState(false);
const [seenAnswer, setSeenAnswer] = useState(false);
const [leaving, setLeaving] = useState<'left' | 'right' | null>(null);
const { streak, burst, record, reset, hot } = useStreak();
const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]);
const total = state.order.length;
const done = state.index >= total;
const card = done ? undefined : byId.get(state.order[state.index]);
const busy = leaving !== null;
useEffect(() => {
setFlipped(false);
setSeenAnswer(false);
setLeaving(null);
}, [state.index, state.round, card?.id]);
const flip = () => {
if (busy || done) return;
setFlipped((f) => !f);
setSeenAnswer(true);
};
const grade = (known: boolean) => {
if (!card || busy || !seenAnswer) return;
setLeaving(known ? 'right' : 'left');
record(known);
onGrade?.(card.id, known);
const next: CramState = {
...state,
index: state.index + 1,
known: known ? [...state.known.filter((x) => x !== card.id), card.id] : state.known.filter((x) => x !== card.id),
unknown: known ? state.unknown.filter((x) => x !== card.id) : [...state.unknown.filter((x) => x !== card.id), card.id],
};
setTimeout(() => onState(next), SWIPE_MS);
};
const move = (delta: number) => !busy && onState({ ...state, index: Math.max(0, Math.min(total, state.index + delta)) });
const restart = (shuffled = state.shuffled) => {
reset();
onState(freshCramState(cards, shuffled));
};
const studyUnknown = () => {
reset();
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
};
useHotkeys({
space: (e) => (e.preventDefault(), flip()),
Enter: flip,
ArrowUp: (e) => (e.preventDefault(), flip()),
ArrowDown: (e) => (e.preventDefault(), flip()),
ArrowRight: () => grade(true),
ArrowLeft: () => grade(false),
'1': () => grade(false),
'2': () => grade(true),
Backspace: () => move(-1),
s: () => move(1),
});
return (
<div className="flex min-h-dvh flex-col bg-paper">
<StudyTopBar
title={title}
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : 'Browse')}
onExit={onExit}
exitLabel={exitLabel}
progress={total ? Math.min(1, state.index / total) : 0}
hot={hot}
right={
<>
<StreakChip streak={streak} />
<span className="num text-[13px] font-medium text-ink-2">
{Math.min(state.index + 1, total)}/{total}
</span>
<IconButton label={state.shuffled ? 'Shuffled. Restart in order' : 'Shuffle and restart'} active={state.shuffled} onClick={() => restart(!state.shuffled)}>
<Shuffle />
</IconButton>
</>
}
/>
<main className="mx-auto flex w-full max-w-4xl flex-1 flex-col justify-center px-4 py-6 sm:px-6 sm:py-8">
{done || !card ? (
<div className="card m-auto w-full max-w-xl animate-in p-7 text-center sm:p-10">
<div className="mx-auto mb-4 w-fit">
<Ring value={total ? state.known.length / (state.known.length + state.unknown.length || 1) : 0} size={104} stroke={9} tone="good">
<span className="display num text-[28px]">{state.known.length}</span>
</Ring>
</div>
<h2 className="display text-[28px]">{state.unknown.length === 0 ? 'You know them all' : 'Round complete'}</h2>
<p className="mt-2 text-[15px] text-ink-2">
{state.known.length} known{state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of {plural(total, 'card')}.
</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
{state.unknown.length > 0 && (
<Button variant="primary" size="lg" icon={<RotateCcw />} onClick={studyUnknown}>
Study the {state.unknown.length} again
</Button>
)}
<Button size="lg" icon={<RotateCcw />} onClick={() => restart()}>
Start over
</Button>
<Button size="lg" variant="ghost" onClick={onExit}>
Done
</Button>
</div>
</div>
) : (
<FlipCard cardKey={`${state.round}:${state.index}:${card.id}`} front={card.front} back={card.back} hint={card.hint} flipped={flipped} onFlip={flip} leaving={leaving} burst={burst} footer={renderExtra?.(card)} label={state.known.includes(card.id) ? 'Question · marked known' : state.unknown.includes(card.id) ? 'Question · still learning' : undefined} />
)}
</main>
{!done && card && (
<StudyFooter>
<div className="flex items-center gap-2">
<IconButton label="Previous card (Backspace)" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
<ArrowLeft />
</IconButton>
{seenAnswer ? (
<>
<Button size="lg" className="h-14 flex-1 border-bad/40 text-bad hover:bg-bad-soft" icon={<X />} disabled={busy} onClick={() => grade(false)}>
Still learning
</Button>
<Button size="lg" className="h-14 flex-1 border-good/40 text-good hover:bg-good-soft" icon={<Check />} disabled={busy} onClick={() => grade(true)}>
Know it
</Button>
</>
) : (
<Button size="lg" variant="primary" className="h-14 flex-1" onClick={flip}>
Show answer
</Button>
)}
<IconButton label="Skip card (S)" onClick={() => move(1)} disabled={busy}>
<SkipForward />
</IconButton>
</div>
<KeyHints
items={[
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
[<Kbd>←</Kbd>, 'still learning'],
[<Kbd>→</Kbd>, 'know it'],
]}
/>
</StudyFooter>
)}
</div>
);
}