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>
This commit is contained in:
parent
c59591ccb9
commit
aed14cd04f
13 changed files with 769 additions and 216 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import { BookOpen, CircleAlert, CircleCheck, FileUp, Layers, NotebookPen, TriangleAlert } from 'lucide-react';
|
||||
import { BookOpen, Check, CircleAlert, CircleCheck, Copy, FileUp, Layers, MessageSquareText, NotebookPen, RotateCcw, TriangleAlert } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
|
|
@ -7,12 +7,117 @@ import { DECK_JSON_TEMPLATE, parseImport, QUIZ_JSON_TEMPLATE, summarizeIssues, T
|
|||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useRefresh } from '@/lib/queries';
|
||||
import type { Draft } from '@/lib/types';
|
||||
import { cx, downloadText, plural, useDebounced } from '@/lib/util';
|
||||
import { Badge, Button, Callout, Dialog, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Textarea } from '@/ui';
|
||||
import { copyText, cx, downloadText, plural, useDebounced } from '@/lib/util';
|
||||
import { Badge, Button, Callout, Dialog, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Segmented, Spinner, Textarea } from '@/ui';
|
||||
|
||||
const KIND_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||
const DETECTED = { json: 'JSON', 'text-quiz': 'Question blocks', 'text-cards': 'Term and definition list', none: '' };
|
||||
|
||||
/**
|
||||
* Instructions to paste into ChatGPT, Claude, Gemini or any other chatbot so that it answers
|
||||
* in a format this dialog can import. Editable, because everyone ends up tuning the wording.
|
||||
*/
|
||||
function LlmInstructionsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const [kind, setKind] = useState<'quiz' | 'deck'>('quiz');
|
||||
const [data, setData] = useState<{ quiz: string; deck: string; customized: { quiz: boolean; deck: boolean } } | null>(null);
|
||||
const [text, setText] = useState('');
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
const res = await api.get<{ quiz: string; deck: string; customized: { quiz: boolean; deck: boolean } }>('/api/llm-instructions');
|
||||
setData(res);
|
||||
return res;
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setCopied(false);
|
||||
load()
|
||||
.then((res) => setText(res[kind]))
|
||||
.catch((e) => toast.error(errorMessage(e)));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open]);
|
||||
useEffect(() => {
|
||||
if (data) setText(data[kind]);
|
||||
setCopied(false);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [kind]);
|
||||
|
||||
const dirty = data !== null && text !== data[kind];
|
||||
const save = async (value: string | null) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.put('/api/llm-instructions', { kind, text: value });
|
||||
const res = await load();
|
||||
setText(res[kind]);
|
||||
toast.success(value === null ? 'Back to the built-in instructions' : 'Saved as your instructions');
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Instructions for a chatbot"
|
||||
description="Paste these into ChatGPT, Claude, Gemini or any other AI along with your notes. Then paste its JSON answer into the import box."
|
||||
size="lg"
|
||||
footer={
|
||||
<>
|
||||
{data?.customized[kind] && (
|
||||
<Button variant="ghost" className="mr-auto" icon={<RotateCcw />} disabled={busy} onClick={() => save(null)}>
|
||||
Reset to built-in
|
||||
</Button>
|
||||
)}
|
||||
{dirty && (
|
||||
<Button loading={busy} onClick={() => save(text)}>
|
||||
Save my version
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={copied ? <Check /> : <Copy />}
|
||||
disabled={!text.trim()}
|
||||
onClick={async () => {
|
||||
if (await copyText(text)) {
|
||||
setCopied(true);
|
||||
toast.success('Instructions copied');
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{copied ? 'Copied' : 'Copy instructions'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Segmented
|
||||
label="Content type"
|
||||
value={kind}
|
||||
onChange={setKind}
|
||||
className="mb-3"
|
||||
options={[
|
||||
{ value: 'quiz', label: 'Quiz questions', icon: <BookOpen /> },
|
||||
{ value: 'deck', label: 'Flashcards', icon: <Layers /> },
|
||||
]}
|
||||
/>
|
||||
{data ? (
|
||||
<Textarea value={text} onChange={(e) => setText(e.target.value)} rows={16} spellCheck={false} aria-label="Instructions" className="num text-[12.5px] leading-relaxed" />
|
||||
) : (
|
||||
<div className="grid h-64 place-items-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-2 text-[13px] text-ink-3">
|
||||
Change the number of items, add your own rules, and replace the last line with your material. If you have connected an AI model in Settings, "Generate" does all of this for you without copying and pasting.
|
||||
</p>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function ImportDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
|
|
@ -21,6 +126,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
|||
const [titles, setTitles] = useState<Record<number, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [instructionsOpen, setInstructionsOpen] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const debounced = useDebounced(text, 250);
|
||||
|
||||
|
|
@ -108,11 +214,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
|||
<Menu
|
||||
align="start"
|
||||
side="top"
|
||||
trigger={
|
||||
<Button variant="ghost" className="mr-auto">
|
||||
Templates
|
||||
</Button>
|
||||
}
|
||||
trigger={<Button variant="ghost">Templates</Button>}
|
||||
>
|
||||
<MenuLabel>Insert an example</MenuLabel>
|
||||
<MenuItem onSelect={() => insertTemplate(QUIZ_JSON_TEMPLATE)}>Quiz (JSON)</MenuItem>
|
||||
|
|
@ -124,6 +226,9 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
|||
<MenuItem onSelect={() => downloadText('quiz-template.json', QUIZ_JSON_TEMPLATE)}>quiz-template.json</MenuItem>
|
||||
<MenuItem onSelect={() => downloadText('flashcards-template.json', DECK_JSON_TEMPLATE)}>flashcards-template.json</MenuItem>
|
||||
</Menu>
|
||||
<Button variant="ghost" className="mr-auto" icon={<MessageSquareText />} onClick={() => setInstructionsOpen(true)}>
|
||||
AI instructions
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
|
|
@ -168,6 +273,8 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<LlmInstructionsDialog open={instructionsOpen} onClose={() => setInstructionsOpen(false)} />
|
||||
|
||||
{parsed && (
|
||||
<div className="mt-5 space-y-3" aria-live="polite">
|
||||
{parsed.notices.map((n, i) => (
|
||||
|
|
|
|||
|
|
@ -1,12 +1,93 @@
|
|||
import { ArrowLeft, ArrowRight, Check, Lightbulb, RotateCcw, Shuffle, X } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
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 { Badge, Button, IconButton, Kbd, ProgressBar } from '@/ui';
|
||||
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,
|
||||
|
|
@ -16,6 +97,8 @@ export function FlipCard({
|
|||
label,
|
||||
cardKey,
|
||||
footer,
|
||||
leaving,
|
||||
burst,
|
||||
}: {
|
||||
front: string;
|
||||
back: string;
|
||||
|
|
@ -25,38 +108,41 @@ export function FlipCard({
|
|||
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);
|
||||
// Only animate the front when it comes back from the answer, not when a new card arrives.
|
||||
const [turned, setTurned] = useState(false);
|
||||
useEffect(() => {
|
||||
setShowHint(false);
|
||||
setTurned(false);
|
||||
}, [cardKey]);
|
||||
useEffect(() => {
|
||||
if (flipped) setTurned(true);
|
||||
}, [flipped]);
|
||||
const face = 'flip-face flex min-h-[320px] flex-col rounded-[22px] border border-line bg-surface shadow-2 sm:min-h-[380px]';
|
||||
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-[28px] sm:text-[34px] leading-tight text-center' : text.length < 220 ? 'text-[21px] sm:text-[24px] leading-snug text-center' : 'text-[17px] sm:text-[18px]');
|
||||
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="w-full animate-in">
|
||||
<div className="flip-inner" data-flipped={flipped} data-turned={turned}>
|
||||
<div className={cx(face, 'flip-front')}>
|
||||
<button type="button" onClick={onFlip} aria-label="Show answer" className="flex flex-1 cursor-pointer flex-col rounded-[22px] text-left">
|
||||
<div className="flex items-center justify-between px-5 pt-4">
|
||||
<span className="eyebrow">{label ?? 'Front'}</span>
|
||||
<span className="text-xs text-ink-3">Tap to flip</span>
|
||||
</div>
|
||||
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10">
|
||||
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
|
||||
{front}
|
||||
</Markdown>
|
||||
</div>
|
||||
</button>
|
||||
<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-5 py-3">
|
||||
<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" />
|
||||
|
|
@ -70,27 +156,32 @@ export function FlipCard({
|
|||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={cx(face, 'flip-back')}>
|
||||
<button type="button" onClick={onFlip} aria-label="Show question" className="flex cursor-pointer items-center justify-between rounded-t-[22px] px-5 pt-4 text-left">
|
||||
<span className="eyebrow">Back</span>
|
||||
<span className="max-w-[70%] truncate text-xs text-ink-3">{front.replace(/[#*_`>]/g, '').slice(0, 80)}</span>
|
||||
</button>
|
||||
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10" aria-live="polite">
|
||||
<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="border-t border-line px-5 py-3">{footer}</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' }: { title: string; subtitle?: ReactNode; onExit: () => void; right?: ReactNode; progress?: number; exitLabel?: string }) {
|
||||
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-3xl items-center gap-2 px-3 sm:px-5">
|
||||
<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>
|
||||
|
|
@ -100,11 +191,38 @@ export function StudyTopBar({ title, subtitle, onExit, right, progress, exitLabe
|
|||
</div>
|
||||
{right}
|
||||
</div>
|
||||
{progress !== undefined && <ProgressBar value={progress} tone="ink" className="h-[3px] rounded-none" label="Progress" />}
|
||||
{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 {
|
||||
|
|
@ -168,39 +286,60 @@ export function CramSession({
|
|||
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]);
|
||||
useEffect(() => setFlipped(false), [state.index, state.round]);
|
||||
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) return;
|
||||
if (!card || busy || !seenAnswer) return;
|
||||
setLeaving(known ? 'right' : 'left');
|
||||
record(known);
|
||||
onGrade?.(card.id, known);
|
||||
onState({
|
||||
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 move = (delta: number) => onState({ ...state, index: Math.max(0, Math.min(total, state.index + delta)) });
|
||||
const restart = (shuffled = state.shuffled) => onState(freshCramState(cards, shuffled));
|
||||
const studyUnknown = () => {
|
||||
const pool = cards.filter((c) => state.unknown.includes(c.id));
|
||||
onState({ ...freshCramState(pool, true, state.round + 1) });
|
||||
reset();
|
||||
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
|
||||
};
|
||||
|
||||
useHotkeys({
|
||||
space: (e) => {
|
||||
e.preventDefault();
|
||||
if (!done) setFlipped((f) => !f);
|
||||
},
|
||||
Enter: () => !done && setFlipped((f) => !f),
|
||||
ArrowRight: () => move(1),
|
||||
ArrowLeft: () => move(-1),
|
||||
'1': () => flipped && grade(false),
|
||||
'2': () => flipped && grade(true),
|
||||
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 (
|
||||
|
|
@ -211,8 +350,10 @@ export function CramSession({
|
|||
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>
|
||||
|
|
@ -222,9 +363,9 @@ export function CramSession({
|
|||
</>
|
||||
}
|
||||
/>
|
||||
<main className="mx-auto flex w-full max-w-2xl flex-1 flex-col px-4 pt-6 pb-36 sm:px-5 sm:pt-10">
|
||||
<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 animate-in p-7 text-center sm:p-10">
|
||||
<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>
|
||||
|
|
@ -249,49 +390,41 @@ export function CramSession({
|
|||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FlipCard cardKey={`${state.round}:${card.id}`} front={card.front} back={card.back} hint={card.hint} flipped={flipped} onFlip={() => setFlipped((f) => !f)} footer={renderExtra?.(card)} />
|
||||
<div className="mt-4 flex justify-center gap-1.5">
|
||||
{state.known.includes(card.id) && <Badge tone="good">Marked known</Badge>}
|
||||
{state.unknown.includes(card.id) && <Badge tone="warn">Still learning</Badge>}
|
||||
</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 && (
|
||||
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
|
||||
<div className="mx-auto flex h-[76px] max-w-2xl items-center gap-2 px-3 sm:px-5">
|
||||
<IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0}>
|
||||
<StudyFooter>
|
||||
<div className="flex items-center gap-2">
|
||||
<IconButton label="Previous card (Backspace)" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
|
||||
<ArrowLeft />
|
||||
</IconButton>
|
||||
{flipped ? (
|
||||
{seenAnswer ? (
|
||||
<>
|
||||
<Button size="lg" className="flex-1 border-warn/40 text-warn hover:bg-warn-soft" icon={<RotateCcw />} onClick={() => grade(false)}>
|
||||
<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
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>1</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
<Button size="lg" className="flex-1 border-good/40 text-good hover:bg-good-soft" icon={<Check />} onClick={() => grade(true)}>
|
||||
<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
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>2</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button size="lg" variant="primary" className="flex-1" onClick={() => setFlipped(true)}>
|
||||
<Button size="lg" variant="primary" className="h-14 flex-1" onClick={flip}>
|
||||
Show answer
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>Space</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<IconButton label="Skip card" onClick={() => move(1)}>
|
||||
<ArrowRight />
|
||||
<IconButton label="Skip card (S)" onClick={() => move(1)} disabled={busy}>
|
||||
<SkipForward />
|
||||
</IconButton>
|
||||
</div>
|
||||
</footer>
|
||||
<KeyHints
|
||||
items={[
|
||||
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
|
||||
[<Kbd>←</Kbd>, 'still learning'],
|
||||
[<Kbd>→</Kbd>, 'know it'],
|
||||
]}
|
||||
/>
|
||||
</StudyFooter>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -71,13 +71,30 @@ function OptionList({
|
|||
);
|
||||
}
|
||||
|
||||
function Verdict({ score }: { score: number }) {
|
||||
/** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */
|
||||
function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null {
|
||||
if (question.type !== 'multi') return null;
|
||||
const correctIds = question.options.filter((o) => o.correct).map((o) => o.id);
|
||||
const right = selected.filter((id) => correctIds.includes(id)).length;
|
||||
const wrong = selected.length - right;
|
||||
if (right === correctIds.length && wrong === 0) return null;
|
||||
if (sata === 'strict') return 'All-or-nothing scoring is on, so every correct choice (and no others) is needed for credit.';
|
||||
const earned = Math.max(0, right - wrong);
|
||||
return `Partial credit: ${right} correct ${right === 1 ? 'choice' : 'choices'}${wrong > 0 ? ` minus ${wrong} incorrect` : ''} = ${earned} of ${correctIds.length} ${correctIds.length === 1 ? 'point' : 'points'} for this question.`;
|
||||
}
|
||||
|
||||
const fmtPoints = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
|
||||
|
||||
function Verdict({ score, detail }: { score: number; detail?: string | null }) {
|
||||
const full = isFullyCorrect(score);
|
||||
const partial = !full && score > 0;
|
||||
return (
|
||||
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')} role="status">
|
||||
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
|
||||
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
|
||||
<div role="status">
|
||||
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')}>
|
||||
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
|
||||
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
|
||||
</div>
|
||||
{detail && <p className="mt-1 text-[13px] text-ink-2">{detail}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -125,6 +142,19 @@ export function QuizRunner(p: RunnerProps) {
|
|||
const answeredCount = p.questions.filter((q) => (p.mode === 'practice' ? p.answers[q.id]?.checked : (p.answers[q.id]?.selected.length ?? 0) > 0)).length;
|
||||
const flagged = p.flags.includes(question.id);
|
||||
const isLast = index === total - 1;
|
||||
// Running score for practice mode (select-all questions can earn part of a point).
|
||||
const live = useMemo(() => {
|
||||
if (p.mode !== 'practice') return null;
|
||||
let n = 0;
|
||||
let points = 0;
|
||||
for (const q of p.questions) {
|
||||
const a = p.answers[q.id];
|
||||
if (!a?.checked) continue;
|
||||
n += 1;
|
||||
points += scoreQuestion(q, a.selected, p.sataScoring);
|
||||
}
|
||||
return n > 0 ? { n, points, percent: Math.round((points / n) * 100) } : null;
|
||||
}, [p.mode, p.questions, p.answers, p.sataScoring]);
|
||||
const remaining = p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
|
||||
|
||||
// Session clock: pauses while the tab is hidden.
|
||||
|
|
@ -201,6 +231,17 @@ export function QuizRunner(p: RunnerProps) {
|
|||
<div className="truncate text-sm font-semibold">{p.title}</div>
|
||||
<div className="text-xs text-ink-3">{p.mode === 'exam' ? 'Exam' : 'Practice'}</div>
|
||||
</div>
|
||||
{live && (
|
||||
<div
|
||||
className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', live.percent >= 80 ? 'bg-good-soft text-good' : live.percent >= 60 ? 'bg-warn-soft text-warn' : 'bg-bad-soft text-bad')}
|
||||
aria-label={`Score so far: ${fmtPoints(live.points)} of ${live.n} correct, ${live.percent} percent`}
|
||||
>
|
||||
<span className="hidden sm:inline">
|
||||
{fmtPoints(live.points)}/{live.n} correct ·
|
||||
</span>
|
||||
{live.percent}%
|
||||
</div>
|
||||
)}
|
||||
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}>
|
||||
<Clock className="size-3.5" />
|
||||
{formatDuration(remaining ?? elapsed)}
|
||||
|
|
@ -233,7 +274,7 @@ export function QuizRunner(p: RunnerProps) {
|
|||
|
||||
{checked && (
|
||||
<div className="mt-5 animate-in space-y-4">
|
||||
<Verdict score={score} />
|
||||
<Verdict score={score} detail={creditDetail(question, selected, p.sataScoring)} />
|
||||
{question.rationale && (
|
||||
<div className="rounded-[14px] border border-line bg-surface p-4">
|
||||
<div className="eyebrow mb-1.5">Rationale</div>
|
||||
|
|
@ -419,7 +460,7 @@ export function QuizResults(p: ResultsProps) {
|
|||
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
|
||||
<h1 className="display text-[30px]">{headline}</h1>
|
||||
<p className="mt-1.5 text-[15px] text-ink-2">
|
||||
<span className="num font-semibold text-ink">{Number.isInteger(points) ? points : points.toFixed(1)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
|
||||
<span className="num font-semibold text-ink">{fmtPoints(points)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
|
||||
{p.elapsedSec > 0 ? ` in ${formatMinutes(p.elapsedSec)}` : ''}
|
||||
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
|
||||
</p>
|
||||
|
|
@ -490,6 +531,7 @@ export function QuizResults(p: ResultsProps) {
|
|||
{r.q.stem}
|
||||
</Markdown>
|
||||
<OptionList question={r.q} selected={r.selected} revealed />
|
||||
{r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && <p className="mt-2.5 text-[13px] text-ink-2">{creditDetail(r.q, r.selected, p.sataScoring)}</p>}
|
||||
{r.q.rationale && (
|
||||
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
|
||||
<div className="eyebrow mb-1">Rationale</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue