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
|
|
@ -144,7 +144,11 @@ const TOOLS: ToolSpec[] = [
|
||||||
const documents = q<Record<string, any>>(`SELECT id, title, kind, status, page_count AS pages, token_count AS approx_tokens, folder_id FROM documents WHERE class_id = ? ORDER BY sort_order`);
|
const documents = q<Record<string, any>>(`SELECT id, title, kind, status, page_count AS pages, token_count AS approx_tokens, folder_id FROM documents WHERE class_id = ? ORDER BY sort_order`);
|
||||||
const notes = q<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE class_id = ? ORDER BY sort_order`);
|
const notes = q<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE class_id = ? ORDER BY sort_order`);
|
||||||
const folders = q<Record<string, any>>(`SELECT id, name FROM folders WHERE class_id = ? ORDER BY sort_order`);
|
const folders = q<Record<string, any>>(`SELECT id, name FROM folders WHERE class_id = ? ORDER BY sort_order`);
|
||||||
return { output: { class: { id: cls.id, name: cls.name }, folders, quizzes, decks, documents, notes }, summary: `${quizzes.length + decks.length + documents.length + notes.length} items in ${cls.name}` };
|
const withUrl = (rows: Record<string, any>[], base: string) => rows.map((x) => ({ ...x, url: `/${base}/${x.id}` }));
|
||||||
|
return {
|
||||||
|
output: { class: { id: cls.id, name: cls.name, url: `/classes/${cls.id}` }, folders, quizzes: withUrl(quizzes, 'quizzes'), decks: withUrl(decks, 'decks'), documents: withUrl(documents, 'documents'), notes: withUrl(notes, 'notes') },
|
||||||
|
summary: `${quizzes.length + decks.length + documents.length + notes.length} items in ${cls.name}`,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -217,7 +221,7 @@ const TOOLS: ToolSpec[] = [
|
||||||
{
|
{
|
||||||
def: {
|
def: {
|
||||||
name: 'search_library',
|
name: 'search_library',
|
||||||
description: 'Search quiz questions, flashcards and titles by keyword. Use to find existing material on a topic.',
|
description: 'Search quiz questions, flashcards, notes and titles by keyword. Use to find existing material on a topic. Every result has a url you can link to.',
|
||||||
parameters: obj({ query: S, class_id: S }, ['query']),
|
parameters: obj({ query: S, class_id: S }, ['query']),
|
||||||
},
|
},
|
||||||
label: (i) => `Searching your library for "${clip(String(i.query ?? ''), 50)}"`,
|
label: (i) => `Searching your library for "${clip(String(i.query ?? ''), 50)}"`,
|
||||||
|
|
@ -239,14 +243,28 @@ const TOOLS: ToolSpec[] = [
|
||||||
like,
|
like,
|
||||||
...p,
|
...p,
|
||||||
);
|
);
|
||||||
|
const URL_BASE: Record<string, string> = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents' };
|
||||||
const titles = [
|
const titles = [
|
||||||
...db.all<Record<string, any>>(`SELECT 'quiz' AS kind, z.id, z.title FROM quizzes z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
...db.all<Record<string, any>>(`SELECT 'quiz' AS kind, z.id, z.title FROM quizzes z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
||||||
...db.all<Record<string, any>>(`SELECT 'deck' AS kind, z.id, z.title FROM decks z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
...db.all<Record<string, any>>(`SELECT 'deck' AS kind, z.id, z.title FROM decks z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
||||||
...db.all<Record<string, any>>(`SELECT 'note' AS kind, z.id, z.title FROM notes z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
...db.all<Record<string, any>>(`SELECT 'note' AS kind, z.id, z.title FROM notes z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
||||||
];
|
...db.all<Record<string, any>>(`SELECT 'document' AS kind, z.id, z.title FROM documents z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p),
|
||||||
|
].map((x) => ({ ...x, url: `/${URL_BASE[x.kind]}/${x.id}` }));
|
||||||
|
const notes = db
|
||||||
|
.all<Record<string, any>>(`SELECT z.id, z.title, z.content FROM notes z WHERE z.content LIKE ? ESCAPE '\\' ${cls} LIMIT 6`, like, ...p)
|
||||||
|
.map((n) => {
|
||||||
|
const at = Math.max(0, String(n.content).toLowerCase().indexOf(String(input.query ?? '').toLowerCase()) - 120);
|
||||||
|
return { id: n.id, title: n.title, url: `/notes/${n.id}`, excerpt: clip(String(n.content).slice(at), 400) };
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
output: { titles, questions: questions.map((q) => ({ ...q, stem: clip(q.stem, 300) })), cards: cards.map((c) => ({ ...c, front: clip(c.front, 200), back: clip(c.back, 300) })) },
|
output: {
|
||||||
summary: `${titles.length + questions.length + cards.length} matches`,
|
titles,
|
||||||
|
questions: questions.map((q) => ({ ...q, stem: clip(q.stem, 300), url: `/quizzes/${q.quiz_id}?q=${q.id}` })),
|
||||||
|
cards: cards.map((c) => ({ ...c, front: clip(c.front, 200), back: clip(c.back, 300), url: `/decks/${c.deck_id}?card=${c.id}` })),
|
||||||
|
notes,
|
||||||
|
note: 'For passages inside uploaded documents, use search_documents.',
|
||||||
|
},
|
||||||
|
summary: `${titles.length + questions.length + cards.length + notes.length} matches`,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -262,6 +280,7 @@ const TOOLS: ToolSpec[] = [
|
||||||
output: {
|
output: {
|
||||||
id: quiz.id,
|
id: quiz.id,
|
||||||
title: quiz.title,
|
title: quiz.title,
|
||||||
|
url: `/quizzes/${quiz.id}`,
|
||||||
class_id: quiz.class_id,
|
class_id: quiz.class_id,
|
||||||
total_questions: all.length,
|
total_questions: all.length,
|
||||||
questions: all.slice(offset, offset + limit).map((q) => ({
|
questions: all.slice(offset, offset + limit).map((q) => ({
|
||||||
|
|
@ -286,11 +305,20 @@ const TOOLS: ToolSpec[] = [
|
||||||
const offset = Math.max(0, Number(input.offset) || 0);
|
const offset = Math.max(0, Number(input.offset) || 0);
|
||||||
const limit = Math.max(1, Math.min(150, Number(input.limit) || 60));
|
const limit = Math.max(1, Math.min(150, Number(input.limit) || 60));
|
||||||
return {
|
return {
|
||||||
output: { id: deck.id, title: deck.title, class_id: deck.class_id, total_cards: all.length, cards: all.slice(offset, offset + limit).map((c) => ({ id: c.id, front: clip(c.front, 300), back: clip(c.back, 500) })) },
|
output: { id: deck.id, title: deck.title, url: `/decks/${deck.id}`, class_id: deck.class_id, total_cards: all.length, cards: all.slice(offset, offset + limit).map((c) => ({ id: c.id, front: clip(c.front, 300), back: clip(c.back, 500) })) },
|
||||||
summary: `${deck.title} (${all.length} cards)`,
|
summary: `${deck.title} (${all.length} cards)`,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
def: { name: 'read_note', description: 'Read one of the user\'s notes or study guides (Markdown).', parameters: obj({ note_id: S }, ['note_id']) },
|
||||||
|
label: () => 'Reading a note',
|
||||||
|
run: (input, { app }) => {
|
||||||
|
const note = app.db.get<{ id: string; title: string; content: string; class_id: string }>('SELECT id, title, content, class_id FROM notes WHERE id = ?', String(input.note_id));
|
||||||
|
if (!note) throw notFound('Note');
|
||||||
|
return { output: { id: note.id, title: note.title, url: `/notes/${note.id}`, class_id: note.class_id, content: clip(note.content, 24000) }, summary: note.title };
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
def: {
|
def: {
|
||||||
name: 'get_performance',
|
name: 'get_performance',
|
||||||
|
|
@ -832,6 +860,8 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
|
||||||
`How to work:
|
`How to work:
|
||||||
- Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find.
|
- Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find.
|
||||||
- Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. If the documents do not cover something, say so, then answer from general knowledge and label it as such.
|
- Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. If the documents do not cover something, say so, then answer from general knowledge and label it as such.
|
||||||
|
- You can browse everything: list_materials and search_library for quizzes, flashcards and notes; get_quiz, get_deck and read_note to open them; search_documents and read_document for uploaded files.
|
||||||
|
- When you mention a specific quiz, deck, note or document, link it with Markdown using the url the tool gave you, for example [Cardiac drug cards](/decks/abc123). Never invent a url.
|
||||||
- To create study material, call generate_quiz, generate_flashcards or write_study_guide. They read the source documents themselves, so pass ids and a topic rather than text. Do not search first unless you need to work out which documents are relevant.
|
- To create study material, call generate_quiz, generate_flashcards or write_study_guide. They read the source documents themselves, so pass ids and a topic rather than text. Do not search first unless you need to work out which documents are relevant.
|
||||||
- Everything you create is a DRAFT shown as a preview card. Never say it was saved or added; tell the user to review and save it.
|
- Everything you create is a DRAFT shown as a preview card. Never say it was saved or added; tell the user to review and save it.
|
||||||
- Deleting, moving and renaming require propose_changes and the user's confirmation. Never claim a change was made before a system note confirms it.
|
- Deleting, moving and renaming require propose_changes and the user's confirmation. Never claim a change was made before a system note confirms it.
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,9 @@ import { Hono } from 'hono';
|
||||||
import { bodyLimit } from 'hono/body-limit';
|
import { bodyLimit } from 'hono/body-limit';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { questionToDraft, validateDraft, type ContentDraft } from '../../shared/content.ts';
|
import { questionToDraft, validateDraft, type ContentDraft } from '../../shared/content.ts';
|
||||||
import { draftsFromValue } from '../../shared/importer.ts';
|
import { draftsFromValue, LLM_INSTRUCTIONS } from '../../shared/importer.ts';
|
||||||
import { badRequest, HttpError, idParam, readBody, type AppContext } from '../http.ts';
|
import { badRequest, HttpError, idParam, readBody, type AppContext } from '../http.ts';
|
||||||
import { appSettingsSchema, getAppSettings, setSetting } from '../settings.ts';
|
import { appSettingsSchema, deleteSetting, getAppSettings, getSetting, setSetting } from '../settings.ts';
|
||||||
import { createSnapshot, exportBundle, fullBackupStream, listBackups } from '../services/backup.ts';
|
import { createSnapshot, exportBundle, fullBackupStream, listBackups } from '../services/backup.ts';
|
||||||
import { createClass, createDeck, createFolder, createNote, createQuiz, draftCardToInput, draftQuestionToInput, getClass, getDeck, getQuiz, listCards, listQuestions } from '../services/content.ts';
|
import { createClass, createDeck, createFolder, createNote, createQuiz, draftCardToInput, draftQuestionToInput, getClass, getDeck, getQuiz, listCards, listQuestions } from '../services/content.ts';
|
||||||
import { createTemplate, deleteTemplate, listTemplates, templateInputSchema, updateTemplate } from '../services/templates.ts';
|
import { createTemplate, deleteTemplate, listTemplates, templateInputSchema, updateTemplate } from '../services/templates.ts';
|
||||||
|
|
@ -85,6 +85,24 @@ export function dataRoutes(app: AppContext): Hono {
|
||||||
return c.json({ settings: next });
|
return c.json({ settings: next });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/* ------------------------------ instructions for outside chatbots ------------------------------ */
|
||||||
|
|
||||||
|
r.get('/llm-instructions', (c) =>
|
||||||
|
c.json({
|
||||||
|
quiz: getSetting<string | null>(db, 'llm.quiz', null) ?? LLM_INSTRUCTIONS.quiz,
|
||||||
|
deck: getSetting<string | null>(db, 'llm.deck', null) ?? LLM_INSTRUCTIONS.deck,
|
||||||
|
customized: { quiz: getSetting<string | null>(db, 'llm.quiz', null) !== null, deck: getSetting<string | null>(db, 'llm.deck', null) !== null },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Saves an edited copy; `text: null` goes back to the built-in wording. */
|
||||||
|
r.put('/llm-instructions', async (c) => {
|
||||||
|
const body = await readBody(c, z.object({ kind: z.enum(['quiz', 'deck']), text: z.string().trim().min(20).max(20000).nullable() }));
|
||||||
|
if (body.text === null) deleteSetting(db, `llm.${body.kind}`);
|
||||||
|
else setSetting(db, `llm.${body.kind}`, body.text);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
/* ------------------------------ import ------------------------------ */
|
/* ------------------------------ import ------------------------------ */
|
||||||
|
|
||||||
r.post('/import', bodyLimit({ maxSize: 30 * 1024 * 1024 }), async (c) => {
|
r.post('/import', bodyLimit({ maxSize: 30 * 1024 * 1024 }), async (c) => {
|
||||||
|
|
|
||||||
|
|
@ -559,3 +559,73 @@ export function draftsFromValue(value: unknown): { items: ContentDraft[]; notice
|
||||||
collect(value, items, notices);
|
collect(value, items, notices);
|
||||||
return { items, notices };
|
return { items, notices };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Instructions for writing importable content with an outside chatbot */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export const LLM_INSTRUCTIONS: Record<'quiz' | 'deck', string> = {
|
||||||
|
quiz: `You are writing practice questions that will be imported into a study app.
|
||||||
|
Reply with ONE JSON object and nothing else: no commentary and no Markdown code fence.
|
||||||
|
|
||||||
|
Use exactly this shape:
|
||||||
|
{
|
||||||
|
"kind": "quiz",
|
||||||
|
"title": "Short title",
|
||||||
|
"description": "One sentence about what this covers",
|
||||||
|
"questions": [
|
||||||
|
{
|
||||||
|
"type": "single",
|
||||||
|
"stem": "The question",
|
||||||
|
"options": [
|
||||||
|
{ "text": "Answer choice", "correct": true, "why": "Why this choice is right or wrong" }
|
||||||
|
],
|
||||||
|
"rationale": "Teaching explanation of the correct answer",
|
||||||
|
"topic": "Short topic label",
|
||||||
|
"difficulty": "medium"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
- "type" is "single" (multiple choice) or "multi" (select all that apply).
|
||||||
|
- "single" questions have exactly 4 options and exactly one with "correct": true.
|
||||||
|
- "multi" questions have 5 or 6 options, 2 to 5 of them correct, and the stem ends with "Select all that apply."
|
||||||
|
- Write NCLEX-style questions that test clinical judgment: a short client scenario, one clear question, priority wording where it fits (first, best, most important), and distractors that are plausible but wrong for a specific reason. Never use "all of the above" or "none of the above".
|
||||||
|
- Every option needs a one-sentence "why". The "rationale" explains the principle behind the correct answer.
|
||||||
|
- "topic" is a short label. Reuse the same label for related questions and keep the number of different topics small.
|
||||||
|
- "difficulty" is "easy", "medium" or "hard".
|
||||||
|
- Markdown is allowed inside strings (bold, lists, tables). Write line breaks inside strings as \\n.
|
||||||
|
- The output must be valid JSON: double quotes around every key and string, no trailing commas.
|
||||||
|
- Base everything on the material below. Do not add facts that are not in it.
|
||||||
|
|
||||||
|
Write 20 questions.
|
||||||
|
|
||||||
|
Material:
|
||||||
|
[paste your notes or lecture content here]`,
|
||||||
|
deck: `You are writing flashcards that will be imported into a study app.
|
||||||
|
Reply with ONE JSON object and nothing else: no commentary and no Markdown code fence.
|
||||||
|
|
||||||
|
Use exactly this shape:
|
||||||
|
{
|
||||||
|
"kind": "deck",
|
||||||
|
"title": "Short title",
|
||||||
|
"description": "One sentence about what this covers",
|
||||||
|
"cards": [
|
||||||
|
{ "front": "Term or question", "back": "Answer", "hint": "Optional memory aid", "tags": ["topic"] }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
- One fact or idea per card. Fronts are specific questions or terms; backs are short.
|
||||||
|
- For medications, put the generic name on the front and use a short Markdown list on the back: class, action, key adverse effects, nursing considerations.
|
||||||
|
- "hint" is optional. Leave it out or use "" when there is no good memory aid.
|
||||||
|
- Markdown is allowed inside strings (bold, lists, tables). Write line breaks inside strings as \\n.
|
||||||
|
- The output must be valid JSON: double quotes around every key and string, no trailing commas.
|
||||||
|
- Base everything on the material below. Do not add facts that are not in it.
|
||||||
|
|
||||||
|
Write 30 cards covering the most testable facts.
|
||||||
|
|
||||||
|
Material:
|
||||||
|
[paste your notes or lecture content here]`,
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -540,6 +540,8 @@ export function Shell() {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { open: assistantOpen, seed } = useAssistantState();
|
const { open: assistantOpen, seed } = useAssistantState();
|
||||||
const onAssistantPage = location.pathname.startsWith('/assistant');
|
const onAssistantPage = location.pathname.startsWith('/assistant');
|
||||||
|
// Study screens lay themselves out edge to edge and bring their own header and footer.
|
||||||
|
const immersive = location.pathname === '/review' || /^\/decks\/[^/]+\/cram$/.test(location.pathname);
|
||||||
|
|
||||||
useHotkeys({
|
useHotkeys({
|
||||||
'mod+k': (e) => {
|
'mod+k': (e) => {
|
||||||
|
|
@ -578,8 +580,8 @@ export function Shell() {
|
||||||
</a>
|
</a>
|
||||||
<Sidebar onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
|
<Sidebar onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
|
||||||
<div className="flex min-w-0 flex-1 flex-col">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
<MobileNav onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
|
{!immersive && <MobileNav onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />}
|
||||||
<main id="main" tabIndex={-1} className="mx-auto w-full max-w-[1080px] flex-1 px-4 pt-6 pb-28 outline-none sm:px-8 lg:pt-10 lg:pb-16">
|
<main id="main" tabIndex={-1} className={cx('w-full flex-1 outline-none', !immersive && 'mx-auto max-w-[1080px] px-4 pt-6 pb-28 sm:px-8 lg:pt-10 lg:pb-16')}>
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -597,7 +599,7 @@ export function Shell() {
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</aside>
|
</aside>
|
||||||
)}
|
)}
|
||||||
{!showDrawer && !onAssistantPage && isDesktop && (
|
{!showDrawer && !onAssistantPage && !immersive && isDesktop && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => assistant.open()}
|
onClick={() => assistant.open()}
|
||||||
|
|
|
||||||
|
|
@ -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 { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
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 { api, errorMessage } from '@/lib/api';
|
||||||
import { useRefresh } from '@/lib/queries';
|
import { useRefresh } from '@/lib/queries';
|
||||||
import type { Draft } from '@/lib/types';
|
import type { Draft } from '@/lib/types';
|
||||||
import { cx, downloadText, plural, useDebounced } from '@/lib/util';
|
import { copyText, cx, downloadText, plural, useDebounced } from '@/lib/util';
|
||||||
import { Badge, Button, Callout, Dialog, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Textarea } from '@/ui';
|
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 KIND_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||||
const DETECTED = { json: 'JSON', 'text-quiz': 'Question blocks', 'text-cards': 'Term and definition list', none: '' };
|
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 }) {
|
export function ImportDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const refresh = useRefresh();
|
const refresh = useRefresh();
|
||||||
|
|
@ -21,6 +126,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
||||||
const [titles, setTitles] = useState<Record<number, string>>({});
|
const [titles, setTitles] = useState<Record<number, string>>({});
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [dragging, setDragging] = useState(false);
|
const [dragging, setDragging] = useState(false);
|
||||||
|
const [instructionsOpen, setInstructionsOpen] = useState(false);
|
||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
const debounced = useDebounced(text, 250);
|
const debounced = useDebounced(text, 250);
|
||||||
|
|
||||||
|
|
@ -108,11 +214,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
||||||
<Menu
|
<Menu
|
||||||
align="start"
|
align="start"
|
||||||
side="top"
|
side="top"
|
||||||
trigger={
|
trigger={<Button variant="ghost">Templates</Button>}
|
||||||
<Button variant="ghost" className="mr-auto">
|
|
||||||
Templates
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<MenuLabel>Insert an example</MenuLabel>
|
<MenuLabel>Insert an example</MenuLabel>
|
||||||
<MenuItem onSelect={() => insertTemplate(QUIZ_JSON_TEMPLATE)}>Quiz (JSON)</MenuItem>
|
<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('quiz-template.json', QUIZ_JSON_TEMPLATE)}>quiz-template.json</MenuItem>
|
||||||
<MenuItem onSelect={() => downloadText('flashcards-template.json', DECK_JSON_TEMPLATE)}>flashcards-template.json</MenuItem>
|
<MenuItem onSelect={() => downloadText('flashcards-template.json', DECK_JSON_TEMPLATE)}>flashcards-template.json</MenuItem>
|
||||||
</Menu>
|
</Menu>
|
||||||
|
<Button variant="ghost" className="mr-auto" icon={<MessageSquareText />} onClick={() => setInstructionsOpen(true)}>
|
||||||
|
AI instructions
|
||||||
|
</Button>
|
||||||
<Button variant="ghost" onClick={onClose}>
|
<Button variant="ghost" onClick={onClose}>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -168,6 +273,8 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<LlmInstructionsDialog open={instructionsOpen} onClose={() => setInstructionsOpen(false)} />
|
||||||
|
|
||||||
{parsed && (
|
{parsed && (
|
||||||
<div className="mt-5 space-y-3" aria-live="polite">
|
<div className="mt-5 space-y-3" aria-live="polite">
|
||||||
{parsed.notices.map((n, i) => (
|
{parsed.notices.map((n, i) => (
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,93 @@
|
||||||
import { ArrowLeft, ArrowRight, Check, Lightbulb, RotateCcw, Shuffle, X } from 'lucide-react';
|
import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
|
||||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||||
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
|
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
|
||||||
import { Markdown } from '@/ui/Markdown';
|
import { Markdown } from '@/ui/Markdown';
|
||||||
import { Badge, Button, IconButton, Kbd, ProgressBar } from '@/ui';
|
import { Button, IconButton, Kbd, ProgressBar } from '@/ui';
|
||||||
import { Ring } from './charts';
|
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 ------------------------------ */
|
/* ------------------------------ the card ------------------------------ */
|
||||||
|
|
||||||
|
const stop = (e: { stopPropagation: () => void }) => e.stopPropagation();
|
||||||
|
|
||||||
export function FlipCard({
|
export function FlipCard({
|
||||||
front,
|
front,
|
||||||
back,
|
back,
|
||||||
|
|
@ -16,6 +97,8 @@ export function FlipCard({
|
||||||
label,
|
label,
|
||||||
cardKey,
|
cardKey,
|
||||||
footer,
|
footer,
|
||||||
|
leaving,
|
||||||
|
burst,
|
||||||
}: {
|
}: {
|
||||||
front: string;
|
front: string;
|
||||||
back: string;
|
back: string;
|
||||||
|
|
@ -25,38 +108,41 @@ export function FlipCard({
|
||||||
label?: ReactNode;
|
label?: ReactNode;
|
||||||
/** Changing this replays the entrance animation and resets the hint. */
|
/** Changing this replays the entrance animation and resets the hint. */
|
||||||
cardKey: string;
|
cardKey: string;
|
||||||
|
/** Extra content under the answer (kept clickable without flipping the card). */
|
||||||
footer?: ReactNode;
|
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);
|
const [showHint, setShowHint] = useState(false);
|
||||||
// Only animate the front when it comes back from the answer, not when a new card arrives.
|
useEffect(() => setShowHint(false), [cardKey]);
|
||||||
const [turned, setTurned] = useState(false);
|
const face = 'flip-face flex min-h-[max(320px,min(60vh,680px))] flex-col rounded-[24px] border border-line bg-surface shadow-2';
|
||||||
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]';
|
|
||||||
// Short answers read best large and centred; long ones as normal text.
|
// 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 (
|
return (
|
||||||
<div key={cardKey} className="w-full animate-in">
|
<div key={cardKey} className={cx('flip-scene relative w-full animate-in', leaving === 'left' && 'swipe-left', leaving === 'right' && 'swipe-right')}>
|
||||||
<div className="flip-inner" data-flipped={flipped} data-turned={turned}>
|
{/* The whole card is the flip target, on both sides. Space, Enter and the arrow keys do the same. */}
|
||||||
<div className={cx(face, 'flip-front')}>
|
<div
|
||||||
<button type="button" onClick={onFlip} aria-label="Show answer" className="flex flex-1 cursor-pointer flex-col rounded-[22px] text-left">
|
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"
|
||||||
<div className="flex items-center justify-between px-5 pt-4">
|
data-flipped={flipped}
|
||||||
<span className="eyebrow">{label ?? 'Front'}</span>
|
role="button"
|
||||||
<span className="text-xs text-ink-3">Tap to flip</span>
|
tabIndex={0}
|
||||||
</div>
|
aria-label={flipped ? 'Flashcard, answer side. Activate to show the question.' : 'Flashcard, question side. Activate to show the answer.'}
|
||||||
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10">
|
onClick={onFlip}
|
||||||
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
|
>
|
||||||
{front}
|
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
|
||||||
</Markdown>
|
<div className="flex items-center justify-between px-6 pt-5">
|
||||||
</div>
|
<span className="eyebrow">{label ?? 'Question'}</span>
|
||||||
</button>
|
<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 && (
|
{hint && (
|
||||||
<div className="border-t border-line px-5 py-3">
|
<div className="border-t border-line px-6 py-3" onClick={stop}>
|
||||||
{showHint ? (
|
{showHint ? (
|
||||||
<div className="flex items-start gap-2 text-sm text-ink-2">
|
<div className="flex items-start gap-2 text-sm text-ink-2">
|
||||||
<Lightbulb className="mt-0.5 size-4 shrink-0 text-warn" />
|
<Lightbulb className="mt-0.5 size-4 shrink-0 text-warn" />
|
||||||
|
|
@ -70,27 +156,32 @@ export function FlipCard({
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className={cx(face, 'flip-back')}>
|
<div className={cx(face, 'flip-back border-accent/30')} inert={flipped ? undefined : true}>
|
||||||
<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">
|
<div className="flex items-center justify-between gap-4 px-6 pt-5">
|
||||||
<span className="eyebrow">Back</span>
|
<span className="eyebrow text-accent">Answer</span>
|
||||||
<span className="max-w-[70%] truncate text-xs text-ink-3">{front.replace(/[#*_`>]/g, '').slice(0, 80)}</span>
|
<span className="max-w-[70%] truncate text-xs text-ink-3">{front.replace(/[#*_`>]/g, '').slice(0, 90)}</span>
|
||||||
</button>
|
</div>
|
||||||
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10" aria-live="polite">
|
<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))}>
|
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(back))}>
|
||||||
{back}
|
{back}
|
||||||
</Markdown>
|
</Markdown>
|
||||||
</div>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
|
{burst && <StreakBurst key={burst.id} streak={burst.streak} tier={burst.tier} />}
|
||||||
</div>
|
</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 (
|
return (
|
||||||
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
|
<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}>
|
<IconButton label={exitLabel} onClick={onExit}>
|
||||||
<X />
|
<X />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
|
|
@ -100,11 +191,38 @@ export function StudyTopBar({ title, subtitle, onExit, right, progress, exitLabe
|
||||||
</div>
|
</div>
|
||||||
{right}
|
{right}
|
||||||
</div>
|
</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>
|
</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 ------------------------------ */
|
/* ------------------------------ browse / cram ------------------------------ */
|
||||||
|
|
||||||
export interface CramState {
|
export interface CramState {
|
||||||
|
|
@ -168,39 +286,60 @@ export function CramSession({
|
||||||
renderExtra?: (card: CramCard) => ReactNode;
|
renderExtra?: (card: CramCard) => ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const [flipped, setFlipped] = useState(false);
|
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 byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]);
|
||||||
const total = state.order.length;
|
const total = state.order.length;
|
||||||
const done = state.index >= total;
|
const done = state.index >= total;
|
||||||
const card = done ? undefined : byId.get(state.order[state.index]);
|
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) => {
|
const grade = (known: boolean) => {
|
||||||
if (!card) return;
|
if (!card || busy || !seenAnswer) return;
|
||||||
|
setLeaving(known ? 'right' : 'left');
|
||||||
|
record(known);
|
||||||
onGrade?.(card.id, known);
|
onGrade?.(card.id, known);
|
||||||
onState({
|
const next: CramState = {
|
||||||
...state,
|
...state,
|
||||||
index: state.index + 1,
|
index: state.index + 1,
|
||||||
known: known ? [...state.known.filter((x) => x !== card.id), card.id] : state.known.filter((x) => x !== card.id),
|
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],
|
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 studyUnknown = () => {
|
||||||
const pool = cards.filter((c) => state.unknown.includes(c.id));
|
reset();
|
||||||
onState({ ...freshCramState(pool, true, state.round + 1) });
|
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
|
||||||
};
|
};
|
||||||
|
|
||||||
useHotkeys({
|
useHotkeys({
|
||||||
space: (e) => {
|
space: (e) => (e.preventDefault(), flip()),
|
||||||
e.preventDefault();
|
Enter: flip,
|
||||||
if (!done) setFlipped((f) => !f);
|
ArrowUp: (e) => (e.preventDefault(), flip()),
|
||||||
},
|
ArrowDown: (e) => (e.preventDefault(), flip()),
|
||||||
Enter: () => !done && setFlipped((f) => !f),
|
ArrowRight: () => grade(true),
|
||||||
ArrowRight: () => move(1),
|
ArrowLeft: () => grade(false),
|
||||||
ArrowLeft: () => move(-1),
|
'1': () => grade(false),
|
||||||
'1': () => flipped && grade(false),
|
'2': () => grade(true),
|
||||||
'2': () => flipped && grade(true),
|
Backspace: () => move(-1),
|
||||||
|
s: () => move(1),
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -211,8 +350,10 @@ export function CramSession({
|
||||||
onExit={onExit}
|
onExit={onExit}
|
||||||
exitLabel={exitLabel}
|
exitLabel={exitLabel}
|
||||||
progress={total ? Math.min(1, state.index / total) : 0}
|
progress={total ? Math.min(1, state.index / total) : 0}
|
||||||
|
hot={hot}
|
||||||
right={
|
right={
|
||||||
<>
|
<>
|
||||||
|
<StreakChip streak={streak} />
|
||||||
<span className="num text-[13px] font-medium text-ink-2">
|
<span className="num text-[13px] font-medium text-ink-2">
|
||||||
{Math.min(state.index + 1, total)}/{total}
|
{Math.min(state.index + 1, total)}/{total}
|
||||||
</span>
|
</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 ? (
|
{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">
|
<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">
|
<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>
|
<span className="display num text-[28px]">{state.known.length}</span>
|
||||||
|
|
@ -249,49 +390,41 @@ export function CramSession({
|
||||||
</div>
|
</div>
|
||||||
</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} />
|
||||||
<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>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
{!done && card && (
|
{!done && card && (
|
||||||
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
|
<StudyFooter>
|
||||||
<div className="mx-auto flex h-[76px] max-w-2xl items-center gap-2 px-3 sm:px-5">
|
<div className="flex items-center gap-2">
|
||||||
<IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0}>
|
<IconButton label="Previous card (Backspace)" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
|
||||||
<ArrowLeft />
|
<ArrowLeft />
|
||||||
</IconButton>
|
</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
|
Still learning
|
||||||
<span className="hidden sm:inline">
|
|
||||||
<Kbd>1</Kbd>
|
|
||||||
</span>
|
|
||||||
</Button>
|
</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
|
Know it
|
||||||
<span className="hidden sm:inline">
|
|
||||||
<Kbd>2</Kbd>
|
|
||||||
</span>
|
|
||||||
</Button>
|
</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
|
Show answer
|
||||||
<span className="hidden sm:inline">
|
|
||||||
<Kbd>Space</Kbd>
|
|
||||||
</span>
|
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<IconButton label="Skip card" onClick={() => move(1)}>
|
<IconButton label="Skip card (S)" onClick={() => move(1)} disabled={busy}>
|
||||||
<ArrowRight />
|
<SkipForward />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
<KeyHints
|
||||||
|
items={[
|
||||||
|
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
|
||||||
|
[<Kbd>←</Kbd>, 'still learning'],
|
||||||
|
[<Kbd>→</Kbd>, 'know it'],
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</StudyFooter>
|
||||||
)}
|
)}
|
||||||
</div>
|
</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 full = isFullyCorrect(score);
|
||||||
const partial = !full && score > 0;
|
const partial = !full && score > 0;
|
||||||
return (
|
return (
|
||||||
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')} role="status">
|
<div role="status">
|
||||||
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
|
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')}>
|
||||||
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
|
{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>
|
</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 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 flagged = p.flags.includes(question.id);
|
||||||
const isLast = index === total - 1;
|
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;
|
const remaining = p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
|
||||||
|
|
||||||
// Session clock: pauses while the tab is hidden.
|
// 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="truncate text-sm font-semibold">{p.title}</div>
|
||||||
<div className="text-xs text-ink-3">{p.mode === 'exam' ? 'Exam' : 'Practice'}</div>
|
<div className="text-xs text-ink-3">{p.mode === 'exam' ? 'Exam' : 'Practice'}</div>
|
||||||
</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'}>
|
<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" />
|
<Clock className="size-3.5" />
|
||||||
{formatDuration(remaining ?? elapsed)}
|
{formatDuration(remaining ?? elapsed)}
|
||||||
|
|
@ -233,7 +274,7 @@ export function QuizRunner(p: RunnerProps) {
|
||||||
|
|
||||||
{checked && (
|
{checked && (
|
||||||
<div className="mt-5 animate-in space-y-4">
|
<div className="mt-5 animate-in space-y-4">
|
||||||
<Verdict score={score} />
|
<Verdict score={score} detail={creditDetail(question, selected, p.sataScoring)} />
|
||||||
{question.rationale && (
|
{question.rationale && (
|
||||||
<div className="rounded-[14px] border border-line bg-surface p-4">
|
<div className="rounded-[14px] border border-line bg-surface p-4">
|
||||||
<div className="eyebrow mb-1.5">Rationale</div>
|
<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>
|
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
|
||||||
<h1 className="display text-[30px]">{headline}</h1>
|
<h1 className="display text-[30px]">{headline}</h1>
|
||||||
<p className="mt-1.5 text-[15px] text-ink-2">
|
<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)}` : ''}
|
{p.elapsedSec > 0 ? ` in ${formatMinutes(p.elapsedSec)}` : ''}
|
||||||
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
|
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
|
||||||
</p>
|
</p>
|
||||||
|
|
@ -490,6 +531,7 @@ export function QuizResults(p: ResultsProps) {
|
||||||
{r.q.stem}
|
{r.q.stem}
|
||||||
</Markdown>
|
</Markdown>
|
||||||
<OptionList question={r.q} selected={r.selected} revealed />
|
<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 && (
|
{r.q.rationale && (
|
||||||
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
|
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
|
||||||
<div className="eyebrow mb-1">Rationale</div>
|
<div className="eyebrow mb-1">Rationale</div>
|
||||||
|
|
|
||||||
|
|
@ -114,15 +114,11 @@ const router = createBrowserRouter([
|
||||||
// Public share links: no login, no app chrome.
|
// Public share links: no login, no app chrome.
|
||||||
{ path: '/s/:token', element: page(<SharedPage />), errorElement: <RouteError /> },
|
{ path: '/s/:token', element: page(<SharedPage />), errorElement: <RouteError /> },
|
||||||
{ path: '/s/:token/:kind/:itemId', element: page(<SharedPage />), errorElement: <RouteError /> },
|
{ path: '/s/:token/:kind/:itemId', element: page(<SharedPage />), errorElement: <RouteError /> },
|
||||||
// Focus mode: study sessions take the whole screen.
|
// Focus mode: quiz sessions take the whole screen.
|
||||||
{
|
{
|
||||||
element: <Private />,
|
element: <Private />,
|
||||||
errorElement: <RouteError />,
|
errorElement: <RouteError />,
|
||||||
children: [
|
children: [{ path: '/session/:attemptId', element: <SessionPage /> }],
|
||||||
{ path: '/session/:attemptId', element: <SessionPage /> },
|
|
||||||
{ path: '/review', element: <ReviewPage /> },
|
|
||||||
{ path: '/decks/:deckId/cram', element: <CramPage /> },
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
element: <ShellRoute />,
|
element: <ShellRoute />,
|
||||||
|
|
@ -132,6 +128,9 @@ const router = createBrowserRouter([
|
||||||
{ path: '/classes/:classId', element: page(<ClassPage />) },
|
{ path: '/classes/:classId', element: page(<ClassPage />) },
|
||||||
{ path: '/quizzes/:quizId', element: page(<QuizPage />) },
|
{ path: '/quizzes/:quizId', element: page(<QuizPage />) },
|
||||||
{ path: '/decks/:deckId', element: page(<DeckPage />) },
|
{ path: '/decks/:deckId', element: page(<DeckPage />) },
|
||||||
|
// Flashcard study keeps the sidebar on desktop and takes the whole screen on phones.
|
||||||
|
{ path: '/review', element: page(<ReviewPage />) },
|
||||||
|
{ path: '/decks/:deckId/cram', element: page(<CramPage />) },
|
||||||
{ path: '/documents/:docId', element: page(<DocumentPage />) },
|
{ path: '/documents/:docId', element: page(<DocumentPage />) },
|
||||||
{ path: '/notes/:noteId', element: page(<NotePage />) },
|
{ path: '/notes/:noteId', element: page(<NotePage />) },
|
||||||
{ path: '/drafts/:draftId', element: page(<DraftPage />) },
|
{ path: '/drafts/:draftId', element: page(<DraftPage />) },
|
||||||
|
|
|
||||||
|
|
@ -377,6 +377,31 @@ export default function ClassPage() {
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Inside each section, items are grouped under a subheading per type.
|
||||||
|
const KIND_ORDER = ['quiz', 'deck', 'document', 'note'] as const;
|
||||||
|
const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', document: 'Documents', note: 'Notes' } as const;
|
||||||
|
const KIND_HEADING_ICON = { quiz: <BookOpen />, deck: <Layers />, document: <FileText />, note: <NotebookPen /> } as const;
|
||||||
|
const section = (items: Item[]) => {
|
||||||
|
if (filter !== 'all') return <ul className="card divide-y divide-line overflow-hidden">{items.map(row)}</ul>;
|
||||||
|
return (
|
||||||
|
<div className="card overflow-hidden">
|
||||||
|
{KIND_ORDER.filter((k) => items.some((i) => i.kind === k)).map((k, n) => {
|
||||||
|
const list = items.filter((i) => i.kind === k);
|
||||||
|
return (
|
||||||
|
<section key={k} aria-label={KIND_HEADING[k]}>
|
||||||
|
<h3 className={cx('eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5', n > 0 && 'border-t')}>
|
||||||
|
{KIND_HEADING_ICON[k]}
|
||||||
|
{KIND_HEADING[k]}
|
||||||
|
<span className="num font-normal">{list.length}</span>
|
||||||
|
</h3>
|
||||||
|
<ul className="divide-y divide-line">{list.map(row)}</ul>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const loose = visible.filter((i) => !i.folderId || !data.folders.some((f) => f.id === i.folderId));
|
const loose = visible.filter((i) => !i.folderId || !data.folders.some((f) => f.id === i.folderId));
|
||||||
const searching = query.trim().length > 0 || filter !== 'all';
|
const searching = query.trim().length > 0 || filter !== 'all';
|
||||||
const isEmpty = data.items.length === 0 && uploads.length === 0;
|
const isEmpty = data.items.length === 0 && uploads.length === 0;
|
||||||
|
|
@ -593,7 +618,7 @@ export default function ClassPage() {
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{loose.length > 0 && <ul className="card divide-y divide-line overflow-hidden">{loose.map(row)}</ul>}
|
{loose.length > 0 && section(loose)}
|
||||||
{data.folders.map((f) => {
|
{data.folders.map((f) => {
|
||||||
const items = visible.filter((i) => i.folderId === f.id);
|
const items = visible.filter((i) => i.folderId === f.id);
|
||||||
if (items.length === 0 && searching) return null;
|
if (items.length === 0 && searching) return null;
|
||||||
|
|
@ -640,7 +665,7 @@ export default function ClassPage() {
|
||||||
</div>
|
</div>
|
||||||
{!isCollapsed &&
|
{!isCollapsed &&
|
||||||
(items.length > 0 ? (
|
(items.length > 0 ? (
|
||||||
<ul className="card divide-y divide-line overflow-hidden">{items.map(row)}</ul>
|
section(items)
|
||||||
) : (
|
) : (
|
||||||
<div className="rounded-[14px] border border-dashed border-line-strong px-4 py-4 text-[13px] text-ink-3">Empty. Use "Move" on any item to put it here.</div>
|
<div className="rounded-[14px] border border-dashed border-line-strong px-4 py-4 text-[13px] text-ink-3">Empty. Use "Move" on any item to put it here.</div>
|
||||||
))}
|
))}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { useNavigate, useSearchParams } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { CardEditor } from '@/features/editors';
|
import { CardEditor } from '@/features/editors';
|
||||||
import { Explain } from '@/features/Explain';
|
import { Explain } from '@/features/Explain';
|
||||||
import { FlipCard, StudyTopBar } from '@/features/flashcards';
|
import { FlipCard, KeyHints, StreakChip, StudyFooter, StudyTopBar, useStreak } from '@/features/flashcards';
|
||||||
import { api, errorMessage } from '@/lib/api';
|
import { api, errorMessage } from '@/lib/api';
|
||||||
import { useAiStatus, useRefresh } from '@/lib/queries';
|
import { useAiStatus, useRefresh } from '@/lib/queries';
|
||||||
import type { DueCounts, QueueCard } from '@/lib/types';
|
import type { DueCounts, QueueCard } from '@/lib/types';
|
||||||
|
|
@ -46,9 +46,12 @@ export default function ReviewPage() {
|
||||||
|
|
||||||
const [queue, setQueue] = useState<QueueCard[] | null>(null);
|
const [queue, setQueue] = useState<QueueCard[] | null>(null);
|
||||||
const [flipped, setFlipped] = useState(false);
|
const [flipped, setFlipped] = useState(false);
|
||||||
|
const [seenAnswer, setSeenAnswer] = useState(false);
|
||||||
|
const [leaving, setLeaving] = useState<'left' | 'right' | null>(null);
|
||||||
|
const { streak, burst, record, reset: resetStreak, hot } = useStreak();
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [done, setDone] = useState({ reviewed: 0, again: 0 });
|
const [done, setDone] = useState({ reviewed: 0, again: 0 });
|
||||||
const [last, setLast] = useState<{ cardId: string; snapshot: QueueCard[]; wasAgain: boolean } | null>(null);
|
const [last, setLast] = useState<{ cardId: string; snapshot: QueueCard[]; wasAgain: boolean; streakBefore: number } | null>(null);
|
||||||
const [editing, setEditing] = useState<QueueCard | null>(null);
|
const [editing, setEditing] = useState<QueueCard | null>(null);
|
||||||
const [draft, setDraft] = useState({ front: '', back: '', hint: '', tags: [] as string[] });
|
const [draft, setDraft] = useState({ front: '', back: '', hint: '', tags: [] as string[] });
|
||||||
const startedAt = useRef(Date.now());
|
const startedAt = useRef(Date.now());
|
||||||
|
|
@ -63,15 +66,29 @@ export default function ReviewPage() {
|
||||||
}, [query.data, queue, deckId, classId]);
|
}, [query.data, queue, deckId, classId]);
|
||||||
|
|
||||||
const current = queue?.[0];
|
const current = queue?.[0];
|
||||||
useEffect(() => setFlipped(false), [current?.card.id]);
|
useEffect(() => {
|
||||||
|
setFlipped(false);
|
||||||
|
setSeenAnswer(false);
|
||||||
|
setLeaving(null);
|
||||||
|
}, [current?.card.id, current?.card.reps]);
|
||||||
|
|
||||||
|
const flip = useCallback(() => {
|
||||||
|
if (!current || busy) return;
|
||||||
|
setFlipped((f) => !f);
|
||||||
|
setSeenAnswer(true);
|
||||||
|
}, [current, busy]);
|
||||||
|
|
||||||
const rate = useCallback(
|
const rate = useCallback(
|
||||||
async (rating: 1 | 2 | 3 | 4) => {
|
async (rating: 1 | 2 | 3 | 4) => {
|
||||||
if (!current || !queue || busy) return;
|
if (!current || !queue || busy || !seenAnswer) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
const snapshot = queue;
|
const snapshot = queue;
|
||||||
|
const streakBefore = streak;
|
||||||
|
// The card swipes away while the new schedule is being saved.
|
||||||
|
setLeaving(rating === 1 ? 'left' : 'right');
|
||||||
try {
|
try {
|
||||||
const res = await api.post<{ result: QueueCard }>('/api/review/answer', { cardId: current.card.id, rating });
|
const [res] = await Promise.all([api.post<{ result: QueueCard }>('/api/review/answer', { cardId: current.card.id, rating }), new Promise((r) => setTimeout(r, 230))]);
|
||||||
|
record(rating > 1);
|
||||||
const updated = res.result;
|
const updated = res.result;
|
||||||
const rest = queue.slice(1);
|
const rest = queue.slice(1);
|
||||||
const dueSoon = (updated.card.state === 1 || updated.card.state === 3) && (updated.card.due ?? 0) - Date.now() < LEARN_AHEAD_MS;
|
const dueSoon = (updated.card.state === 1 || updated.card.state === 3) && (updated.card.due ?? 0) - Date.now() < LEARN_AHEAD_MS;
|
||||||
|
|
@ -82,19 +99,20 @@ export default function ReviewPage() {
|
||||||
}
|
}
|
||||||
setQueue(rest);
|
setQueue(rest);
|
||||||
setDone((d) => ({ reviewed: d.reviewed + 1, again: d.again + (rating === 1 ? 1 : 0) }));
|
setDone((d) => ({ reviewed: d.reviewed + 1, again: d.again + (rating === 1 ? 1 : 0) }));
|
||||||
setLast({ cardId: current.card.id, snapshot, wasAgain: rating === 1 });
|
setLast({ cardId: current.card.id, snapshot, wasAgain: rating === 1, streakBefore });
|
||||||
if (rest.length === 0) {
|
if (rest.length === 0) {
|
||||||
// The first load is capped; fetch anything that is still due.
|
// The first load is capped; fetch anything that is still due.
|
||||||
const more = await api.get<QueueResponse>(`/api/review/queue?${scope}`).catch(() => null);
|
const more = await api.get<QueueResponse>(`/api/review/queue?${scope}`).catch(() => null);
|
||||||
if (more && more.cards.length > 0) setQueue(more.cards);
|
if (more && more.cards.length > 0) setQueue(more.cards);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
setLeaving(null);
|
||||||
toast.error(errorMessage(e));
|
toast.error(errorMessage(e));
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[current, queue, busy, scope],
|
[current, queue, busy, scope, seenAnswer, streak, record],
|
||||||
);
|
);
|
||||||
|
|
||||||
const undo = useCallback(async () => {
|
const undo = useCallback(async () => {
|
||||||
|
|
@ -104,13 +122,14 @@ export default function ReviewPage() {
|
||||||
const res = await api.post<{ result: QueueCard }>('/api/review/undo', { cardId: last.cardId });
|
const res = await api.post<{ result: QueueCard }>('/api/review/undo', { cardId: last.cardId });
|
||||||
setQueue(last.snapshot.map((c) => (c.card.id === last.cardId ? res.result : c)));
|
setQueue(last.snapshot.map((c) => (c.card.id === last.cardId ? res.result : c)));
|
||||||
setDone((d) => ({ reviewed: Math.max(0, d.reviewed - 1), again: Math.max(0, d.again - (last.wasAgain ? 1 : 0)) }));
|
setDone((d) => ({ reviewed: Math.max(0, d.reviewed - 1), again: Math.max(0, d.again - (last.wasAgain ? 1 : 0)) }));
|
||||||
|
resetStreak(last.streakBefore);
|
||||||
setLast(null);
|
setLast(null);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error(errorMessage(e));
|
toast.error(errorMessage(e));
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
}, [last, busy]);
|
}, [last, busy, resetStreak]);
|
||||||
|
|
||||||
const suspend = async () => {
|
const suspend = async () => {
|
||||||
if (!current || !queue) return;
|
if (!current || !queue) return;
|
||||||
|
|
@ -136,19 +155,17 @@ export default function ReviewPage() {
|
||||||
};
|
};
|
||||||
|
|
||||||
useHotkeys({
|
useHotkeys({
|
||||||
space: (e) => {
|
space: (e) => (e.preventDefault(), flip()),
|
||||||
e.preventDefault();
|
Enter: flip,
|
||||||
if (current) setFlipped((f) => !f);
|
ArrowUp: (e) => (e.preventDefault(), flip()),
|
||||||
},
|
ArrowDown: (e) => (e.preventDefault(), flip()),
|
||||||
Enter: () => {
|
// Left = missed it, right = got it. The number keys give the finer four-way rating.
|
||||||
if (!current) return;
|
ArrowLeft: () => void rate(1),
|
||||||
if (flipped) void rate(3);
|
ArrowRight: () => void rate(3),
|
||||||
else setFlipped(true);
|
'1': () => void rate(1),
|
||||||
},
|
'2': () => void rate(2),
|
||||||
'1': () => flipped && void rate(1),
|
'3': () => void rate(3),
|
||||||
'2': () => flipped && void rate(2),
|
'4': () => void rate(4),
|
||||||
'3': () => flipped && void rate(3),
|
|
||||||
'4': () => flipped && void rate(4),
|
|
||||||
u: () => void undo(),
|
u: () => void undo(),
|
||||||
'mod+z': (e) => {
|
'mod+z': (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
@ -180,8 +197,10 @@ export default function ReviewPage() {
|
||||||
subtitle={scopeTitle.current}
|
subtitle={scopeTitle.current}
|
||||||
onExit={exit}
|
onExit={exit}
|
||||||
progress={totalPlanned ? done.reviewed / totalPlanned : 1}
|
progress={totalPlanned ? done.reviewed / totalPlanned : 1}
|
||||||
|
hot={hot}
|
||||||
right={
|
right={
|
||||||
<>
|
<>
|
||||||
|
<StreakChip streak={streak} />
|
||||||
<div className="hidden items-center gap-1 sm:flex" aria-label="Cards remaining by type">
|
<div className="hidden items-center gap-1 sm:flex" aria-label="Cards remaining by type">
|
||||||
<Badge tone="accent">{counts.fresh} new</Badge>
|
<Badge tone="accent">{counts.fresh} new</Badge>
|
||||||
<Badge tone="warn">{counts.learning} learning</Badge>
|
<Badge tone="warn">{counts.learning} learning</Badge>
|
||||||
|
|
@ -218,9 +237,9 @@ export default function ReviewPage() {
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<main className="mx-auto flex w-full max-w-2xl flex-1 flex-col px-4 pt-6 pb-40 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">
|
||||||
{!current ? (
|
{!current ? (
|
||||||
<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">
|
||||||
<CircleCheck className="mx-auto mb-3 size-12 text-good" strokeWidth={1.6} />
|
<CircleCheck className="mx-auto mb-3 size-12 text-good" strokeWidth={1.6} />
|
||||||
<h1 className="display text-[30px]">{done.reviewed > 0 ? 'Review complete' : 'Nothing due right now'}</h1>
|
<h1 className="display text-[30px]">{done.reviewed > 0 ? 'Review complete' : 'Nothing due right now'}</h1>
|
||||||
<p className="mx-auto mt-2 max-w-sm text-[15px] text-ink-2">
|
<p className="mx-auto mt-2 max-w-sm text-[15px] text-ink-2">
|
||||||
|
|
@ -254,7 +273,9 @@ export default function ReviewPage() {
|
||||||
back={current.card.back}
|
back={current.card.back}
|
||||||
hint={current.card.hint}
|
hint={current.card.hint}
|
||||||
flipped={flipped}
|
flipped={flipped}
|
||||||
onFlip={() => setFlipped((f) => !f)}
|
onFlip={flip}
|
||||||
|
leaving={leaving}
|
||||||
|
burst={burst}
|
||||||
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
|
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|
@ -262,47 +283,38 @@ export default function ReviewPage() {
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{current && (
|
{current && (
|
||||||
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
|
<StudyFooter>
|
||||||
<div className="mx-auto max-w-2xl px-3 py-3 sm:px-5">
|
{seenAnswer ? (
|
||||||
{flipped ? (
|
<div className="grid grid-cols-4 gap-2">
|
||||||
<div className="grid grid-cols-4 gap-2">
|
{current.previews.map((p) => (
|
||||||
{current.previews.map((p) => (
|
<button
|
||||||
<button
|
key={p.rating}
|
||||||
key={p.rating}
|
type="button"
|
||||||
type="button"
|
disabled={busy}
|
||||||
disabled={busy}
|
onClick={() => rate(p.rating)}
|
||||||
onClick={() => rate(p.rating)}
|
className={cx('flex h-[60px] flex-col items-center justify-center rounded-[13px] border bg-surface shadow-1 transition-colors active:scale-[0.98] disabled:opacity-60', RATING_STYLE[p.rating])}
|
||||||
className={cx('flex h-[58px] flex-col items-center justify-center rounded-[13px] border bg-surface shadow-1 transition-colors active:scale-[0.98] disabled:opacity-60', RATING_STYLE[p.rating])}
|
>
|
||||||
>
|
<span className="text-[15px] font-semibold">{p.label}</span>
|
||||||
<span className="text-[15px] font-semibold">{p.label}</span>
|
<span className="num text-[11px] opacity-80">{p.interval}</span>
|
||||||
<span className="num text-[11px] opacity-80">{p.interval}</span>
|
</button>
|
||||||
</button>
|
))}
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Button size="lg" variant="primary" block className="h-[58px]" onClick={() => setFlipped(true)}>
|
|
||||||
Show answer
|
|
||||||
<span className="hidden sm:inline">
|
|
||||||
<Kbd>Space</Kbd>
|
|
||||||
</span>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<div className="mt-2 hidden justify-center gap-4 text-[11px] text-ink-3 sm:flex">
|
|
||||||
<span>
|
|
||||||
<Kbd>1</Kbd>–<Kbd>4</Kbd> rate
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
<Kbd>Enter</Kbd> good
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
<Kbd>U</Kbd> undo
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
<Kbd>E</Kbd> edit
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
) : (
|
||||||
</footer>
|
<Button size="lg" variant="primary" block className="h-[60px]" onClick={flip}>
|
||||||
|
Show answer
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<KeyHints
|
||||||
|
items={[
|
||||||
|
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
|
||||||
|
[<Kbd>←</Kbd>, 'again'],
|
||||||
|
[<Kbd>→</Kbd>, 'good'],
|
||||||
|
[<><Kbd>1</Kbd>–<Kbd>4</Kbd></>, 'rate'],
|
||||||
|
[<Kbd>U</Kbd>, 'undo'],
|
||||||
|
[<Kbd>E</Kbd>, 'edit'],
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</StudyFooter>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Dialog
|
<Dialog
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun } from 'lucide-react';
|
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun, Timer } from 'lucide-react';
|
||||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||||
import { Link, useNavigate, useParams } from 'react-router';
|
import { Link, useNavigate, useParams } from 'react-router';
|
||||||
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
|
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
|
||||||
|
|
@ -9,7 +9,7 @@ import { api, ApiError } from '@/lib/api';
|
||||||
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
|
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
|
||||||
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useTheme } from '@/lib/util';
|
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useTheme } from '@/lib/util';
|
||||||
import { Markdown } from '@/ui/Markdown';
|
import { Markdown } from '@/ui/Markdown';
|
||||||
import { Button, EmptyState, IconButton, PageLoading, Switch } from '@/ui';
|
import { Button, EmptyState, IconButton, Input, PageLoading, Switch } from '@/ui';
|
||||||
|
|
||||||
/* ------------------------------ frame ------------------------------ */
|
/* ------------------------------ frame ------------------------------ */
|
||||||
|
|
||||||
|
|
@ -61,9 +61,10 @@ interface QuizState {
|
||||||
index: number;
|
index: number;
|
||||||
elapsed: number;
|
elapsed: number;
|
||||||
done: boolean;
|
done: boolean;
|
||||||
|
timeLimitSec?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, only?: string[]): QuizState {
|
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, timeLimitSec: number | null, only?: string[]): QuizState {
|
||||||
const seed = (Math.random() * 2 ** 32) >>> 0;
|
const seed = (Math.random() * 2 ** 32) >>> 0;
|
||||||
let ids = quiz.questions.map((q) => q.id).filter((id) => !only || only.includes(id));
|
let ids = quiz.questions.map((q) => q.id).filter((id) => !only || only.includes(id));
|
||||||
if (shuffleQ) ids = seededShuffle(ids, seed);
|
if (shuffleQ) ids = seededShuffle(ids, seed);
|
||||||
|
|
@ -72,12 +73,13 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
|
||||||
const optionIds = q.options.map((o) => o.id);
|
const optionIds = q.options.map((o) => o.id);
|
||||||
optionOrder[q.id] = shuffleO ? seededShuffle(optionIds, seed + i + 1) : optionIds;
|
optionOrder[q.id] = shuffleO ? seededShuffle(optionIds, seed + i + 1) : optionIds;
|
||||||
});
|
});
|
||||||
return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false };
|
return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false, timeLimitSec };
|
||||||
}
|
}
|
||||||
|
|
||||||
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
|
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
|
||||||
const [state, setState] = useLocalStorage<QuizState | null>(storageKey, null);
|
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 [prefs, setPrefs] = useLocalStorage('sd.pub.prefs2', { mode: 'practice' as 'practice' | 'exam', shuffleQ: true, shuffleO: true, timed: false, minutes: 0 });
|
||||||
|
const minutes = prefs.minutes > 0 ? prefs.minutes : Math.max(5, Math.round(quiz.questions.length * 1.2));
|
||||||
const [running, setRunning] = useState(false);
|
const [running, setRunning] = useState(false);
|
||||||
|
|
||||||
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
|
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
|
||||||
|
|
@ -95,7 +97,7 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
|
||||||
}, [quiz, state]);
|
}, [quiz, state]);
|
||||||
|
|
||||||
const begin = (only?: string[]) => {
|
const begin = (only?: string[]) => {
|
||||||
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, only));
|
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, prefs.mode === 'exam' && prefs.timed ? minutes * 60 : null, only));
|
||||||
setRunning(true);
|
setRunning(true);
|
||||||
window.scrollTo(0, 0);
|
window.scrollTo(0, 0);
|
||||||
};
|
};
|
||||||
|
|
@ -140,7 +142,7 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
|
||||||
flags={state.flags}
|
flags={state.flags}
|
||||||
index={state.index}
|
index={state.index}
|
||||||
elapsedSec={state.elapsed}
|
elapsedSec={state.elapsed}
|
||||||
timeLimitSec={null}
|
timeLimitSec={state.timeLimitSec ?? null}
|
||||||
sataScoring="partial"
|
sataScoring="partial"
|
||||||
exitLabel="Pause"
|
exitLabel="Pause"
|
||||||
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
|
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
|
||||||
|
|
@ -200,7 +202,20 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
|
||||||
<div className="mt-4 space-y-3.5">
|
<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.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" />
|
<Switch checked={prefs.shuffleO} onChange={(v) => setPrefs((p) => ({ ...p, shuffleO: v }))} label="Shuffle answer choices" />
|
||||||
|
{prefs.mode === 'exam' && (
|
||||||
|
<>
|
||||||
|
<Switch checked={prefs.timed} onChange={(v) => setPrefs((p) => ({ ...p, timed: v }))} label="Time limit" description="The exam submits itself when time runs out." />
|
||||||
|
{prefs.timed && (
|
||||||
|
<label className="flex items-center gap-2 text-sm text-ink-2">
|
||||||
|
<Timer className="size-4 text-ink-3" />
|
||||||
|
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setPrefs((p) => ({ ...p, minutes: Math.max(1, Math.min(600, Math.round(Number(e.target.value)) || 1)) }))} className="w-24" aria-label="Minutes" />
|
||||||
|
minutes
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<p className="mt-4 text-[13px] text-ink-3">Select-all-that-apply questions give partial credit: a point for each correct choice, minus one for each incorrect choice, never below zero.</p>
|
||||||
<Button variant={inProgress ? 'secondary' : 'primary'} size="lg" block className="mt-5" icon={<Play className="fill-current" />} onClick={() => begin()}>
|
<Button variant={inProgress ? 'secondary' : 'primary'} size="lg" block className="mt-5" icon={<Play className="fill-current" />} onClick={() => begin()}>
|
||||||
{inProgress ? 'Start over' : 'Start'}
|
{inProgress ? 'Start over' : 'Start'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -420,44 +420,138 @@
|
||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Flashcard flip. Both faces are stacked in one grid cell so the card keeps the height of
|
/* Flashcard: a real two-sided card that turns over its horizontal axis. Both faces share
|
||||||
the taller side; only the active face is visible, and it swings in when it appears.
|
one grid cell, so the card is always as tall as its taller side. */
|
||||||
(Deliberately not a preserve-3d/backface construction: that breaks in several
|
.flip-scene {
|
||||||
compositing situations, and this keeps the hidden side out of the accessibility tree.) */
|
perspective: 2000px;
|
||||||
.flip-inner {
|
}
|
||||||
|
.flip-card {
|
||||||
display: grid;
|
display: grid;
|
||||||
perspective: 1600px;
|
cursor: pointer;
|
||||||
|
transform-style: preserve-3d;
|
||||||
|
transition: transform 420ms cubic-bezier(0.3, 0.75, 0.25, 1);
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
}
|
||||||
|
.flip-card[data-flipped='true'] {
|
||||||
|
transform: rotateX(180deg);
|
||||||
}
|
}
|
||||||
.flip-face {
|
.flip-face {
|
||||||
grid-area: 1 / 1;
|
grid-area: 1 / 1;
|
||||||
transform-origin: center;
|
backface-visibility: hidden;
|
||||||
will-change: transform;
|
-webkit-backface-visibility: hidden;
|
||||||
}
|
}
|
||||||
.flip-inner[data-flipped='true'] .flip-front,
|
.flip-back {
|
||||||
.flip-inner[data-flipped='false'] .flip-back {
|
transform: rotateX(180deg);
|
||||||
visibility: hidden;
|
|
||||||
}
|
}
|
||||||
.flip-inner[data-flipped='true'] .flip-back {
|
.swipe-left {
|
||||||
animation: sd-flip 340ms cubic-bezier(0.2, 0.8, 0.2, 1);
|
animation: sd-swipe-left 260ms cubic-bezier(0.4, 0, 0.9, 0.6) forwards;
|
||||||
}
|
}
|
||||||
.flip-inner[data-flipped='false'][data-turned='true'] .flip-front {
|
.swipe-right {
|
||||||
animation: sd-flip-back 340ms cubic-bezier(0.2, 0.8, 0.2, 1);
|
animation: sd-swipe-right 260ms cubic-bezier(0.4, 0, 0.9, 0.6) forwards;
|
||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.flip-face {
|
.flip-card {
|
||||||
animation: none !important;
|
transition: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Streak flames. The yellow-to-orange ramp is the same in both themes on purpose. */
|
||||||
|
.streak-bar {
|
||||||
|
background-image: linear-gradient(100deg, #fbbf24, #fb923c 35%, #ea580c 55%, #fb923c 75%, #fbbf24);
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: sd-flame-flow 2.6s linear infinite;
|
||||||
|
box-shadow: 0 0 12px rgb(234 88 12 / 0.5);
|
||||||
|
}
|
||||||
|
.streak-chip {
|
||||||
|
animation: sd-pop 280ms cubic-bezier(0.2, 0.9, 0.3, 1.3);
|
||||||
|
}
|
||||||
|
.streak-chip-hot {
|
||||||
|
color: #451a03;
|
||||||
|
background-image: linear-gradient(100deg, #fbbf24, #ea580c);
|
||||||
|
box-shadow: 0 2px 12px rgb(234 88 12 / 0.4);
|
||||||
|
}
|
||||||
|
.streak-scrim {
|
||||||
|
background: radial-gradient(circle at 50% 46%, color-mix(in srgb, var(--surface) 94%, transparent) 0%, color-mix(in srgb, var(--surface) 78%, transparent) 42%, transparent 76%);
|
||||||
|
animation: sd-streak-scrim var(--streak-ms, 1800ms) ease-out forwards;
|
||||||
|
}
|
||||||
|
.streak-pop {
|
||||||
|
animation: sd-streak-pop var(--streak-ms, 1800ms) cubic-bezier(0.2, 0.9, 0.3, 1.2) forwards;
|
||||||
|
}
|
||||||
|
.streak-flame {
|
||||||
|
animation: sd-flicker 0.9s ease-in-out infinite;
|
||||||
|
transform-origin: 50% 85%;
|
||||||
|
filter: drop-shadow(0 6px 22px rgb(234 88 12 / 0.55));
|
||||||
|
}
|
||||||
|
.streak-heading {
|
||||||
|
background-image: linear-gradient(180deg, #fbbf24, #ea580c);
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
background-clip: text;
|
||||||
|
color: transparent;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes sd-flip {
|
@keyframes sd-swipe-left {
|
||||||
from {
|
to {
|
||||||
transform: rotateY(-88deg);
|
transform: translateX(-70px) rotate(-6deg);
|
||||||
|
opacity: 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@keyframes sd-flip-back {
|
@keyframes sd-swipe-right {
|
||||||
from {
|
to {
|
||||||
transform: rotateY(88deg);
|
transform: translateX(70px) rotate(6deg);
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes sd-flame-flow {
|
||||||
|
to {
|
||||||
|
background-position: -200% 50%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes sd-flicker {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: scale(1) rotate(0);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
transform: scale(1.07) rotate(-2.5deg);
|
||||||
|
}
|
||||||
|
60% {
|
||||||
|
transform: scale(0.96) rotate(2deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes sd-streak-pop {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(26px) scale(0.55);
|
||||||
|
}
|
||||||
|
28% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(-2px) scale(1.1);
|
||||||
|
}
|
||||||
|
40% {
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
78% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-14px) scale(0.96);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes sd-streak-scrim {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
14% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
76% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { memo, type ReactNode } from 'react';
|
import { memo, type ReactNode } from 'react';
|
||||||
import ReactMarkdown, { type Components } from 'react-markdown';
|
import ReactMarkdown, { type Components } from 'react-markdown';
|
||||||
|
import { Link } from 'react-router';
|
||||||
import remarkGfm from 'remark-gfm';
|
import remarkGfm from 'remark-gfm';
|
||||||
import { cx } from '@/lib/util';
|
import { cx } from '@/lib/util';
|
||||||
|
|
||||||
|
|
@ -11,11 +12,16 @@ export interface Citation {
|
||||||
}
|
}
|
||||||
|
|
||||||
const BASE: Components = {
|
const BASE: Components = {
|
||||||
a: ({ href, children }) => (
|
a: ({ href, children }) =>
|
||||||
<a href={href} target={href?.startsWith('/') ? undefined : '_blank'} rel="noreferrer noopener">
|
// Links to pages inside the app (the assistant uses these to point at quizzes, decks and notes)
|
||||||
{children}
|
// navigate without a reload; everything else opens in a new tab.
|
||||||
</a>
|
href && href.startsWith('/') && !href.startsWith('//') && !href.startsWith('/api/') && !href.startsWith('/media/') ? (
|
||||||
),
|
<Link to={href}>{children}</Link>
|
||||||
|
) : (
|
||||||
|
<a href={href} target="_blank" rel="noreferrer noopener">
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
),
|
||||||
table: ({ children }) => (
|
table: ({ children }) => (
|
||||||
<div className="table-wrap">
|
<div className="table-wrap">
|
||||||
<table>{children}</table>
|
<table>{children}</table>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue