import { ArrowLeft, Check, Flame, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react'; import { useCallback, useEffect, 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, 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 = { 1: 1600, 2: 1900, 3: 2400 }; const BURST_COPY: Record = { 1: 'On a roll', 2: 'Hot streak', 3: 'Unstoppable' }; export function StreakChip({ streak }: { streak: number }) { if (streak < 2) return null; const hot = streak >= STREAK_HOT; return ( {hot && } {streak} in a row ); } /** Milestone moment: the count, marked with a highlighter stroke, in the app's own type and colours. */ function StreakBurst({ streak, tier }: { streak: number; tier: StreakTier }) { const size = { 1: 'text-6xl', 2: 'text-7xl', 3: 'text-8xl md:text-9xl' }[tier]; return (
{BURST_COPY[tier]} {streak} in a row
); } /** 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 | 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, onSwipe, }: { 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; /** Horizontal touch gestures grade an answer without interfering with vertical scrolling. */ onSwipe?: (known: boolean) => void; }) { const [showHint, setShowHint] = useState(false); const touch = useRef<{ x: number; y: number } | null>(null); const suppressClick = useRef(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 (
{/* The whole card is the flip target, on both sides. Space, Enter and the arrow keys do the same. */}
{ const target = e.target as HTMLElement; if (!onSwipe || target.closest('button,a,input,textarea,select')) return; const p = e.touches[0]; touch.current = { x: p.clientX, y: p.clientY }; suppressClick.current = false; }} onTouchCancel={() => { touch.current = null; }} onTouchEnd={(e) => { const start = touch.current; touch.current = null; if (!start || !onSwipe) return; const p = e.changedTouches[0]; const dx = p.clientX - start.x; const dy = p.clientY - start.y; if (Math.abs(dx) >= 80 && Math.abs(dx) > Math.abs(dy) * 1.5) { suppressClick.current = true; onSwipe(dx > 0); } }} onClick={() => { if (suppressClick.current) { suppressClick.current = false; return; } onFlip(); }} >
{label ?? 'Question'} Tap the card to flip it
{front}
{hint && (
{showHint ? (
{hint}
) : ( )}
)}
Answer {front.replace(/[#*_`>]/g, '').slice(0, 90)}
{back}
{footer && (
{footer}
)}
{burst && }
); } 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 (
{title}
{subtitle &&
{subtitle}
}
{right}
{progress !== undefined && (
)}
); } /** Footer that stays at the bottom of the study column, in or out of the app shell. */ export function StudyFooter({ children }: { children: ReactNode }) { return (
{children}
); } 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; /** Standard mode option: a missed card goes to the back of the pile until it is known. */ repeatMissed?: boolean; /** Cards that were missed at least once in this session (repeat mode). */ retried?: string[]; } export interface CramCard { id: string; front: string; back: string; hint?: string; } export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1, repeatMissed = false): CramState { const ids = cards.map((c) => c.id); return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round, repeatMissed, retried: [] }; } /** 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, repeatMissed: Boolean(state.repeatMissed), retried: (state.retried ?? []).filter((id) => valid.has(id)), }; } 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); // Repeat mode: a missed card goes to the back of the pile and comes round again. const requeue = !known && state.repeatMissed; const next: CramState = { ...state, index: state.index + 1, order: requeue ? [...state.order, card.id] : state.order, retried: requeue ? [...new Set([...(state.retried ?? []), card.id])] : state.retried, 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, 1, state.repeatMissed)); }; const shuffleRemaining = () => { if (busy) return; const remaining = state.order.slice(state.index); const ordered = state.shuffled ? cards.filter((c) => remaining.includes(c.id)).map((c) => c.id) : shuffle(remaining); onState({ ...state, shuffled: !state.shuffled, order: [...state.order.slice(0, state.index), ...ordered] }); }; const studyUnknown = () => { reset(); onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1, state.repeatMissed)); }; 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 (
1 ? `Round ${state.round}: still learning` : state.repeatMissed ? 'Standard · missed cards repeat' : 'Standard')} onExit={onExit} exitLabel={exitLabel} progress={total ? Math.min(1, state.index / total) : 0} hot={hot} right={ <> {Math.min(state.index + 1, total)}/{total} } />
{done || !card ? (
{state.known.length}

{state.unknown.length === 0 ? 'You know them all' : 'Round complete'}

{state.repeatMissed ? `All ${plural(state.known.length, 'card')} known${state.retried?.length ? `; ${state.retried.length} took more than one try` : ' on the first try'}.` : `${state.known.length} known${state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of ${plural(total, 'card')}.`}

{state.unknown.length > 0 && ( )}
) : ( )}
{!done && card && (
move(-1)} disabled={state.index === 0 || busy}> {seenAnswer ? ( <> ) : ( )} move(1)} disabled={busy}>
)}
); }