All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
Generation - Every quiz is NCLEX style; "Practice exam" writes 50 questions. - Calculation questions only when the material involves calculations (max 5 per exam). - Broad topics: the class's topics are listed in the prompt, a quick grouping call maps narrow labels onto broad ones, and leftover variants are merged. - Exact select-all count per batch; option order shuffled. - Python check: at most 3 runs, fixed problems count as passed, cosmetic remarks ignored. Assistant - Text, tool steps and cards appear in the order they happen, with paragraph breaks between steps. - Optional thinking box: fixed height, follows the newest text, can be scrolled back. - "+" opens a material picker listing recent items; items can be dragged in from class pages; shorter placeholder. MCP servers - Streamable HTTP client; encrypted headers. - Per-server instructions and switches for chat, Explain, generation and the quiz check. - Settings UI. Share links - Optional "Explain this" and "Ask about this material" per link, off by default. - Items are loaded on the server and checked against the share; no tools; rate-limited. - Migration 4 stores the switches. Study and documents - Standard flashcard mode (optionally repeat missed cards until known) next to spaced repetition. - Streak visuals restyled in the app palette. - Side by side / Original document views, with sandboxed previews of Word and PowerPoint files. Other - Built-in embedding model baked into the image; sharp stubbed if it cannot load; real load error shown in Settings. - Python runner blocks network and process modules in JavaScript too. - "View questions and answers" removed from the quiz start screen. - Docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
443 lines
19 KiB
TypeScript
443 lines
19 KiB
TypeScript
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<StreakTier, number> = { 1: 1600, 2: 1900, 3: 2400 };
|
|
const BURST_COPY: Record<StreakTier, string> = { 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 (
|
|
<span key={hot ? 'hot' : 'warm'} className={cx('streak-chip num inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-xs font-semibold whitespace-nowrap', hot ? 'streak-chip-hot' : 'bg-ink/7 text-ink-2')}>
|
|
{hot && <Flame className="size-3.5 shrink-0" strokeWidth={2.4} />}
|
|
{streak} in a row
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/** 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 (
|
|
<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 text-center">
|
|
<span className="flex items-center gap-1.5 text-xs font-semibold tracking-[0.16em] text-accent uppercase">
|
|
<Flame className="streak-flame size-4" strokeWidth={2.4} />
|
|
{BURST_COPY[tier]}
|
|
</span>
|
|
<span className={cx('streak-mark num mt-2 px-4 leading-none font-semibold tracking-tight text-ink', size)}>{streak}</span>
|
|
<span className="mt-2 font-serif text-xl text-ink-2 italic">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,
|
|
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 (
|
|
<div key={cardKey} className={cx('flip-scene relative w-full', !leaving && '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.'}
|
|
style={{ touchAction: onSwipe ? 'pan-y' : undefined }}
|
|
onTouchStart={(e) => {
|
|
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();
|
|
}}
|
|
>
|
|
<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">Tap the card to flip it</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>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<div className="flex min-h-dvh flex-col bg-paper">
|
|
<StudyTopBar
|
|
title={title}
|
|
subtitle={subtitle ?? (state.round > 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={
|
|
<>
|
|
<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 ? 'Put remaining cards in order' : 'Shuffle remaining cards'} active={state.shuffled} disabled={busy || done} onClick={shuffleRemaining}>
|
|
<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.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')}.`}
|
|
</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} onSwipe={seenAnswer && !busy ? grade : undefined} 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" 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" onClick={() => move(1)} disabled={busy}>
|
|
<SkipForward />
|
|
</IconButton>
|
|
</div>
|
|
</StudyFooter>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|