Add the V2 web app: design system, shell, study flows, AI, settings, sharing
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
eae109c166
commit
74a98ac1f1
52 changed files with 11976 additions and 1 deletions
36
.env.example
Normal file
36
.env.example
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# Study Desk configuration. Every value is optional.
|
||||
# In Docker, set these as container environment variables instead of using this file.
|
||||
|
||||
# Where the database, uploads and backups live. Default: /data in the container, ./data otherwise.
|
||||
# DATA_DIR=/data
|
||||
|
||||
# Port and bind address.
|
||||
# PORT=3726
|
||||
# HOST=0.0.0.0
|
||||
|
||||
# First-run administrator password. If unset, the first visit shows a setup screen that asks
|
||||
# for the one-time code printed in the log (also written to DATA_DIR/setup-code.txt).
|
||||
# ADMIN_PASSWORD=
|
||||
|
||||
# Forgot the password? Set this, restart once, sign in, then remove it again.
|
||||
# RESET_ADMIN_PASSWORD=
|
||||
|
||||
# Secret used to encrypt AI provider API keys at rest. If unset, a random key is generated and
|
||||
# stored in DATA_DIR/secret.key. Set it explicitly if you want the key kept outside the data folder.
|
||||
# APP_SECRET=
|
||||
|
||||
# Cookie "Secure" flag: auto (default: on whenever the request arrived over HTTPS), true or false.
|
||||
# COOKIE_SECURE=auto
|
||||
|
||||
# Trust X-Forwarded-* headers from a reverse proxy (default true). Set false if the container
|
||||
# is exposed directly to the internet without a proxy.
|
||||
# TRUST_PROXY=true
|
||||
|
||||
# Largest upload accepted, in megabytes.
|
||||
# MAX_UPLOAD_MB=100
|
||||
|
||||
# Number of automatic daily database snapshots to keep.
|
||||
# BACKUP_KEEP=7
|
||||
|
||||
# Timezone used for "today", streaks and due dates until you change it in Settings.
|
||||
# TZ=America/Phoenix
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -15,3 +15,4 @@ coverage/
|
|||
.DS_Store
|
||||
npm-debug.log*
|
||||
.test-data/
|
||||
.claude/
|
||||
|
|
|
|||
14
scripts/build-server.mjs
Normal file
14
scripts/build-server.mjs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
// Bundles the server into one file. Dependencies stay external and are installed in the image.
|
||||
import { build } from 'esbuild';
|
||||
|
||||
await build({
|
||||
entryPoints: ['server/main.ts'],
|
||||
outfile: 'dist/server/main.js',
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
format: 'esm',
|
||||
target: 'node24',
|
||||
packages: 'external',
|
||||
sourcemap: true,
|
||||
logLevel: 'info',
|
||||
});
|
||||
60
scripts/make-icons.mjs
Normal file
60
scripts/make-icons.mjs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
// Renders the PNG app icons (no image library needed): a dark tile with two "cards".
|
||||
import fs from 'node:fs';
|
||||
import zlib from 'node:zlib';
|
||||
|
||||
function png(size, draw) {
|
||||
const px = Buffer.alloc(size * size * 4);
|
||||
draw(px, size);
|
||||
const raw = Buffer.alloc((size * 4 + 1) * size);
|
||||
for (let y = 0; y < size; y++) px.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4);
|
||||
const chunk = (type, data) => {
|
||||
const len = Buffer.alloc(4);
|
||||
len.writeUInt32BE(data.length);
|
||||
const body = Buffer.concat([Buffer.from(type), data]);
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(zlib.crc32(body) >>> 0);
|
||||
return Buffer.concat([len, body, crc]);
|
||||
};
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(size, 0);
|
||||
ihdr.writeUInt32BE(size, 4);
|
||||
ihdr[8] = 8;
|
||||
ihdr[9] = 6;
|
||||
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
const hex = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
|
||||
|
||||
function icon(px, size) {
|
||||
const s = size / 64;
|
||||
const set = (x, y, [r, g, b], a = 1) => {
|
||||
if (x < 0 || y < 0 || x >= size || y >= size) return;
|
||||
const i = (y * size + x) * 4;
|
||||
px[i] = px[i] * (1 - a) + r * a;
|
||||
px[i + 1] = px[i + 1] * (1 - a) + g * a;
|
||||
px[i + 2] = px[i + 2] * (1 - a) + b * a;
|
||||
px[i + 3] = 255;
|
||||
};
|
||||
const rrect = (x0, y0, w, h, r, color, rot = 0, cx = 0, cy = 0, alpha = 1) => {
|
||||
const cos = Math.cos(-rot), sin = Math.sin(-rot);
|
||||
for (let y = 0; y < size; y++)
|
||||
for (let x = 0; x < size; x++) {
|
||||
// rotate the sample point back into the rectangle's frame
|
||||
const dx = x + 0.5 - cx * s, dy = y + 0.5 - cy * s;
|
||||
const lx = (dx * cos - dy * sin) / s + cx, ly = (dx * sin + dy * cos) / s + cy;
|
||||
const qx = Math.max(x0 + r - lx, 0, lx - (x0 + w - r)), qy = Math.max(y0 + r - ly, 0, ly - (y0 + h - r));
|
||||
const d = Math.hypot(qx, qy) - r;
|
||||
const a = Math.max(0, Math.min(1, 0.5 - d * s));
|
||||
if (a > 0 && lx >= x0 - 1 && lx <= x0 + w + 1 && ly >= y0 - 1 && ly <= y0 + h + 1) set(x, y, color, a * alpha);
|
||||
}
|
||||
};
|
||||
rrect(0, 0, 64, 64, 0, hex('#1B1A17')); // full-bleed so maskable crops look right
|
||||
rrect(14, 17, 30, 36, 4, hex('#FBFAF7'), (-7 * Math.PI) / 180, 29, 35);
|
||||
rrect(21, 13, 30, 36, 4, hex('#FFE36E'));
|
||||
rrect(27, 23, 18, 3.4, 1.7, hex('#1B1A17'));
|
||||
rrect(27, 30.5, 13, 3.4, 1.7, hex('#1B1A17'), 0, 0, 0, 0.55);
|
||||
rrect(27, 38, 15.5, 3.4, 1.7, hex('#1B1A17'), 0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
for (const size of [180, 192, 512]) fs.writeFileSync(`web/public/icon-${size}.png`, png(size, icon));
|
||||
console.log('icons written');
|
||||
|
|
@ -17,6 +17,12 @@ function log(level: 'info' | 'warn' | 'error', message: string, extra?: unknown)
|
|||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
// Optional .env file for running outside Docker. Real environment variables always win.
|
||||
try {
|
||||
process.loadEnvFile('.env');
|
||||
} catch {
|
||||
/* no .env file: that is the normal case in a container */
|
||||
}
|
||||
const config = loadConfig();
|
||||
log('info', `Study Desk ${APP_VERSION} starting (data: ${config.dataDir})`);
|
||||
|
||||
|
|
|
|||
|
|
@ -71,12 +71,19 @@ export function documentRoutes(app: AppContext): Hono {
|
|||
|
||||
r.get('/documents/:id/chunks', (c) => {
|
||||
const doc = getDocument(db, idParam(c));
|
||||
const offset = Math.max(0, Number(c.req.query('offset') ?? 0) || 0);
|
||||
let offset = Math.max(0, Number(c.req.query('offset') ?? 0) || 0);
|
||||
const limit = Math.min(100, Math.max(1, Number(c.req.query('limit') ?? 40) || 40));
|
||||
// Deep link to one passage (from search or a citation): start just before it.
|
||||
const around = Number(c.req.query('around'));
|
||||
if (Number.isFinite(around) && around > 0) {
|
||||
const hit = db.get<{ seq: number }>('SELECT seq FROM chunks WHERE id = ? AND document_id = ?', around, doc.id);
|
||||
if (hit) offset = Math.max(0, hit.seq - 1);
|
||||
}
|
||||
const chunks = listChunks(db, doc.id, offset, limit);
|
||||
return c.json({
|
||||
chunks: chunks.map((ch) => ({ id: ch.id, seq: ch.seq, text: ch.text, heading: ch.heading, pageStart: ch.pageStart, pageEnd: ch.pageEnd, label: sourceLabel(ch) })),
|
||||
total: doc.chunk_count,
|
||||
offset,
|
||||
nextOffset: chunks.length === limit && offset + limit < doc.chunk_count ? offset + limit : null,
|
||||
});
|
||||
});
|
||||
|
|
|
|||
31
vite.config.ts
Normal file
31
vite.config.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { fileURLToPath } from 'node:url';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
const api = process.env.API_ORIGIN ?? 'http://localhost:3726';
|
||||
|
||||
export default defineConfig({
|
||||
root: 'web',
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@shared': fileURLToPath(new URL('./shared', import.meta.url)),
|
||||
'@': fileURLToPath(new URL('./web/src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: false,
|
||||
proxy: {
|
||||
'/api': { target: api, changeOrigin: false },
|
||||
'/media': { target: api, changeOrigin: false },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: '../dist/web',
|
||||
emptyOutDir: true,
|
||||
sourcemap: false,
|
||||
chunkSizeWarningLimit: 900,
|
||||
},
|
||||
});
|
||||
20
web/index.html
Normal file
20
web/index.html
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#FBFAF7" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#151412" media="(prefers-color-scheme: dark)" />
|
||||
<meta name="description" content="Study Desk: quizzes, spaced-repetition flashcards and study materials." />
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/icon-180.png" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>Study Desk</title>
|
||||
<script src="/theme.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
web/public/icon-180.png
Normal file
BIN
web/public/icon-180.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
web/public/icon-192.png
Normal file
BIN
web/public/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
web/public/icon-512.png
Normal file
BIN
web/public/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.1 KiB |
8
web/public/icon.svg
Normal file
8
web/public/icon.svg
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<rect width="64" height="64" rx="14" fill="#1B1A17"/>
|
||||
<rect x="14" y="17" width="30" height="36" rx="4" fill="#FBFAF7" transform="rotate(-7 29 35)"/>
|
||||
<rect x="21" y="13" width="30" height="36" rx="4" fill="#FFE36E"/>
|
||||
<rect x="27" y="23" width="18" height="3.4" rx="1.7" fill="#1B1A17"/>
|
||||
<rect x="27" y="30.5" width="13" height="3.4" rx="1.7" fill="#1B1A17" opacity=".55"/>
|
||||
<rect x="27" y="38" width="15.5" height="3.4" rx="1.7" fill="#1B1A17" opacity=".55"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 539 B |
15
web/public/manifest.webmanifest
Normal file
15
web/public/manifest.webmanifest
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"name": "Study Desk",
|
||||
"short_name": "Study Desk",
|
||||
"description": "Quizzes, spaced-repetition flashcards and study materials.",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#FBFAF7",
|
||||
"theme_color": "#1B1A17",
|
||||
"icons": [
|
||||
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" },
|
||||
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
|
||||
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
2
web/public/robots.txt
Normal file
2
web/public/robots.txt
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
User-agent: *
|
||||
Disallow: /
|
||||
50
web/public/sw.js
Normal file
50
web/public/sw.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
/* Study Desk service worker: makes the app installable and keeps the shell available offline.
|
||||
* API calls are never cached, so study data is always live. */
|
||||
const CACHE = 'studydesk-shell-v1';
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(['/', '/icon.svg', '/manifest.webmanifest'])).then(() => self.skipWaiting()));
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches
|
||||
.keys()
|
||||
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
||||
.then(() => self.clients.claim()),
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const req = event.request;
|
||||
if (req.method !== 'GET') return;
|
||||
const url = new URL(req.url);
|
||||
if (url.origin !== self.location.origin || url.pathname.startsWith('/api/') || url.pathname.startsWith('/media/')) return;
|
||||
|
||||
// Hashed build assets never change: serve from cache, fill on first use.
|
||||
if (url.pathname.startsWith('/assets/')) {
|
||||
event.respondWith(
|
||||
caches.match(req).then(
|
||||
(hit) =>
|
||||
hit ||
|
||||
fetch(req).then((res) => {
|
||||
if (res.ok) caches.open(CACHE).then((c) => c.put(req, res.clone()));
|
||||
return res.clone();
|
||||
}),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Pages: always try the network so updates arrive, fall back to the cached shell offline.
|
||||
if (req.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
fetch(req)
|
||||
.then((res) => {
|
||||
if (res.ok) caches.open(CACHE).then((c) => c.put('/', res.clone()));
|
||||
return res.clone();
|
||||
})
|
||||
.catch(() => caches.match('/').then((hit) => hit || new Response('Study Desk is offline.', { status: 503, headers: { 'Content-Type': 'text/plain' } }))),
|
||||
);
|
||||
}
|
||||
});
|
||||
10
web/public/theme.js
Normal file
10
web/public/theme.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
// Applies the saved theme before first paint (kept as a file so the CSP can stay script-src 'self').
|
||||
(function () {
|
||||
try {
|
||||
var saved = localStorage.getItem('sd.theme') || 'system';
|
||||
var dark = saved === 'dark' || (saved === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
||||
} catch (e) {
|
||||
document.documentElement.dataset.theme = 'light';
|
||||
}
|
||||
})();
|
||||
615
web/src/app/Shell.tsx
Normal file
615
web/src/app/Shell.tsx
Normal file
|
|
@ -0,0 +1,615 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { BookOpen, ChartColumn, FileText, GraduationCap, Layers, Library, LogOut, Monitor, Moon, MoreHorizontal, NotebookPen, Plus, Search, Settings, Sparkles, Sun, X } from 'lucide-react';
|
||||
import { lazy, Suspense, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { CLASS_COLORS, type ClassColor } from '@shared/content';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { assistant, useAssistantState } from '@/lib/assistantStore';
|
||||
import { qk, useClasses, useOverview, useRefresh } from '@/lib/queries';
|
||||
import type { ClassInfo, SearchHit } from '@/lib/types';
|
||||
import { cx, modKey, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util';
|
||||
import { Brand } from '@/pages/Auth';
|
||||
import { Button, ClassDot, Dialog, Field, IconButton, Input, Kbd, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea } from '@/ui';
|
||||
|
||||
const AssistantPanel = lazy(() => import('@/features/AssistantPanel'));
|
||||
|
||||
/* ------------------------------ class dialog ------------------------------ */
|
||||
|
||||
export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; onOpenChange: (o: boolean) => void; existing?: ClassInfo }) {
|
||||
const refresh = useRefresh();
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [color, setColor] = useState<ClassColor | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setName(existing?.name ?? '');
|
||||
setCode(existing?.code ?? '');
|
||||
setDescription(existing?.description ?? '');
|
||||
setColor(existing?.color ?? null);
|
||||
}, [open, existing]);
|
||||
|
||||
const save = async () => {
|
||||
if (!name.trim()) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
if (existing) {
|
||||
await api.patch(`/api/classes/${existing.id}`, { name, code, description, color: color ?? existing.color });
|
||||
toast.success('Class updated');
|
||||
} else {
|
||||
const res = await api.post<{ class: ClassInfo }>('/api/classes', { name, code, description, color: color ?? undefined });
|
||||
navigate(`/classes/${res.class.id}`);
|
||||
}
|
||||
await refresh();
|
||||
onOpenChange(false);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={existing ? 'Edit class' : 'New class'}
|
||||
description={existing ? undefined : 'A class holds the quizzes, flashcards, documents and notes for one course.'}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" onClick={save} loading={busy} disabled={!name.trim()}>
|
||||
{existing ? 'Save' : 'Create class'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-[1fr_140px]">
|
||||
<Field label="Name">
|
||||
<Input autoFocus value={name} onChange={(e) => setName(e.target.value)} placeholder="Pharmacology" maxLength={120} />
|
||||
</Field>
|
||||
<Field label="Course code" optional>
|
||||
<Input value={code} onChange={(e) => setCode(e.target.value)} placeholder="NUR 356" maxLength={40} />
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Description" optional>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={2} maxLength={2000} />
|
||||
</Field>
|
||||
<div>
|
||||
<div className="mb-2 text-[13px] font-medium">Colour</div>
|
||||
<div className="flex flex-wrap gap-2" role="radiogroup" aria-label="Class colour">
|
||||
{CLASS_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={(color ?? existing?.color) === c}
|
||||
aria-label={c}
|
||||
onClick={() => setColor(c)}
|
||||
className={cx('size-8 rounded-full bg-tab ring-offset-2 ring-offset-surface transition-shadow', `tab-${c}`, (color ?? existing?.color) === c ? 'ring-2 ring-ink' : 'hover:ring-2 hover:ring-line-strong')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" hidden />
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ command palette ------------------------------ */
|
||||
|
||||
const HIT_ICON: Record<SearchHit['kind'], ReactNode> = {
|
||||
class: <GraduationCap />,
|
||||
quiz: <BookOpen />,
|
||||
deck: <Layers />,
|
||||
note: <NotebookPen />,
|
||||
document: <FileText />,
|
||||
question: <BookOpen />,
|
||||
card: <Layers />,
|
||||
passage: <FileText />,
|
||||
};
|
||||
const HIT_LABEL: Record<SearchHit['kind'], string> = { class: 'Class', quiz: 'Quiz', deck: 'Deck', note: 'Note', document: 'Document', question: 'Question', card: 'Card', passage: 'Passage' };
|
||||
|
||||
function hitUrl(hit: SearchHit): string {
|
||||
switch (hit.kind) {
|
||||
case 'class':
|
||||
return `/classes/${hit.id}`;
|
||||
case 'quiz':
|
||||
return `/quizzes/${hit.id}`;
|
||||
case 'deck':
|
||||
return `/decks/${hit.id}`;
|
||||
case 'note':
|
||||
return `/notes/${hit.id}`;
|
||||
case 'document':
|
||||
return `/documents/${hit.id}`;
|
||||
case 'question':
|
||||
return `/quizzes/${hit.parentId}?q=${hit.id}`;
|
||||
case 'card':
|
||||
return `/decks/${hit.parentId}?card=${hit.id}`;
|
||||
case 'passage':
|
||||
return `/documents/${hit.parentId}?chunk=${hit.id}`;
|
||||
}
|
||||
}
|
||||
|
||||
function CommandPalette({ open, onOpenChange, onNewClass }: { open: boolean; onOpenChange: (o: boolean) => void; onNewClass: () => void }) {
|
||||
const navigate = useNavigate();
|
||||
const [query, setQuery] = useState('');
|
||||
const [index, setIndex] = useState(0);
|
||||
const debounced = useDebounced(query.trim(), 160);
|
||||
const classes = useClasses();
|
||||
const search = useQuery({
|
||||
queryKey: ['search', debounced],
|
||||
queryFn: ({ signal }) => api.get<{ results: SearchHit[] }>(`/api/search?q=${encodeURIComponent(debounced)}`, signal).then((r) => r.results),
|
||||
enabled: open && debounced.length >= 2,
|
||||
staleTime: 10_000,
|
||||
});
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setQuery('');
|
||||
setIndex(0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
type Row = { key: string; icon: ReactNode; title: string; meta?: string; sub?: string; color?: string; run: () => void };
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
const go = (url: string) => () => {
|
||||
onOpenChange(false);
|
||||
navigate(url);
|
||||
};
|
||||
if (debounced.length >= 2) {
|
||||
return (search.data ?? []).map((h) => ({
|
||||
key: `${h.kind}:${h.id}`,
|
||||
icon: HIT_ICON[h.kind],
|
||||
title: h.title,
|
||||
meta: HIT_LABEL[h.kind],
|
||||
sub: [h.snippet, h.kind !== 'class' ? h.className : ''].filter(Boolean).join(' · '),
|
||||
color: h.classColor,
|
||||
run: go(hitUrl(h)),
|
||||
}));
|
||||
}
|
||||
const q = query.trim().toLowerCase();
|
||||
const base: Row[] = [
|
||||
{ key: 'home', icon: <Library />, title: 'Today', run: go('/') },
|
||||
{ key: 'review', icon: <Layers />, title: 'Review due flashcards', run: go('/review') },
|
||||
{ key: 'assistant', icon: <Sparkles />, title: 'Ask the assistant', run: () => (onOpenChange(false), assistant.open({ newChat: true })) },
|
||||
{ key: 'insights', icon: <ChartColumn />, title: 'Insights', run: go('/insights') },
|
||||
{ key: 'new-class', icon: <Plus />, title: 'New class', run: () => (onOpenChange(false), onNewClass()) },
|
||||
{ key: 'settings', icon: <Settings />, title: 'Settings', run: go('/settings') },
|
||||
...(classes.data ?? []).filter((c) => !c.archived).map((c) => ({ key: `class:${c.id}`, icon: <GraduationCap />, title: c.name, meta: 'Class', color: c.color, run: go(`/classes/${c.id}`) })),
|
||||
];
|
||||
return q ? base.filter((r) => r.title.toLowerCase().includes(q)) : base;
|
||||
}, [debounced, query, search.data, classes.data, navigate, onOpenChange, onNewClass]);
|
||||
|
||||
useEffect(() => setIndex(0), [rows.length, debounced]);
|
||||
useEffect(() => {
|
||||
listRef.current?.querySelector(`[data-index="${index}"]`)?.scrollIntoView({ block: 'nearest' });
|
||||
}, [index]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange} title="Search" bare size="lg">
|
||||
<div data-hotkeys="allow">
|
||||
<div className="relative border-y border-line">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-5 size-[18px] -translate-y-1/2 text-ink-3" aria-hidden />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setIndex((i) => Math.min(rows.length - 1, i + 1));
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setIndex((i) => Math.max(0, i - 1));
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
rows[index]?.run();
|
||||
}
|
||||
}}
|
||||
placeholder="Search questions, cards, documents, classes…"
|
||||
aria-label="Search"
|
||||
role="combobox"
|
||||
aria-expanded
|
||||
aria-controls="palette-list"
|
||||
className="h-13 w-full bg-transparent pr-5 pl-12 text-[15px] outline-none placeholder:text-ink-3"
|
||||
/>
|
||||
</div>
|
||||
<div ref={listRef} id="palette-list" role="listbox" className="max-h-[52vh] min-h-[180px] overflow-y-auto p-2">
|
||||
{search.isFetching && debounced.length >= 2 && rows.length === 0 ? (
|
||||
<div className="grid h-40 place-items-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="grid h-40 place-items-center px-6 text-center text-sm text-ink-3">{debounced.length >= 2 ? `Nothing matches "${debounced}".` : 'Type at least two characters to search everything.'}</div>
|
||||
) : (
|
||||
rows.map((r, i) => (
|
||||
<button
|
||||
key={r.key}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === index}
|
||||
data-index={i}
|
||||
onMouseMove={() => setIndex(i)}
|
||||
onClick={r.run}
|
||||
className={cx('flex w-full items-center gap-3 rounded-[10px] px-3 py-2 text-left', i === index && 'bg-ink/7')}
|
||||
>
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-lg bg-sunken text-ink-2 [&>svg]:size-4">{r.icon}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium">{r.title}</span>
|
||||
{r.sub && <span className="block truncate text-xs text-ink-3">{r.sub}</span>}
|
||||
</span>
|
||||
{r.color && <ClassDot color={r.color} />}
|
||||
{r.meta && <span className="shrink-0 text-xs text-ink-3">{r.meta}</span>}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<div className="hidden items-center gap-4 border-t border-line px-5 py-2.5 text-xs text-ink-3 sm:flex">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>↑</Kbd>
|
||||
<Kbd>↓</Kbd> to move
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd> to open
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>Esc</Kbd> to close
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ navigation ------------------------------ */
|
||||
|
||||
function ThemeMenu({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useTheme();
|
||||
const opts: { value: ThemeChoice; label: string; icon: ReactNode }[] = [
|
||||
{ value: 'light', label: 'Light', icon: <Sun /> },
|
||||
{ value: 'dark', label: 'Dark', icon: <Moon /> },
|
||||
{ value: 'system', label: 'Match system', icon: <Monitor /> },
|
||||
];
|
||||
return (
|
||||
<Menu trigger={children} side="top" align="start">
|
||||
<MenuLabel>Appearance</MenuLabel>
|
||||
{opts.map((o) => (
|
||||
<MenuItem key={o.value} icon={o.icon} onSelect={() => setTheme(o.value)} hint={theme === o.value ? '✓' : undefined}>
|
||||
{o.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
function useLogout() {
|
||||
const qc = useQueryClient();
|
||||
return async () => {
|
||||
try {
|
||||
await api.post('/api/auth/logout');
|
||||
} finally {
|
||||
qc.clear();
|
||||
await qc.invalidateQueries({ queryKey: qk.auth });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function NavItem({ to, icon, children, badge, end }: { to: string; icon: ReactNode; children: ReactNode; badge?: ReactNode; end?: boolean }) {
|
||||
return (
|
||||
<NavLink
|
||||
to={to}
|
||||
end={end}
|
||||
className={({ isActive }) =>
|
||||
cx('group flex h-9 items-center gap-2.5 rounded-[9px] px-2.5 text-sm font-medium transition-colors [&>svg]:size-[18px] [&>svg]:shrink-0', isActive ? 'bg-ink/8 text-ink' : 'text-ink-2 hover:bg-ink/5 hover:text-ink')
|
||||
}
|
||||
>
|
||||
{icon}
|
||||
<span className="flex-1 truncate">{children}</span>
|
||||
{badge}
|
||||
</NavLink>
|
||||
);
|
||||
}
|
||||
|
||||
function DueBadge({ n }: { n: number }) {
|
||||
if (!n) return null;
|
||||
return <span className="num rounded-full bg-marker px-1.5 py-px text-[11px] font-semibold text-marker-ink">{n > 999 ? '999+' : n}</span>;
|
||||
}
|
||||
|
||||
function Sidebar({ onSearch, onNewClass }: { onSearch: () => void; onNewClass: () => void }) {
|
||||
const classes = useClasses();
|
||||
const overview = useOverview();
|
||||
const logout = useLogout();
|
||||
const [theme] = useTheme();
|
||||
const active = (classes.data ?? []).filter((c) => !c.archived);
|
||||
const archived = (classes.data ?? []).filter((c) => c.archived);
|
||||
|
||||
return (
|
||||
<aside className="sticky top-0 hidden h-dvh w-[252px] shrink-0 flex-col border-r border-line bg-paper lg:flex">
|
||||
<div className="px-4 pt-5 pb-3">
|
||||
<Link to="/" className="inline-flex rounded-lg">
|
||||
<Brand />
|
||||
</Link>
|
||||
</div>
|
||||
<div className="px-3 pb-2">
|
||||
<button type="button" onClick={onSearch} className="flex h-9 w-full items-center gap-2 rounded-[10px] border border-line-strong bg-surface px-2.5 text-sm text-ink-3 shadow-1 hover:border-ink-3">
|
||||
<Search className="size-4" aria-hidden />
|
||||
<span className="flex-1 text-left">Search</span>
|
||||
<Kbd>{modKey} K</Kbd>
|
||||
</button>
|
||||
</div>
|
||||
<nav aria-label="Main" className="space-y-0.5 px-3">
|
||||
<NavItem to="/" end icon={<Library />}>
|
||||
Today
|
||||
</NavItem>
|
||||
<NavItem to="/review" icon={<Layers />} badge={<DueBadge n={overview.data?.due.total ?? 0} />}>
|
||||
Review
|
||||
</NavItem>
|
||||
<NavItem to="/assistant" icon={<Sparkles />}>
|
||||
Assistant
|
||||
</NavItem>
|
||||
<NavItem to="/insights" icon={<ChartColumn />}>
|
||||
Insights
|
||||
</NavItem>
|
||||
</nav>
|
||||
|
||||
<div className="mt-5 flex items-center justify-between px-5 pb-1.5">
|
||||
<span className="eyebrow">Classes</span>
|
||||
<IconButton label="New class" size="sm" onClick={onNewClass} className="-mr-2 size-7">
|
||||
<Plus />
|
||||
</IconButton>
|
||||
</div>
|
||||
<nav aria-label="Classes" className="min-h-0 flex-1 space-y-0.5 overflow-y-auto px-3 pb-3">
|
||||
{classes.isLoading && <div className="space-y-2 px-2 pt-1">{[0, 1, 2].map((i) => <div key={i} className="skeleton h-6" />)}</div>}
|
||||
{active.map((c) => (
|
||||
<NavLink
|
||||
key={c.id}
|
||||
to={`/classes/${c.id}`}
|
||||
className={({ isActive }) => cx('flex h-9 items-center gap-2.5 rounded-[9px] px-2.5 text-sm transition-colors', isActive ? 'bg-ink/8 font-medium text-ink' : 'text-ink-2 hover:bg-ink/5 hover:text-ink')}
|
||||
>
|
||||
<ClassDot color={c.color} />
|
||||
<span className="flex-1 truncate">{c.name}</span>
|
||||
<DueBadge n={c.due} />
|
||||
</NavLink>
|
||||
))}
|
||||
{!classes.isLoading && active.length === 0 && (
|
||||
<button type="button" onClick={onNewClass} className="mt-1 w-full rounded-[10px] border border-dashed border-line-strong px-3 py-3 text-left text-[13px] text-ink-3 hover:border-ink-3 hover:text-ink-2">
|
||||
Create your first class to get started.
|
||||
</button>
|
||||
)}
|
||||
{archived.length > 0 && (
|
||||
<details className="pt-2">
|
||||
<summary className="px-2.5 py-1 text-xs text-ink-3 hover:text-ink-2">Archived ({archived.length})</summary>
|
||||
{archived.map((c) => (
|
||||
<NavLink key={c.id} to={`/classes/${c.id}`} className="flex h-8 items-center gap-2.5 rounded-[9px] px-2.5 text-sm text-ink-3 hover:bg-ink/5">
|
||||
<ClassDot color={c.color} className="opacity-50" />
|
||||
<span className="truncate">{c.name}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
</details>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="flex items-center gap-1 border-t border-line px-3 py-2.5">
|
||||
<NavLink to="/settings" className={({ isActive }) => cx('flex h-9 flex-1 items-center gap-2.5 rounded-[9px] px-2.5 text-sm font-medium', isActive ? 'bg-ink/8 text-ink' : 'text-ink-2 hover:bg-ink/5 hover:text-ink')}>
|
||||
<Settings className="size-[18px]" />
|
||||
Settings
|
||||
</NavLink>
|
||||
<ThemeMenu>
|
||||
<IconButton label="Appearance" size="sm" tooltip={false}>
|
||||
{theme === 'dark' ? <Moon /> : theme === 'light' ? <Sun /> : <Monitor />}
|
||||
</IconButton>
|
||||
</ThemeMenu>
|
||||
<IconButton label="Sign out" size="sm" onClick={logout}>
|
||||
<LogOut />
|
||||
</IconButton>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileNav({ onSearch, onNewClass }: { onSearch: () => void; onNewClass: () => void }) {
|
||||
const classes = useClasses();
|
||||
const overview = useOverview();
|
||||
const logout = useLogout();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const [, setTheme] = useTheme();
|
||||
const [classesOpen, setClassesOpen] = useState(false);
|
||||
const tab = (active: boolean) => cx('flex flex-1 flex-col items-center justify-center gap-0.5 text-[11px] font-medium [&>svg]:size-[21px]', active ? 'text-ink' : 'text-ink-3');
|
||||
const onClass = location.pathname.startsWith('/classes');
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="sticky top-0 z-30 flex h-13 items-center justify-between border-b border-line bg-paper/92 px-4 backdrop-blur lg:hidden">
|
||||
<Link to="/" className="rounded-lg">
|
||||
<Brand />
|
||||
</Link>
|
||||
<IconButton label="Search" onClick={onSearch} tooltip={false}>
|
||||
<Search />
|
||||
</IconButton>
|
||||
</header>
|
||||
<nav aria-label="Main" className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-paper/95 backdrop-blur lg:hidden">
|
||||
<div className="flex h-14">
|
||||
<NavLink to="/" end className={({ isActive }) => tab(isActive)}>
|
||||
<Library />
|
||||
Today
|
||||
</NavLink>
|
||||
<button type="button" className={tab(onClass)} onClick={() => setClassesOpen(true)}>
|
||||
<GraduationCap />
|
||||
Classes
|
||||
</button>
|
||||
<NavLink to="/review" className={({ isActive }) => cx(tab(isActive), 'relative')}>
|
||||
<Layers />
|
||||
Review
|
||||
{(overview.data?.due.total ?? 0) > 0 && <span className="absolute top-1.5 left-1/2 ml-2 size-2 rounded-full bg-marker ring-2 ring-paper" />}
|
||||
</NavLink>
|
||||
<NavLink to="/assistant" className={({ isActive }) => tab(isActive)}>
|
||||
<Sparkles />
|
||||
Assistant
|
||||
</NavLink>
|
||||
<Menu
|
||||
side="top"
|
||||
trigger={
|
||||
<button type="button" className={tab(location.pathname.startsWith('/settings') || location.pathname.startsWith('/insights'))}>
|
||||
<MoreHorizontal />
|
||||
More
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={<ChartColumn />} onSelect={() => navigate('/insights')}>
|
||||
Insights
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Settings />} onSelect={() => navigate('/settings')}>
|
||||
Settings
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>Appearance</MenuLabel>
|
||||
<MenuItem icon={<Sun />} onSelect={() => setTheme('light')}>
|
||||
Light
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Moon />} onSelect={() => setTheme('dark')}>
|
||||
Dark
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Monitor />} onSelect={() => setTheme('system')}>
|
||||
Match system
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<LogOut />} onSelect={logout}>
|
||||
Sign out
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</nav>
|
||||
<Dialog open={classesOpen} onOpenChange={setClassesOpen} title="Classes" bare>
|
||||
<div className="px-3 pb-4">
|
||||
{(classes.data ?? []).map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setClassesOpen(false);
|
||||
navigate(`/classes/${c.id}`);
|
||||
}}
|
||||
className={cx('flex h-12 w-full items-center gap-3 rounded-xl px-3 text-left text-[15px] hover:bg-ink/5', c.archived && 'opacity-60')}
|
||||
>
|
||||
<ClassDot color={c.color} className="size-3" />
|
||||
<span className="flex-1 truncate font-medium">{c.name}</span>
|
||||
<DueBadge n={c.due} />
|
||||
</button>
|
||||
))}
|
||||
<Button
|
||||
block
|
||||
className="mt-2"
|
||||
icon={<Plus />}
|
||||
onClick={() => {
|
||||
setClassesOpen(false);
|
||||
onNewClass();
|
||||
}}
|
||||
>
|
||||
New class
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ shell ------------------------------ */
|
||||
|
||||
export function Shell() {
|
||||
const [paletteOpen, setPaletteOpen] = useState(false);
|
||||
const [classDialog, setClassDialog] = useState(false);
|
||||
const isDesktop = useIsDesktop();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { open: assistantOpen, seed } = useAssistantState();
|
||||
const onAssistantPage = location.pathname.startsWith('/assistant');
|
||||
|
||||
useHotkeys({
|
||||
'mod+k': (e) => {
|
||||
e.preventDefault();
|
||||
setPaletteOpen((v) => !v);
|
||||
},
|
||||
'mod+j': (e) => {
|
||||
e.preventDefault();
|
||||
if (onAssistantPage) return;
|
||||
assistant.toggle();
|
||||
},
|
||||
'/': (e) => {
|
||||
e.preventDefault();
|
||||
setPaletteOpen(true);
|
||||
},
|
||||
});
|
||||
|
||||
// On phones the assistant is a full page rather than a drawer.
|
||||
useEffect(() => {
|
||||
if (assistantOpen && !isDesktop && !onAssistantPage) {
|
||||
assistant.close();
|
||||
navigate('/assistant', { state: { seed } });
|
||||
}
|
||||
}, [assistantOpen, isDesktop, onAssistantPage, navigate, seed]);
|
||||
|
||||
useEffect(() => {
|
||||
if (onAssistantPage && assistantOpen) assistant.close();
|
||||
}, [onAssistantPage, assistantOpen]);
|
||||
|
||||
const showDrawer = assistantOpen && isDesktop && !onAssistantPage;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh">
|
||||
<a href="#main" className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-3 focus:z-[90] focus:rounded-lg focus:bg-ink focus:px-3 focus:py-2 focus:text-paper">
|
||||
Skip to content
|
||||
</a>
|
||||
<Sidebar onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<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">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
{showDrawer && (
|
||||
<aside aria-label="Assistant" className="sticky top-0 z-20 hidden h-dvh w-[420px] shrink-0 animate-drawer flex-col border-l border-line bg-surface lg:flex xl:w-[460px]">
|
||||
<Suspense fallback={<div className="grid flex-1 place-items-center"><Spinner /></div>}>
|
||||
<AssistantPanel
|
||||
variant="drawer"
|
||||
headerAction={
|
||||
<IconButton label="Close assistant" size="sm" onClick={() => assistant.close()}>
|
||||
<X />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</Suspense>
|
||||
</aside>
|
||||
)}
|
||||
{!showDrawer && !onAssistantPage && isDesktop && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => assistant.open()}
|
||||
className="fixed right-6 bottom-6 z-20 flex h-11 items-center gap-2 rounded-full bg-ink pr-4 pl-3.5 text-sm font-medium text-paper shadow-2 transition-transform hover:-translate-y-0.5"
|
||||
>
|
||||
<Sparkles className="size-4 text-marker" />
|
||||
Assistant
|
||||
<span className="ml-1 rounded border border-paper/25 px-1 py-px font-mono text-[10px] text-paper/70">{modKey} J</span>
|
||||
</button>
|
||||
)}
|
||||
<CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} onNewClass={() => setClassDialog(true)} />
|
||||
<ClassDialog open={classDialog} onOpenChange={setClassDialog} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
706
web/src/features/AiSettings.tsx
Normal file
706
web/src/features/AiSettings.tsx
Normal file
|
|
@ -0,0 +1,706 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Brain, Check, CircleAlert, Eye, ExternalLink, KeyRound, MoreHorizontal, Pencil, Plus, RefreshCw, Search, Server, Trash2, Wrench, Zap } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk } from '@/lib/queries';
|
||||
import type { AdapterMeta, AiModel, AiStatus, Provider, ProviderKind, TaskConfig, TaskName, TaskSettings } from '@/lib/types';
|
||||
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
|
||||
import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui';
|
||||
|
||||
interface Meta {
|
||||
adapters: AdapterMeta[];
|
||||
tasks: Record<TaskName, { label: string; description: string }>;
|
||||
catalogUpdated: string;
|
||||
}
|
||||
|
||||
const KIND_BLURB: Record<ProviderKind, string> = {
|
||||
openai: 'GPT models with an OpenAI API key.',
|
||||
anthropic: 'Claude models with an Anthropic API key.',
|
||||
gemini: 'Gemini models with a Google AI Studio key.',
|
||||
openai_compatible: 'OpenRouter, Groq, Together, LM Studio, vLLM and other compatible servers.',
|
||||
ollama: 'Models running on your own machine or server.',
|
||||
};
|
||||
|
||||
function useAiData() {
|
||||
const qc = useQueryClient();
|
||||
const meta = useQuery({ queryKey: ['ai', 'meta'], queryFn: () => api.get<Meta>('/api/ai/meta'), staleTime: Infinity });
|
||||
const providers = useQuery({ queryKey: qk.aiProviders, queryFn: () => api.get<{ providers: Provider[] }>('/api/ai/providers').then((r) => r.providers) });
|
||||
const models = useQuery({ queryKey: qk.aiModels, queryFn: () => api.get<{ models: AiModel[] }>('/api/ai/models').then((r) => r.models) });
|
||||
const tasks = useQuery({ queryKey: ['ai', 'tasks'], queryFn: () => api.get<{ tasks: TaskSettings }>('/api/ai/tasks').then((r) => r.tasks) });
|
||||
const status = useQuery({ queryKey: qk.aiStatus, queryFn: () => api.get<AiStatus>('/api/ai/status') });
|
||||
const reload = () => qc.invalidateQueries({ queryKey: ['ai'] });
|
||||
return { meta, providers, models, tasks, status, reload };
|
||||
}
|
||||
|
||||
/* ------------------------------ provider dialog ------------------------------ */
|
||||
|
||||
function ProviderDialog({ open, onClose, adapters, existing, onSaved }: { open: boolean; onClose: () => void; adapters: AdapterMeta[]; existing: Provider | null; onSaved: (p: Provider, isNew: boolean) => void }) {
|
||||
const [kind, setKind] = useState<ProviderKind | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [baseUrl, setBaseUrl] = useState('');
|
||||
const [headers, setHeaders] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const adapter = adapters.find((a) => a.kind === kind);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setKind(existing?.kind ?? null);
|
||||
setName(existing?.name ?? '');
|
||||
setApiKey('');
|
||||
setBaseUrl(existing?.baseUrl ?? '');
|
||||
setHeaders('');
|
||||
}, [open, existing]);
|
||||
|
||||
const pick = (k: ProviderKind) => {
|
||||
const a = adapters.find((x) => x.kind === k)!;
|
||||
setKind(k);
|
||||
setName(k === 'openai_compatible' ? '' : a.label);
|
||||
setBaseUrl(k === 'ollama' ? (a.defaultBaseUrl ?? '') : '');
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!kind || !adapter) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const parsedHeaders: Record<string, string> = {};
|
||||
for (const line of headers.split('\n')) {
|
||||
const at = line.indexOf(':');
|
||||
if (at > 0) parsedHeaders[line.slice(0, at).trim()] = line.slice(at + 1).trim();
|
||||
}
|
||||
const body = {
|
||||
name: name.trim() || adapter.label,
|
||||
kind,
|
||||
baseUrl: baseUrl.trim() || null,
|
||||
apiKey: apiKey.trim() ? apiKey.trim() : existing ? undefined : null,
|
||||
headers: headers.trim() ? parsedHeaders : existing ? undefined : {},
|
||||
};
|
||||
const res = existing ? await api.patch<{ provider: Provider }>(`/api/ai/providers/${existing.id}`, body) : await api.post<{ provider: Provider }>('/api/ai/providers', body);
|
||||
onSaved(res.provider, !existing);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const needsUrl = adapter?.requiresBaseUrl;
|
||||
const canSave = Boolean(kind) && (!needsUrl || baseUrl.trim()) && (!adapter?.requiresApiKey || apiKey.trim() || existing?.hasKey);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={existing ? `Edit ${existing.name}` : kind ? `Connect ${adapter?.label}` : 'Add an AI provider'}
|
||||
description={!kind ? 'Keys are encrypted and stay on your server. They are never sent to the browser.' : undefined}
|
||||
footer={
|
||||
kind ? (
|
||||
<>
|
||||
{!existing && (
|
||||
<Button variant="ghost" className="mr-auto" onClick={() => setKind(null)}>
|
||||
Back
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} disabled={!canSave} onClick={save}>
|
||||
{existing ? 'Save' : 'Connect'}
|
||||
</Button>
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{!kind ? (
|
||||
<div className="grid gap-2">
|
||||
{adapters.map((a) => (
|
||||
<button key={a.kind} type="button" onClick={() => pick(a.kind)} className="flex items-center gap-3 rounded-xl border border-line-strong p-3.5 text-left hover:border-ink-3 hover:bg-ink/3">
|
||||
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-sunken text-ink-2">{a.kind === 'ollama' || a.kind === 'openai_compatible' ? <Server className="size-[18px]" /> : <Brain className="size-[18px]" />}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-semibold">{a.label}</span>
|
||||
<span className="block text-[13px] text-ink-2">{KIND_BLURB[a.kind]}</span>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
adapter && (
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (canSave) void save();
|
||||
}}
|
||||
>
|
||||
<Field label="Name" hint="Shown in model pickers. Useful when you connect the same service with two keys.">
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder={adapter.kind === 'openai_compatible' ? 'OpenRouter' : adapter.label} maxLength={80} />
|
||||
</Field>
|
||||
{(needsUrl || adapter.kind === 'ollama') && (
|
||||
<Field label="Server URL" hint={adapter.kind === 'ollama' ? 'From inside Docker, "localhost" is the container. Use your server address, for example http://192.168.1.10:11434.' : 'The API root, for example https://openrouter.ai/api/v1 or http://192.168.1.10:1234/v1.'}>
|
||||
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={adapter.defaultBaseUrl ?? 'https://…/v1'} inputMode="url" spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
)}
|
||||
<Field
|
||||
label="API key"
|
||||
optional={!adapter.requiresApiKey}
|
||||
hint={
|
||||
<>
|
||||
{existing?.hasKey ? `Stored key: ${existing.keyPreview}. Leave blank to keep it. ` : ''}
|
||||
{adapter.requiresApiKey && (
|
||||
<a href={adapter.docsUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 font-medium text-accent hover:underline">
|
||||
Get a key <ExternalLink className="size-3" />
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Input type="password" value={apiKey} onChange={(e) => setApiKey(e.target.value)} placeholder={existing?.hasKey ? '••••••••' : adapter.keyHint} autoComplete="off" spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
<details className="rounded-xl border border-line">
|
||||
<summary className="px-3.5 py-2.5 text-sm font-medium text-ink-2 hover:text-ink">Advanced</summary>
|
||||
<div className="space-y-4 border-t border-line p-3.5">
|
||||
{!needsUrl && adapter.kind !== 'ollama' && (
|
||||
<Field label="Custom endpoint" optional hint="Only for proxies and gateways. Leave blank for the official API.">
|
||||
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={adapter.defaultBaseUrl ?? ''} spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Extra HTTP headers" optional hint={existing?.headerNames.length ? `Stored: ${existing.headerNames.join(', ')}. Entering anything here replaces them.` : 'One per line, as Name: value.'}>
|
||||
<Textarea rows={2} value={headers} onChange={(e) => setHeaders(e.target.value)} placeholder="HTTP-Referer: https://study.example.com" spellCheck={false} className="num text-[13px]" />
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
<button type="submit" hidden />
|
||||
</form>
|
||||
)
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ model dialog ------------------------------ */
|
||||
|
||||
function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClose: () => void; onSaved: () => void }) {
|
||||
const [label, setLabel] = useState('');
|
||||
const [caps, setCaps] = useState(model?.capabilities ?? { tools: true, vision: false, pdf: false, reasoning: false, temperature: true });
|
||||
const [ctx, setCtx] = useState('');
|
||||
const [maxOut, setMaxOut] = useState('');
|
||||
const [priceIn, setPriceIn] = useState('');
|
||||
const [priceOut, setPriceOut] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!model) return;
|
||||
setLabel(model.label);
|
||||
setCaps(model.capabilities);
|
||||
setCtx(model.contextWindow?.toString() ?? '');
|
||||
setMaxOut(model.maxOutput?.toString() ?? '');
|
||||
setPriceIn(model.priceIn?.toString() ?? '');
|
||||
setPriceOut(model.priceOut?.toString() ?? '');
|
||||
}, [model]);
|
||||
const num = (s: string) => (s.trim() === '' ? null : Number(s));
|
||||
const save = async () => {
|
||||
if (!model) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut) });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open={model !== null}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Model details"
|
||||
description={model?.model}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} onClick={save}>
|
||||
Save
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Field label="Display name">
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} />
|
||||
</Field>
|
||||
<div className="space-y-3.5 rounded-xl border border-line p-4">
|
||||
<Switch checked={caps.tools} onChange={(v) => setCaps({ ...caps, tools: v })} label="Tool calling" description="Needed for the assistant to act on your library. Generation falls back to plain JSON without it." />
|
||||
<Switch checked={caps.vision} onChange={(v) => setCaps({ ...caps, vision: v })} label="Reads images" />
|
||||
<Switch checked={caps.pdf} onChange={(v) => setCaps({ ...caps, pdf: v })} label="Reads PDF files directly" description="Used to transcribe scanned PDFs." />
|
||||
<Switch checked={caps.reasoning} onChange={(v) => setCaps({ ...caps, reasoning: v })} label="Adjustable reasoning effort" />
|
||||
<Switch checked={caps.temperature} onChange={(v) => setCaps({ ...caps, temperature: v })} label="Accepts a temperature" description="Turn off for models that reject it." />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field label="Context window" hint="Tokens">
|
||||
<Input type="number" min={0} value={ctx} onChange={(e) => setCtx(e.target.value)} placeholder="Unknown" />
|
||||
</Field>
|
||||
<Field label="Max output" hint="Tokens">
|
||||
<Input type="number" min={0} value={maxOut} onChange={(e) => setMaxOut(e.target.value)} placeholder="Unknown" />
|
||||
</Field>
|
||||
<Field label="Input price" hint="USD per million tokens">
|
||||
<Input type="number" min={0} step="0.01" value={priceIn} onChange={(e) => setPriceIn(e.target.value)} placeholder="Unknown" />
|
||||
</Field>
|
||||
<Field label="Output price" hint="USD per million tokens">
|
||||
<Input type="number" min={0} step="0.01" value={priceOut} onChange={(e) => setPriceOut(e.target.value)} placeholder="Unknown" />
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ provider card ------------------------------ */
|
||||
|
||||
function ProviderCard({ provider, models, adapter, onEdit, reload }: { provider: Provider; models: AiModel[]; adapter?: AdapterMeta; onEdit: () => void; reload: () => void }) {
|
||||
const confirm = useConfirm();
|
||||
const [busy, setBusy] = useState<'test' | 'discover' | null>(null);
|
||||
const [showAll, setShowAll] = useState(false);
|
||||
const [filter, setFilter] = useState('');
|
||||
const [manual, setManual] = useState('');
|
||||
const [editing, setEditing] = useState<AiModel | null>(null);
|
||||
const enabled = models.filter((m) => m.enabled);
|
||||
const needle = filter.trim().toLowerCase();
|
||||
const list = (showAll || enabled.length === 0 ? models : enabled).filter((m) => !needle || m.model.toLowerCase().includes(needle) || m.label.toLowerCase().includes(needle));
|
||||
|
||||
const test = async () => {
|
||||
setBusy('test');
|
||||
try {
|
||||
const res = await api.post<{ result: { ok: boolean; message: string } }>(`/api/ai/providers/${provider.id}/test`);
|
||||
if (res.result.ok) toast.success(res.result.message);
|
||||
else toast.error(res.result.message);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
reload();
|
||||
}
|
||||
};
|
||||
const discover = async () => {
|
||||
setBusy('discover');
|
||||
try {
|
||||
const res = await api.post<{ added: number; total: number }>(`/api/ai/providers/${provider.id}/discover`);
|
||||
toast.success(res.added > 0 ? `Found ${plural(res.added, 'new model')}` : `Model list is up to date (${res.total})`);
|
||||
if (enabled.length === 0) setShowAll(true);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
reload();
|
||||
}
|
||||
};
|
||||
const toggleModel = async (m: AiModel, on: boolean) => {
|
||||
await api.patch(`/api/ai/models/${m.id}`, { enabled: on }).catch((e) => toast.error(errorMessage(e)));
|
||||
reload();
|
||||
};
|
||||
const addManual = async () => {
|
||||
if (!manual.trim()) return;
|
||||
try {
|
||||
await api.post('/api/ai/models', { providerId: provider.id, model: manual.trim() });
|
||||
setManual('');
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const remove = async () => {
|
||||
if (!(await confirm({ title: `Remove ${provider.name}?`, message: 'Its key and model list are deleted. Tasks that used its models fall back to your default model.', confirmLabel: 'Remove', danger: true }))) return;
|
||||
await api.del(`/api/ai/providers/${provider.id}`).catch((e) => toast.error(errorMessage(e)));
|
||||
reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cx('card overflow-hidden', !provider.enabled && 'opacity-70')}>
|
||||
<div className="flex flex-wrap items-center gap-3 px-4 py-3.5">
|
||||
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-sunken text-ink-2">{provider.kind === 'ollama' || provider.kind === 'openai_compatible' ? <Server className="size-[18px]" /> : <Brain className="size-[18px]" />}</span>
|
||||
<div className="min-w-0 flex-1 basis-40">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold">{provider.name}</span>
|
||||
<Badge>{adapter?.label ?? provider.kind}</Badge>
|
||||
{!provider.enabled && <Badge tone="warn">Off</Badge>}
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-2.5 text-xs text-ink-3">
|
||||
{provider.hasKey && (
|
||||
<span className="num flex items-center gap-1">
|
||||
<KeyRound className="size-3" /> {provider.keyPreview}
|
||||
</span>
|
||||
)}
|
||||
{provider.baseUrl && <span className="num truncate">{provider.baseUrl}</span>}
|
||||
{provider.lastTestOk !== null && (
|
||||
<span className={cx('flex items-center gap-1', provider.lastTestOk ? 'text-good' : 'text-bad')}>
|
||||
{provider.lastTestOk ? <Check className="size-3" /> : <CircleAlert className="size-3" />}
|
||||
{provider.lastTestOk ? 'Connected' : provider.lastTestMessage} · {timeAgo(provider.lastTestAt)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button size="sm" loading={busy === 'test'} disabled={busy !== null} onClick={test} icon={<Zap />}>
|
||||
Test
|
||||
</Button>
|
||||
<Button size="sm" loading={busy === 'discover'} disabled={busy !== null} onClick={discover} icon={<RefreshCw />}>
|
||||
Find models
|
||||
</Button>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Provider options" size="sm" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={<Pencil />} onSelect={onEdit}>
|
||||
Edit connection
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<Zap />}
|
||||
onSelect={async () => {
|
||||
await api.patch(`/api/ai/providers/${provider.id}`, { name: provider.name, kind: provider.kind, baseUrl: provider.baseUrl, enabled: !provider.enabled }).catch((e) => toast.error(errorMessage(e)));
|
||||
reload();
|
||||
}}
|
||||
>
|
||||
{provider.enabled ? 'Turn off' : 'Turn on'}
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
|
||||
Remove
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line bg-paper/50">
|
||||
{models.length === 0 ? (
|
||||
<p className="px-4 py-4 text-[13px] text-ink-2">No models yet. Use "Find models" to load the list, or add a model id below.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-2 px-4 pt-3 pb-1.5">
|
||||
<span className="eyebrow">
|
||||
{enabled.length} of {models.length} models on
|
||||
</span>
|
||||
{models.length > 8 && (showAll || enabled.length === 0) && (
|
||||
<div className="relative ml-auto">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-ink-3" />
|
||||
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter models" aria-label="Filter models" className="h-8 w-44 pl-7 text-[13px]" />
|
||||
</div>
|
||||
)}
|
||||
{enabled.length > 0 && enabled.length < models.length && (
|
||||
<button type="button" className={cx('text-xs font-medium text-accent hover:underline', !(models.length > 8 && showAll) && 'ml-auto')} onClick={() => setShowAll(!showAll)}>
|
||||
{showAll ? 'Show only models that are on' : `Show all ${models.length}`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<ul className="max-h-80 divide-y divide-line overflow-y-auto">
|
||||
{list.map((m) => (
|
||||
<li key={m.id} className="flex items-center gap-3 px-4 py-2">
|
||||
<input type="checkbox" role="switch" aria-label={`Use ${m.label}`} checked={m.enabled} onChange={(e) => toggleModel(m, e.target.checked)} className="size-4 shrink-0 accent-[var(--accent)]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{m.label}</div>
|
||||
<div className="num truncate text-[11px] text-ink-3">{m.model}</div>
|
||||
</div>
|
||||
<div className="hidden shrink-0 items-center gap-1 sm:flex">
|
||||
{m.capabilities.tools && (
|
||||
<Tooltip label="Tool calling">
|
||||
<span className="grid size-6 place-items-center rounded-md bg-sunken text-ink-3">
|
||||
<Wrench className="size-3.5" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{m.capabilities.vision && (
|
||||
<Tooltip label={m.capabilities.pdf ? 'Reads images and PDFs' : 'Reads images'}>
|
||||
<span className="grid size-6 place-items-center rounded-md bg-sunken text-ink-3">
|
||||
<Eye className="size-3.5" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{m.capabilities.reasoning && (
|
||||
<Tooltip label="Adjustable reasoning">
|
||||
<span className="grid size-6 place-items-center rounded-md bg-sunken text-ink-3">
|
||||
<Brain className="size-3.5" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<span className="num hidden w-28 shrink-0 text-right text-[11px] text-ink-3 md:block">{m.priceIn !== null && m.priceOut !== null ? `$${m.priceIn} / $${m.priceOut}` : 'price unknown'}</span>
|
||||
<IconButton label={`Edit ${m.label}`} size="sm" onClick={() => setEditing(m)}>
|
||||
<Pencil />
|
||||
</IconButton>
|
||||
</li>
|
||||
))}
|
||||
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">No models match.</li>}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
<form
|
||||
className="flex gap-2 border-t border-line px-4 py-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void addManual();
|
||||
}}
|
||||
>
|
||||
<Input value={manual} onChange={(e) => setManual(e.target.value)} placeholder="Add a model id manually" aria-label="Model id" spellCheck={false} className="num h-9 text-[13px]" />
|
||||
<Button type="submit" size="sm" className="h-9" icon={<Plus />} disabled={!manual.trim()}>
|
||||
Add
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
<ModelDialog model={editing} onClose={() => setEditing(null)} onSaved={reload} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ tasks ------------------------------ */
|
||||
|
||||
function TaskRow({ name, label, description, config, models, resolved, onChange }: { name: TaskName | 'default'; label: string; description: string; config: TaskConfig; models: AiModel[]; resolved?: string; onChange: (c: TaskConfig) => void }) {
|
||||
const model = models.find((m) => m.id === config.modelId);
|
||||
const hasOverrides = config.temperature !== null || config.reasoningEffort !== null || config.maxOutputTokens !== null;
|
||||
const byProvider = useMemo(() => {
|
||||
const map = new Map<string, AiModel[]>();
|
||||
for (const m of models) map.set(m.providerName, [...(map.get(m.providerName) ?? []), m]);
|
||||
return [...map.entries()];
|
||||
}, [models]);
|
||||
return (
|
||||
<div className="px-4 py-3.5">
|
||||
<div className="grid items-center gap-x-4 gap-y-2 sm:grid-cols-[1fr_280px]">
|
||||
<div>
|
||||
<div className="text-sm font-semibold">{label}</div>
|
||||
<div className="text-[13px] text-ink-2">{description}</div>
|
||||
</div>
|
||||
<Select value={config.modelId ?? ''} onChange={(e) => onChange({ ...config, modelId: e.target.value || null })} aria-label={`Model for ${label}`}>
|
||||
<option value="">{name === 'default' ? 'First available model' : `Same as default${resolved ? ` (${resolved})` : ''}`}</option>
|
||||
{byProvider.map(([provider, list]) => (
|
||||
<optgroup key={provider} label={provider}>
|
||||
{list.map((m) => (
|
||||
<option key={m.id} value={m.id} disabled={name === 'vision' && !m.capabilities.vision}>
|
||||
{m.label}
|
||||
{name === 'vision' && !m.capabilities.vision ? ' (no vision)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<details className="mt-2" open={hasOverrides}>
|
||||
<summary className="w-fit text-xs font-medium text-ink-3 hover:text-ink-2">Parameters{hasOverrides ? ' (customised)' : ''}</summary>
|
||||
<div className="mt-2.5 grid gap-3 sm:grid-cols-3">
|
||||
<Field label="Reasoning effort" hint={model && !model.capabilities.reasoning ? 'Not supported by this model' : undefined}>
|
||||
<Select value={config.reasoningEffort ?? ''} onChange={(e) => onChange({ ...config, reasoningEffort: (e.target.value || null) as TaskConfig['reasoningEffort'] })}>
|
||||
<option value="">Model default</option>
|
||||
<option value="none">Off / minimal</option>
|
||||
<option value="low">Low</option>
|
||||
<option value="medium">Medium</option>
|
||||
<option value="high">High</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
|
||||
<Input type="number" min={0} max={2} step={0.1} value={config.temperature ?? ''} placeholder="Model default" onChange={(e) => onChange({ ...config, temperature: e.target.value === '' ? null : Math.max(0, Math.min(2, Number(e.target.value))) })} />
|
||||
</Field>
|
||||
<Field label="Output limit" hint="Tokens per response">
|
||||
<Input type="number" min={256} step={256} value={config.maxOutputTokens ?? ''} placeholder="Automatic" onChange={(e) => onChange({ ...config, maxOutputTokens: e.target.value === '' ? null : Math.max(256, Math.round(Number(e.target.value))) })} />
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ usage ------------------------------ */
|
||||
|
||||
function Usage() {
|
||||
const [days, setDays] = useState(30);
|
||||
const q = useQuery({ queryKey: ['ai', 'usage', days], queryFn: () => api.get<any>(`/api/ai/usage?days=${days}`) });
|
||||
const u = q.data;
|
||||
return (
|
||||
<Section
|
||||
title="Usage"
|
||||
action={
|
||||
<Select value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label="Period" className="h-8 w-32 text-[13px]">
|
||||
<option value={7}>Last 7 days</option>
|
||||
<option value={30}>Last 30 days</option>
|
||||
<option value={90}>Last 90 days</option>
|
||||
</Select>
|
||||
}
|
||||
>
|
||||
{!u ? (
|
||||
<Skeleton className="h-28" />
|
||||
) : u.total.calls === 0 ? (
|
||||
<div className="card px-4 py-5 text-sm text-ink-2">No AI requests in this period.</div>
|
||||
) : (
|
||||
<div className="card overflow-hidden">
|
||||
<div className="grid grid-cols-3 divide-x divide-line border-b border-line">
|
||||
{[
|
||||
['Estimated cost', formatCost(u.total.cost)],
|
||||
['Requests', u.total.calls.toLocaleString()],
|
||||
['Tokens in / out', `${formatTokens(u.total.input)} / ${formatTokens(u.total.output)}`],
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="px-4 py-3">
|
||||
<div className="eyebrow">{k}</div>
|
||||
<div className="num mt-1 text-lg font-semibold">{v}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-[13px]">
|
||||
<thead>
|
||||
<tr className="text-left text-ink-3">
|
||||
<th className="px-4 py-2 font-medium">Model</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Requests</th>
|
||||
<th className="px-3 py-2 text-right font-medium">In</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Out</th>
|
||||
<th className="px-4 py-2 text-right font-medium">Cost</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line border-t border-line">
|
||||
{u.byModel.map((m: any) => (
|
||||
<tr key={`${m.provider}:${m.model}`}>
|
||||
<td className="px-4 py-2">
|
||||
<div className="font-medium">{m.model}</div>
|
||||
<div className="text-xs text-ink-3">
|
||||
{m.provider}
|
||||
{m.errors > 0 ? ` · ${plural(m.errors, 'failed request')}` : ''}
|
||||
</div>
|
||||
</td>
|
||||
<td className="num px-3 py-2 text-right">{m.calls}</td>
|
||||
<td className="num px-3 py-2 text-right">{formatTokens(m.input)}</td>
|
||||
<td className="num px-3 py-2 text-right">{formatTokens(m.output)}</td>
|
||||
<td className="num px-4 py-2 text-right">{m.unpriced > 0 && !m.cost ? 'no price set' : formatCost(m.cost)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 border-t border-line px-4 py-2.5 text-xs text-ink-3">
|
||||
{u.byTask.map((t: any) => (
|
||||
<span key={t.task}>
|
||||
{t.task}: <span className="num text-ink-2">{formatCost(t.cost)}</span> ({t.calls})
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{u.recentErrors.length > 0 && (
|
||||
<details className="border-t border-line">
|
||||
<summary className="px-4 py-2.5 text-[13px] font-medium text-bad">Recent errors ({u.recentErrors.length})</summary>
|
||||
<ul className="space-y-1.5 px-4 pb-3 text-[13px]">
|
||||
{u.recentErrors.map((e: any, i: number) => (
|
||||
<li key={i} className="text-ink-2">
|
||||
<span className="text-ink-3">{timeAgo(e.at)} · {e.model}:</span> {e.error}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-2 text-xs text-ink-3">Costs are estimates from token counts and the list prices on each model (editable). Your provider's bill is the source of truth.</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ page section ------------------------------ */
|
||||
|
||||
export default function AiSettings() {
|
||||
const { meta, providers, models, tasks, status, reload } = useAiData();
|
||||
const [dialog, setDialog] = useState<{ open: boolean; existing: Provider | null }>({ open: false, existing: null });
|
||||
const usable = (models.data ?? []).filter((m) => m.available);
|
||||
|
||||
const afterSave = async (p: Provider, isNew: boolean) => {
|
||||
await reload();
|
||||
// A new connection is tested and its models loaded straight away.
|
||||
try {
|
||||
const test = await api.post<{ result: { ok: boolean; message: string } }>(`/api/ai/providers/${p.id}/test`);
|
||||
if (!test.result.ok) {
|
||||
toast.error(test.result.message);
|
||||
} else {
|
||||
const found = await api.post<{ added: number; total: number }>(`/api/ai/providers/${p.id}/discover`).catch(() => null);
|
||||
toast.success(isNew ? `${p.name} connected${found ? `: ${plural(found.total, 'model')} found. Switch on the ones you want.` : ''}` : test.result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
await reload();
|
||||
};
|
||||
|
||||
const saveTask = async (name: TaskName | 'default', config: TaskConfig) => {
|
||||
try {
|
||||
await api.put('/api/ai/tasks', { [name]: config });
|
||||
await reload();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
if (!meta.data || !providers.data || !models.data || !tasks.data) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-24" />
|
||||
<Skeleton className="h-48" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{providers.data.length > 0 && usable.length === 0 && (
|
||||
<Callout tone="warn" icon={<CircleAlert />} title="No models are switched on" className="mb-5">
|
||||
Use "Find models" on a provider, then tick the models you want to use.
|
||||
</Callout>
|
||||
)}
|
||||
<Section
|
||||
title="Providers and models"
|
||||
action={
|
||||
<Button size="sm" variant="primary" icon={<Plus />} onClick={() => setDialog({ open: true, existing: null })}>
|
||||
Add provider
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{providers.data.length === 0 ? (
|
||||
<div className="card border-dashed">
|
||||
<EmptyState
|
||||
icon={<Brain />}
|
||||
title="Connect an AI model"
|
||||
action={
|
||||
<Button variant="primary" icon={<Plus />} onClick={() => setDialog({ open: true, existing: null })}>
|
||||
Add provider
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Study Desk works without AI. Connecting a model adds question and flashcard generation from your documents, explanations, and the assistant. You can connect several providers and use different models for different jobs.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{providers.data.map((p) => (
|
||||
<ProviderCard key={p.id} provider={p} models={models.data!.filter((m) => m.providerId === p.id)} adapter={meta.data!.adapters.find((a) => a.kind === p.kind)} onEdit={() => setDialog({ open: true, existing: p })} reload={reload} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-2.5 text-xs text-ink-3">
|
||||
API keys are encrypted on the server and never sent back to the browser. A ChatGPT, Claude or Gemini app subscription is separate from API access and cannot be used here: each provider bills API usage on its own.
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
{usable.length > 0 && (
|
||||
<Section title="Which model does what">
|
||||
<div className="card divide-y divide-line">
|
||||
<TaskRow name="default" label="Default model" description="Used for everything that has no model of its own below." config={tasks.data.default} models={usable} onChange={(c) => saveTask('default', c)} />
|
||||
{(Object.keys(meta.data.tasks) as TaskName[]).map((t) => (
|
||||
<TaskRow key={t} name={t} label={meta.data!.tasks[t].label} description={meta.data!.tasks[t].description} config={tasks.data![t]} models={usable} resolved={status.data?.resolved[t]?.label} onChange={(c) => saveTask(t, c)} />
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-2.5 text-xs text-ink-3">You can also pick a different model for a single draft from "More options" when generating.</p>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{providers.data.length > 0 && <Usage />}
|
||||
|
||||
<ProviderDialog open={dialog.open} onClose={() => setDialog((d) => ({ ...d, open: false }))} adapters={meta.data.adapters} existing={dialog.existing} onSaved={afterSave} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
496
web/src/features/AssistantPanel.tsx
Normal file
496
web/src/features/AssistantPanel.tsx
Normal file
|
|
@ -0,0 +1,496 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowUp, BookOpen, Check, ChevronRight, CircleAlert, FileText, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage, streamEvents } from '@/lib/api';
|
||||
import { assistant, useAssistantState } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, ToolActivity, UiItem } from '@/lib/types';
|
||||
import { cx, plural, timeAgo } from '@/lib/util';
|
||||
import { citedSources, Markdown, type Citation } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui';
|
||||
|
||||
interface Conversation {
|
||||
id: string;
|
||||
title: string;
|
||||
classId: string | null;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const;
|
||||
const DRAFT_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||
|
||||
/* ------------------------------ message parts ------------------------------ */
|
||||
|
||||
function ToolLine({ tool }: { tool: ToolActivity }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-[13px] text-ink-2">
|
||||
{tool.status === 'running' ? <LoaderCircle className="size-3.5 shrink-0 animate-spin text-accent" /> : tool.status === 'error' ? <CircleAlert className="size-3.5 shrink-0 text-bad" /> : <Check className="size-3.5 shrink-0 text-good" />}
|
||||
<span className="min-w-0 truncate">
|
||||
{tool.label}
|
||||
{tool.summary && <span className={cx('ml-1.5', tool.status === 'error' ? 'text-bad' : 'text-ink-3')}>· {tool.summary}</span>}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DraftCard({ item, onNavigate }: { item: Extract<UiItem, { type: 'draft' }>; onNavigate: () => void }) {
|
||||
const gone = item.status === 'discarded';
|
||||
const saved = item.status === 'saved';
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1">
|
||||
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-accent-soft text-accent [&>svg]:size-[18px]">{DRAFT_ICON[item.kind]}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-semibold">{item.title}</div>
|
||||
<div className="text-xs text-ink-3">
|
||||
{item.kind === 'note' ? 'Draft note' : `Draft · ${plural(item.count, item.kind === 'quiz' ? 'question' : 'card')}`}
|
||||
{saved ? ' · saved' : gone ? ' · discarded' : ' · not saved yet'}
|
||||
</div>
|
||||
</div>
|
||||
{!gone && (
|
||||
<Link to={`/drafts/${item.draftId}`} onClick={onNavigate}>
|
||||
<Button size="sm" variant={saved ? 'secondary' : 'primary'}>
|
||||
{saved ? 'Open' : 'Review'}
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionCard({ item, onResolved }: { item: Extract<UiItem, { type: 'action' }>; onResolved: (status: string, result: string) => void }) {
|
||||
const [busy, setBusy] = useState<'confirm' | 'cancel' | null>(null);
|
||||
const resolve = async (confirm: boolean) => {
|
||||
setBusy(confirm ? 'confirm' : 'cancel');
|
||||
try {
|
||||
const res = await api.post<{ status: string; result: string }>(`/api/ai/actions/${item.actionId}`, { confirm });
|
||||
onResolved(res.status, res.result);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
const destructive = item.changes.some((c) => c.startsWith('Delete'));
|
||||
return (
|
||||
<div className={cx('rounded-[14px] border bg-surface p-3.5 shadow-1', item.status === 'pending' ? 'border-warn/50' : 'border-line')}>
|
||||
<div className="text-sm font-semibold">{item.status === 'pending' ? 'Approve these changes?' : 'Proposed changes'}</div>
|
||||
<div className="mt-0.5 text-[13px] text-ink-2">{item.summary}</div>
|
||||
<ul className="mt-2 space-y-0.5 text-[13px]">
|
||||
{item.changes.map((c, i) => (
|
||||
<li key={i} className="flex gap-2">
|
||||
<span className="text-ink-3">•</span>
|
||||
<span>{c}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{item.status === 'pending' ? (
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Button size="sm" variant={destructive ? 'danger' : 'primary'} loading={busy === 'confirm'} disabled={busy !== null} onClick={() => resolve(true)}>
|
||||
Confirm
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" loading={busy === 'cancel'} disabled={busy !== null} onClick={() => resolve(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className={cx('mt-2.5 flex items-center gap-1.5 text-[13px] font-medium', item.status === 'confirmed' ? 'text-good' : item.status === 'failed' ? 'text-bad' : 'text-ink-3')}>
|
||||
{item.status === 'confirmed' ? <Check className="size-4" /> : <X className="size-4" />}
|
||||
{item.result ?? (item.status === 'confirmed' ? 'Done' : 'Cancelled')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void }) {
|
||||
const navigate = useNavigate();
|
||||
const [toolsOpen, setToolsOpen] = useState(false);
|
||||
const citations = useMemo<Citation[]>(() => message.ui.flatMap((u) => (u.type === 'sources' ? u.items : [])), [message.ui]);
|
||||
const cited = useMemo(() => citedSources(message.text, citations), [message.text, citations]);
|
||||
const openCite = (c: Citation) => {
|
||||
onNavigate();
|
||||
navigate(`/documents/${c.documentId}?chunk=${c.chunkId}`);
|
||||
};
|
||||
const cards = message.ui.filter((u) => u.type !== 'sources');
|
||||
const running = message.tools.filter((t) => t.status === 'running');
|
||||
const finished = message.tools.filter((t) => t.status !== 'running');
|
||||
const thinking = message.pending && !message.text && running.length === 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
{finished.length > 0 && (
|
||||
<div>
|
||||
<button type="button" aria-expanded={toolsOpen} onClick={() => setToolsOpen(!toolsOpen)} className="flex items-center gap-1 text-xs font-medium text-ink-3 hover:text-ink-2">
|
||||
<ChevronRight className={cx('size-3.5 transition-transform', toolsOpen && 'rotate-90')} />
|
||||
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
|
||||
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
|
||||
</button>
|
||||
{toolsOpen && <div className="mt-1.5 space-y-1 border-l-2 border-line pl-3">{finished.map((t) => <ToolLine key={t.id} tool={t} />)}</div>}
|
||||
</div>
|
||||
)}
|
||||
{running.map((t) => (
|
||||
<ToolLine key={t.id} tool={t} />
|
||||
))}
|
||||
{thinking && (
|
||||
<div className="flex items-center gap-2 text-[13px] text-ink-3" role="status">
|
||||
<Spinner className="size-3.5" label="Thinking" /> {message.reasoning ? 'Thinking it through' : 'Thinking'}
|
||||
</div>
|
||||
)}
|
||||
{message.text && <Markdown citations={citations} onCite={openCite} className="text-[15px]">{message.text}</Markdown>}
|
||||
{cards.map((item, i) =>
|
||||
item.type === 'draft' ? (
|
||||
<DraftCard key={i} item={item} onNavigate={onNavigate} />
|
||||
) : item.type === 'action' ? (
|
||||
<ActionCard key={i} item={item} onResolved={(status, result) => onAction(item.actionId, status, result)} />
|
||||
) : item.type === 'link' ? (
|
||||
<Link key={i} to={`/${ITEM_URL[item.kind]}/${item.id}`} onClick={onNavigate} className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1 hover:border-ink-3">
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-marker text-marker-ink">
|
||||
<Play className="size-4 fill-current" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{item.title}</span>
|
||||
<ChevronRight className="size-4 text-ink-3" />
|
||||
</Link>
|
||||
) : null,
|
||||
)}
|
||||
{cited.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 pt-0.5">
|
||||
{cited.map(({ n, cite }) => (
|
||||
<button key={cite.ref} type="button" onClick={() => openCite(cite)} className="flex max-w-full items-center gap-1.5 rounded-full border border-line bg-surface py-1 pr-2.5 pl-1 text-xs text-ink-2 hover:border-ink-3 hover:text-ink">
|
||||
<span className="num grid size-[18px] shrink-0 place-items-center rounded-full bg-accent-soft text-[10.5px] font-semibold text-accent">{n}</span>
|
||||
<FileText className="size-3 shrink-0" />
|
||||
<span className="truncate">{cite.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{message.error && (
|
||||
<Callout tone="bad" icon={<CircleAlert />} className="py-2.5">
|
||||
{message.error}
|
||||
</Callout>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ panel ------------------------------ */
|
||||
|
||||
export default function AssistantPanel({
|
||||
variant,
|
||||
headerAction,
|
||||
conversationId: routeConversationId,
|
||||
onConversationChange,
|
||||
}: {
|
||||
variant: 'drawer' | 'page';
|
||||
headerAction?: ReactNode;
|
||||
conversationId?: string;
|
||||
onConversationChange?: (id: string | null) => void;
|
||||
}) {
|
||||
const ai = useAiStatus();
|
||||
const classes = useClasses();
|
||||
const refresh = useRefresh();
|
||||
const qc = useQueryClient();
|
||||
const { seed, context } = useAssistantState();
|
||||
const [conversationId, setConversationId] = useState<string | null>(routeConversationId ?? null);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loadingHistory, setLoadingHistory] = useState(false);
|
||||
const [focusDocs, setFocusDocs] = useState<string[]>([]);
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const stick = useRef(true);
|
||||
const handledSeed = useRef(0);
|
||||
|
||||
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: Conversation[] }>('/api/ai/conversations').then((r) => r.conversations), staleTime: 30_000 });
|
||||
|
||||
const load = useCallback(async (id: string) => {
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
setMessages(res.messages);
|
||||
setConversationId(id);
|
||||
stick.current = true;
|
||||
} catch {
|
||||
setConversationId(null);
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId);
|
||||
if (!routeConversationId && variant === 'page' && conversationId && !busy) {
|
||||
setConversationId(null);
|
||||
setMessages([]);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [routeConversationId]);
|
||||
|
||||
const newChat = useCallback(() => {
|
||||
abort.current?.abort();
|
||||
setConversationId(null);
|
||||
setMessages([]);
|
||||
setFocusDocs([]);
|
||||
onConversationChange?.(null);
|
||||
setTimeout(() => inputRef.current?.focus(), 30);
|
||||
}, [onConversationChange]);
|
||||
|
||||
const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds;
|
||||
const className = classes.data?.find((c) => c.id === context.classId)?.name;
|
||||
|
||||
const send = useCallback(
|
||||
async (text: string, opts: { conversationId?: string | null; documentIds?: string[]; classId?: string | null } = {}) => {
|
||||
const message = text.trim();
|
||||
if (!message || busy) return;
|
||||
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationId;
|
||||
setBusy(true);
|
||||
setInput('');
|
||||
stick.current = true;
|
||||
const pendingId = `p${Date.now()}`;
|
||||
setMessages((m) => [...m, { id: `u${Date.now()}`, role: 'user', text: message, tools: [], ui: [], createdAt: Date.now() }, { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
|
||||
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
let newId: string | null = null;
|
||||
try {
|
||||
await streamEvents<AssistantEvent>(
|
||||
'/api/ai/chat',
|
||||
{ conversationId: convo, message, context: { classId: opts.classId !== undefined ? opts.classId : context.classId, documentIds: opts.documentIds ?? activeDocs } },
|
||||
(e) => {
|
||||
if (e.type === 'start') {
|
||||
newId = e.conversationId;
|
||||
patch((m) => ({ ...m, model: e.model }));
|
||||
} else if (e.type === 'text') patch((m) => ({ ...m, text: m.text + e.delta }));
|
||||
else if (e.type === 'reasoning') patch((m) => ({ ...m, reasoning: (m.reasoning ?? '') + e.delta }));
|
||||
else if (e.type === 'tool') patch((m) => ({ ...m, tools: m.tools.some((t) => t.id === e.tool.id) ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] }));
|
||||
else if (e.type === 'ui') patch((m) => ({ ...m, ui: [...m.ui, e.item] }));
|
||||
else if (e.type === 'error') patch((m) => ({ ...m, error: e.message }));
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') patch((m) => ({ ...m, error: errorMessage(e) }));
|
||||
} finally {
|
||||
patch((m) => ({ ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : controller.signal.aborted ? '*(Stopped.)*' : m.text) }));
|
||||
setBusy(false);
|
||||
if (newId && newId !== convo) {
|
||||
setConversationId(newId);
|
||||
onConversationChange?.(newId);
|
||||
}
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
// Tools may have created drafts, classes or sessions.
|
||||
void refresh();
|
||||
}
|
||||
},
|
||||
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh],
|
||||
);
|
||||
|
||||
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
|
||||
useEffect(() => {
|
||||
if (!seed || handledSeed.current === seed.id || !ai.data) return;
|
||||
handledSeed.current = seed.id;
|
||||
assistant.consumeSeed();
|
||||
if (seed.newChat) {
|
||||
abort.current?.abort();
|
||||
setConversationId(null);
|
||||
setMessages([]);
|
||||
onConversationChange?.(null);
|
||||
}
|
||||
setFocusDocs(seed.documentIds ?? []);
|
||||
if (seed.prompt && seed.autoSend && ai.data.ready) void send(seed.prompt, { conversationId: seed.newChat ? null : undefined, documentIds: seed.documentIds, classId: seed.classId });
|
||||
else {
|
||||
if (seed.prompt) setInput(seed.prompt);
|
||||
setTimeout(() => inputRef.current?.focus(), 60);
|
||||
}
|
||||
}, [seed, ai.data, send, onConversationChange]);
|
||||
|
||||
// Keep the newest content in view unless the user has scrolled up to read.
|
||||
useEffect(() => {
|
||||
const el = scroller.current;
|
||||
if (el && stick.current) el.scrollTop = el.scrollHeight;
|
||||
}, [messages]);
|
||||
useEffect(() => () => abort.current?.abort(), []);
|
||||
|
||||
const updateAction = (actionId: string, status: string, result: string) => {
|
||||
setMessages((list) => list.map((m) => ({ ...m, ui: m.ui.map((u) => (u.type === 'action' && u.actionId === actionId ? { ...u, status: status as typeof u.status, result } : u)) })));
|
||||
void refresh();
|
||||
};
|
||||
|
||||
const suggestions = useMemo(() => {
|
||||
if (activeDocs.length > 0) {
|
||||
return ['Summarise the key points of this document', 'Make flashcards from this, focusing on medications and adverse effects', 'Write 15 NCLEX-style questions from this', 'What are the most testable concepts here?'];
|
||||
}
|
||||
if (className) {
|
||||
return [`Create a 20-question NCLEX-style quiz using the documents in ${className}`, 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', `What should I focus on in ${className} this week?`, 'Make a study guide from all the documents in this class'];
|
||||
}
|
||||
return ['What should I study today?', 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', 'Explain the difference between left-sided and right-sided heart failure', 'Start a practice session with the questions I miss most'];
|
||||
}, [activeDocs.length, className]);
|
||||
|
||||
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-0')}>
|
||||
<span className="grid size-8 place-items-center rounded-[10px] bg-ink text-marker">
|
||||
<Sparkles className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-semibold">Assistant</div>
|
||||
<div className="truncate text-xs text-ink-3">{ai.data?.resolved.chat ? ai.data.resolved.chat.label : ai.data && !ai.data.ready ? 'Not set up' : ''}</div>
|
||||
</div>
|
||||
<IconButton label="New chat" size="sm" onClick={newChat}>
|
||||
<Plus />
|
||||
</IconButton>
|
||||
{variant === 'drawer' && (
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="History" size="sm" tooltip={false}>
|
||||
<History />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuLabel>Recent conversations</MenuLabel>
|
||||
{(history.data ?? []).length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3">Nothing yet</div>}
|
||||
{(history.data ?? []).slice(0, 12).map((c) => (
|
||||
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={timeAgo(c.updatedAt)}>
|
||||
{c.title}
|
||||
</MenuItem>
|
||||
))}
|
||||
{conversationId && (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
<MenuItem
|
||||
icon={<Trash2 />}
|
||||
danger
|
||||
onSelect={async () => {
|
||||
await api.del(`/api/ai/conversations/${conversationId}`).catch(() => undefined);
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
newChat();
|
||||
}}
|
||||
>
|
||||
Delete this conversation
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
)}
|
||||
{headerAction}
|
||||
</header>
|
||||
|
||||
<div
|
||||
ref={scroller}
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget;
|
||||
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
|
||||
}}
|
||||
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-1')}
|
||||
aria-live="polite"
|
||||
>
|
||||
{ai.isLoading || loadingHistory ? (
|
||||
<div className="grid h-full place-items-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
) : !ai.data?.ready ? (
|
||||
<div className="mx-auto max-w-sm pt-8">
|
||||
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model to use the assistant">
|
||||
Add a provider such as OpenAI, Anthropic, Google Gemini or a local model, then switch on a model.
|
||||
<div className="mt-3">
|
||||
<Link to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()}>
|
||||
<Button size="sm" variant="primary">
|
||||
Open AI settings
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</Callout>
|
||||
</div>
|
||||
) : messages.length === 0 ? (
|
||||
<div className="mx-auto flex h-full max-w-md flex-col justify-center pb-6">
|
||||
<h2 className="display text-[26px]">What are we working on?</h2>
|
||||
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review.</p>
|
||||
<div className="mt-5 space-y-2">
|
||||
{suggestions.map((s) => (
|
||||
<button key={s} type="button" onClick={() => send(s)} className="group flex w-full items-center gap-3 rounded-[13px] border border-line bg-surface px-3.5 py-2.5 text-left text-sm shadow-1 hover:border-ink-3">
|
||||
<span className="flex-1">{s}</span>
|
||||
<ArrowUp className="size-4 shrink-0 rotate-45 text-ink-3 group-hover:text-ink" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
{messages.map((m) =>
|
||||
m.role === 'user' ? (
|
||||
<div key={m.id} className="flex justify-end">
|
||||
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">{m.text}</div>
|
||||
</div>
|
||||
) : (
|
||||
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && undefined} onAction={updateAction} />
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ai.data?.ready && (
|
||||
<div className={cx('safe-bottom shrink-0 border-t border-line px-3 pt-2.5 pb-3', variant === 'page' && 'lg:px-0')}>
|
||||
<div className="mx-auto max-w-2xl">
|
||||
{contextLabel && (
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<Badge tone="accent" className="max-w-full">
|
||||
{activeDocs.length > 0 ? <FileText /> : <BookOpen />}
|
||||
<span className="truncate">Looking at: {contextLabel}</span>
|
||||
</Badge>
|
||||
{focusDocs.length > 0 && (
|
||||
<button type="button" className="text-xs text-ink-3 hover:text-ink" onClick={() => setFocusDocs([])}>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="flex items-end gap-2 rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (busy) abort.current?.abort();
|
||||
else void send(input);
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
rows={1}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
e.target.style.height = 'auto';
|
||||
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
if (!busy) void send(input);
|
||||
}
|
||||
}}
|
||||
placeholder="Ask anything, or describe what to create…"
|
||||
aria-label="Message the assistant"
|
||||
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!busy && !input.trim()}
|
||||
aria-label={busy ? 'Stop' : 'Send'}
|
||||
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
|
||||
>
|
||||
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
110
web/src/features/Explain.tsx
Normal file
110
web/src/features/Explain.tsx
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import { CornerDownLeft, Sparkles, Square } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { errorMessage, streamEvents } from '@/lib/api';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, Callout, Spinner } from '@/ui';
|
||||
|
||||
type ExplainBody =
|
||||
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string }
|
||||
| { kind: 'card'; front: string; back: string }
|
||||
| { kind: 'text'; text: string };
|
||||
|
||||
type Event = { type: 'text'; delta: string } | { type: 'error'; message: string } | { type: 'done' };
|
||||
|
||||
/** "Explain with AI": streams a short explanation and accepts follow-up questions. */
|
||||
export function Explain({ body, label = 'Explain with AI', className }: { body: ExplainBody; label?: string; className?: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [turns, setTurns] = useState<{ ask?: string; text: string }[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [ask, setAsk] = useState('');
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
const key = JSON.stringify(body);
|
||||
|
||||
useEffect(() => {
|
||||
// A different question: start over.
|
||||
abort.current?.abort();
|
||||
setOpen(false);
|
||||
setTurns([]);
|
||||
setError('');
|
||||
setAsk('');
|
||||
}, [key]);
|
||||
useEffect(() => () => abort.current?.abort(), []);
|
||||
|
||||
const run = async (question?: string) => {
|
||||
setOpen(true);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setTurns((t) => [...t, { ask: question, text: '' }]);
|
||||
const controller = new AbortController();
|
||||
abort.current = controller;
|
||||
try {
|
||||
await streamEvents<Event>(
|
||||
'/api/ai/explain',
|
||||
{ ...body, ask: question },
|
||||
(e) => {
|
||||
if (e.type === 'text') setTurns((t) => t.map((x, i) => (i === t.length - 1 ? { ...x, text: x.text + e.delta } : x)));
|
||||
else if (e.type === 'error') setError(e.message);
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<Button size="sm" variant="ghost" icon={<Sparkles />} className={className} onClick={() => run()}>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={className}>
|
||||
<div className="rounded-xl border border-accent/25 bg-accent-soft/50 p-4">
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5 text-accent">
|
||||
<Sparkles className="size-3.5" /> AI explanation
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{turns.map((t, i) => (
|
||||
<div key={i}>
|
||||
{t.ask && <div className="mb-1 text-[13px] font-medium text-ink-2">{t.ask}</div>}
|
||||
{t.text ? <Markdown className="text-[14.5px]">{t.text}</Markdown> : busy && i === turns.length - 1 ? <Spinner className="size-4" label="Thinking" /> : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<Callout tone="bad" className="mt-3 py-2">
|
||||
{error}
|
||||
</Callout>
|
||||
)}
|
||||
<form
|
||||
className="mt-3 flex gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (busy) return abort.current?.abort();
|
||||
const question = ask.trim();
|
||||
if (!question) return;
|
||||
setAsk('');
|
||||
void run(question);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={ask}
|
||||
onChange={(e) => setAsk(e.target.value)}
|
||||
placeholder="Ask a follow-up…"
|
||||
aria-label="Follow-up question"
|
||||
className="h-9 min-w-0 flex-1 rounded-[9px] border border-line-strong bg-surface px-3 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
<Button type="submit" size="sm" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Ask'}>
|
||||
{busy ? 'Stop' : 'Ask'}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="mt-2 text-[11px] text-ink-3">AI can be wrong. Check anything important against your course material.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
321
web/src/features/GenerateDialog.tsx
Normal file
321
web/src/features/GenerateDialog.tsx
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, FileText, Layers, NotebookPen, Sparkles, Target } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk, useAiModels, useAiStatus, useClass } from '@/lib/queries';
|
||||
import type { DocumentItem, Template } from '@/lib/types';
|
||||
import { cx, formatTokens } from '@/lib/util';
|
||||
import { Button, Callout, Dialog, Field, Input, Segmented, Select, Textarea } from '@/ui';
|
||||
|
||||
export interface GeneratePreset {
|
||||
kind?: 'quiz' | 'deck' | 'note';
|
||||
documentIds?: string[];
|
||||
deckId?: string;
|
||||
quizId?: string;
|
||||
noteId?: string;
|
||||
weakAreas?: boolean;
|
||||
focus?: string;
|
||||
/** Label for a fixed source (conversion), shown instead of the source picker. */
|
||||
sourceLabel?: string;
|
||||
}
|
||||
|
||||
type SourceMode = 'documents' | 'text' | 'topic' | 'weak';
|
||||
|
||||
export function GenerateDialog({ open, onClose, classId, folderId, preset }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null; preset?: GeneratePreset }) {
|
||||
const navigate = useNavigate();
|
||||
const ai = useAiStatus();
|
||||
const models = useAiModels();
|
||||
const cls = useClass(open ? classId : undefined);
|
||||
const templates = useQuery({ queryKey: [...qk.templates, 'generation'], queryFn: () => api.get<{ templates: Template[] }>('/api/templates?kind=generation').then((r) => r.templates), enabled: open });
|
||||
|
||||
const [kind, setKind] = useState<'quiz' | 'deck' | 'note'>('quiz');
|
||||
const [mode, setMode] = useState<SourceMode>('documents');
|
||||
const [docIds, setDocIds] = useState<string[]>([]);
|
||||
const [text, setText] = useState('');
|
||||
const [focus, setFocus] = useState('');
|
||||
const [count, setCount] = useState(15);
|
||||
const [style, setStyle] = useState<'nclex' | 'standard' | 'recall'>('nclex');
|
||||
const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed');
|
||||
const [sata, setSata] = useState(30);
|
||||
const [cardStyle, setCardStyle] = useState<'concise' | 'detailed' | 'medication' | 'definition'>('concise');
|
||||
const [noteStyle, setNoteStyle] = useState<'study_guide' | 'summary' | 'outline' | 'cheat_sheet'>('study_guide');
|
||||
const [instructions, setInstructions] = useState('');
|
||||
const [modelId, setModelId] = useState('');
|
||||
const [templateId, setTemplateId] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const docs = useMemo(() => (cls.data?.items.filter((i): i is DocumentItem => i.kind === 'document') ?? []).filter((d) => d.status === 'ready' && d.tokenCount > 0), [cls.data]);
|
||||
const fixedSource = Boolean(preset?.deckId || preset?.quizId || preset?.noteId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const k = preset?.kind ?? 'quiz';
|
||||
setKind(k);
|
||||
setDocIds(preset?.documentIds ?? []);
|
||||
setMode(preset?.weakAreas ? 'weak' : 'documents');
|
||||
setFocus(preset?.focus ?? '');
|
||||
setText('');
|
||||
setInstructions('');
|
||||
setTemplateId('');
|
||||
setModelId('');
|
||||
setCount(k === 'deck' ? 30 : 15);
|
||||
setStyle('nclex');
|
||||
setDifficulty('mixed');
|
||||
setSata(30);
|
||||
setCardStyle('concise');
|
||||
setNoteStyle('study_guide');
|
||||
}, [open, preset]);
|
||||
|
||||
// With no usable documents, default to describing a topic.
|
||||
useEffect(() => {
|
||||
if (open && cls.isSuccess && docs.length === 0 && mode === 'documents' && !fixedSource) setMode('topic');
|
||||
}, [open, cls.isSuccess, docs.length, mode, fixedSource]);
|
||||
|
||||
const applyTemplate = (id: string) => {
|
||||
setTemplateId(id);
|
||||
const t = templates.data?.find((x) => x.id === id);
|
||||
if (!t) return;
|
||||
const p = t.payload;
|
||||
if (p.kind && !preset?.kind) setKind(p.kind);
|
||||
if (typeof p.count === 'number') setCount(p.count);
|
||||
if (p.style) setStyle(p.style);
|
||||
if (p.difficulty) setDifficulty(p.difficulty);
|
||||
if (typeof p.sataShare === 'number') setSata(Math.round(p.sataShare * 100));
|
||||
if (p.cardStyle) setCardStyle(p.cardStyle);
|
||||
if (p.noteStyle) setNoteStyle(p.noteStyle);
|
||||
setInstructions(typeof p.instructions === 'string' ? p.instructions : '');
|
||||
};
|
||||
|
||||
const selectedTokens = docs.filter((d) => docIds.includes(d.id)).reduce((n, d) => n + d.tokenCount, 0);
|
||||
const canSubmit =
|
||||
fixedSource || (mode === 'documents' && docIds.length > 0) || (mode === 'text' && text.trim().length > 20) || (mode === 'topic' && focus.trim().length > 2) || mode === 'weak';
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const source: Record<string, unknown> = {};
|
||||
if (preset?.deckId) source.deckId = preset.deckId;
|
||||
else if (preset?.quizId) source.quizId = preset.quizId;
|
||||
else if (preset?.noteId) source.noteId = preset.noteId;
|
||||
else if (mode === 'documents') source.documentIds = docIds;
|
||||
else if (mode === 'text') source.text = text;
|
||||
else if (mode === 'weak') source.weakAreas = true;
|
||||
const body: Record<string, unknown> = { kind, classId, folderId: folderId ?? null, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
|
||||
if (kind === 'quiz') Object.assign(body, { count, style, difficulty, sataShare: sata / 100 });
|
||||
else if (kind === 'deck') Object.assign(body, { count, cardStyle });
|
||||
else Object.assign(body, { noteStyle });
|
||||
if (fixedSource && kind !== 'note') delete body.count;
|
||||
const res = await api.post<{ draftId: string }>('/api/ai/generate', body);
|
||||
onClose();
|
||||
navigate(`/drafts/${res.draftId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const kinds = [
|
||||
{ value: 'quiz' as const, label: 'Quiz', icon: <BookOpen /> },
|
||||
{ value: 'deck' as const, label: 'Flashcards', icon: <Layers /> },
|
||||
{ value: 'note' as const, label: 'Study guide', icon: <NotebookPen /> },
|
||||
];
|
||||
const usable = (models.data ?? []).filter((m) => m.available);
|
||||
const defaultModel = ai.data?.resolved.generate;
|
||||
const relevantTemplates = (templates.data ?? []).filter((t) => t.payload.kind === kind);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Generate with AI"
|
||||
description="You will get a draft to review and edit. Nothing is saved until you say so."
|
||||
size="lg"
|
||||
footer={
|
||||
ai.data?.ready ? (
|
||||
<>
|
||||
<span className="mr-auto hidden text-xs text-ink-3 sm:block">{defaultModel && !modelId ? `Using ${defaultModel.label}` : ''}</span>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" icon={<Sparkles />} loading={busy} disabled={!canSubmit} onClick={submit}>
|
||||
Generate draft
|
||||
</Button>
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{ai.isLoading ? null : !ai.data?.ready ? (
|
||||
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model first">
|
||||
Add a provider (OpenAI, Anthropic, Gemini, or a local model) and switch on at least one model.
|
||||
<div className="mt-3">
|
||||
<Link to="/settings/ai" onClick={onClose}>
|
||||
<Button variant="primary" size="sm">
|
||||
Open AI settings
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</Callout>
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
{!preset?.kind && <Segmented label="What to create" value={kind} onChange={(k) => (setKind(k), setCount(k === 'deck' ? 30 : 15), setTemplateId(''))} options={kinds} className="w-full" />}
|
||||
|
||||
{fixedSource ? (
|
||||
<Callout icon={preset?.deckId ? <Layers /> : preset?.quizId ? <BookOpen /> : <NotebookPen />}>
|
||||
Source: <strong className="text-ink">{preset?.sourceLabel}</strong>
|
||||
</Callout>
|
||||
) : (
|
||||
<div>
|
||||
<div className="mb-2 text-[13px] font-medium">Based on</div>
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
{(
|
||||
[
|
||||
{ v: 'documents', label: 'Documents', icon: <FileText />, hint: docs.length ? `${docs.length} ready` : 'None yet' },
|
||||
{ v: 'text', label: 'Pasted notes', icon: <NotebookPen />, hint: 'Paste text' },
|
||||
{ v: 'topic', label: 'A topic', icon: <Sparkles />, hint: 'No source' },
|
||||
{ v: 'weak', label: 'Weak areas', icon: <Target />, hint: 'From results' },
|
||||
] as const
|
||||
).map((o) => (
|
||||
<button
|
||||
key={o.v}
|
||||
type="button"
|
||||
disabled={o.v === 'documents' && docs.length === 0}
|
||||
aria-pressed={mode === o.v}
|
||||
onClick={() => setMode(o.v)}
|
||||
className={cx(
|
||||
'rounded-xl border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-45',
|
||||
mode === o.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3',
|
||||
)}
|
||||
>
|
||||
<span className={cx('mb-1 block [&>svg]:size-4', mode === o.v ? 'text-accent' : 'text-ink-3')}>{o.icon}</span>
|
||||
<span className="block text-sm font-medium">{o.label}</span>
|
||||
<span className="block text-xs text-ink-3">{o.hint}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{mode === 'documents' && (
|
||||
<div className="mt-3">
|
||||
<div className="max-h-44 overflow-y-auto rounded-xl border border-line">
|
||||
{docs.map((d) => (
|
||||
<label key={d.id} className="flex cursor-pointer items-center gap-3 border-b border-line px-3 py-2 last:border-0 hover:bg-ink/4">
|
||||
<input type="checkbox" className="size-4 accent-[var(--accent)]" checked={docIds.includes(d.id)} onChange={(e) => setDocIds((ids) => (e.target.checked ? [...ids, d.id] : ids.filter((x) => x !== d.id)))} />
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{d.title}</span>
|
||||
<span className="num shrink-0 text-xs text-ink-3">{d.pageCount ? `${d.pageCount} p · ` : ''}~{formatTokens(d.tokenCount)} tokens</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1.5 flex items-center justify-between text-xs text-ink-3">
|
||||
<button type="button" className="font-medium text-accent hover:underline" onClick={() => setDocIds(docIds.length === docs.length ? [] : docs.map((d) => d.id))}>
|
||||
{docIds.length === docs.length ? 'Clear selection' : 'Select all'}
|
||||
</button>
|
||||
{selectedTokens > 0 && <span>~{formatTokens(selectedTokens)} tokens selected. Long material is read in parts automatically.</span>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{mode === 'text' && <Textarea className="mt-3" rows={6} value={text} onChange={(e) => setText(e.target.value)} placeholder="Paste lecture notes, a chapter summary, or anything you want turned into study material." aria-label="Pasted notes" />}
|
||||
{mode === 'weak' && (
|
||||
<Callout className="mt-3" icon={<Target />}>
|
||||
Uses the questions you have missed most in this class, plus matching passages from its documents, to write new {kind === 'deck' ? 'cards' : kind === 'note' ? 'review notes' : 'questions'} on the same concepts.
|
||||
</Callout>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Field label={mode === 'topic' && !fixedSource ? 'Topic' : 'Focus'} optional={!(mode === 'topic' && !fixedSource)} hint={mode === 'documents' && !fixedSource ? 'Narrows a long document to the relevant sections.' : undefined}>
|
||||
<Input value={focus} onChange={(e) => setFocus(e.target.value)} placeholder={kind === 'deck' ? 'Medications and adverse effects' : 'Pediatric respiratory disorders'} maxLength={600} />
|
||||
</Field>
|
||||
|
||||
{relevantTemplates.length > 0 && (
|
||||
<Field label="Preset" optional hint={relevantTemplates.find((t) => t.id === templateId)?.description}>
|
||||
<Select value={templateId} onChange={(e) => applyTemplate(e.target.value)}>
|
||||
<option value="">Custom</option>
|
||||
{relevantTemplates.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{kind === 'quiz' && (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{!fixedSource && (
|
||||
<Field label="Questions">
|
||||
<Input type="number" min={1} max={100} value={count} onChange={(e) => setCount(Math.max(1, Math.min(100, Number(e.target.value) || 1)))} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Style">
|
||||
<Select value={style} onChange={(e) => setStyle(e.target.value as typeof style)}>
|
||||
<option value="nclex">NCLEX-style (clinical judgment)</option>
|
||||
<option value="standard">Standard exam questions</option>
|
||||
<option value="recall">Quick recall</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Difficulty">
|
||||
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>
|
||||
<option value="mixed">Mixed</option>
|
||||
<option value="easy">Easy</option>
|
||||
<option value="medium">Medium</option>
|
||||
<option value="hard">Hard</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label={`Select-all-that-apply: ${sata}%`}>
|
||||
<input type="range" min={0} max={100} step={10} value={sata} onChange={(e) => setSata(Number(e.target.value))} className="mt-2.5 w-full accent-[var(--accent)]" />
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
{kind === 'deck' && (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{!fixedSource && (
|
||||
<Field label="Cards">
|
||||
<Input type="number" min={1} max={200} value={count} onChange={(e) => setCount(Math.max(1, Math.min(200, Number(e.target.value) || 1)))} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Card style">
|
||||
<Select value={cardStyle} onChange={(e) => setCardStyle(e.target.value as typeof cardStyle)}>
|
||||
<option value="concise">Concise (one fact per card)</option>
|
||||
<option value="detailed">Detailed (short bullet lists)</option>
|
||||
<option value="medication">Medication cards</option>
|
||||
<option value="definition">Terms and definitions</option>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
{kind === 'note' && (
|
||||
<Field label="Format">
|
||||
<Select value={noteStyle} onChange={(e) => setNoteStyle(e.target.value as typeof noteStyle)}>
|
||||
<option value="study_guide">Study guide</option>
|
||||
<option value="summary">Summary</option>
|
||||
<option value="outline">Outline</option>
|
||||
<option value="cheat_sheet">Cheat sheet</option>
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
<details className="group rounded-xl border border-line">
|
||||
<summary className="px-3.5 py-2.5 text-sm font-medium text-ink-2 hover:text-ink">More options</summary>
|
||||
<div className="space-y-4 border-t border-line p-3.5">
|
||||
<Field label="Extra instructions" optional>
|
||||
<Textarea rows={2} value={instructions} onChange={(e) => setInstructions(e.target.value)} placeholder="Emphasise prioritisation. Include lab values with units." maxLength={4000} />
|
||||
</Field>
|
||||
<Field label="Model" hint="Overrides the model chosen for content generation in Settings, for this draft only.">
|
||||
<Select value={modelId} onChange={(e) => setModelId(e.target.value)}>
|
||||
<option value="">Default{defaultModel ? ` (${defaultModel.label})` : ''}</option>
|
||||
{usable.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.label} · {m.providerName}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
242
web/src/features/ImportDialog.tsx
Normal file
242
web/src/features/ImportDialog.tsx
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
import { BookOpen, CircleAlert, CircleCheck, FileUp, Layers, NotebookPen, TriangleAlert } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import type { ContentDraft } from '@shared/content';
|
||||
import { DECK_JSON_TEMPLATE, parseImport, QUIZ_JSON_TEMPLATE, summarizeIssues, TEXT_CARDS_TEMPLATE, TEXT_QUIZ_TEMPLATE } from '@shared/importer';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useRefresh } from '@/lib/queries';
|
||||
import type { Draft } from '@/lib/types';
|
||||
import { cx, downloadText, plural, useDebounced } from '@/lib/util';
|
||||
import { Badge, Button, Callout, Dialog, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Textarea } from '@/ui';
|
||||
|
||||
const KIND_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||
const DETECTED = { json: 'JSON', 'text-quiz': 'Question blocks', 'text-cards': 'Term and definition list', none: '' };
|
||||
|
||||
export function ImportDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const [text, setText] = useState('');
|
||||
const [filename, setFilename] = useState('');
|
||||
const [titles, setTitles] = useState<Record<number, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const debounced = useDebounced(text, 250);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setText('');
|
||||
setFilename('');
|
||||
setTitles({});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const parsed = useMemo(() => {
|
||||
if (!debounced.trim()) return null;
|
||||
const fallbackTitle = filename ? filename.replace(/\.[^.]+$/, '').replace(/[._-]+/g, ' ') : undefined;
|
||||
return parseImport(debounced, { fallbackTitle });
|
||||
}, [debounced, filename]);
|
||||
|
||||
const items = useMemo(
|
||||
() =>
|
||||
(parsed?.items ?? []).map((raw, i) => {
|
||||
const draft = { ...raw, title: titles[i] ?? raw.title } as ContentDraft;
|
||||
const summary = summarizeIssues(draft);
|
||||
const count = draft.kind === 'quiz' ? draft.questions.length : draft.kind === 'deck' ? draft.cards.length : 1;
|
||||
const badItems = new Set(summary.issues.filter((x) => x.level === 'error' && x.index !== undefined).map((x) => x.index)).size;
|
||||
return { draft, summary, count, badItems, titleMissing: !draft.title.trim() };
|
||||
}),
|
||||
[parsed, titles],
|
||||
);
|
||||
const importable = items.filter((x) => x.summary.errors === 0);
|
||||
const blocked = items.length - importable.length;
|
||||
|
||||
const readFile = async (file: File) => {
|
||||
if (file.size > 20 * 1024 * 1024) return toast.error('That file is larger than 20 MB.');
|
||||
setFilename(file.name);
|
||||
setText(await file.text());
|
||||
setTitles({});
|
||||
};
|
||||
|
||||
const review = async (draft: ContentDraft) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.post<{ draft: Draft }>('/api/drafts', { payload: draft, classId, folderId });
|
||||
onClose();
|
||||
navigate(`/drafts/${res.draft.id}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const importAll = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.post<{ created: { kind: string; id: string; title: string }[] }>('/api/import', { classId, folderId, items: importable.map((x) => x.draft) });
|
||||
await refresh();
|
||||
toast.success(`Imported ${plural(res.created.length, 'item')}`);
|
||||
onClose();
|
||||
if (res.created.length === 1) {
|
||||
const c = res.created[0];
|
||||
navigate(`/${c.kind === 'quiz' ? 'quizzes' : c.kind === 'deck' ? 'decks' : 'notes'}/${c.id}`);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const insertTemplate = (t: string) => {
|
||||
setText(t);
|
||||
setFilename('');
|
||||
setTitles({});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Import"
|
||||
description="Paste content or drop a file. You will see exactly what was understood before anything is saved."
|
||||
size="lg"
|
||||
footer={
|
||||
<>
|
||||
<Menu
|
||||
align="start"
|
||||
side="top"
|
||||
trigger={
|
||||
<Button variant="ghost" className="mr-auto">
|
||||
Templates
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<MenuLabel>Insert an example</MenuLabel>
|
||||
<MenuItem onSelect={() => insertTemplate(QUIZ_JSON_TEMPLATE)}>Quiz (JSON)</MenuItem>
|
||||
<MenuItem onSelect={() => insertTemplate(DECK_JSON_TEMPLATE)}>Flashcards (JSON)</MenuItem>
|
||||
<MenuItem onSelect={() => insertTemplate(TEXT_QUIZ_TEMPLATE)}>Questions (plain text)</MenuItem>
|
||||
<MenuItem onSelect={() => insertTemplate(TEXT_CARDS_TEMPLATE)}>Flashcards (tab separated)</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>Download</MenuLabel>
|
||||
<MenuItem onSelect={() => downloadText('quiz-template.json', QUIZ_JSON_TEMPLATE)}>quiz-template.json</MenuItem>
|
||||
<MenuItem onSelect={() => downloadText('flashcards-template.json', DECK_JSON_TEMPLATE)}>flashcards-template.json</MenuItem>
|
||||
</Menu>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} disabled={importable.length === 0 || importable.some((x) => x.titleMissing)} onClick={importAll}>
|
||||
{importable.length > 0 ? `Import ${plural(importable.length, 'item')}` : 'Import'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cx('relative rounded-xl', dragging && 'ring-2 ring-accent ring-offset-2 ring-offset-surface')}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragging(false);
|
||||
const f = e.dataTransfer.files[0];
|
||||
if (f) void readFile(f);
|
||||
}}
|
||||
>
|
||||
<Textarea
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
setTitles({});
|
||||
}}
|
||||
rows={9}
|
||||
spellCheck={false}
|
||||
aria-label="Content to import"
|
||||
placeholder={'Paste JSON, question blocks, or a term/definition list…\n\n1. Which finding needs immediate action?\nA. Heart rate 88\n*B. Oxygen saturation 84%\nRationale: …'}
|
||||
className="num min-h-44 text-[13px] leading-relaxed"
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-ink-3">
|
||||
<input ref={fileRef} type="file" accept=".json,.txt,.md,.csv,.tsv,application/json,text/*" hidden onChange={(e) => e.target.files?.[0] && readFile(e.target.files[0]).then(() => (e.target.value = ''))} />
|
||||
<Button size="sm" icon={<FileUp />} onClick={() => fileRef.current?.click()}>
|
||||
Choose file
|
||||
</Button>
|
||||
<span>{filename ? filename : 'or drop a .json, .txt or .csv file here. Study Desk V1 exports work too.'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{parsed && (
|
||||
<div className="mt-5 space-y-3" aria-live="polite">
|
||||
{parsed.notices.map((n, i) => (
|
||||
<Callout key={i} tone={n.level === 'error' ? 'bad' : 'warn'} icon={n.level === 'error' ? <CircleAlert /> : <TriangleAlert />} className="py-2.5">
|
||||
{n.message}
|
||||
</Callout>
|
||||
))}
|
||||
{items.length > 0 && (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="eyebrow">
|
||||
Found {plural(items.length, 'item')}
|
||||
{parsed.detected !== 'none' ? ` · ${DETECTED[parsed.detected]}` : ''}
|
||||
</span>
|
||||
{blocked > 0 && <span className="text-xs text-bad">{plural(blocked, 'item')} need fixing</span>}
|
||||
</div>
|
||||
<ul className="divide-y divide-line rounded-xl border border-line">
|
||||
{items.map((it, i) => (
|
||||
<li key={i} className="p-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-sunken text-ink-2 [&>svg]:size-4">{KIND_ICON[it.draft.kind]}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Input
|
||||
value={it.draft.title}
|
||||
onChange={(e) => setTitles((t) => ({ ...t, [i]: e.target.value }))}
|
||||
placeholder="Give this a title"
|
||||
aria-label="Title"
|
||||
aria-invalid={it.titleMissing}
|
||||
className="h-8 border-transparent bg-transparent px-1.5 font-medium shadow-none hover:border-line-strong focus:bg-surface"
|
||||
/>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-1.5 px-1.5 text-xs text-ink-3">
|
||||
<span>{it.draft.kind === 'quiz' ? plural(it.count, 'question') : it.draft.kind === 'deck' ? plural(it.count, 'card') : 'Note'}</span>
|
||||
{it.summary.errors === 0 ? (
|
||||
<Badge tone="good">
|
||||
<CircleCheck /> Ready
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge tone="bad">
|
||||
<CircleAlert /> {it.badItems > 0 ? `${it.badItems} with problems` : plural(it.summary.errors, 'problem')}
|
||||
</Badge>
|
||||
)}
|
||||
{it.summary.warnings > 0 && <Badge tone="warn">{plural(it.summary.warnings, 'note')}</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" variant={it.summary.errors > 0 ? 'primary' : 'secondary'} onClick={() => review(it.draft)} disabled={busy}>
|
||||
{it.summary.errors > 0 ? 'Fix' : 'Review'}
|
||||
</Button>
|
||||
</div>
|
||||
{it.summary.errors > 0 && (
|
||||
<ul className="mt-2 space-y-0.5 pl-12 text-[13px] text-bad">
|
||||
{it.summary.issues
|
||||
.filter((x) => x.level === 'error')
|
||||
.slice(0, 4)
|
||||
.map((x, k) => (
|
||||
<li key={k}>
|
||||
{x.index !== undefined ? `${it.draft.kind === 'quiz' ? 'Question' : 'Card'} ${x.index + 1}: ` : ''}
|
||||
{x.message}
|
||||
</li>
|
||||
))}
|
||||
{it.summary.errors > 4 && <li className="text-ink-3">and {it.summary.errors - 4} more. Open "Fix" to correct them.</li>}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
162
web/src/features/charts.tsx
Normal file
162
web/src/features/charts.tsx
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { useMemo } from 'react';
|
||||
import type { DayActivity } from '@/lib/types';
|
||||
import { cx } from '@/lib/util';
|
||||
import { Tooltip } from '@/ui';
|
||||
|
||||
/** GitHub-style activity grid. Weeks run left to right, days top to bottom (Sunday first). */
|
||||
export function Heatmap({ days, goal, weeks = 26, className }: { days: DayActivity[]; goal: number; weeks?: number; className?: string }) {
|
||||
const { columns, months } = useMemo(() => {
|
||||
const recent = days.slice(-weeks * 7 - 6);
|
||||
// Pad the front so the first column starts on a Sunday.
|
||||
const first = recent[0] ? new Date(`${recent[0].date}T12:00:00Z`).getUTCDay() : 0;
|
||||
const cells: (DayActivity | null)[] = [...Array<null>(first).fill(null), ...recent];
|
||||
const cols: (DayActivity | null)[][] = [];
|
||||
for (let i = 0; i < cells.length; i += 7) cols.push(cells.slice(i, i + 7));
|
||||
const trimmed = cols.slice(-weeks);
|
||||
const labels: { index: number; label: string }[] = [];
|
||||
let last = -1;
|
||||
trimmed.forEach((col, i) => {
|
||||
const d = col.find(Boolean);
|
||||
if (!d) return;
|
||||
const month = Number(d.date.slice(5, 7));
|
||||
if (month !== last) {
|
||||
last = month;
|
||||
if (i < trimmed.length - 1) labels.push({ index: i, label: new Date(`${d.date}T12:00:00Z`).toLocaleDateString(undefined, { month: 'short', timeZone: 'UTC' }) });
|
||||
}
|
||||
});
|
||||
return { columns: trimmed, months: labels };
|
||||
}, [days, weeks]);
|
||||
|
||||
const level = (total: number) => (total === 0 ? 0 : total < goal * 0.5 ? 1 : total < goal ? 2 : total < goal * 2.5 ? 3 : 4);
|
||||
const shade = ['bg-ink/6', 'bg-accent/25', 'bg-accent/45', 'bg-accent/75', 'bg-accent'];
|
||||
|
||||
return (
|
||||
<div className={cx('overflow-x-auto', className)}>
|
||||
<div className="inline-block min-w-full">
|
||||
<div className="relative mb-1 h-4 text-[10px] text-ink-3" aria-hidden>
|
||||
{months.map((m) => (
|
||||
<span key={m.index} className="absolute" style={{ left: `calc(${m.index} * (100% / ${columns.length}))` }}>
|
||||
{m.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid gap-[3px]" style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(9px, 1fr))` }} role="img" aria-label={`Study activity for the last ${weeks} weeks`}>
|
||||
{columns.map((col, ci) => (
|
||||
<div key={ci} className="grid grid-rows-7 gap-[3px]">
|
||||
{Array.from({ length: 7 }, (_, ri) => {
|
||||
const d = col[ri];
|
||||
if (!d) return <span key={ri} className="aspect-square" />;
|
||||
const label = `${new Date(`${d.date}T12:00:00Z`).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' })}: ${d.total === 0 ? 'no study' : `${d.cards} cards, ${d.questions} questions`}`;
|
||||
return (
|
||||
<Tooltip key={ri} label={label} side="top">
|
||||
<span className={cx('aspect-square rounded-[3px]', shade[level(d.total)])} />
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Circular progress with content in the middle. */
|
||||
export function Ring({ value, size = 64, stroke = 6, children, tone = 'accent' }: { value: number; size?: number; stroke?: number; children?: React.ReactNode; tone?: 'accent' | 'good' | 'warn' | 'bad' | 'marker' }) {
|
||||
const r = (size - stroke) / 2;
|
||||
const c = 2 * Math.PI * r;
|
||||
const v = Math.max(0, Math.min(1, value));
|
||||
const color = { accent: 'var(--accent)', good: 'var(--good)', warn: 'var(--warn)', bad: 'var(--bad)', marker: 'var(--marker)' }[tone];
|
||||
return (
|
||||
<div className="relative shrink-0" style={{ width: size, height: size }}>
|
||||
<svg width={size} height={size} className="-rotate-90" aria-hidden>
|
||||
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke} />
|
||||
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - v)} className="transition-[stroke-dashoffset] duration-500" />
|
||||
</svg>
|
||||
<div className="absolute inset-0 grid place-items-center">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Daily accuracy as a line with dots; days without answers leave a gap. */
|
||||
export function AccuracyChart({ points, height = 150 }: { points: { date: string; answered: number; accuracy: number | null }[]; height?: number }) {
|
||||
const w = 600;
|
||||
const pad = { l: 30, r: 8, t: 10, b: 20 };
|
||||
const innerW = w - pad.l - pad.r;
|
||||
const innerH = height - pad.t - pad.b;
|
||||
const x = (i: number) => pad.l + (points.length <= 1 ? innerW / 2 : (i / (points.length - 1)) * innerW);
|
||||
const y = (v: number) => pad.t + (1 - v) * innerH;
|
||||
const segments: string[] = [];
|
||||
let cur = '';
|
||||
points.forEach((p, i) => {
|
||||
if (p.accuracy === null) {
|
||||
if (cur) segments.push(cur);
|
||||
cur = '';
|
||||
} else cur += `${cur ? 'L' : 'M'}${x(i).toFixed(1)},${y(p.accuracy).toFixed(1)} `;
|
||||
});
|
||||
if (cur) segments.push(cur);
|
||||
const has = points.some((p) => p.accuracy !== null);
|
||||
const ticks = [0, 0.5, 1];
|
||||
const labelEvery = Math.max(1, Math.round(points.length / 6));
|
||||
return (
|
||||
<svg viewBox={`0 0 ${w} ${height}`} className="w-full" role="img" aria-label="Accuracy over time">
|
||||
{ticks.map((t) => (
|
||||
<g key={t}>
|
||||
<line x1={pad.l} x2={w - pad.r} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeDasharray={t === 0 ? undefined : '3 4'} />
|
||||
<text x={pad.l - 6} y={y(t) + 3.5} textAnchor="end" fontSize="10" fill="var(--ink-3)" fontFamily="var(--font-mono)">
|
||||
{t * 100}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{points.map((p, i) =>
|
||||
i % labelEvery === 0 ? (
|
||||
<text key={p.date} x={x(i)} y={height - 4} textAnchor="middle" fontSize="10" fill="var(--ink-3)">
|
||||
{new Date(`${p.date}T12:00:00Z`).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' })}
|
||||
</text>
|
||||
) : null,
|
||||
)}
|
||||
{segments.map((d, i) => (
|
||||
<path key={i} d={d} fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
|
||||
))}
|
||||
{points.map((p, i) => (p.accuracy === null ? null : <circle key={p.date} cx={x(i)} cy={y(p.accuracy)} r={points.length > 45 ? 1.8 : 3} fill="var(--surface)" stroke="var(--accent)" strokeWidth="2"><title>{`${p.date}: ${Math.round(p.accuracy * 100)}% of ${p.answered}`}</title></circle>))}
|
||||
{!has && (
|
||||
<text x={w / 2} y={height / 2} textAnchor="middle" fontSize="13" fill="var(--ink-3)">
|
||||
No questions answered in this period
|
||||
</text>
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small bar chart: flashcard reviews coming due per day. */
|
||||
export function ForecastBars({ values, className }: { values: number[]; className?: string }) {
|
||||
const max = Math.max(1, ...values);
|
||||
const day = (i: number) => (i === 0 ? 'Today' : i === 1 ? 'Tomorrow' : new Date(Date.now() + i * 86_400_000).toLocaleDateString(undefined, { weekday: 'short' }));
|
||||
return (
|
||||
<div className={cx('flex h-28 items-end gap-1.5', className)} role="img" aria-label="Upcoming flashcard reviews by day">
|
||||
{values.map((v, i) => (
|
||||
<Tooltip key={i} label={`${day(i)}: ${v} due`} side="top">
|
||||
<div className="flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-1">
|
||||
<span className="num text-[10px] text-ink-3">{v || ''}</span>
|
||||
<div className={cx('w-full rounded-t-[4px]', i === 0 ? 'bg-accent' : 'bg-accent/35')} style={{ height: `${Math.max(v ? 6 : 2, (v / max) * 100)}%`, maxHeight: 'calc(100% - 30px)', minHeight: 2 }} />
|
||||
<span className="w-full truncate text-center text-[10px] text-ink-3">{i === 0 ? 'Today' : day(i).slice(0, 2)}</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Horizontal accuracy bar with the percentage. */
|
||||
export function AccuracyBar({ value, className }: { value: number; className?: string }) {
|
||||
const p = Math.round(value * 100);
|
||||
const tone = p >= 80 ? 'bg-good' : p >= 60 ? 'bg-warn' : 'bg-bad';
|
||||
return (
|
||||
<div className={cx('flex items-center gap-2', className)}>
|
||||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink/8">
|
||||
<div className={cx('h-full rounded-full', tone)} style={{ width: `${Math.max(3, p)}%` }} />
|
||||
</div>
|
||||
<span className="num w-9 text-right text-xs text-ink-2">{p}%</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
372
web/src/features/dialogs.tsx
Normal file
372
web/src/features/dialogs.tsx
Normal file
|
|
@ -0,0 +1,372 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Check, Copy, ExternalLink, Globe, Link2Off, RefreshCw } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { ClassDetail, Share, Template } from '@/lib/types';
|
||||
import { copyText, plural, timeAgo } from '@/lib/util';
|
||||
import { Button, Callout, Dialog, Field, Input, Select, Spinner, Switch, Textarea } from '@/ui';
|
||||
|
||||
const ENDPOINT = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents' } as const;
|
||||
export type EditableKind = keyof typeof ENDPOINT;
|
||||
const NOUN = { quiz: 'quiz', deck: 'deck', note: 'note', document: 'document', folder: 'folder', class: 'class' } as const;
|
||||
|
||||
/* ------------------------------ rename ------------------------------ */
|
||||
|
||||
export function RenameDialog({
|
||||
target,
|
||||
onClose,
|
||||
}: {
|
||||
target: { kind: EditableKind | 'folder'; id: string; title: string; description?: string } | null;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const refresh = useRefresh();
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setTitle(target.title);
|
||||
setDescription(target.description ?? '');
|
||||
}
|
||||
}, [target]);
|
||||
const withDescription = target?.kind === 'quiz' || target?.kind === 'deck';
|
||||
|
||||
const save = async () => {
|
||||
if (!target || !title.trim()) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
if (target.kind === 'folder') await api.patch(`/api/folders/${target.id}`, { name: title });
|
||||
else await api.patch(`/api/${ENDPOINT[target.kind]}/${target.id}`, withDescription ? { title, description } : { title });
|
||||
await refresh();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={target !== null}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Rename ${target ? NOUN[target.kind] : ''}`}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} disabled={!title.trim()} onClick={save}>
|
||||
Save
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<Field label={target?.kind === 'folder' ? 'Name' : 'Title'}>
|
||||
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} maxLength={200} onFocus={(e) => e.target.select()} />
|
||||
</Field>
|
||||
{withDescription && (
|
||||
<Field label="Description" optional>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={3} maxLength={4000} />
|
||||
</Field>
|
||||
)}
|
||||
<button type="submit" hidden />
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ move ------------------------------ */
|
||||
|
||||
export function MoveDialog({ target, onClose }: { target: { kind: EditableKind; id: string; title: string; classId: string; folderId: string | null } | null; onClose: () => void }) {
|
||||
const refresh = useRefresh();
|
||||
const classes = useClasses();
|
||||
const [classId, setClassId] = useState('');
|
||||
const [folderId, setFolderId] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const detail = useQuery({ queryKey: qk.class(classId), queryFn: () => api.get<ClassDetail>(`/api/classes/${classId}`), enabled: Boolean(classId) && target !== null });
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setClassId(target.classId);
|
||||
setFolderId(target.folderId ?? '');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
const save = async () => {
|
||||
if (!target) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.post('/api/items/move', { items: [{ kind: target.kind, id: target.id }], classId, folderId: folderId || null });
|
||||
await refresh();
|
||||
toast.success('Moved');
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={target !== null}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Move"
|
||||
description={target ? `Choose where "${target.title}" should live.` : undefined}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} onClick={save}>
|
||||
Move here
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Field label="Class">
|
||||
<Select
|
||||
value={classId}
|
||||
onChange={(e) => {
|
||||
setClassId(e.target.value);
|
||||
setFolderId('');
|
||||
}}
|
||||
>
|
||||
{(classes.data ?? []).map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Folder">
|
||||
<Select value={folderId} onChange={(e) => setFolderId(e.target.value)} disabled={detail.isLoading}>
|
||||
<option value="">No folder</option>
|
||||
{(detail.data?.folders ?? []).map((f) => (
|
||||
<option key={f.id} value={f.id}>
|
||||
{f.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ new item ------------------------------ */
|
||||
|
||||
export function NewItemDialog({ kind, classId, folderId, onClose }: { kind: 'quiz' | 'deck' | 'note' | 'folder' | null; classId: string; folderId?: string | null; onClose: () => void }) {
|
||||
const refresh = useRefresh();
|
||||
const navigate = useNavigate();
|
||||
const [title, setTitle] = useState('');
|
||||
const [templateId, setTemplateId] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const templates = useQuery({
|
||||
queryKey: [...qk.templates, kind],
|
||||
queryFn: () => api.get<{ templates: Template[] }>(`/api/templates?kind=${kind}`).then((r) => r.templates),
|
||||
enabled: kind === 'quiz' || kind === 'deck',
|
||||
});
|
||||
useEffect(() => {
|
||||
if (kind) {
|
||||
setTitle('');
|
||||
setTemplateId('');
|
||||
}
|
||||
}, [kind]);
|
||||
|
||||
const create = async () => {
|
||||
if (!kind || !title.trim()) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
if (kind === 'folder') {
|
||||
await api.post(`/api/classes/${classId}/folders`, { name: title });
|
||||
await refresh();
|
||||
} else if (templateId) {
|
||||
const res = await api.post<{ created: { kind: string; id: string } }>(`/api/templates/${templateId}/use`, { classId, folderId, title });
|
||||
await refresh();
|
||||
navigate(`/${res.created.kind === 'quiz' ? 'quizzes' : 'decks'}/${res.created.id}`);
|
||||
} else if (kind === 'quiz') {
|
||||
const res = await api.post<{ quiz: { id: string } }>('/api/quizzes', { classId, folderId, title });
|
||||
await refresh();
|
||||
navigate(`/quizzes/${res.quiz.id}?edit=1`);
|
||||
} else if (kind === 'deck') {
|
||||
const res = await api.post<{ deck: { id: string } }>('/api/decks', { classId, folderId, title });
|
||||
await refresh();
|
||||
navigate(`/decks/${res.deck.id}?edit=1`);
|
||||
} else {
|
||||
const res = await api.post<{ note: { id: string } }>('/api/notes', { classId, folderId, title });
|
||||
await refresh();
|
||||
navigate(`/notes/${res.note.id}?edit=1`);
|
||||
}
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const labels = { quiz: 'New quiz', deck: 'New flashcard deck', note: 'New note', folder: 'New folder' };
|
||||
const placeholders = { quiz: 'Cardiac medications', deck: 'Lab values', note: 'Exam 2 review', folder: 'Unit 3' };
|
||||
return (
|
||||
<Dialog
|
||||
open={kind !== null}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={kind ? labels[kind] : ''}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} disabled={!title.trim()} onClick={create}>
|
||||
Create
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void create();
|
||||
}}
|
||||
>
|
||||
<Field label={kind === 'folder' ? 'Name' : 'Title'}>
|
||||
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} placeholder={kind ? placeholders[kind] : ''} maxLength={200} />
|
||||
</Field>
|
||||
{(kind === 'quiz' || kind === 'deck') && (templates.data?.length ?? 0) > 0 && (
|
||||
<Field label="Start from" hint={templates.data?.find((t) => t.id === templateId)?.description}>
|
||||
<Select value={templateId} onChange={(e) => setTemplateId(e.target.value)}>
|
||||
<option value="">Blank {kind}</option>
|
||||
{templates.data!.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.name}
|
||||
{t.builtin ? '' : ' (yours)'}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
<button type="submit" hidden />
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ share ------------------------------ */
|
||||
|
||||
export type ShareKind = 'quiz' | 'deck' | 'folder' | 'class' | 'note' | 'document';
|
||||
|
||||
export function shareUrl(token: string): string {
|
||||
return `${window.location.origin}/s/${token}`;
|
||||
}
|
||||
|
||||
const SHARE_BLURB: Record<ShareKind, string> = {
|
||||
quiz: 'Anyone with the link can take this quiz and see answers, rationales and their score. They cannot change it.',
|
||||
deck: 'Anyone with the link can study these flashcards. They cannot change them.',
|
||||
note: 'Anyone with the link can read this note.',
|
||||
document: 'Anyone with the link can view and download this file.',
|
||||
folder: 'Anyone with the link can study the quizzes, decks and notes in this folder. Uploaded documents are not included.',
|
||||
class: 'Anyone with the link can study every quiz, deck and note in this class. Uploaded documents are not included.',
|
||||
};
|
||||
|
||||
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
|
||||
const refresh = useRefresh();
|
||||
const [share, setShare] = useState<Share | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!target) return;
|
||||
setShare(null);
|
||||
setCopied(false);
|
||||
setLoading(true);
|
||||
api
|
||||
.get<{ shares: (Share & { kind: string; targetId: string })[] }>('/api/shares')
|
||||
.then((r) => setShare(r.shares.find((s) => s.kind === target.kind && s.targetId === target.id) ?? null))
|
||||
.catch(() => undefined)
|
||||
.finally(() => setLoading(false));
|
||||
}, [target]);
|
||||
|
||||
const act = async (fn: () => Promise<{ share: Share } | void>) => {
|
||||
try {
|
||||
const res = await fn();
|
||||
if (res && 'share' in res) setShare(res.share);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const toggle = (on: boolean) => {
|
||||
if (!target) return;
|
||||
void act(() => (share ? api.patch<{ share: Share }>(`/api/shares/${share.id}`, { enabled: on }) : api.post<{ share: Share }>('/api/shares', { kind: target.kind, targetId: target.id })));
|
||||
};
|
||||
const url = share ? shareUrl(share.token) : '';
|
||||
const copy = async () => {
|
||||
if (await copyText(url)) {
|
||||
setCopied(true);
|
||||
toast.success('Link copied');
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
const on = Boolean(share?.enabled);
|
||||
|
||||
return (
|
||||
<Dialog open={target !== null} onOpenChange={(o) => !o && onClose()} title="Share" description={target?.title}>
|
||||
{loading ? (
|
||||
<div className="grid h-32 place-items-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
) : (
|
||||
target && (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-xl border border-line bg-paper p-4">
|
||||
<Switch checked={on} onChange={toggle} label="Public link" description={SHARE_BLURB[target.kind]} />
|
||||
</div>
|
||||
{on && share ? (
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<Input readOnly value={url} onFocus={(e) => e.target.select()} aria-label="Share link" className="num text-[13px]" />
|
||||
<Button variant="primary" icon={copied ? <Check /> : <Copy />} onClick={copy}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-[13px] text-ink-3">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Globe className="size-3.5" />
|
||||
{share.viewCount > 0 ? `Opened ${plural(share.viewCount, 'time')}, last ${timeAgo(share.lastViewedAt)}` : 'Not opened yet'}
|
||||
</span>
|
||||
<span className="flex gap-1">
|
||||
<a href={url} target="_blank" rel="noreferrer" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6">
|
||||
<ExternalLink className="size-3.5" /> Preview
|
||||
</a>
|
||||
<button type="button" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6" onClick={() => act(() => api.post<{ share: Share }>(`/api/shares/${share.id}/rotate`))}>
|
||||
<RefreshCw className="size-3.5" /> New link
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[13px] text-ink-3">"New link" replaces the address, so the old one stops working. Visitors study on their own; nothing they do touches your progress.</p>
|
||||
</>
|
||||
) : (
|
||||
<Callout icon={<Link2Off />}>{share ? 'The link is off. Anyone who has it sees a "no longer available" page.' : 'Sharing is off. Nobody else can see this.'}</Callout>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
311
web/src/features/editors.tsx
Normal file
311
web/src/features/editors.tsx
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
import { Check, ImagePlus, MessageSquareText, Plus, Trash2 } from 'lucide-react';
|
||||
import { useRef, useState, type ReactNode } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { DIFFICULTIES, LIMITS, optionLetter, type DraftCard, type DraftQuestion, type Issue, type QuestionType } from '@shared/content';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { cx } from '@/lib/util';
|
||||
import { IconButton, Input, Segmented, Select, Textarea } from '@/ui';
|
||||
|
||||
/* ------------------------------ markdown textarea with image paste ------------------------------ */
|
||||
|
||||
export function MarkdownArea({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
rows = 2,
|
||||
label,
|
||||
className,
|
||||
autoFocus,
|
||||
serif,
|
||||
invalid,
|
||||
images = true,
|
||||
onKeyDown,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
rows?: number;
|
||||
label: string;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
serif?: boolean;
|
||||
invalid?: boolean;
|
||||
images?: boolean;
|
||||
onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const insert = (snippet: string) => {
|
||||
const el = ref.current;
|
||||
const start = el?.selectionStart ?? value.length;
|
||||
const end = el?.selectionEnd ?? value.length;
|
||||
const before = value.slice(0, start);
|
||||
const pad = before && !before.endsWith('\n') ? '\n\n' : '';
|
||||
onChange(`${before}${pad}${snippet}\n${value.slice(end)}`);
|
||||
};
|
||||
|
||||
const uploadImage = async (file: File) => {
|
||||
if (!file.type.startsWith('image/')) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await api.upload<{ markdown: string }>('/api/media', form);
|
||||
insert(res.markdown);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cx('group/md relative', className)}>
|
||||
<Textarea
|
||||
ref={ref}
|
||||
autoGrow
|
||||
rows={rows}
|
||||
value={value}
|
||||
autoFocus={autoFocus}
|
||||
aria-label={label}
|
||||
aria-invalid={invalid}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
onPaste={(e) => {
|
||||
if (!images) return;
|
||||
const file = [...e.clipboardData.files].find((f) => f.type.startsWith('image/'));
|
||||
if (file) {
|
||||
e.preventDefault();
|
||||
void uploadImage(file);
|
||||
}
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
if (!images) return;
|
||||
const file = [...e.dataTransfer.files].find((f) => f.type.startsWith('image/'));
|
||||
if (file) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void uploadImage(file);
|
||||
}
|
||||
}}
|
||||
className={cx(serif && 'font-serif text-[16.5px] leading-normal', images && 'pr-10')}
|
||||
/>
|
||||
{images && (
|
||||
<>
|
||||
<input ref={fileRef} type="file" accept="image/png,image/jpeg,image/gif,image/webp" hidden onChange={(e) => (e.target.files?.[0] && uploadImage(e.target.files[0]), (e.target.value = ''))} />
|
||||
<IconButton label={uploading ? 'Uploading image' : 'Add image'} size="sm" disabled={uploading} onClick={() => fileRef.current?.click()} className="absolute top-1 right-1 opacity-50 group-focus-within/md:opacity-100 hover:opacity-100">
|
||||
<ImagePlus className={uploading ? 'animate-pulse' : undefined} />
|
||||
</IconButton>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldLabel({ children, action }: { children: ReactNode; action?: ReactNode }) {
|
||||
return (
|
||||
<div className="mb-1.5 flex items-center justify-between">
|
||||
<span className="eyebrow">{children}</span>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function IssueList({ issues }: { issues: Issue[] }) {
|
||||
if (issues.length === 0) return null;
|
||||
return (
|
||||
<ul className="space-y-0.5 text-[13px]">
|
||||
{issues.map((i, k) => (
|
||||
<li key={k} className={i.level === 'error' ? 'text-bad' : 'text-warn'}>
|
||||
{i.level === 'error' ? '• ' : '• '}
|
||||
{i.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ question ------------------------------ */
|
||||
|
||||
export function QuestionEditor({
|
||||
value,
|
||||
onChange,
|
||||
issues = [],
|
||||
topics = [],
|
||||
autoFocus,
|
||||
onSubmit,
|
||||
}: {
|
||||
value: DraftQuestion;
|
||||
onChange: (q: DraftQuestion) => void;
|
||||
issues?: Issue[];
|
||||
topics?: string[];
|
||||
autoFocus?: boolean;
|
||||
/** Ctrl/Cmd+Enter inside any field. */
|
||||
onSubmit?: () => void;
|
||||
}) {
|
||||
const [whyOpen, setWhyOpen] = useState<Record<number, boolean>>({});
|
||||
const set = (patch: Partial<DraftQuestion>) => onChange({ ...value, ...patch });
|
||||
const has = (field: string) => issues.some((i) => i.field === field && i.level === 'error');
|
||||
const submitKey = (e: React.KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
onSubmit?.();
|
||||
}
|
||||
};
|
||||
|
||||
const setType = (type: QuestionType) => {
|
||||
if (type === 'single') {
|
||||
// Keep only the first marked answer so the question stays valid.
|
||||
let seen = false;
|
||||
set({ type, options: value.options.map((o) => ({ ...o, correct: o.correct && !seen ? (seen = true) : false })) });
|
||||
} else set({ type });
|
||||
};
|
||||
const setOption = (i: number, patch: Partial<DraftQuestion['options'][number]>) => set({ options: value.options.map((o, k) => (k === i ? { ...o, ...patch } : o)) });
|
||||
const toggleCorrect = (i: number) => {
|
||||
if (value.type === 'single') set({ options: value.options.map((o, k) => ({ ...o, correct: k === i })) });
|
||||
else setOption(i, { correct: !value.options[i].correct });
|
||||
};
|
||||
const listId = `topics-${topics.length}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-5" onKeyDown={submitKey}>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Segmented
|
||||
size="sm"
|
||||
label="Question type"
|
||||
value={value.type}
|
||||
onChange={setType}
|
||||
options={[
|
||||
{ value: 'single', label: 'Multiple choice' },
|
||||
{ value: 'multi', label: 'Select all that apply' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<FieldLabel>Question</FieldLabel>
|
||||
<MarkdownArea label="Question text" value={value.stem} onChange={(stem) => set({ stem })} placeholder="A client with heart failure reports…" rows={2} serif autoFocus={autoFocus} invalid={has('stem')} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<FieldLabel>{value.type === 'single' ? 'Answer choices · mark the correct one' : 'Answer choices · mark every correct one'}</FieldLabel>
|
||||
<ul className="space-y-2">
|
||||
{value.options.map((o, i) => (
|
||||
<li key={i}>
|
||||
<div className="flex items-start gap-2">
|
||||
<button
|
||||
type="button"
|
||||
role={value.type === 'single' ? 'radio' : 'checkbox'}
|
||||
aria-checked={o.correct}
|
||||
aria-label={`Mark choice ${optionLetter(i)} as ${o.correct ? 'incorrect' : 'correct'}`}
|
||||
onClick={() => toggleCorrect(i)}
|
||||
className={cx(
|
||||
'num mt-1 grid size-8 shrink-0 place-items-center border text-[13px] font-semibold transition-colors',
|
||||
value.type === 'single' ? 'rounded-full' : 'rounded-[9px]',
|
||||
o.correct ? 'border-good bg-good text-white dark:text-[#10241a]' : 'border-line-strong bg-surface text-ink-3 hover:border-good hover:text-good',
|
||||
)}
|
||||
>
|
||||
{o.correct ? <Check className="size-4" strokeWidth={3} /> : optionLetter(i)}
|
||||
</button>
|
||||
<Textarea autoGrow rows={1} value={o.text} onChange={(e) => setOption(i, { text: e.target.value })} aria-label={`Choice ${optionLetter(i)}`} placeholder={`Choice ${optionLetter(i)}`} className="min-h-10 flex-1" />
|
||||
<IconButton label={`Explain choice ${optionLetter(i)}`} size="sm" className="mt-1" active={Boolean(whyOpen[i] || o.why)} onClick={() => setWhyOpen((w) => ({ ...w, [i]: !(w[i] ?? Boolean(o.why)) }))}>
|
||||
<MessageSquareText />
|
||||
</IconButton>
|
||||
<IconButton label={`Remove choice ${optionLetter(i)}`} size="sm" className="mt-1" disabled={value.options.length <= 2} onClick={() => set({ options: value.options.filter((_, k) => k !== i) })}>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
</div>
|
||||
{(whyOpen[i] ?? Boolean(o.why)) && (
|
||||
<Textarea autoGrow rows={1} value={o.why ?? ''} onChange={(e) => setOption(i, { why: e.target.value })} aria-label={`Why choice ${optionLetter(i)} is ${o.correct ? 'correct' : 'incorrect'}`} placeholder={`Why this is ${o.correct ? 'correct' : 'incorrect'} (optional)`} className="mt-1.5 ml-10 w-[calc(100%-2.5rem)] bg-sunken text-[13px]" />
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{value.options.length < LIMITS.options && (
|
||||
<button type="button" onClick={() => set({ options: [...value.options, { text: '', correct: false, why: '' }] })} className="mt-2 ml-10 inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium text-accent hover:bg-accent-soft">
|
||||
<Plus className="size-4" /> Add choice
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<FieldLabel>Rationale</FieldLabel>
|
||||
<MarkdownArea label="Rationale" value={value.rationale} onChange={(rationale) => set({ rationale })} placeholder="Why the correct answer is correct. Shown after answering." rows={2} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_160px]">
|
||||
<div>
|
||||
<FieldLabel>Topic</FieldLabel>
|
||||
<Input value={value.topic} onChange={(e) => set({ topic: e.target.value })} placeholder="Heart failure" maxLength={LIMITS.topic} list={listId} aria-label="Topic" />
|
||||
<datalist id={listId}>
|
||||
{topics.map((t) => (
|
||||
<option key={t} value={t} />
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel>Difficulty</FieldLabel>
|
||||
<Select value={value.difficulty} onChange={(e) => set({ difficulty: e.target.value as DraftQuestion['difficulty'] })} aria-label="Difficulty">
|
||||
{DIFFICULTIES.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{d[0].toUpperCase() + d.slice(1)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<IssueList issues={issues} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ card ------------------------------ */
|
||||
|
||||
export function CardEditor({ value, onChange, issues = [], autoFocus, onSubmit, showHint }: { value: DraftCard; onChange: (c: DraftCard) => void; issues?: Issue[]; autoFocus?: boolean; onSubmit?: () => void; showHint?: boolean }) {
|
||||
const [hintOpen, setHintOpen] = useState(Boolean(value.hint) || Boolean(showHint));
|
||||
const set = (patch: Partial<DraftCard>) => onChange({ ...value, ...patch });
|
||||
const has = (field: string) => issues.some((i) => i.field === field && i.level === 'error');
|
||||
return (
|
||||
<div
|
||||
onKeyDown={(e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
onSubmit?.();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<FieldLabel>Front</FieldLabel>
|
||||
<MarkdownArea label="Front" value={value.front} onChange={(front) => set({ front })} rows={3} autoFocus={autoFocus} invalid={has('front')} placeholder="Term or question" />
|
||||
</div>
|
||||
<div>
|
||||
<FieldLabel
|
||||
action={
|
||||
!hintOpen ? (
|
||||
<button type="button" className="text-xs font-medium text-accent hover:underline" onClick={() => setHintOpen(true)}>
|
||||
Add hint
|
||||
</button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
Back
|
||||
</FieldLabel>
|
||||
<MarkdownArea label="Back" value={value.back} onChange={(back) => set({ back })} rows={3} invalid={has('back')} placeholder="Answer" />
|
||||
</div>
|
||||
</div>
|
||||
{hintOpen && (
|
||||
<div className="mt-3">
|
||||
<FieldLabel>Hint</FieldLabel>
|
||||
<Input value={value.hint ?? ''} onChange={(e) => set({ hint: e.target.value })} placeholder="A mnemonic or nudge shown on request" aria-label="Hint" />
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2">
|
||||
<IssueList issues={issues} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
290
web/src/features/flashcards.tsx
Normal file
290
web/src/features/flashcards.tsx
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
import { ArrowLeft, ArrowRight, Check, Lightbulb, RotateCcw, Shuffle, X } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, IconButton, Kbd, ProgressBar } from '@/ui';
|
||||
import { Ring } from './charts';
|
||||
|
||||
/* ------------------------------ the card ------------------------------ */
|
||||
|
||||
export function FlipCard({
|
||||
front,
|
||||
back,
|
||||
hint,
|
||||
flipped,
|
||||
onFlip,
|
||||
label,
|
||||
cardKey,
|
||||
footer,
|
||||
}: {
|
||||
front: string;
|
||||
back: string;
|
||||
hint?: string;
|
||||
flipped: boolean;
|
||||
onFlip: () => void;
|
||||
label?: ReactNode;
|
||||
/** Changing this replays the entrance animation and resets the hint. */
|
||||
cardKey: string;
|
||||
footer?: ReactNode;
|
||||
}) {
|
||||
const [showHint, setShowHint] = useState(false);
|
||||
useEffect(() => setShowHint(false), [cardKey]);
|
||||
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.
|
||||
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]');
|
||||
return (
|
||||
<div key={cardKey} className="flip w-full animate-in">
|
||||
<div className="flip-inner" data-flipped={flipped}>
|
||||
<div className={cx(face, 'flip-front')}>
|
||||
<button type="button" onClick={onFlip} aria-label="Show answer" className="flex flex-1 cursor-pointer flex-col rounded-[22px] text-left">
|
||||
<div className="flex items-center justify-between px-5 pt-4">
|
||||
<span className="eyebrow">{label ?? 'Front'}</span>
|
||||
<span className="text-xs text-ink-3">Tap to flip</span>
|
||||
</div>
|
||||
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10">
|
||||
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
|
||||
{front}
|
||||
</Markdown>
|
||||
</div>
|
||||
</button>
|
||||
{hint && (
|
||||
<div className="border-t border-line px-5 py-3">
|
||||
{showHint ? (
|
||||
<div className="flex items-start gap-2 text-sm text-ink-2">
|
||||
<Lightbulb className="mt-0.5 size-4 shrink-0 text-warn" />
|
||||
<Markdown>{hint}</Markdown>
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" onClick={() => setShowHint(true)} className="flex items-center gap-1.5 text-[13px] font-medium text-ink-2 hover:text-ink">
|
||||
<Lightbulb className="size-4" /> Show hint
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={cx(face, 'flip-back')}>
|
||||
<button type="button" onClick={onFlip} aria-label="Show question" className="flex cursor-pointer items-center justify-between rounded-t-[22px] px-5 pt-4 text-left">
|
||||
<span className="eyebrow">Back</span>
|
||||
<span className="max-w-[70%] truncate text-xs text-ink-3">{front.replace(/[#*_`>]/g, '').slice(0, 80)}</span>
|
||||
</button>
|
||||
<div className="grid flex-1 place-items-center px-6 py-6 sm:px-10" aria-live="polite">
|
||||
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(back))}>
|
||||
{back}
|
||||
</Markdown>
|
||||
</div>
|
||||
{footer && <div className="border-t border-line px-5 py-3">{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StudyTopBar({ title, subtitle, onExit, right, progress, exitLabel = 'Exit' }: { title: string; subtitle?: ReactNode; onExit: () => void; right?: ReactNode; progress?: number; exitLabel?: string }) {
|
||||
return (
|
||||
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
|
||||
<div className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-3 sm:px-5">
|
||||
<IconButton label={exitLabel} onClick={onExit}>
|
||||
<X />
|
||||
</IconButton>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-semibold">{title}</div>
|
||||
{subtitle && <div className="truncate text-xs text-ink-3">{subtitle}</div>}
|
||||
</div>
|
||||
{right}
|
||||
</div>
|
||||
{progress !== undefined && <ProgressBar value={progress} tone="ink" className="h-[3px] rounded-none" label="Progress" />}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ browse / cram ------------------------------ */
|
||||
|
||||
export interface CramState {
|
||||
order: string[];
|
||||
index: number;
|
||||
known: string[];
|
||||
unknown: string[];
|
||||
shuffled: boolean;
|
||||
/** Which pass this is: 1 = whole deck, 2+ = cards still being learned. */
|
||||
round: number;
|
||||
}
|
||||
|
||||
export interface CramCard {
|
||||
id: string;
|
||||
front: string;
|
||||
back: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1): CramState {
|
||||
const ids = cards.map((c) => c.id);
|
||||
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round };
|
||||
}
|
||||
|
||||
/** Drops cards that no longer exist and clamps the position, so a saved session survives deck edits. */
|
||||
export function reconcileCramState(state: CramState | null | undefined, cards: CramCard[]): CramState | null {
|
||||
if (!state || !Array.isArray(state.order)) return null;
|
||||
const valid = new Set(cards.map((c) => c.id));
|
||||
const order = state.order.filter((id) => valid.has(id));
|
||||
if (order.length === 0) return null;
|
||||
return {
|
||||
order,
|
||||
index: Math.max(0, Math.min(state.index ?? 0, order.length)),
|
||||
known: (state.known ?? []).filter((id) => valid.has(id)),
|
||||
unknown: (state.unknown ?? []).filter((id) => valid.has(id)),
|
||||
shuffled: Boolean(state.shuffled),
|
||||
round: state.round ?? 1,
|
||||
};
|
||||
}
|
||||
|
||||
export function CramSession({
|
||||
title,
|
||||
subtitle,
|
||||
cards,
|
||||
state,
|
||||
onState,
|
||||
onExit,
|
||||
onGrade,
|
||||
exitLabel,
|
||||
renderExtra,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
cards: CramCard[];
|
||||
state: CramState;
|
||||
onState: (s: CramState) => void;
|
||||
onExit: () => void;
|
||||
/** Called when a card is graded (used for activity tracking). */
|
||||
onGrade?: (cardId: string, known: boolean) => void;
|
||||
exitLabel?: string;
|
||||
renderExtra?: (card: CramCard) => ReactNode;
|
||||
}) {
|
||||
const [flipped, setFlipped] = useState(false);
|
||||
const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]);
|
||||
const total = state.order.length;
|
||||
const done = state.index >= total;
|
||||
const card = done ? undefined : byId.get(state.order[state.index]);
|
||||
useEffect(() => setFlipped(false), [state.index, state.round]);
|
||||
|
||||
const grade = (known: boolean) => {
|
||||
if (!card) return;
|
||||
onGrade?.(card.id, known);
|
||||
onState({
|
||||
...state,
|
||||
index: state.index + 1,
|
||||
known: known ? [...state.known.filter((x) => x !== card.id), card.id] : state.known.filter((x) => x !== card.id),
|
||||
unknown: known ? state.unknown.filter((x) => x !== card.id) : [...state.unknown.filter((x) => x !== card.id), card.id],
|
||||
});
|
||||
};
|
||||
const move = (delta: number) => onState({ ...state, index: Math.max(0, Math.min(total, state.index + delta)) });
|
||||
const restart = (shuffled = state.shuffled) => onState(freshCramState(cards, shuffled));
|
||||
const studyUnknown = () => {
|
||||
const pool = cards.filter((c) => state.unknown.includes(c.id));
|
||||
onState({ ...freshCramState(pool, true, state.round + 1) });
|
||||
};
|
||||
|
||||
useHotkeys({
|
||||
space: (e) => {
|
||||
e.preventDefault();
|
||||
if (!done) setFlipped((f) => !f);
|
||||
},
|
||||
Enter: () => !done && setFlipped((f) => !f),
|
||||
ArrowRight: () => move(1),
|
||||
ArrowLeft: () => move(-1),
|
||||
'1': () => flipped && grade(false),
|
||||
'2': () => flipped && grade(true),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh flex-col bg-paper">
|
||||
<StudyTopBar
|
||||
title={title}
|
||||
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : 'Browse')}
|
||||
onExit={onExit}
|
||||
exitLabel={exitLabel}
|
||||
progress={total ? Math.min(1, state.index / total) : 0}
|
||||
right={
|
||||
<>
|
||||
<span className="num text-[13px] font-medium text-ink-2">
|
||||
{Math.min(state.index + 1, total)}/{total}
|
||||
</span>
|
||||
<IconButton label={state.shuffled ? 'Shuffled. Restart in order' : 'Shuffle and restart'} active={state.shuffled} onClick={() => restart(!state.shuffled)}>
|
||||
<Shuffle />
|
||||
</IconButton>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<main className="mx-auto flex w-full max-w-2xl flex-1 flex-col px-4 pt-6 pb-36 sm:px-5 sm:pt-10">
|
||||
{done || !card ? (
|
||||
<div className="card m-auto w-full animate-in p-7 text-center sm:p-10">
|
||||
<div className="mx-auto mb-4 w-fit">
|
||||
<Ring value={total ? state.known.length / (state.known.length + state.unknown.length || 1) : 0} size={104} stroke={9} tone="good">
|
||||
<span className="display num text-[28px]">{state.known.length}</span>
|
||||
</Ring>
|
||||
</div>
|
||||
<h2 className="display text-[28px]">{state.unknown.length === 0 ? 'You know them all' : 'Round complete'}</h2>
|
||||
<p className="mt-2 text-[15px] text-ink-2">
|
||||
{state.known.length} known{state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of {plural(total, 'card')}.
|
||||
</p>
|
||||
<div className="mt-6 flex flex-wrap justify-center gap-2">
|
||||
{state.unknown.length > 0 && (
|
||||
<Button variant="primary" size="lg" icon={<RotateCcw />} onClick={studyUnknown}>
|
||||
Study the {state.unknown.length} again
|
||||
</Button>
|
||||
)}
|
||||
<Button size="lg" icon={<RotateCcw />} onClick={() => restart()}>
|
||||
Start over
|
||||
</Button>
|
||||
<Button size="lg" variant="ghost" onClick={onExit}>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FlipCard cardKey={`${state.round}:${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>
|
||||
{!done && card && (
|
||||
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
|
||||
<div className="mx-auto flex h-[76px] max-w-2xl items-center gap-2 px-3 sm:px-5">
|
||||
<IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0}>
|
||||
<ArrowLeft />
|
||||
</IconButton>
|
||||
{flipped ? (
|
||||
<>
|
||||
<Button size="lg" className="flex-1 border-warn/40 text-warn hover:bg-warn-soft" icon={<RotateCcw />} onClick={() => grade(false)}>
|
||||
Still learning
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>1</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
<Button size="lg" className="flex-1 border-good/40 text-good hover:bg-good-soft" icon={<Check />} onClick={() => grade(true)}>
|
||||
Know it
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>2</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button size="lg" variant="primary" className="flex-1" onClick={() => setFlipped(true)}>
|
||||
Show answer
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>Space</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<IconButton label="Skip card" onClick={() => move(1)}>
|
||||
<ArrowRight />
|
||||
</IconButton>
|
||||
</div>
|
||||
</footer>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
519
web/src/features/quiz.tsx
Normal file
519
web/src/features/quiz.tsx
Normal file
|
|
@ -0,0 +1,519 @@
|
|||
import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { isFullyCorrect, optionLetter, scoreQuestion, type SataScoring } from '@shared/content';
|
||||
import type { AnswerState, SnapshotQuestion } from '@/lib/types';
|
||||
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Dialog, IconButton, Kbd, ProgressBar, Segmented, useConfirm } from '@/ui';
|
||||
import { Ring } from './charts';
|
||||
|
||||
/* ------------------------------ option list ------------------------------ */
|
||||
|
||||
function OptionList({
|
||||
question,
|
||||
selected,
|
||||
revealed,
|
||||
onToggle,
|
||||
}: {
|
||||
question: SnapshotQuestion;
|
||||
selected: string[];
|
||||
/** Show which choices are correct (after checking in practice, or in review). */
|
||||
revealed: boolean;
|
||||
onToggle?: (id: string) => void;
|
||||
}) {
|
||||
const multi = question.type === 'multi';
|
||||
return (
|
||||
<ul className="space-y-2.5" role={multi ? 'group' : 'radiogroup'} aria-label="Answer choices">
|
||||
{question.options.map((o, i) => {
|
||||
const picked = selected.includes(o.id);
|
||||
const state = !revealed ? (picked ? 'picked' : 'idle') : o.correct ? (picked ? 'right' : 'missed') : picked ? 'wrong' : 'idle';
|
||||
const styles = {
|
||||
idle: 'border-line-strong bg-surface',
|
||||
picked: 'border-accent bg-accent-soft ring-1 ring-accent',
|
||||
right: 'border-good bg-good-soft ring-1 ring-good',
|
||||
missed: 'border-good/60 bg-surface border-dashed',
|
||||
wrong: 'border-bad bg-bad-soft ring-1 ring-bad',
|
||||
}[state];
|
||||
const key = {
|
||||
idle: 'border-line-strong text-ink-3 bg-surface',
|
||||
picked: 'border-accent bg-accent text-accent-ink',
|
||||
right: 'border-good bg-good text-white dark:text-[#10241a]',
|
||||
missed: 'border-good text-good bg-surface',
|
||||
wrong: 'border-bad bg-bad text-white dark:text-[#2a1210]',
|
||||
}[state];
|
||||
return (
|
||||
<li key={o.id}>
|
||||
<button
|
||||
type="button"
|
||||
role={multi ? 'checkbox' : 'radio'}
|
||||
aria-checked={picked}
|
||||
disabled={revealed || !onToggle}
|
||||
onClick={() => onToggle?.(o.id)}
|
||||
className={cx('flex w-full items-start gap-3 rounded-[14px] border px-3.5 py-3 text-left transition-[background,border-color,box-shadow] disabled:cursor-default', styles, !revealed && onToggle && 'hover:border-ink-3 active:scale-[0.995]')}
|
||||
>
|
||||
<span className={cx('num mt-px grid size-7 shrink-0 place-items-center border text-[13px] font-semibold', multi ? 'rounded-[8px]' : 'rounded-full', key)}>
|
||||
{state === 'right' || state === 'missed' ? <Check className="size-4" strokeWidth={3} /> : state === 'wrong' ? <X className="size-4" strokeWidth={3} /> : optionLetter(i)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<Markdown className="text-[16px] leading-snug">{o.text}</Markdown>
|
||||
{revealed && (state === 'missed' || state === 'wrong' || state === 'right') && (
|
||||
<span className={cx('mt-1 block text-[13px] font-medium', state === 'wrong' ? 'text-bad' : 'text-good')}>
|
||||
{state === 'right' ? 'Correct' : state === 'missed' ? (multi ? 'Correct, not selected' : 'Correct answer') : 'Your answer'}
|
||||
</span>
|
||||
)}
|
||||
{revealed && o.why && <span className="mt-1 block text-[13.5px] leading-snug text-ink-2">{o.why}</span>}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function Verdict({ score }: { score: number }) {
|
||||
const full = isFullyCorrect(score);
|
||||
const partial = !full && score > 0;
|
||||
return (
|
||||
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')} role="status">
|
||||
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
|
||||
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ runner ------------------------------ */
|
||||
|
||||
export interface RunnerProps {
|
||||
title: string;
|
||||
mode: 'practice' | 'exam';
|
||||
questions: SnapshotQuestion[];
|
||||
answers: Record<string, AnswerState>;
|
||||
flags: string[];
|
||||
index: number;
|
||||
elapsedSec: number;
|
||||
timeLimitSec: number | null;
|
||||
sataScoring: SataScoring;
|
||||
onAnswer: (questionId: string, selected: string[], checked: boolean) => void;
|
||||
onFlags: (flags: string[]) => void;
|
||||
onIndex: (index: number) => void;
|
||||
/** Called every few seconds with the running clock so progress can be saved. */
|
||||
onTick?: (elapsedSec: number) => void;
|
||||
onFinish: (elapsedSec: number) => void;
|
||||
onExit: () => void;
|
||||
finishing?: boolean;
|
||||
/** Extra content under the rationale (AI explanation). */
|
||||
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
|
||||
exitLabel?: string;
|
||||
}
|
||||
|
||||
export function QuizRunner(p: RunnerProps) {
|
||||
const confirm = useConfirm();
|
||||
const [elapsed, setElapsed] = useState(p.elapsedSec);
|
||||
const [navOpen, setNavOpen] = useState(false);
|
||||
const topRef = useRef<HTMLDivElement>(null);
|
||||
const tick = useLatest(p.onTick);
|
||||
const finish = useLatest(p.onFinish);
|
||||
const elapsedRef = useLatest(elapsed);
|
||||
|
||||
const total = p.questions.length;
|
||||
const index = Math.min(p.index, total - 1);
|
||||
const question = p.questions[index];
|
||||
const answer = p.answers[question.id];
|
||||
const selected = answer?.selected ?? [];
|
||||
const checked = p.mode === 'practice' && Boolean(answer?.checked);
|
||||
const answeredCount = p.questions.filter((q) => (p.mode === 'practice' ? p.answers[q.id]?.checked : (p.answers[q.id]?.selected.length ?? 0) > 0)).length;
|
||||
const flagged = p.flags.includes(question.id);
|
||||
const isLast = index === total - 1;
|
||||
const remaining = p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
|
||||
|
||||
// Session clock: pauses while the tab is hidden.
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') setElapsed((e) => e + 1);
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(elapsed);
|
||||
}, [elapsed, tick]);
|
||||
useEffect(() => {
|
||||
if (remaining === 0 && !p.finishing) finish.current(elapsedRef.current);
|
||||
}, [remaining, p.finishing, finish, elapsedRef]);
|
||||
useEffect(() => {
|
||||
topRef.current?.scrollIntoView({ block: 'start' });
|
||||
}, [index]);
|
||||
|
||||
const toggle = (id: string) => {
|
||||
if (checked) return;
|
||||
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
|
||||
p.onAnswer(question.id, next, false);
|
||||
};
|
||||
const check = () => selected.length > 0 && p.onAnswer(question.id, selected, true);
|
||||
const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i)));
|
||||
const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]);
|
||||
|
||||
const requestFinish = async () => {
|
||||
const unanswered = total - answeredCount;
|
||||
if (unanswered > 0) {
|
||||
const ok = await confirm(
|
||||
p.mode === 'exam'
|
||||
? { title: 'Submit the exam?', message: `${plural(unanswered, 'question')} ${unanswered === 1 ? 'is' : 'are'} unanswered and will be marked wrong.`, confirmLabel: 'Submit' }
|
||||
: { title: 'Finish now?', message: `You have answered ${answeredCount} of ${total}. Only answered questions are scored.`, confirmLabel: 'Finish' },
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
p.onFinish(elapsed);
|
||||
};
|
||||
|
||||
const primary = () => {
|
||||
if (p.mode === 'practice' && !checked) return check();
|
||||
if (isLast) return void requestFinish();
|
||||
go(index + 1);
|
||||
};
|
||||
|
||||
useHotkeys({
|
||||
...Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)])),
|
||||
...Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)])),
|
||||
Enter: primary,
|
||||
ArrowRight: () => go(index + 1),
|
||||
ArrowLeft: () => go(index - 1),
|
||||
// "f" doubles as choice F on six-option questions; the flag keeps a dedicated key too.
|
||||
...(question.options.length < 6 ? { f: toggleFlag } : {}),
|
||||
m: toggleFlag,
|
||||
});
|
||||
|
||||
const score = checked ? scoreQuestion(question, selected, p.sataScoring) : 0;
|
||||
const statusOf = (q: SnapshotQuestion) => {
|
||||
const a = p.answers[q.id];
|
||||
if (p.mode === 'practice' && a?.checked) return isFullyCorrect(scoreQuestion(q, a.selected, p.sataScoring)) ? 'right' : 'wrong';
|
||||
return (a?.selected.length ?? 0) > 0 ? 'answered' : 'blank';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh flex-col bg-paper">
|
||||
<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">
|
||||
<IconButton label={p.exitLabel ?? 'Save and exit'} onClick={p.onExit}>
|
||||
<X />
|
||||
</IconButton>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-semibold">{p.title}</div>
|
||||
<div className="text-xs text-ink-3">{p.mode === 'exam' ? 'Exam' : 'Practice'}</div>
|
||||
</div>
|
||||
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}>
|
||||
<Clock className="size-3.5" />
|
||||
{formatDuration(remaining ?? elapsed)}
|
||||
</div>
|
||||
<button type="button" onClick={() => setNavOpen(true)} className="num flex h-9 items-center gap-1.5 rounded-[9px] border border-line-strong bg-surface px-2.5 text-[13px] font-medium shadow-1 hover:border-ink-3" aria-label="Question navigator">
|
||||
<LayoutGrid className="size-3.5 text-ink-3" />
|
||||
{index + 1}/{total}
|
||||
</button>
|
||||
</div>
|
||||
<ProgressBar value={answeredCount / total} tone="ink" className="h-[3px] rounded-none" label="Progress" />
|
||||
</header>
|
||||
|
||||
<main className="mx-auto w-full max-w-3xl flex-1 px-4 pt-6 pb-32 sm:px-5 sm:pt-9">
|
||||
<div ref={topRef} className="scroll-mt-20" />
|
||||
<div key={question.id} className="animate-in">
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
<span className="eyebrow">Question {index + 1}</span>
|
||||
{question.topic && <Badge tone="accent">{question.topic}</Badge>}
|
||||
{flagged && (
|
||||
<Badge tone="marker">
|
||||
<Flag /> Flagged
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Markdown serif className="text-[20px] leading-[1.45] sm:text-[22px]">
|
||||
{question.stem}
|
||||
</Markdown>
|
||||
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : 'Choose one answer.'}</p>
|
||||
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
|
||||
|
||||
{checked && (
|
||||
<div className="mt-5 animate-in space-y-4">
|
||||
<Verdict score={score} />
|
||||
{question.rationale && (
|
||||
<div className="rounded-[14px] border border-line bg-surface p-4">
|
||||
<div className="eyebrow mb-1.5">Rationale</div>
|
||||
<Markdown className="text-[15px]">{question.rationale}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{p.renderExtra?.(
|
||||
question,
|
||||
question.options.filter((o) => selected.includes(o.id)).map((o) => o.text),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
|
||||
<div className="mx-auto flex h-[68px] max-w-3xl items-center gap-2 px-3 sm:px-5">
|
||||
<Button size="lg" variant="ghost" icon={<ArrowLeft />} onClick={() => go(index - 1)} disabled={index === 0} aria-label="Previous question">
|
||||
<span className="hidden sm:inline">Back</span>
|
||||
</Button>
|
||||
<Button size="lg" variant={flagged ? 'marker' : 'ghost'} icon={<Flag className={flagged ? 'fill-current' : undefined} />} onClick={toggleFlag} aria-pressed={flagged}>
|
||||
<span className="hidden sm:inline">{flagged ? 'Flagged' : 'Flag'}</span>
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
{p.mode === 'practice' && !checked ? (
|
||||
<>
|
||||
<Button size="lg" variant="ghost" onClick={() => (isLast ? requestFinish() : go(index + 1))}>
|
||||
{isLast ? 'Finish' : 'Skip'}
|
||||
</Button>
|
||||
<Button size="lg" variant="primary" disabled={selected.length === 0} onClick={check} className="min-w-32">
|
||||
Check
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>↵</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
</>
|
||||
) : isLast ? (
|
||||
<Button size="lg" variant="primary" loading={p.finishing} onClick={requestFinish} className="min-w-32">
|
||||
{p.mode === 'exam' ? 'Submit exam' : 'See results'}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
{p.mode === 'exam' && answeredCount === total && (
|
||||
<Button size="lg" variant="ghost" loading={p.finishing} onClick={requestFinish}>
|
||||
Submit
|
||||
</Button>
|
||||
)}
|
||||
<Button size="lg" variant="primary" onClick={() => go(index + 1)} className="min-w-32">
|
||||
Next <ArrowRight className="size-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<Dialog
|
||||
open={navOpen}
|
||||
onOpenChange={setNavOpen}
|
||||
title="Questions"
|
||||
description={`${answeredCount} of ${total} answered${p.flags.length ? `, ${p.flags.length} flagged` : ''}`}
|
||||
footer={
|
||||
<Button variant="primary" loading={p.finishing} onClick={() => (setNavOpen(false), void requestFinish())}>
|
||||
{p.mode === 'exam' ? 'Submit exam' : 'Finish'}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-6 gap-2 sm:grid-cols-8">
|
||||
{p.questions.map((q, i) => {
|
||||
const s = statusOf(q);
|
||||
return (
|
||||
<button
|
||||
key={q.id}
|
||||
type="button"
|
||||
aria-label={`Question ${i + 1}, ${s === 'blank' ? 'not answered' : s === 'answered' ? 'answered' : s === 'right' ? 'correct' : 'incorrect'}${p.flags.includes(q.id) ? ', flagged' : ''}`}
|
||||
aria-current={i === index}
|
||||
onClick={() => (go(i), setNavOpen(false))}
|
||||
className={cx(
|
||||
'num relative grid aspect-square place-items-center rounded-[10px] border text-sm font-semibold',
|
||||
s === 'right' ? 'border-good bg-good-soft text-good' : s === 'wrong' ? 'border-bad bg-bad-soft text-bad' : s === 'answered' ? 'border-ink bg-ink text-paper' : 'border-line-strong text-ink-2 hover:border-ink-3',
|
||||
i === index && 'ring-2 ring-accent ring-offset-2 ring-offset-surface',
|
||||
)}
|
||||
>
|
||||
{i + 1}
|
||||
{p.flags.includes(q.id) && <span className="absolute -top-1 -right-1 size-3 rounded-full bg-marker ring-2 ring-surface" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-5 hidden flex-wrap gap-x-4 gap-y-2 text-xs text-ink-3 sm:flex">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>1</Kbd>–<Kbd>9</Kbd> or <Kbd>A</Kbd>–<Kbd>E</Kbd> choose
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd> check / next
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>←</Kbd>
|
||||
<Kbd>→</Kbd> move
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Kbd>M</Kbd> flag
|
||||
</span>
|
||||
</div>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ results ------------------------------ */
|
||||
|
||||
export interface ResultsProps {
|
||||
title: string;
|
||||
mode: 'practice' | 'exam';
|
||||
questions: SnapshotQuestion[];
|
||||
answers: Record<string, AnswerState>;
|
||||
flags: string[];
|
||||
elapsedSec: number;
|
||||
sataScoring: SataScoring;
|
||||
completedAt?: number | null;
|
||||
actions: ReactNode;
|
||||
onExit: () => void;
|
||||
exitLabel?: string;
|
||||
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
|
||||
footnote?: ReactNode;
|
||||
}
|
||||
|
||||
export function QuizResults(p: ResultsProps) {
|
||||
const [filter, setFilter] = useState<'all' | 'wrong' | 'flagged'>('all');
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
p.questions.map((q, i) => {
|
||||
const selected = p.answers[q.id]?.selected ?? [];
|
||||
const answered = selected.length > 0;
|
||||
const score = scoreQuestion(q, selected, p.sataScoring);
|
||||
return { q, i, selected, answered, score, correct: isFullyCorrect(score), scored: p.mode === 'exam' || answered };
|
||||
}),
|
||||
[p.questions, p.answers, p.sataScoring, p.mode],
|
||||
);
|
||||
const scored = rows.filter((r) => r.scored);
|
||||
const points = scored.reduce((n, r) => n + r.score, 0);
|
||||
const percent = scored.length ? Math.round((points / scored.length) * 100) : 0;
|
||||
const right = scored.filter((r) => r.correct).length;
|
||||
const partial = scored.filter((r) => !r.correct && r.score > 0).length;
|
||||
const wrong = scored.length - right - partial;
|
||||
const skipped = rows.length - scored.length;
|
||||
const tone = percent >= 80 ? 'good' : percent >= 60 ? 'warn' : 'bad';
|
||||
|
||||
const topics = useMemo(() => {
|
||||
const map = new Map<string, { n: number; s: number }>();
|
||||
for (const r of scored) {
|
||||
const key = r.q.topic || 'General';
|
||||
const cur = map.get(key) ?? { n: 0, s: 0 };
|
||||
cur.n += 1;
|
||||
cur.s += r.score;
|
||||
map.set(key, cur);
|
||||
}
|
||||
return [...map.entries()].map(([topic, v]) => ({ topic, n: v.n, accuracy: v.s / v.n })).sort((a, b) => a.accuracy - b.accuracy);
|
||||
}, [scored]);
|
||||
|
||||
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
|
||||
const headline = percent >= 90 ? 'Excellent work' : percent >= 80 ? 'Strong result' : percent >= 60 ? 'Getting there' : 'Worth another pass';
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-paper">
|
||||
<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">
|
||||
<IconButton label={p.exitLabel ?? 'Close'} onClick={p.onExit}>
|
||||
<X />
|
||||
</IconButton>
|
||||
<div className="min-w-0 flex-1 truncate text-sm font-semibold">{p.title}</div>
|
||||
</div>
|
||||
</header>
|
||||
<main className="mx-auto max-w-3xl animate-in px-4 pt-8 pb-24 sm:px-5">
|
||||
<section className="card p-6 sm:p-8">
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-left">
|
||||
<Ring value={percent / 100} size={128} stroke={11} tone={tone}>
|
||||
<div className="leading-none">
|
||||
<span className="display num text-[38px] font-medium">{percent}</span>
|
||||
<span className="text-lg text-ink-3">%</span>
|
||||
</div>
|
||||
</Ring>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
|
||||
<h1 className="display text-[30px]">{headline}</h1>
|
||||
<p className="mt-1.5 text-[15px] text-ink-2">
|
||||
<span className="num font-semibold text-ink">{Number.isInteger(points) ? points : points.toFixed(1)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
|
||||
{p.elapsedSec > 0 ? ` in ${formatMinutes(p.elapsedSec)}` : ''}
|
||||
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
|
||||
</p>
|
||||
<div className="mt-3 flex flex-wrap justify-center gap-1.5 sm:justify-start">
|
||||
<Badge tone="good">{right} correct</Badge>
|
||||
{partial > 0 && <Badge tone="warn">{partial} partly</Badge>}
|
||||
{wrong > 0 && <Badge tone="bad">{wrong} incorrect</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 flex flex-wrap justify-center gap-2 border-t border-line pt-5 sm:justify-start">{p.actions}</div>
|
||||
{p.footnote && <div className="mt-4 text-[13px] text-ink-3">{p.footnote}</div>}
|
||||
</section>
|
||||
|
||||
{topics.length > 1 && (
|
||||
<section className="mt-6">
|
||||
<h2 className="eyebrow mb-2.5">By topic</h2>
|
||||
<div className="card divide-y divide-line">
|
||||
{topics.map((t) => {
|
||||
const pc = Math.round(t.accuracy * 100);
|
||||
return (
|
||||
<div key={t.topic} className="flex items-center gap-3 px-4 py-2.5">
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">{t.topic}</span>
|
||||
<span className="text-xs text-ink-3">{plural(t.n, 'question')}</span>
|
||||
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-ink/8 sm:w-36">
|
||||
<div className={cx('h-full rounded-full', pc >= 80 ? 'bg-good' : pc >= 60 ? 'bg-warn' : 'bg-bad')} style={{ width: `${Math.max(4, pc)}%` }} />
|
||||
</div>
|
||||
<span className="num w-10 text-right text-[13px] font-medium">{pc}%</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="mt-8">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="eyebrow">Review</h2>
|
||||
<Segmented
|
||||
size="sm"
|
||||
label="Filter questions"
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
options={[
|
||||
{ value: 'all', label: `All ${rows.length}` },
|
||||
{ value: 'wrong', label: `Missed ${scored.length - right}` },
|
||||
...(p.flags.length > 0 ? [{ value: 'flagged' as const, label: `Flagged ${p.flags.length}` }] : []),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
{visible.length === 0 ? (
|
||||
<div className="card px-5 py-8 text-center text-sm text-ink-2">{filter === 'wrong' ? 'Nothing missed. Every scored question was correct.' : 'No questions here.'}</div>
|
||||
) : (
|
||||
<ol className="space-y-3">
|
||||
{visible.map((r) => (
|
||||
<li key={r.q.id} className="card p-4 sm:p-5">
|
||||
<div className="mb-2.5 flex flex-wrap items-center gap-2">
|
||||
<span className="num text-xs font-semibold text-ink-3">{String(r.i + 1).padStart(2, '0')}</span>
|
||||
{!r.scored ? <Badge>Skipped</Badge> : r.correct ? <Badge tone="good">Correct</Badge> : r.score > 0 ? <Badge tone="warn">Partly correct</Badge> : <Badge tone="bad">{r.answered ? 'Incorrect' : 'Not answered'}</Badge>}
|
||||
{r.q.topic && <Badge tone="accent">{r.q.topic}</Badge>}
|
||||
{p.flags.includes(r.q.id) && (
|
||||
<Badge tone="marker">
|
||||
<Flag /> Flagged
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Markdown serif className="mb-3.5 text-[17px]">
|
||||
{r.q.stem}
|
||||
</Markdown>
|
||||
<OptionList question={r.q} selected={r.selected} revealed />
|
||||
{r.q.rationale && (
|
||||
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
|
||||
<div className="eyebrow mb-1">Rationale</div>
|
||||
<Markdown className="text-[14.5px]">{r.q.rationale}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{p.renderExtra && (
|
||||
<div className="mt-3">
|
||||
{p.renderExtra(
|
||||
r.q,
|
||||
r.q.options.filter((o) => r.selected.includes(o.id)).map((o) => o.text),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RetakeIcon() {
|
||||
return <RotateCcw />;
|
||||
}
|
||||
42
web/src/features/study.ts
Normal file
42
web/src/features/study.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useRefresh } from '@/lib/queries';
|
||||
import type { Attempt } from '@/lib/types';
|
||||
|
||||
export type AttemptSource =
|
||||
| { type: 'quiz'; quizId: string }
|
||||
| { type: 'retake'; attemptId: string }
|
||||
| { type: 'missed'; classId?: string; quizId?: string }
|
||||
| { type: 'topics'; classId: string; topics: string[] }
|
||||
| { type: 'questions'; questionIds: string[]; title?: string };
|
||||
|
||||
export interface StartOptions {
|
||||
mode?: 'practice' | 'exam';
|
||||
source: AttemptSource;
|
||||
shuffleQuestions?: boolean;
|
||||
shuffleOptions?: boolean;
|
||||
count?: number;
|
||||
timeLimitMin?: number | null;
|
||||
}
|
||||
|
||||
/** Starts a quiz session and opens it. */
|
||||
export function useStartSession() {
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const [starting, setStarting] = useState(false);
|
||||
const start = async (opts: StartOptions) => {
|
||||
setStarting(true);
|
||||
try {
|
||||
const res = await api.post<{ attempt: Attempt }>('/api/attempts', { mode: 'practice', ...opts });
|
||||
void refresh();
|
||||
navigate(`/session/${res.attempt.id}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setStarting(false);
|
||||
}
|
||||
};
|
||||
return { start, starting };
|
||||
}
|
||||
147
web/src/lib/api.ts
Normal file
147
web/src/lib/api.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
/** Thin client for the Study Desk API: JSON in, JSON out, typed errors, CSRF header on every call. */
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code: string;
|
||||
details?: unknown;
|
||||
constructor(status: number, code: string, message: string, details?: unknown) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
/** Set by the app shell: called when any request comes back 401 so the login screen can appear. */
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
export function setUnauthorizedHandler(fn: (() => void) | null): void {
|
||||
onUnauthorized = fn;
|
||||
}
|
||||
|
||||
const BASE_HEADERS = { 'X-Requested-With': 'studydesk' };
|
||||
|
||||
async function toError(res: Response): Promise<ApiError> {
|
||||
let code = 'http_error';
|
||||
let message = res.status >= 500 ? 'The server ran into a problem. Try again in a moment.' : `Request failed (${res.status})`;
|
||||
let details: unknown;
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body?.error) {
|
||||
code = body.error.code ?? code;
|
||||
message = body.error.message ?? message;
|
||||
details = body.error.details;
|
||||
}
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
return new ApiError(res.status, code, message, details);
|
||||
}
|
||||
|
||||
export async function request<T>(method: string, url: string, body?: unknown, init: { signal?: AbortSignal; publicCall?: boolean } = {}): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
signal: init.signal,
|
||||
headers: body instanceof FormData ? BASE_HEADERS : body !== undefined ? { ...BASE_HEADERS, 'Content-Type': 'application/json' } : BASE_HEADERS,
|
||||
body: body instanceof FormData ? body : body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name === 'AbortError') throw e;
|
||||
throw new ApiError(0, 'network', 'Could not reach the server. Check your connection and try again.');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const err = await toError(res);
|
||||
if (res.status === 401 && !init.publicCall && err.code === 'unauthorized') onUnauthorized?.();
|
||||
throw err;
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal }),
|
||||
post: <T>(url: string, body?: unknown) => request<T>('POST', url, body ?? {}),
|
||||
put: <T>(url: string, body?: unknown) => request<T>('PUT', url, body ?? {}),
|
||||
patch: <T>(url: string, body?: unknown) => request<T>('PATCH', url, body ?? {}),
|
||||
del: <T>(url: string) => request<T>('DELETE', url),
|
||||
upload: <T>(url: string, form: FormData) => request<T>('POST', url, form),
|
||||
/** Public (share-link) calls never trigger the login screen. */
|
||||
pub: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal, publicCall: true }),
|
||||
};
|
||||
|
||||
export function errorMessage(e: unknown, fallback = 'Something went wrong.'): string {
|
||||
if (e instanceof ApiError) return e.message;
|
||||
if (e instanceof Error && e.message) return e.message;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Uploads with progress (fetch cannot report upload progress). */
|
||||
export function uploadWithProgress<T>(url: string, form: FormData, onProgress: (fraction: number) => void): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', url);
|
||||
xhr.setRequestHeader('X-Requested-With', 'studydesk');
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress(e.loaded / e.total);
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError(0, 'network', 'The upload was interrupted. Check your connection and try again.'));
|
||||
xhr.onload = () => {
|
||||
let body: any = null;
|
||||
try {
|
||||
body = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve(body as T);
|
||||
else {
|
||||
if (xhr.status === 401) onUnauthorized?.();
|
||||
reject(new ApiError(xhr.status, body?.error?.code ?? 'http_error', body?.error?.message ?? `Upload failed (${xhr.status})`, body?.error?.details));
|
||||
}
|
||||
};
|
||||
xhr.send(form);
|
||||
});
|
||||
}
|
||||
|
||||
/** POSTs JSON and reads a server-sent event stream of JSON objects. */
|
||||
export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
if (!res.ok || !res.body) {
|
||||
const err = await toError(res);
|
||||
if (res.status === 401) onUnauthorized?.();
|
||||
throw err;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let idx: number;
|
||||
while ((idx = buffer.search(/\r?\n\r?\n/)) >= 0) {
|
||||
const block = buffer.slice(0, idx);
|
||||
buffer = buffer.slice(idx).replace(/^\r?\n\r?\n/, '');
|
||||
const data = block
|
||||
.split(/\r?\n/)
|
||||
.filter((l) => l.startsWith('data:'))
|
||||
.map((l) => l.slice(5).trimStart())
|
||||
.join('\n');
|
||||
if (!data) continue;
|
||||
try {
|
||||
const event = JSON.parse(data) as T;
|
||||
if (event.type !== 'ping') onEvent(event);
|
||||
} catch {
|
||||
/* skip malformed event */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
web/src/lib/assistantStore.ts
Normal file
67
web/src/lib/assistantStore.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
|
||||
export interface AssistantSeed {
|
||||
id: number;
|
||||
prompt?: string;
|
||||
autoSend?: boolean;
|
||||
newChat?: boolean;
|
||||
classId?: string | null;
|
||||
documentIds?: string[];
|
||||
}
|
||||
|
||||
interface State {
|
||||
open: boolean;
|
||||
seed: AssistantSeed | null;
|
||||
/** What the user is currently looking at; supplied by pages. */
|
||||
context: { classId: string | null; documentIds: string[]; label: string };
|
||||
}
|
||||
|
||||
let state: State = { open: false, seed: null, context: { classId: null, documentIds: [], label: '' } };
|
||||
const listeners = new Set<() => void>();
|
||||
const set = (patch: Partial<State>) => {
|
||||
state = { ...state, ...patch };
|
||||
listeners.forEach((fn) => fn());
|
||||
};
|
||||
let seedId = 0;
|
||||
|
||||
export const assistant = {
|
||||
/** Opens the assistant, optionally with a prepared prompt. */
|
||||
open(seed: Omit<AssistantSeed, 'id'> = {}) {
|
||||
seedId += 1;
|
||||
set({ open: true, seed: { id: seedId, ...seed } });
|
||||
},
|
||||
close() {
|
||||
set({ open: false });
|
||||
},
|
||||
toggle() {
|
||||
set({ open: !state.open });
|
||||
},
|
||||
consumeSeed() {
|
||||
if (state.seed) set({ seed: null });
|
||||
},
|
||||
setContext(context: State['context']) {
|
||||
const cur = state.context;
|
||||
if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return;
|
||||
set({ context });
|
||||
},
|
||||
};
|
||||
|
||||
export function useAssistantState(): State {
|
||||
return useSyncExternalStore(
|
||||
(fn) => {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
() => state,
|
||||
() => state,
|
||||
);
|
||||
}
|
||||
|
||||
/** Pages call this so the assistant knows which class or document "this" refers to. */
|
||||
export function useAssistantContext(classId: string | null | undefined, label = '', documentIds: string[] = []): void {
|
||||
const key = documentIds.join(',');
|
||||
useEffect(() => {
|
||||
assistant.setContext({ classId: classId ?? null, documentIds: key ? key.split(',') : [], label });
|
||||
return () => assistant.setContext({ classId: null, documentIds: [], label: '' });
|
||||
}, [classId, label, key]);
|
||||
}
|
||||
54
web/src/lib/queries.ts
Normal file
54
web/src/lib/queries.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback } from 'react';
|
||||
import { api } from './api';
|
||||
import type { AiModel, AiStatus, ClassDetail, ClassListItem, DeckDetail, Overview, QuizDetail } from './types';
|
||||
|
||||
export const qk = {
|
||||
auth: ['auth'] as const,
|
||||
classes: ['classes'] as const,
|
||||
class: (id: string) => ['class', id] as const,
|
||||
quiz: (id: string) => ['quiz', id] as const,
|
||||
deck: (id: string) => ['deck', id] as const,
|
||||
note: (id: string) => ['note', id] as const,
|
||||
document: (id: string) => ['document', id] as const,
|
||||
attempt: (id: string) => ['attempt', id] as const,
|
||||
draft: (id: string) => ['draft', id] as const,
|
||||
drafts: ['drafts'] as const,
|
||||
overview: ['overview'] as const,
|
||||
aiStatus: ['ai', 'status'] as const,
|
||||
aiModels: ['ai', 'models'] as const,
|
||||
aiProviders: ['ai', 'providers'] as const,
|
||||
shares: ['shares'] as const,
|
||||
templates: ['templates'] as const,
|
||||
settings: ['settings'] as const,
|
||||
};
|
||||
|
||||
export const useClasses = () => useQuery({ queryKey: qk.classes, queryFn: ({ signal }) => api.get<{ classes: ClassListItem[] }>('/api/classes', signal).then((r) => r.classes) });
|
||||
|
||||
export const useClass = (id: string | undefined, refetchInterval?: number | false) =>
|
||||
useQuery({ queryKey: qk.class(id ?? ''), queryFn: ({ signal }) => api.get<ClassDetail>(`/api/classes/${id}`, signal), enabled: Boolean(id), refetchInterval });
|
||||
|
||||
export const useQuiz = (id: string | undefined) => useQuery({ queryKey: qk.quiz(id ?? ''), queryFn: ({ signal }) => api.get<QuizDetail>(`/api/quizzes/${id}`, signal), enabled: Boolean(id) });
|
||||
|
||||
export const useDeck = (id: string | undefined) => useQuery({ queryKey: qk.deck(id ?? ''), queryFn: ({ signal }) => api.get<DeckDetail>(`/api/decks/${id}`, signal), enabled: Boolean(id) });
|
||||
|
||||
export const useOverview = () => useQuery({ queryKey: qk.overview, queryFn: ({ signal }) => api.get<Overview>('/api/overview', signal) });
|
||||
|
||||
export const useAiStatus = () => useQuery({ queryKey: qk.aiStatus, queryFn: ({ signal }) => api.get<AiStatus>('/api/ai/status', signal), staleTime: 60_000 });
|
||||
|
||||
export const useAiModels = () => useQuery({ queryKey: qk.aiModels, queryFn: ({ signal }) => api.get<{ models: AiModel[] }>('/api/ai/models', signal).then((r) => r.models), staleTime: 60_000 });
|
||||
|
||||
/**
|
||||
* After a change, refresh everything that could show it. The whole dataset is small and
|
||||
* requests are local, so correctness beats precision here.
|
||||
*/
|
||||
export function useRefresh() {
|
||||
const qc = useQueryClient();
|
||||
return useCallback(
|
||||
(...only: (readonly unknown[])[]) => {
|
||||
if (only.length > 0) return Promise.all(only.map((queryKey) => qc.invalidateQueries({ queryKey })));
|
||||
return qc.invalidateQueries({ predicate: (q) => q.queryKey[0] !== 'auth' && q.queryKey[0] !== 'public' });
|
||||
},
|
||||
[qc],
|
||||
);
|
||||
}
|
||||
514
web/src/lib/types.ts
Normal file
514
web/src/lib/types.ts
Normal file
|
|
@ -0,0 +1,514 @@
|
|||
import type { Card, ClassColor, ContentDraft, Option, Question, QuestionType } from '@shared/content';
|
||||
|
||||
export type { Card, ClassColor, ContentDraft, Option, Question, QuestionType };
|
||||
|
||||
export interface ClassInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
description: string;
|
||||
color: ClassColor;
|
||||
archived: boolean;
|
||||
sortOrder: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
export interface ClassListItem extends ClassInfo {
|
||||
counts: { quizzes: number; decks: number; documents: number; notes: number };
|
||||
due: number;
|
||||
}
|
||||
export interface Folder {
|
||||
id: string;
|
||||
classId: string;
|
||||
name: string;
|
||||
sortOrder: number;
|
||||
shared?: boolean;
|
||||
}
|
||||
export type ItemKind = 'quiz' | 'deck' | 'document' | 'note';
|
||||
|
||||
interface ItemBase {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
folderId: string | null;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
shared: boolean;
|
||||
}
|
||||
export interface QuizItem extends ItemBase {
|
||||
kind: 'quiz';
|
||||
questionCount: number;
|
||||
attempts: number;
|
||||
lastPercent: number | null;
|
||||
lastStudiedAt: number | null;
|
||||
activeAttemptId: string | null;
|
||||
}
|
||||
export interface DeckItem extends ItemBase {
|
||||
kind: 'deck';
|
||||
cardCount: number;
|
||||
dueCount: number;
|
||||
newCount: number;
|
||||
learnedCount: number;
|
||||
}
|
||||
export interface DocumentItem extends ItemBase {
|
||||
kind: 'document';
|
||||
docKind: string;
|
||||
filename: string;
|
||||
size: number;
|
||||
status: 'pending' | 'processing' | 'ready' | 'failed';
|
||||
error: string;
|
||||
progress: number;
|
||||
pageCount: number | null;
|
||||
tokenCount: number;
|
||||
needsOcr: boolean;
|
||||
}
|
||||
export interface NoteItem extends ItemBase {
|
||||
kind: 'note';
|
||||
noteKind: string;
|
||||
}
|
||||
export type Item = QuizItem | DeckItem | DocumentItem | NoteItem;
|
||||
|
||||
export interface DueCounts {
|
||||
learning: number;
|
||||
review: number;
|
||||
new: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface Share {
|
||||
id: string;
|
||||
token: string;
|
||||
enabled: boolean;
|
||||
viewCount: number;
|
||||
lastViewedAt: number | null;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface ClassDetail {
|
||||
class: ClassInfo;
|
||||
folders: Folder[];
|
||||
items: Item[];
|
||||
due: DueCounts;
|
||||
share: Share | null;
|
||||
}
|
||||
|
||||
export interface QuizInfo {
|
||||
id: string;
|
||||
classId: string;
|
||||
folderId: string | null;
|
||||
title: string;
|
||||
description: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface AttemptSummary {
|
||||
id: string;
|
||||
quizId: string | null;
|
||||
classId: string | null;
|
||||
title: string;
|
||||
mode: 'practice' | 'exam';
|
||||
kind: string;
|
||||
status: 'active' | 'completed';
|
||||
questionCount: number;
|
||||
answeredCount: number;
|
||||
currentIndex: number;
|
||||
elapsedSec: number;
|
||||
score: number | null;
|
||||
maxScore: number | null;
|
||||
startedAt: number;
|
||||
updatedAt: number;
|
||||
completedAt: number | null;
|
||||
}
|
||||
|
||||
export interface SnapshotQuestion {
|
||||
id: string;
|
||||
quizId?: string | null;
|
||||
quizTitle?: string;
|
||||
type: QuestionType;
|
||||
stem: string;
|
||||
options: Option[];
|
||||
rationale: string;
|
||||
topic: string;
|
||||
difficulty: string;
|
||||
}
|
||||
|
||||
export interface AnswerState {
|
||||
selected: string[];
|
||||
checked: boolean;
|
||||
at?: number;
|
||||
}
|
||||
|
||||
export interface Attempt {
|
||||
id: string;
|
||||
quizId: string | null;
|
||||
classId: string | null;
|
||||
title: string;
|
||||
mode: 'practice' | 'exam';
|
||||
kind: string;
|
||||
status: 'active' | 'completed';
|
||||
settings: { shuffleQuestions: boolean; shuffleOptions: boolean; timeLimitSec: number | null; sataScoring: 'partial' | 'strict' };
|
||||
questions: SnapshotQuestion[];
|
||||
answers: Record<string, AnswerState>;
|
||||
flags: string[];
|
||||
currentIndex: number;
|
||||
elapsedSec: number;
|
||||
score: number | null;
|
||||
maxScore: number | null;
|
||||
startedAt: number;
|
||||
updatedAt: number;
|
||||
completedAt: number | null;
|
||||
results: Record<string, { score: number; correct: boolean; answered: boolean }> | null;
|
||||
}
|
||||
|
||||
export interface QuizDetail {
|
||||
quiz: QuizInfo;
|
||||
class: ClassInfo;
|
||||
questions: Question[];
|
||||
questionStats: Record<string, { seen: number; correct: number; lastCorrect: boolean }>;
|
||||
history: AttemptSummary[];
|
||||
activeAttempt: AttemptSummary | null;
|
||||
share: Share | null;
|
||||
}
|
||||
|
||||
export interface DeckStats {
|
||||
total: number;
|
||||
new: number;
|
||||
learning: number;
|
||||
young: number;
|
||||
mature: number;
|
||||
suspended: number;
|
||||
dueNow: number;
|
||||
}
|
||||
|
||||
export interface DeckDetail {
|
||||
deck: QuizInfo;
|
||||
class: ClassInfo;
|
||||
cards: Card[];
|
||||
stats: DeckStats;
|
||||
due: DueCounts;
|
||||
session: { state: unknown; updatedAt: number } | null;
|
||||
share: Share | null;
|
||||
}
|
||||
|
||||
export interface RatingPreview {
|
||||
rating: 1 | 2 | 3 | 4;
|
||||
label: string;
|
||||
interval: string;
|
||||
due: number;
|
||||
}
|
||||
export interface QueueCard {
|
||||
card: Card;
|
||||
deckTitle: string;
|
||||
classId: string;
|
||||
className: string;
|
||||
classColor: ClassColor;
|
||||
previews: RatingPreview[];
|
||||
}
|
||||
|
||||
export interface DayActivity {
|
||||
date: string;
|
||||
cards: number;
|
||||
questions: number;
|
||||
total: number;
|
||||
}
|
||||
export interface Streak {
|
||||
current: number;
|
||||
longest: number;
|
||||
todayDone: boolean;
|
||||
todayTotal: number;
|
||||
goal: number;
|
||||
}
|
||||
export interface TopicStat {
|
||||
topic: string;
|
||||
classId: string | null;
|
||||
className: string;
|
||||
classColor: ClassColor;
|
||||
seen: number;
|
||||
accuracy: number;
|
||||
questions: number;
|
||||
}
|
||||
export interface Totals {
|
||||
questionsAnswered: number;
|
||||
accuracy: number | null;
|
||||
cardsReviewed: number;
|
||||
retention: number | null;
|
||||
quizzesCompleted: number;
|
||||
studyDays: number;
|
||||
}
|
||||
export interface AppSettings {
|
||||
timezone: string;
|
||||
newCardsPerDay: number;
|
||||
desiredRetention: number;
|
||||
sataScoring: 'partial' | 'strict';
|
||||
dailyGoal: number;
|
||||
}
|
||||
export interface Overview {
|
||||
settings: AppSettings;
|
||||
due: DueCounts;
|
||||
streak: Streak;
|
||||
activity: DayActivity[];
|
||||
activeAttempts: AttemptSummary[];
|
||||
recentAttempts: AttemptSummary[];
|
||||
weakTopics: TopicStat[];
|
||||
missedCount: number;
|
||||
totals: Totals;
|
||||
forecast: number[];
|
||||
}
|
||||
export interface Insights {
|
||||
range: number;
|
||||
totals: Totals;
|
||||
streak: Streak;
|
||||
activity: DayActivity[];
|
||||
accuracy: { date: string; answered: number; accuracy: number | null }[];
|
||||
topics: TopicStat[];
|
||||
forecast: number[];
|
||||
due: DueCounts;
|
||||
missedCount: number;
|
||||
recentAttempts: AttemptSummary[];
|
||||
}
|
||||
|
||||
export interface DocumentInfo {
|
||||
id: string;
|
||||
classId: string;
|
||||
folderId: string | null;
|
||||
title: string;
|
||||
filename: string;
|
||||
mime: string;
|
||||
docKind: 'pdf' | 'docx' | 'pptx' | 'text' | 'markdown' | 'image';
|
||||
size: number;
|
||||
status: 'pending' | 'processing' | 'ready' | 'failed';
|
||||
error: string;
|
||||
progress: number;
|
||||
pageCount: number | null;
|
||||
charCount: number;
|
||||
tokenCount: number;
|
||||
chunkCount: number;
|
||||
needsOcr: boolean;
|
||||
warnings: string[];
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
export interface DocChunk {
|
||||
id: number;
|
||||
seq: number;
|
||||
text: string;
|
||||
heading: string;
|
||||
pageStart: number | null;
|
||||
pageEnd: number | null;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface NoteInfo {
|
||||
id: string;
|
||||
classId: string;
|
||||
folderId: string | null;
|
||||
title: string;
|
||||
content: string;
|
||||
kind: string;
|
||||
source: Record<string, unknown>;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface SearchHit {
|
||||
kind: 'class' | 'quiz' | 'deck' | 'note' | 'document' | 'question' | 'card' | 'passage';
|
||||
id: string;
|
||||
title: string;
|
||||
snippet: string;
|
||||
classId: string;
|
||||
className: string;
|
||||
classColor: ClassColor;
|
||||
parentId?: string;
|
||||
page?: number | null;
|
||||
}
|
||||
|
||||
export interface ShareListItem extends Share {
|
||||
kind: 'quiz' | 'deck' | 'folder' | 'class' | 'note' | 'document';
|
||||
targetId: string;
|
||||
title: string;
|
||||
classId: string | null;
|
||||
className: string;
|
||||
classColor: ClassColor;
|
||||
}
|
||||
|
||||
/* ------------------------------ AI ------------------------------ */
|
||||
|
||||
export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'openai_compatible' | 'ollama';
|
||||
export interface AdapterMeta {
|
||||
kind: ProviderKind;
|
||||
label: string;
|
||||
defaultBaseUrl: string | null;
|
||||
requiresApiKey: boolean;
|
||||
requiresBaseUrl: boolean;
|
||||
supportsDiscovery: boolean;
|
||||
docsUrl: string;
|
||||
keyHint: string;
|
||||
}
|
||||
export interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: ProviderKind;
|
||||
baseUrl: string | null;
|
||||
hasKey: boolean;
|
||||
keyPreview: string;
|
||||
headerNames: string[];
|
||||
enabled: boolean;
|
||||
lastTestAt: number | null;
|
||||
lastTestOk: boolean | null;
|
||||
lastTestMessage: string;
|
||||
createdAt: number;
|
||||
}
|
||||
export interface ModelCaps {
|
||||
tools: boolean;
|
||||
vision: boolean;
|
||||
pdf: boolean;
|
||||
reasoning: boolean;
|
||||
temperature: boolean;
|
||||
}
|
||||
export interface AiModel {
|
||||
id: string;
|
||||
providerId: string;
|
||||
providerName: string;
|
||||
providerKind: ProviderKind;
|
||||
model: string;
|
||||
label: string;
|
||||
source: string;
|
||||
enabled: boolean;
|
||||
available: boolean;
|
||||
capabilities: ModelCaps;
|
||||
contextWindow: number | null;
|
||||
maxOutput: number | null;
|
||||
priceIn: number | null;
|
||||
priceOut: number | null;
|
||||
}
|
||||
export type TaskName = 'chat' | 'generate' | 'vision' | 'quick';
|
||||
export interface TaskConfig {
|
||||
modelId: string | null;
|
||||
temperature: number | null;
|
||||
reasoningEffort: 'none' | 'low' | 'medium' | 'high' | null;
|
||||
maxOutputTokens: number | null;
|
||||
}
|
||||
export type TaskSettings = Record<TaskName | 'default', TaskConfig>;
|
||||
export interface AiStatus {
|
||||
ready: boolean;
|
||||
modelCount: number;
|
||||
tasks: TaskSettings;
|
||||
resolved: Record<TaskName, { modelId: string; label: string; provider: string } | null>;
|
||||
}
|
||||
|
||||
export interface DraftMeta {
|
||||
origin?: string;
|
||||
model?: string;
|
||||
sources?: { documentId: string; title: string }[];
|
||||
replaceQuestionIds?: string[];
|
||||
targetKind?: 'quiz' | 'deck';
|
||||
targetId?: string;
|
||||
notes?: string[];
|
||||
}
|
||||
export interface Draft {
|
||||
id: string;
|
||||
kind: 'quiz' | 'deck' | 'note';
|
||||
classId: string | null;
|
||||
folderId: string | null;
|
||||
title: string;
|
||||
payload: ContentDraft;
|
||||
meta: DraftMeta;
|
||||
status: 'generating' | 'ready' | 'failed' | 'saved' | 'discarded';
|
||||
progress: number;
|
||||
progressLabel: string;
|
||||
error: string;
|
||||
savedKind: string | null;
|
||||
savedId: string | null;
|
||||
itemCount: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
export type DraftSummary = Omit<Draft, 'payload'>;
|
||||
|
||||
export type UiItem =
|
||||
| { type: 'draft'; draftId: string; kind: 'quiz' | 'deck' | 'note'; title: string; count: number; status: string }
|
||||
| { type: 'action'; actionId: string; summary: string; changes: string[]; status: 'pending' | 'confirmed' | 'cancelled' | 'failed'; result?: string }
|
||||
| { type: 'sources'; items: { ref: string; chunkId: number; documentId: string; label: string }[] }
|
||||
| { type: 'link'; kind: 'quiz' | 'deck' | 'note' | 'document' | 'class' | 'attempt'; id: string; title: string };
|
||||
|
||||
export interface ToolActivity {
|
||||
id: string;
|
||||
name: string;
|
||||
label: string;
|
||||
status: 'running' | 'done' | 'error';
|
||||
summary?: string;
|
||||
}
|
||||
export interface ChatMessage {
|
||||
id: number | string;
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
tools: ToolActivity[];
|
||||
ui: UiItem[];
|
||||
model?: string;
|
||||
error?: string;
|
||||
createdAt: number;
|
||||
pending?: boolean;
|
||||
reasoning?: string;
|
||||
}
|
||||
export type AssistantEvent =
|
||||
| { type: 'start'; conversationId: string; model: string }
|
||||
| { type: 'text'; delta: string }
|
||||
| { type: 'reasoning'; delta: string }
|
||||
| { type: 'tool'; tool: ToolActivity }
|
||||
| { type: 'ui'; item: UiItem }
|
||||
| { type: 'error'; message: string; code: string; detail?: string }
|
||||
| { type: 'done'; conversationId: string; title: string };
|
||||
|
||||
export interface Template {
|
||||
id: string;
|
||||
kind: 'quiz' | 'deck' | 'generation';
|
||||
name: string;
|
||||
description: string;
|
||||
payload: Record<string, any>;
|
||||
builtin: boolean;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
/* ------------------------------ public ------------------------------ */
|
||||
|
||||
export interface PublicQuiz {
|
||||
kind: 'quiz';
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
questions: SnapshotQuestion[];
|
||||
}
|
||||
export interface PublicDeck {
|
||||
kind: 'deck';
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
cards: { id: string; front: string; back: string; hint: string }[];
|
||||
}
|
||||
export interface PublicNote {
|
||||
kind: 'note';
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
export interface PublicDocument {
|
||||
kind: 'document';
|
||||
id: string;
|
||||
title: string;
|
||||
filename: string;
|
||||
docKind: string;
|
||||
size: number;
|
||||
pageCount: number | null;
|
||||
}
|
||||
export interface PublicCollection {
|
||||
kind: 'collection';
|
||||
title: string;
|
||||
subtitle: string;
|
||||
description?: string;
|
||||
color: ClassColor;
|
||||
folders: { id: string; name: string }[];
|
||||
items: { kind: 'quiz' | 'deck' | 'note'; id: string; title: string; description: string; folderId: string | null; count: number }[];
|
||||
}
|
||||
export type PublicPayload = PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection;
|
||||
288
web/src/lib/util.ts
Normal file
288
web/src/lib/util.ts
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
import clsx, { type ClassValue } from 'clsx';
|
||||
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
||||
|
||||
export const cx = (...v: ClassValue[]) => clsx(v);
|
||||
|
||||
/* ------------------------------ formatting ------------------------------ */
|
||||
|
||||
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
|
||||
|
||||
export function timeAgo(ts: number | null | undefined, nowTs = Date.now()): string {
|
||||
if (!ts) return 'never';
|
||||
const diff = ts - nowTs;
|
||||
const abs = Math.abs(diff);
|
||||
if (abs < 45_000) return 'just now';
|
||||
if (abs < 3_600_000) return rtf.format(Math.round(diff / 60_000), 'minute');
|
||||
if (abs < 86_400_000) return rtf.format(Math.round(diff / 3_600_000), 'hour');
|
||||
if (abs < 7 * 86_400_000) return rtf.format(Math.round(diff / 86_400_000), 'day');
|
||||
return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: new Date(ts).getFullYear() === new Date(nowTs).getFullYear() ? undefined : 'numeric' });
|
||||
}
|
||||
|
||||
export function formatDate(ts: number): string {
|
||||
return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
||||
}
|
||||
|
||||
export function formatDateTime(ts: number): string {
|
||||
return new Date(ts).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
||||
}
|
||||
|
||||
export function formatDuration(totalSec: number): string {
|
||||
const s = Math.max(0, Math.round(totalSec));
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const sec = s % 60;
|
||||
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
|
||||
return `${m}:${String(sec).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function formatMinutes(totalSec: number): string {
|
||||
if (totalSec < 60) return `${Math.round(totalSec)}s`;
|
||||
const m = Math.round(totalSec / 60);
|
||||
if (m < 60) return `${m} min`;
|
||||
return `${Math.floor(m / 60)}h ${m % 60}m`;
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||
if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(1)} MB`;
|
||||
return `${(bytes / 1073741824).toFixed(2)} GB`;
|
||||
}
|
||||
|
||||
export function plural(n: number, one: string, many = `${one}s`): string {
|
||||
return `${n.toLocaleString()} ${n === 1 ? one : many}`;
|
||||
}
|
||||
|
||||
export function pct(score: number | null | undefined, max: number | null | undefined): number | null {
|
||||
if (score === null || score === undefined || !max) return null;
|
||||
return Math.round((score / max) * 100);
|
||||
}
|
||||
|
||||
export function formatTokens(n: number | null | undefined): string {
|
||||
if (!n) return '0';
|
||||
if (n < 1000) return String(n);
|
||||
if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`;
|
||||
return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
}
|
||||
|
||||
export function formatCost(n: number | null | undefined): string {
|
||||
if (n === null || n === undefined) return '—';
|
||||
if (n === 0) return '$0.00';
|
||||
if (n < 0.01) return '<$0.01';
|
||||
return `$${n.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export function gradeTone(percent: number | null): 'good' | 'warn' | 'bad' | 'none' {
|
||||
if (percent === null) return 'none';
|
||||
if (percent >= 80) return 'good';
|
||||
if (percent >= 60) return 'warn';
|
||||
return 'bad';
|
||||
}
|
||||
|
||||
export function downloadFile(url: string): void {
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.rel = 'noopener';
|
||||
a.download = '';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
|
||||
export function downloadText(filename: string, text: string, mime = 'application/json'): void {
|
||||
const url = URL.createObjectURL(new Blob([text], { type: mime }));
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
export async function copyText(text: string): Promise<boolean> {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
} catch {
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function shuffle<T>(items: readonly T[]): T[] {
|
||||
const out = [...items];
|
||||
for (let i = out.length - 1; i > 0; i -= 1) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ------------------------------ theme ------------------------------ */
|
||||
|
||||
export type ThemeChoice = 'light' | 'dark' | 'system';
|
||||
const themeListeners = new Set<() => void>();
|
||||
|
||||
function readTheme(): ThemeChoice {
|
||||
try {
|
||||
const v = localStorage.getItem('sd.theme');
|
||||
return v === 'light' || v === 'dark' ? v : 'system';
|
||||
} catch {
|
||||
return 'system';
|
||||
}
|
||||
}
|
||||
|
||||
function applyTheme(choice: ThemeChoice): void {
|
||||
const dark = choice === 'dark' || (choice === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
export function setTheme(choice: ThemeChoice): void {
|
||||
try {
|
||||
localStorage.setItem('sd.theme', choice);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
applyTheme(choice);
|
||||
themeListeners.forEach((fn) => fn());
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||||
applyTheme(readTheme());
|
||||
themeListeners.forEach((fn) => fn());
|
||||
});
|
||||
}
|
||||
|
||||
export function useTheme(): [ThemeChoice, (c: ThemeChoice) => void] {
|
||||
const choice = useSyncExternalStore(
|
||||
(fn) => {
|
||||
themeListeners.add(fn);
|
||||
return () => themeListeners.delete(fn);
|
||||
},
|
||||
readTheme,
|
||||
() => 'system' as ThemeChoice,
|
||||
);
|
||||
return [choice, setTheme];
|
||||
}
|
||||
|
||||
/* ------------------------------ hooks ------------------------------ */
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
return useSyncExternalStore(
|
||||
(fn) => {
|
||||
const mq = window.matchMedia(query);
|
||||
mq.addEventListener('change', fn);
|
||||
return () => mq.removeEventListener('change', fn);
|
||||
},
|
||||
() => window.matchMedia(query).matches,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
|
||||
export const useIsDesktop = () => useMediaQuery('(min-width: 1024px)');
|
||||
|
||||
export function isTypingTarget(target: EventTarget | null): boolean {
|
||||
const el = target as HTMLElement | null;
|
||||
if (!el || !el.tagName) return false;
|
||||
return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Global keyboard shortcuts. Keys are matched on `event.key` (lower-cased), optionally
|
||||
* prefixed with "mod+" (Ctrl or Cmd) or "shift+". Shortcuts never fire while typing
|
||||
* unless they use the modifier.
|
||||
*/
|
||||
export function useHotkeys(map: Record<string, (e: KeyboardEvent) => void>, enabled = true): void {
|
||||
const ref = useRef(map);
|
||||
ref.current = map;
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.defaultPrevented || e.isComposing) return;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if (e.altKey) return;
|
||||
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
|
||||
const combo = `${mod ? 'mod+' : ''}${e.shiftKey && key.length > 1 ? 'shift+' : ''}${key === ' ' ? 'space' : key}`;
|
||||
const handler = ref.current[combo];
|
||||
if (!handler) return;
|
||||
if (!mod && isTypingTarget(e.target)) return;
|
||||
// Leave Enter/Space alone when a button or link has focus so it activates normally.
|
||||
const tag = (e.target as HTMLElement | null)?.tagName;
|
||||
if (!mod && (key === 'Enter' || key === ' ') && (tag === 'BUTTON' || tag === 'A' || tag === 'SUMMARY')) return;
|
||||
if (document.querySelector('[role="dialog"][data-state="open"], [role="menu"][data-state="open"], [role="listbox"]') && !mod) {
|
||||
// A dialog or menu is open: page shortcuts stay out of the way.
|
||||
if (!(e.target as HTMLElement | null)?.closest('[data-hotkeys="allow"]')) return;
|
||||
}
|
||||
handler(e);
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [enabled]);
|
||||
}
|
||||
|
||||
export function useDebounced<T>(value: T, ms: number): T {
|
||||
const [v, setV] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setV(value), ms);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, ms]);
|
||||
return v;
|
||||
}
|
||||
|
||||
export function useLocalStorage<T>(key: string, initial: T): [T, (v: T | ((prev: T) => T)) => void] {
|
||||
const [value, setValue] = useState<T>(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
return raw ? (JSON.parse(raw) as T) : initial;
|
||||
} catch {
|
||||
return initial;
|
||||
}
|
||||
});
|
||||
const set = useCallback(
|
||||
(v: T | ((prev: T) => T)) => {
|
||||
setValue((prev) => {
|
||||
const next = typeof v === 'function' ? (v as (p: T) => T)(prev) : v;
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(next));
|
||||
} catch {
|
||||
/* storage full or unavailable */
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[key],
|
||||
);
|
||||
return [value, set];
|
||||
}
|
||||
|
||||
export function useDocumentTitle(title: string | undefined | null): void {
|
||||
useEffect(() => {
|
||||
if (title) document.title = `${title} · Study Desk`;
|
||||
return () => {
|
||||
document.title = 'Study Desk';
|
||||
};
|
||||
}, [title]);
|
||||
}
|
||||
|
||||
/** Keeps the latest callback without re-subscribing effects. */
|
||||
export function useLatest<T>(value: T) {
|
||||
const ref = useRef(value);
|
||||
ref.current = value;
|
||||
return ref;
|
||||
}
|
||||
|
||||
export const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform ?? '');
|
||||
export const modKey = isMac ? '⌘' : 'Ctrl';
|
||||
182
web/src/main.tsx
Normal file
182
web/src/main.tsx
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { QueryClient, QueryClientProvider, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { lazy, StrictMode, Suspense, useEffect, type ReactNode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { createBrowserRouter, Outlet, RouterProvider, useLocation, useRouteError } from 'react-router';
|
||||
import { Toaster } from 'sonner';
|
||||
import { Shell } from '@/app/Shell';
|
||||
import { api, ApiError, setUnauthorizedHandler } from '@/lib/api';
|
||||
import { qk } from '@/lib/queries';
|
||||
import { useTheme } from '@/lib/util';
|
||||
import { LoginPage, SetupPage } from '@/pages/Auth';
|
||||
import { Button, ConfirmProvider, ErrorState, PageLoading, TooltipProvider } from '@/ui';
|
||||
import './styles.css';
|
||||
|
||||
const Home = lazy(() => import('@/pages/Home'));
|
||||
const ClassPage = lazy(() => import('@/pages/ClassPage'));
|
||||
const QuizPage = lazy(() => import('@/pages/QuizPage'));
|
||||
const SessionPage = lazy(() => import('@/pages/SessionPage'));
|
||||
const DeckPage = lazy(() => import('@/pages/DeckPage'));
|
||||
const ReviewPage = lazy(() => import('@/pages/ReviewPage'));
|
||||
const CramPage = lazy(() => import('@/pages/CramPage'));
|
||||
const DocumentPage = lazy(() => import('@/pages/DocumentPage'));
|
||||
const NotePage = lazy(() => import('@/pages/NotePage'));
|
||||
const DraftPage = lazy(() => import('@/pages/DraftPage'));
|
||||
const AssistantPage = lazy(() => import('@/pages/AssistantPage'));
|
||||
const InsightsPage = lazy(() => import('@/pages/InsightsPage'));
|
||||
const SettingsPage = lazy(() => import('@/pages/SettingsPage'));
|
||||
const SharedPage = lazy(() => import('@/pages/SharedPage'));
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 15_000,
|
||||
refetchOnWindowFocus: true,
|
||||
retry: (count, error) => !(error instanceof ApiError && error.status >= 400 && error.status < 500) && count < 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function AuthGate({ children }: { children: ReactNode }) {
|
||||
const qc = useQueryClient();
|
||||
const status = useQuery({ queryKey: qk.auth, queryFn: () => api.get<{ configured: boolean; authenticated: boolean }>('/api/auth/status'), staleTime: Infinity, retry: 1 });
|
||||
useEffect(() => {
|
||||
setUnauthorizedHandler(() => {
|
||||
qc.setQueryData(qk.auth, (prev: { configured: boolean; authenticated: boolean } | undefined) => (prev ? { ...prev, authenticated: false } : prev));
|
||||
});
|
||||
return () => setUnauthorizedHandler(null);
|
||||
}, [qc]);
|
||||
if (status.isLoading) return <PageLoading />;
|
||||
if (status.isError) return <ErrorState title="Cannot reach Study Desk" message="The server did not respond. Check that the container is running, then try again." onRetry={() => status.refetch()} className="mt-24" />;
|
||||
if (!status.data?.configured) return <SetupPage />;
|
||||
if (!status.data.authenticated) return <LoginPage />;
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function ScrollToTop() {
|
||||
const { pathname } = useLocation();
|
||||
useEffect(() => {
|
||||
window.scrollTo(0, 0);
|
||||
}, [pathname]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function Private() {
|
||||
return (
|
||||
<AuthGate>
|
||||
<ScrollToTop />
|
||||
<Suspense fallback={<PageLoading />}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
</AuthGate>
|
||||
);
|
||||
}
|
||||
|
||||
function ShellRoute() {
|
||||
return (
|
||||
<AuthGate>
|
||||
<ScrollToTop />
|
||||
<Shell />
|
||||
</AuthGate>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteError() {
|
||||
const error = useRouteError() as Error | undefined;
|
||||
// A new deploy invalidates old chunk names; one reload fixes it.
|
||||
const stale = /dynamically imported module|Importing a module script failed|Failed to fetch/i.test(error?.message ?? '');
|
||||
return (
|
||||
<div className="mt-24">
|
||||
<ErrorState title={stale ? 'Study Desk was updated' : 'This page hit a problem'} message={stale ? 'Reload to get the latest version.' : (error?.message ?? 'An unexpected error occurred.')} />
|
||||
<div className="flex justify-center gap-2">
|
||||
<Button variant="primary" onClick={() => window.location.reload()}>
|
||||
Reload
|
||||
</Button>
|
||||
<Button onClick={() => (window.location.href = '/')}>Go to Today</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NotFound() {
|
||||
return (
|
||||
<div className="mt-20">
|
||||
<ErrorState title="Page not found" message="That page does not exist, or the item was deleted." />
|
||||
<div className="flex justify-center">
|
||||
<Button onClick={() => (window.location.href = '/')}>Go to Today</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const page = (el: ReactNode) => <Suspense fallback={<PageLoading />}>{el}</Suspense>;
|
||||
|
||||
const router = createBrowserRouter([
|
||||
// Public share links: no login, no app chrome.
|
||||
{ path: '/s/:token', element: page(<SharedPage />), errorElement: <RouteError /> },
|
||||
{ path: '/s/:token/:kind/:itemId', element: page(<SharedPage />), errorElement: <RouteError /> },
|
||||
// Focus mode: study sessions take the whole screen.
|
||||
{
|
||||
element: <Private />,
|
||||
errorElement: <RouteError />,
|
||||
children: [
|
||||
{ path: '/session/:attemptId', element: <SessionPage /> },
|
||||
{ path: '/review', element: <ReviewPage /> },
|
||||
{ path: '/decks/:deckId/cram', element: <CramPage /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
element: <ShellRoute />,
|
||||
errorElement: <RouteError />,
|
||||
children: [
|
||||
{ path: '/', element: page(<Home />) },
|
||||
{ path: '/classes/:classId', element: page(<ClassPage />) },
|
||||
{ path: '/quizzes/:quizId', element: page(<QuizPage />) },
|
||||
{ path: '/decks/:deckId', element: page(<DeckPage />) },
|
||||
{ path: '/documents/:docId', element: page(<DocumentPage />) },
|
||||
{ path: '/notes/:noteId', element: page(<NotePage />) },
|
||||
{ path: '/drafts/:draftId', element: page(<DraftPage />) },
|
||||
{ path: '/assistant', element: page(<AssistantPage />) },
|
||||
{ path: '/assistant/:conversationId', element: page(<AssistantPage />) },
|
||||
{ path: '/insights', element: page(<InsightsPage />) },
|
||||
{ path: '/settings', element: page(<SettingsPage />) },
|
||||
{ path: '/settings/:tab', element: page(<SettingsPage />) },
|
||||
{ path: '*', element: <NotFound /> },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
function ThemedToaster() {
|
||||
useTheme();
|
||||
const dark = document.documentElement.dataset.theme === 'dark';
|
||||
return (
|
||||
<Toaster
|
||||
theme={dark ? 'dark' : 'light'}
|
||||
position="bottom-center"
|
||||
offset={20}
|
||||
mobileOffset={{ bottom: 76 }}
|
||||
toastOptions={{
|
||||
style: { background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 12, fontFamily: 'var(--font-sans)', fontSize: 14, boxShadow: 'var(--shadow-2)' },
|
||||
actionButtonStyle: { background: 'var(--marker)', color: 'var(--marker-ink)', fontWeight: 600 },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TooltipProvider delayDuration={400} skipDelayDuration={200}>
|
||||
<ConfirmProvider>
|
||||
<RouterProvider router={router} />
|
||||
<ThemedToaster />
|
||||
</ConfirmProvider>
|
||||
</TooltipProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
if ('serviceWorker' in navigator && import.meta.env.PROD) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker.register('/sw.js').catch(() => undefined);
|
||||
});
|
||||
}
|
||||
51
web/src/pages/AssistantPage.tsx
Normal file
51
web/src/pages/AssistantPage.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { MessageSquare, Trash2 } from 'lucide-react';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import AssistantPanel from '@/features/AssistantPanel';
|
||||
import { api } from '@/lib/api';
|
||||
import { cx, timeAgo, useDocumentTitle } from '@/lib/util';
|
||||
import { IconButton, useConfirm } from '@/ui';
|
||||
|
||||
export default function AssistantPage() {
|
||||
useDocumentTitle('Assistant');
|
||||
const { conversationId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const confirm = useConfirm();
|
||||
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: { id: string; title: string; updatedAt: number }[] }>('/api/ai/conversations').then((r) => r.conversations) });
|
||||
|
||||
const remove = async (id: string) => {
|
||||
if (!(await confirm({ title: 'Delete this conversation?', confirmLabel: 'Delete', danger: true, message: 'The messages are removed. Drafts and anything you saved are kept.' }))) return;
|
||||
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
|
||||
await qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
if (id === conversationId) navigate('/assistant');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="-mx-4 -mt-6 -mb-28 flex h-[calc(100dvh-52px-56px)] sm:-mx-8 lg:mx-0 lg:-mt-10 lg:-mb-16 lg:h-dvh lg:gap-6">
|
||||
<aside className="hidden w-60 shrink-0 flex-col border-r border-line py-6 pr-3 lg:flex">
|
||||
<div className="eyebrow mb-2 px-2">Conversations</div>
|
||||
<div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto">
|
||||
{(history.data ?? []).length === 0 && <p className="px-2 text-[13px] text-ink-3">Your conversations will be listed here.</p>}
|
||||
{(history.data ?? []).map((c) => (
|
||||
<div key={c.id} className={cx('group flex items-center rounded-[9px]', c.id === conversationId ? 'bg-ink/8' : 'hover:bg-ink/5')}>
|
||||
<button type="button" onClick={() => navigate(`/assistant/${c.id}`)} className="min-w-0 flex-1 px-2.5 py-2 text-left">
|
||||
<span className="flex items-center gap-2">
|
||||
<MessageSquare className="size-3.5 shrink-0 text-ink-3" />
|
||||
<span className="truncate text-sm">{c.title}</span>
|
||||
</span>
|
||||
<span className="pl-[22px] text-[11px] text-ink-3">{timeAgo(c.updatedAt)}</span>
|
||||
</button>
|
||||
<IconButton label="Delete conversation" size="sm" className="mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100" onClick={() => remove(c.id)}>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<AssistantPanel variant="page" conversationId={conversationId} onConversationChange={(id) => navigate(id ? `/assistant/${id}` : '/assistant', { replace: true })} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
125
web/src/pages/Auth.tsx
Normal file
125
web/src/pages/Auth.tsx
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { KeyRound, LockKeyhole } from 'lucide-react';
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk } from '@/lib/queries';
|
||||
import { useDocumentTitle } from '@/lib/util';
|
||||
import { Button, Callout, Field, Input } from '@/ui';
|
||||
|
||||
export function Brand({ size = 'md' }: { size?: 'md' | 'lg' }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2.5">
|
||||
<img src="/icon.svg" alt="" className={size === 'lg' ? 'size-11 rounded-[12px]' : 'size-8 rounded-[9px]'} />
|
||||
<span className={size === 'lg' ? 'display text-[28px]' : 'display text-[21px]'}>Study Desk</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthFrame({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<main className="grid min-h-dvh place-items-center px-5 py-10">
|
||||
<div className="w-full max-w-[400px] animate-in">
|
||||
<div className="mb-8 flex justify-center">
|
||||
<Brand size="lg" />
|
||||
</div>
|
||||
<div className="card p-6 sm:p-7">
|
||||
<h1 className="display text-2xl">{title}</h1>
|
||||
<p className="mt-1.5 mb-6 text-sm text-ink-2">{subtitle}</p>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
useDocumentTitle('Sign in');
|
||||
const qc = useQueryClient();
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!password) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await api.post('/api/auth/login', { password });
|
||||
qc.clear();
|
||||
await qc.invalidateQueries({ queryKey: qk.auth });
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
setPassword('');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame title="Welcome back" subtitle="Enter your password to open your study desk.">
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<Field label="Password" error={error || undefined}>
|
||||
<Input type="password" autoFocus autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} aria-invalid={Boolean(error)} />
|
||||
</Field>
|
||||
<Button type="submit" variant="primary" size="lg" block loading={busy} icon={<LockKeyhole />}>
|
||||
Sign in
|
||||
</Button>
|
||||
</form>
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function SetupPage() {
|
||||
useDocumentTitle('Set up');
|
||||
const qc = useQueryClient();
|
||||
const [code, setCode] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const mismatch = confirm.length > 0 && password !== confirm;
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (password.length < 8) return setError('Use at least 8 characters.');
|
||||
if (password !== confirm) return setError('The passwords do not match.');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await api.post('/api/auth/setup', { code, password });
|
||||
await qc.invalidateQueries({ queryKey: qk.auth });
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame title="Set up Study Desk" subtitle="Create the administrator password. You are the only account on this desk.">
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<Callout tone="accent" icon={<KeyRound />}>
|
||||
Find the one-time <strong>setup code</strong> in the container log, or in <code className="num text-[12px]">setup-code.txt</code> inside the data folder.
|
||||
</Callout>
|
||||
<Field label="Setup code">
|
||||
<Input autoFocus value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="XXXXX-XXXXX" autoComplete="off" spellCheck={false} className="num tracking-widest" required />
|
||||
</Field>
|
||||
<Field label="Password" hint="At least 8 characters. A short sentence works well.">
|
||||
<Input type="password" autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
|
||||
</Field>
|
||||
<Field label="Confirm password" error={mismatch ? 'The passwords do not match.' : undefined}>
|
||||
<Input type="password" autoComplete="new-password" value={confirm} onChange={(e) => setConfirm(e.target.value)} required aria-invalid={mismatch} />
|
||||
</Field>
|
||||
{error && (
|
||||
<Callout tone="bad" className="py-2.5">
|
||||
{error}
|
||||
</Callout>
|
||||
)}
|
||||
<Button type="submit" variant="primary" size="lg" block loading={busy}>
|
||||
Create password and continue
|
||||
</Button>
|
||||
</form>
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
729
web/src/pages/ClassPage.tsx
Normal file
729
web/src/pages/ClassPage.tsx
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
import {
|
||||
Archive,
|
||||
ArrowDownAZ,
|
||||
BookOpen,
|
||||
ChevronDown,
|
||||
Clock,
|
||||
Copy,
|
||||
Download,
|
||||
FileImage,
|
||||
FileText,
|
||||
FileUp,
|
||||
Folder as FolderIcon,
|
||||
FolderInput,
|
||||
FolderPlus,
|
||||
Layers,
|
||||
MoreHorizontal,
|
||||
NotebookPen,
|
||||
Pencil,
|
||||
Play,
|
||||
Plus,
|
||||
Presentation,
|
||||
Search,
|
||||
Share2,
|
||||
Sparkles,
|
||||
Trash2,
|
||||
TriangleAlert,
|
||||
Upload,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { ClassDialog } from '@/app/Shell';
|
||||
import { MoveDialog, NewItemDialog, RenameDialog, ShareDialog, type EditableKind, type ShareKind } from '@/features/dialogs';
|
||||
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
||||
import { ImportDialog } from '@/features/ImportDialog';
|
||||
import { useStartSession } from '@/features/study';
|
||||
import { api, errorMessage, uploadWithProgress } from '@/lib/api';
|
||||
import { assistant, useAssistantContext } from '@/lib/assistantStore';
|
||||
import { useClass, useRefresh } from '@/lib/queries';
|
||||
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
|
||||
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
|
||||
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
|
||||
|
||||
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
|
||||
|
||||
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', document: 'documents', note: 'notes' } as const;
|
||||
|
||||
function DocIcon({ kind }: { kind: string }) {
|
||||
if (kind === 'pptx') return <Presentation />;
|
||||
if (kind === 'image') return <FileImage />;
|
||||
return <FileText />;
|
||||
}
|
||||
|
||||
function KindIcon({ item }: { item: Item }) {
|
||||
const tone = { quiz: 'bg-accent-soft text-accent', deck: 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker', document: 'bg-sunken text-ink-2', note: 'bg-good-soft text-good' }[item.kind];
|
||||
return (
|
||||
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', tone)}>
|
||||
{item.kind === 'quiz' ? <BookOpen /> : item.kind === 'deck' ? <Layers /> : item.kind === 'note' ? <NotebookPen /> : <DocIcon kind={(item as DocumentItem).docKind} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function itemMeta(item: Item): ReactNode {
|
||||
if (item.kind === 'quiz') {
|
||||
const q = item as QuizItem;
|
||||
return (
|
||||
<>
|
||||
<span>{plural(q.questionCount, 'question')}</span>
|
||||
{q.lastPercent !== null && (
|
||||
<span className={cx('num font-medium', { good: 'text-good', warn: 'text-warn', bad: 'text-bad', none: '' }[gradeTone(q.lastPercent)])}>Last {q.lastPercent}%</span>
|
||||
)}
|
||||
{q.lastStudiedAt && <span>{timeAgo(q.lastStudiedAt)}</span>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (item.kind === 'deck') {
|
||||
const d = item as DeckItem;
|
||||
return (
|
||||
<>
|
||||
<span>{plural(d.cardCount, 'card')}</span>
|
||||
{d.cardCount > 0 && <span>{d.learnedCount} learned</span>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (item.kind === 'document') {
|
||||
const d = item as DocumentItem;
|
||||
return (
|
||||
<>
|
||||
<span className="uppercase">{d.docKind === 'markdown' ? 'MD' : d.docKind}</span>
|
||||
{d.pageCount ? <span>{plural(d.pageCount, d.docKind === 'pptx' ? 'slide' : 'page')}</span> : null}
|
||||
<span>{formatBytes(d.size)}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <span className="truncate">{item.description || 'Empty note'}</span>;
|
||||
}
|
||||
|
||||
interface Uploading {
|
||||
id: number;
|
||||
name: string;
|
||||
progress: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export default function ClassPage() {
|
||||
const { classId = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const { start } = useStartSession();
|
||||
const [polling, setPolling] = useState(false);
|
||||
const q = useClass(classId, polling ? 1500 : false);
|
||||
const data = q.data;
|
||||
useDocumentTitle(data?.class.name);
|
||||
useAssistantContext(classId, data?.class.name);
|
||||
|
||||
const [filter, setFilter] = useState<Filter>('all');
|
||||
const [query, setQuery] = useState('');
|
||||
const [sort, setSort] = useLocalStorage<'recent' | 'title'>('sd.classSort', 'recent');
|
||||
const [collapsed, setCollapsed] = useLocalStorage<Record<string, boolean>>(`sd.folders.${classId}`, {});
|
||||
const [newKind, setNewKind] = useState<{ kind: 'quiz' | 'deck' | 'note' | 'folder'; folderId?: string | null } | null>(null);
|
||||
const [rename, setRename] = useState<Parameters<typeof RenameDialog>[0]['target']>(null);
|
||||
const [move, setMove] = useState<Parameters<typeof MoveDialog>[0]['target']>(null);
|
||||
const [share, setShare] = useState<{ kind: ShareKind; id: string; title: string } | null>(null);
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
|
||||
const [editClass, setEditClass] = useState(false);
|
||||
const [pasteOpen, setPasteOpen] = useState(false);
|
||||
const [uploads, setUploads] = useState<Uploading[]>([]);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const dragDepth = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
setPolling(Boolean(data?.items.some((i) => i.kind === 'document' && (i.status === 'pending' || i.status === 'processing'))));
|
||||
}, [data]);
|
||||
useEffect(() => {
|
||||
setFilter('all');
|
||||
setQuery('');
|
||||
}, [classId]);
|
||||
|
||||
const upload = async (files: File[]) => {
|
||||
for (const file of files) {
|
||||
const id = Date.now() + Math.random();
|
||||
setUploads((u) => [...u, { id, name: file.name, progress: 0 }]);
|
||||
const form = new FormData();
|
||||
form.append('classId', classId);
|
||||
form.append('file', file);
|
||||
try {
|
||||
await uploadWithProgress('/api/documents', form, (p) => setUploads((u) => u.map((x) => (x.id === id ? { ...x, progress: p } : x))));
|
||||
setUploads((u) => u.filter((x) => x.id !== id));
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
setUploads((u) => u.map((x) => (x.id === id ? { ...x, error: errorMessage(e) } : x)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const counts = useMemo(() => {
|
||||
const c = { all: 0, quiz: 0, deck: 0, document: 0, note: 0 };
|
||||
for (const i of data?.items ?? []) {
|
||||
c.all += 1;
|
||||
c[i.kind] += 1;
|
||||
}
|
||||
return c;
|
||||
}, [data]);
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
const list = (data?.items ?? []).filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
|
||||
return list.sort((a, b) => (sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : b.updatedAt - a.updatedAt));
|
||||
}, [data, filter, query, sort]);
|
||||
|
||||
if (q.isError) return <ErrorState title="Class not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-10 w-72" />
|
||||
<Skeleton className="h-11 w-full" />
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-16" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const cls = data.class;
|
||||
const remove = async (item: Item) => {
|
||||
const noun = item.kind === 'deck' ? 'deck' : item.kind;
|
||||
const extra = item.kind === 'quiz' ? ' Its attempt history stays in your statistics.' : item.kind === 'deck' ? ' Review progress for its cards will be lost.' : item.kind === 'document' ? ' The uploaded file is removed from the server.' : '';
|
||||
if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${item.title}" will be permanently deleted.${extra}`, confirmLabel: 'Delete', danger: true }))) return;
|
||||
try {
|
||||
await api.del(`/api/${ITEM_URL[item.kind]}/${item.id}`);
|
||||
await refresh();
|
||||
toast.success('Deleted');
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const duplicate = async (item: Item) => {
|
||||
try {
|
||||
await api.post(`/api/${ITEM_URL[item.kind]}/${item.id}/duplicate`, {});
|
||||
await refresh();
|
||||
toast.success('Duplicated');
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const removeFolder = async (f: Folder) => {
|
||||
if (!(await confirm({ title: 'Delete this folder?', message: `"${f.name}" will be removed. Everything inside it stays in the class.`, confirmLabel: 'Delete folder', danger: true }))) return;
|
||||
await api.del(`/api/folders/${f.id}`).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
};
|
||||
const deleteClass = async () => {
|
||||
if (!(await confirm({ title: `Delete ${cls.name}?`, message: `This permanently deletes the class and everything in it: ${plural(counts.quiz, 'quiz', 'quizzes')}, ${plural(counts.deck, 'deck')}, ${plural(counts.document, 'document')} and ${plural(counts.note, 'note')}. Export it first if you might want it back.`, confirmLabel: 'Delete class', danger: true })))
|
||||
return;
|
||||
try {
|
||||
await api.del(`/api/classes/${cls.id}`);
|
||||
await refresh();
|
||||
navigate('/');
|
||||
toast.success('Class deleted');
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
const primaryAction = (item: Item): ReactNode => {
|
||||
if (item.kind === 'quiz') {
|
||||
const z = item as QuizItem;
|
||||
if (z.activeAttemptId)
|
||||
return (
|
||||
<Link to={`/session/${z.activeAttemptId}`}>
|
||||
<Button size="sm" variant="marker" icon={<Play className="fill-current" />}>
|
||||
Resume
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
if (z.questionCount > 0)
|
||||
return (
|
||||
<Link to={`/quizzes/${z.id}?start=1`}>
|
||||
<Button size="sm" icon={<Play className="fill-current" />}>
|
||||
Start
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (item.kind === 'deck') {
|
||||
const d = item as DeckItem;
|
||||
if (d.dueCount + Math.min(d.newCount, 20) > 0 && d.cardCount > 0)
|
||||
return (
|
||||
<Link to={`/review?deckId=${d.id}`}>
|
||||
<Button size="sm" variant={d.dueCount > 0 ? 'marker' : 'secondary'} icon={<Play className="fill-current" />}>
|
||||
{d.dueCount > 0 ? `Review ${d.dueCount}` : 'Learn'}
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
if (d.cardCount > 0)
|
||||
return (
|
||||
<Link to={`/decks/${d.id}/cram`}>
|
||||
<Button size="sm">Browse</Button>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const row = (item: Item) => {
|
||||
const doc = item.kind === 'document' ? (item as DocumentItem) : null;
|
||||
const busy = doc && (doc.status === 'pending' || doc.status === 'processing');
|
||||
return (
|
||||
<li key={`${item.kind}:${item.id}`} className="group relative flex items-center gap-3 px-3 py-2.5 hover:bg-ink/[0.035] sm:px-4">
|
||||
<KindIcon item={item} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link to={`/${ITEM_URL[item.kind]}/${item.id}`} className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0">
|
||||
{item.title}
|
||||
</Link>
|
||||
<div className="mt-0.5 flex items-center gap-x-2.5 overflow-hidden text-xs whitespace-nowrap text-ink-3">
|
||||
{busy ? (
|
||||
<>
|
||||
<span>{doc.status === 'pending' ? 'Waiting to be read' : 'Reading…'}</span>
|
||||
<ProgressBar value={doc.progress} className="w-24" />
|
||||
</>
|
||||
) : doc?.status === 'failed' ? (
|
||||
<span className="flex items-center gap-1 truncate text-bad">
|
||||
<TriangleAlert className="size-3.5 shrink-0" />
|
||||
<span className="truncate">{doc.error || 'Could not be read'}</span>
|
||||
</span>
|
||||
) : (
|
||||
itemMeta(item)
|
||||
)}
|
||||
{doc?.needsOcr && doc.status === 'ready' && <Badge tone="warn">Needs AI reading</Badge>}
|
||||
{item.shared && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative z-10 flex shrink-0 items-center gap-1">
|
||||
<span className="hidden sm:block">{primaryAction(item)}</span>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label={`Actions for ${item.title}`} size="sm" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{item.kind === 'quiz' && (item as QuizItem).questionCount > 0 && (
|
||||
<>
|
||||
<MenuItem icon={<Play />} onSelect={() => start({ source: { type: 'quiz', quizId: item.id } })}>
|
||||
Quick practice
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', quizId: item.id, sourceLabel: item.title })}>
|
||||
Make flashcards from this
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
{item.kind === 'deck' && (item as DeckItem).cardCount > 0 && (
|
||||
<>
|
||||
<MenuItem icon={<Layers />} onSelect={() => navigate(`/decks/${item.id}/cram`)}>
|
||||
Browse all cards
|
||||
</MenuItem>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', deckId: item.id, sourceLabel: item.title })}>
|
||||
Make a quiz from this
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
{item.kind === 'document' && doc?.status === 'ready' && (
|
||||
<>
|
||||
<MenuItem icon={<Sparkles />} onSelect={() => setGenerate({ documentIds: [item.id] })}>
|
||||
Generate from this
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Sparkles />} onSelect={() => assistant.open({ documentIds: [item.id], classId, newChat: true })}>
|
||||
Ask about this
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
{item.kind === 'note' && (
|
||||
<MenuItem icon={<Sparkles />} onSelect={() => setGenerate({ noteId: item.id, sourceLabel: item.title })}>
|
||||
Generate from this
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setRename({ kind: item.kind as EditableKind, id: item.id, title: item.title, description: item.kind === 'quiz' || item.kind === 'deck' ? item.description : undefined })}>
|
||||
Rename
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FolderInput />} onSelect={() => setMove({ kind: item.kind as EditableKind, id: item.id, title: item.title, classId, folderId: item.folderId })}>
|
||||
Move
|
||||
</MenuItem>
|
||||
{(item.kind === 'quiz' || item.kind === 'deck') && (
|
||||
<MenuItem icon={<Copy />} onSelect={() => duplicate(item)}>
|
||||
Duplicate
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare({ kind: item.kind, id: item.id, title: item.title })}>
|
||||
Share
|
||||
</MenuItem>
|
||||
{(item.kind === 'quiz' || item.kind === 'deck') && (
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/${ITEM_URL[item.kind]}/${item.id}/export`)}>
|
||||
Export JSON
|
||||
</MenuItem>
|
||||
)}
|
||||
{item.kind === 'document' && (
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/documents/${item.id}/file?download=1`)}>
|
||||
Download original
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={() => remove(item)}>
|
||||
Delete
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const loose = visible.filter((i) => !i.folderId || !data.folders.some((f) => f.id === i.folderId));
|
||||
const searching = query.trim().length > 0 || filter !== 'all';
|
||||
const isEmpty = data.items.length === 0 && uploads.length === 0;
|
||||
|
||||
const addMenu = (
|
||||
<Menu
|
||||
trigger={
|
||||
<Button variant="primary" icon={<Plus />}>
|
||||
Add
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz' })}>
|
||||
New quiz
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck' })}>
|
||||
New flashcard deck
|
||||
</MenuItem>
|
||||
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note' })}>
|
||||
New note
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FolderPlus />} onSelect={() => setNewKind({ kind: 'folder' })}>
|
||||
New folder
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Upload />} onSelect={() => fileRef.current?.click()}>
|
||||
Upload documents
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FileText />} onSelect={() => setPasteOpen(true)}>
|
||||
Paste text as a document
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FileUp />} onSelect={() => setImportOpen(true)}>
|
||||
Import quizzes or cards
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('animate-in', `tab-${cls.color}`)}
|
||||
onDragEnter={(e) => {
|
||||
if (!e.dataTransfer.types.includes('Files')) return;
|
||||
dragDepth.current += 1;
|
||||
setDragging(true);
|
||||
}}
|
||||
onDragLeave={() => {
|
||||
dragDepth.current = Math.max(0, dragDepth.current - 1);
|
||||
if (dragDepth.current === 0) setDragging(false);
|
||||
}}
|
||||
onDragOver={(e) => e.dataTransfer.types.includes('Files') && e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
if (!e.dataTransfer.files.length) return;
|
||||
e.preventDefault();
|
||||
dragDepth.current = 0;
|
||||
setDragging(false);
|
||||
void upload([...e.dataTransfer.files]);
|
||||
}}
|
||||
>
|
||||
<input ref={fileRef} type="file" multiple hidden accept=".pdf,.docx,.pptx,.txt,.md,.markdown,.csv,.png,.jpg,.jpeg,.webp,.gif" onChange={(e) => (e.target.files && upload([...e.target.files]), (e.target.value = ''))} />
|
||||
|
||||
<header className="mb-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
|
||||
<div className="min-w-0 border-l-[5px] border-tab pl-4">
|
||||
<div className="eyebrow mb-1 flex items-center gap-2">
|
||||
{cls.code || 'Class'}
|
||||
{cls.archived && <Badge>Archived</Badge>}
|
||||
{data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<h1 className="display text-[30px] sm:text-[38px]">{cls.name}</h1>
|
||||
{cls.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{cls.description}</p>}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{data.due.total > 0 && (
|
||||
<Link to={`/review?classId=${cls.id}`}>
|
||||
<Button variant="marker" icon={<Play className="fill-current" />}>
|
||||
Review {data.due.total}
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
<Button icon={<Sparkles />} onClick={() => setGenerate({})}>
|
||||
Generate
|
||||
</Button>
|
||||
{addMenu}
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Class options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setEditClass(true)}>
|
||||
Edit class
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare({ kind: 'class', id: cls.id, title: cls.name })}>
|
||||
Share whole class
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/export/class/${cls.id}`)}>
|
||||
Export class (JSON)
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<Archive />}
|
||||
onSelect={async () => {
|
||||
await api.patch(`/api/classes/${cls.id}`, { archived: !cls.archived }).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
}}
|
||||
>
|
||||
{cls.archived ? 'Unarchive' : 'Archive'}
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={deleteClass}>
|
||||
Delete class
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{isEmpty ? (
|
||||
<div className="card border-dashed">
|
||||
<EmptyState
|
||||
icon={<Upload />}
|
||||
title="Fill this class with material"
|
||||
action={
|
||||
<>
|
||||
<Button variant="primary" icon={<Upload />} onClick={() => fileRef.current?.click()}>
|
||||
Upload documents
|
||||
</Button>
|
||||
<Button icon={<FileUp />} onClick={() => setImportOpen(true)}>
|
||||
Import
|
||||
</Button>
|
||||
<Button icon={<BookOpen />} onClick={() => setNewKind({ kind: 'quiz' })}>
|
||||
New quiz
|
||||
</Button>
|
||||
<Button icon={<Layers />} onClick={() => setNewKind({ kind: 'deck' })}>
|
||||
New deck
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
Drop lecture slides, PDFs or notes anywhere on this page, import existing quizzes and flashcards, or write your own.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||
<div className="-mx-1 flex max-w-full gap-1 overflow-x-auto px-1 pb-1">
|
||||
{(
|
||||
[
|
||||
['all', 'All'],
|
||||
['quiz', 'Quizzes'],
|
||||
['deck', 'Flashcards'],
|
||||
['document', 'Documents'],
|
||||
['note', 'Notes'],
|
||||
] as const
|
||||
).map(([v, label]) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
aria-pressed={filter === v}
|
||||
onClick={() => setFilter(v)}
|
||||
className={cx('flex h-9 shrink-0 items-center gap-1.5 rounded-full border px-3.5 text-sm font-medium transition-colors', filter === v ? 'border-ink bg-ink text-paper' : 'border-line-strong bg-surface text-ink-2 hover:border-ink-3 hover:text-ink')}
|
||||
>
|
||||
{label}
|
||||
<span className={cx('num text-xs', filter === v ? 'text-paper/65' : 'text-ink-3')}>{counts[v]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
|
||||
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter" aria-label="Filter this class" className="h-9 w-36 pl-8 sm:w-48" />
|
||||
</div>
|
||||
<Segmented
|
||||
size="sm"
|
||||
label="Sort"
|
||||
value={sort}
|
||||
onChange={setSort}
|
||||
options={[
|
||||
{ value: 'recent', label: <span className="sr-only">Recent</span>, icon: <Clock /> },
|
||||
{ value: 'title', label: <span className="sr-only">A to Z</span>, icon: <ArrowDownAZ /> },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{uploads.length > 0 && (
|
||||
<ul className="card mb-4 divide-y divide-line">
|
||||
{uploads.map((u) => (
|
||||
<li key={u.id} className="flex items-center gap-3 px-4 py-2.5">
|
||||
<Upload className={cx('size-4 shrink-0', u.error ? 'text-bad' : 'text-ink-3')} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{u.name}</div>
|
||||
{u.error ? <div className="text-[13px] text-bad">{u.error}</div> : <ProgressBar value={u.progress} className="mt-1.5" label={`Uploading ${u.name}`} />}
|
||||
</div>
|
||||
{u.error && (
|
||||
<IconButton label="Dismiss" size="sm" onClick={() => setUploads((x) => x.filter((y) => y.id !== u.id))}>
|
||||
<X />
|
||||
</IconButton>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState title={searching ? 'Nothing matches' : 'Nothing here yet'} icon={<Search />}>
|
||||
{query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'}
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{loose.length > 0 && <ul className="card divide-y divide-line overflow-hidden">{loose.map(row)}</ul>}
|
||||
{data.folders.map((f) => {
|
||||
const items = visible.filter((i) => i.folderId === f.id);
|
||||
if (items.length === 0 && searching) return null;
|
||||
const isCollapsed = collapsed[f.id] && !searching;
|
||||
return (
|
||||
<section key={f.id} aria-label={f.name}>
|
||||
<div className="mb-1.5 flex items-center gap-1">
|
||||
<button type="button" aria-expanded={!isCollapsed} onClick={() => setCollapsed((c) => ({ ...c, [f.id]: !c[f.id] }))} className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-lg px-1.5 text-left hover:bg-ink/5">
|
||||
<ChevronDown className={cx('size-4 shrink-0 text-ink-3 transition-transform', isCollapsed && '-rotate-90')} />
|
||||
<FolderIcon className="size-4 shrink-0 text-tab" />
|
||||
<span className="truncate text-sm font-semibold">{f.name}</span>
|
||||
<span className="num text-xs text-ink-3">{items.length}</span>
|
||||
{f.shared && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</button>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label={`Folder options for ${f.name}`} size="sm" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz', folderId: f.id })}>
|
||||
New quiz here
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck', folderId: f.id })}>
|
||||
New deck here
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setRename({ kind: 'folder', id: f.id, title: f.name })}>
|
||||
Rename
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare({ kind: 'folder', id: f.id, title: f.name })}>
|
||||
Share folder
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={() => removeFolder(f)}>
|
||||
Delete folder
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
{!isCollapsed &&
|
||||
(items.length > 0 ? (
|
||||
<ul className="card divide-y divide-line overflow-hidden">{items.map(row)}</ul>
|
||||
) : (
|
||||
<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>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{dragging && (
|
||||
<div className="pointer-events-none fixed inset-0 z-40 grid place-items-center bg-paper/85 backdrop-blur-sm">
|
||||
<div className="rounded-3xl border-2 border-dashed border-accent bg-surface px-12 py-10 text-center shadow-3">
|
||||
<Upload className="mx-auto mb-3 size-9 text-accent" />
|
||||
<div className="display text-2xl">Drop to add to {cls.name}</div>
|
||||
<div className="mt-1 text-sm text-ink-2">PDF, Word, PowerPoint, text, Markdown and images</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<NewItemDialog kind={newKind?.kind ?? null} classId={classId} folderId={newKind?.folderId} onClose={() => setNewKind(null)} />
|
||||
<RenameDialog target={rename} onClose={() => setRename(null)} />
|
||||
<MoveDialog target={move} onClose={() => setMove(null)} />
|
||||
<ShareDialog target={share} onClose={() => setShare(null)} />
|
||||
<ImportDialog open={importOpen} onClose={() => setImportOpen(false)} classId={classId} />
|
||||
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} preset={generate ?? undefined} />
|
||||
<ClassDialog open={editClass} onOpenChange={setEditClass} existing={cls} />
|
||||
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: () => void; classId: string }) {
|
||||
const refresh = useRefresh();
|
||||
const [title, setTitle] = useState('');
|
||||
const [text, setText] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setTitle('');
|
||||
setText('');
|
||||
}
|
||||
}, [open]);
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.post('/api/documents/text', { classId, title, text });
|
||||
await refresh();
|
||||
toast.success('Added as a document');
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Paste text as a document"
|
||||
description="Pasted notes become a searchable document that AI can read and cite."
|
||||
size="lg"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" loading={busy} disabled={!title.trim() || text.trim().length < 2} onClick={save}>
|
||||
Add document
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Field label="Title">
|
||||
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Week 4 lecture notes" maxLength={200} />
|
||||
</Field>
|
||||
<Field label="Text" hint="Markdown headings (#, ##) are used as section titles.">
|
||||
<Textarea rows={12} value={text} onChange={(e) => setText(e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
69
web/src/pages/CramPage.tsx
Normal file
69
web/src/pages/CramPage.tsx
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { Explain } from '@/features/Explain';
|
||||
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
|
||||
import { useDocumentTitle } from '@/lib/util';
|
||||
import { Button, EmptyState, ErrorState, PageLoading } from '@/ui';
|
||||
|
||||
/** Browse every card in a deck, self-graded. Does not affect the spaced-repetition schedule. */
|
||||
export default function CramPage() {
|
||||
const { deckId = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const ai = useAiStatus();
|
||||
const q = useDeck(deckId);
|
||||
const data = q.data;
|
||||
useDocumentTitle(data ? `Browse · ${data.deck.title}` : undefined);
|
||||
const [state, setState] = useState<CramState | null>(null);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const latest = useRef<CramState | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!data || state) return;
|
||||
setState(reconcileCramState(data.session?.state as CramState | null, data.cards) ?? freshCramState(data.cards, false));
|
||||
}, [data, state]);
|
||||
|
||||
const persist = (next: CramState) => {
|
||||
setState(next);
|
||||
latest.current = next;
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => {
|
||||
void api.put(`/api/decks/${deckId}/session`, { state: next }).catch(() => undefined);
|
||||
}, 600);
|
||||
};
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
if (latest.current) void api.put(`/api/decks/${deckId}/session`, { state: latest.current }).catch(() => undefined);
|
||||
},
|
||||
[deckId],
|
||||
);
|
||||
|
||||
if (q.isError) return <ErrorState title="Deck not found" message={errorMessage(q.error)} className="pt-24" />;
|
||||
if (!data || !state) return <PageLoading />;
|
||||
const exit = () => {
|
||||
void refresh();
|
||||
navigate(`/decks/${deckId}`);
|
||||
};
|
||||
if (data.cards.length === 0) {
|
||||
return (
|
||||
<div className="pt-24">
|
||||
<EmptyState title="This deck has no cards yet" action={<Button onClick={exit}>Back to deck</Button>} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<CramSession
|
||||
title={data.deck.title}
|
||||
cards={data.cards}
|
||||
state={state}
|
||||
onState={persist}
|
||||
onExit={exit}
|
||||
exitLabel="Save and exit"
|
||||
onGrade={(cardId, known) => void api.post('/api/review/cram', { cardId, known }).catch(() => undefined)}
|
||||
renderExtra={ai.data?.ready ? (card) => <Explain body={{ kind: 'card', front: card.front, back: card.back }} /> : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
354
web/src/pages/DeckPage.tsx
Normal file
354
web/src/pages/DeckPage.tsx
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
import { BookOpen, ChevronRight, Copy, Download, Eye, EyeOff, FolderInput, Layers, ListPlus, MoreHorizontal, Pencil, Play, Plus, RotateCcw, Search, Share2, Stamp, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { blankCard, type Card, type DraftCard } from '@shared/content';
|
||||
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
|
||||
import { CardEditor } from '@/features/editors';
|
||||
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useAssistantContext } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
|
||||
import { cx, downloadFile, plural, useDocumentTitle } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Tooltip, useConfirm } from '@/ui';
|
||||
import { BulkAddDialog } from './QuizPage';
|
||||
|
||||
function dueLabel(card: Card): { text: string; tone: 'neutral' | 'accent' | 'good' | 'warn' } {
|
||||
if (card.suspended) return { text: 'Suspended', tone: 'neutral' };
|
||||
if (card.state === 0) return { text: 'New', tone: 'accent' };
|
||||
if (card.state === 1 || card.state === 3) return { text: 'Learning', tone: 'warn' };
|
||||
const days = card.due ? Math.ceil((card.due - Date.now()) / 86_400_000) : 0;
|
||||
if (days <= 0) return { text: 'Due', tone: 'warn' };
|
||||
return { text: days === 1 ? 'Tomorrow' : days < 31 ? `${days} days` : days < 365 ? `${Math.round(days / 30)} mo` : `${(days / 365).toFixed(1)} y`, tone: 'good' };
|
||||
}
|
||||
|
||||
export default function DeckPage() {
|
||||
const { deckId = '' } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const q = useDeck(deckId);
|
||||
const data = q.data;
|
||||
useDocumentTitle(data?.deck.title);
|
||||
useAssistantContext(data?.deck.classId, data?.deck.title);
|
||||
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<DraftCard>(blankCard());
|
||||
const [fresh, setFresh] = useState<DraftCard>(blankCard());
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [filter, setFilter] = useState('');
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
const [rename, setRename] = useState(false);
|
||||
const [move, setMove] = useState(false);
|
||||
const [share, setShare] = useState(false);
|
||||
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
|
||||
const addRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!data) return;
|
||||
if (params.get('edit')) {
|
||||
setTimeout(() => addRef.current?.querySelector('textarea')?.focus(), 80);
|
||||
const next = new URLSearchParams(params);
|
||||
next.delete('edit');
|
||||
setParams(next, { replace: true });
|
||||
}
|
||||
const target = params.get('card');
|
||||
if (target) setTimeout(() => document.getElementById(`card-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data?.deck.id]);
|
||||
|
||||
const shown = useMemo(() => {
|
||||
const needle = filter.trim().toLowerCase();
|
||||
return (data?.cards ?? []).filter((c) => !needle || c.front.toLowerCase().includes(needle) || c.back.toLowerCase().includes(needle));
|
||||
}, [data, filter]);
|
||||
|
||||
if (q.isError) return <ErrorState title="Deck not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-10 w-96 max-w-full" />
|
||||
<Skeleton className="h-20" />
|
||||
<Skeleton className="h-64" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const { deck, cards, stats, due } = data;
|
||||
const act = async (fn: () => Promise<unknown>, ok?: string) => {
|
||||
try {
|
||||
await fn();
|
||||
await refresh();
|
||||
if (ok) toast.success(ok);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
const addCard = async () => {
|
||||
if (!fresh.front.trim() || !fresh.back.trim()) return;
|
||||
setAdding(true);
|
||||
await act(() => api.post(`/api/decks/${deck.id}/cards`, { cards: [fresh] }));
|
||||
setFresh(blankCard());
|
||||
setAdding(false);
|
||||
setTimeout(() => addRef.current?.querySelector('textarea')?.focus(), 40);
|
||||
};
|
||||
const saveEdit = async () => {
|
||||
if (!editing || !draft.front.trim() || !draft.back.trim()) return;
|
||||
await act(() => api.patch(`/api/cards/${editing}`, draft));
|
||||
setEditing(null);
|
||||
};
|
||||
const deleteDeck = async () => {
|
||||
if (!(await confirm({ title: 'Delete this deck?', message: `"${deck.title}", its ${plural(cards.length, 'card')} and their review progress will be permanently deleted.`, confirmLabel: 'Delete deck', danger: true }))) return;
|
||||
try {
|
||||
await api.del(`/api/decks/${deck.id}`);
|
||||
await refresh();
|
||||
navigate(`/classes/${deck.classId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const resetDeck = async () => {
|
||||
if (!(await confirm({ title: 'Reset review progress?', message: 'Every card in this deck goes back to "new" and its schedule is cleared. The cards themselves are kept.', confirmLabel: 'Reset progress', danger: true }))) return;
|
||||
await act(() => api.post(`/api/decks/${deck.id}/reset`), 'Progress reset');
|
||||
};
|
||||
|
||||
const active = Math.max(1, stats.total - stats.suspended);
|
||||
const segments = [
|
||||
{ label: 'New', n: stats.new, cls: 'bg-accent' },
|
||||
{ label: 'Learning', n: stats.learning, cls: 'bg-warn' },
|
||||
{ label: 'Young', n: stats.young, cls: 'bg-good/55' },
|
||||
{ label: 'Mature', n: stats.mature, cls: 'bg-good' },
|
||||
];
|
||||
const canStudy = due.total > 0;
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${data.class.color}`)}>
|
||||
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
|
||||
<Link to={`/classes/${data.class.id}`} className="flex items-center gap-1.5 hover:text-ink">
|
||||
<ClassDot color={data.class.color} />
|
||||
{data.class.name}
|
||||
</Link>
|
||||
<ChevronRight className="size-3.5" />
|
||||
<span>Flashcards</span>
|
||||
</nav>
|
||||
|
||||
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
|
||||
<div className="min-w-0">
|
||||
<h1 className="display text-[30px] sm:text-[36px]">{deck.title}</h1>
|
||||
{deck.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{deck.description}</p>}
|
||||
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-ink-2">
|
||||
<span>{plural(stats.total, 'card')}</span>
|
||||
{due.total > 0 && (
|
||||
<span>
|
||||
<strong className="marker num text-ink">{due.total}</strong> to study now
|
||||
</span>
|
||||
)}
|
||||
{data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Link to={`/review?deckId=${deck.id}`} aria-disabled={!canStudy} className={cx(!canStudy && 'pointer-events-none')}>
|
||||
<Button variant={canStudy ? 'primary' : 'secondary'} size="lg" icon={<Play className="fill-current" />} disabled={!canStudy}>
|
||||
{canStudy ? `Review ${due.total}` : 'Nothing due'}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={`/decks/${deck.id}/cram`} className={cx(cards.length === 0 && 'pointer-events-none')}>
|
||||
<Button size="lg" icon={<Layers />} disabled={cards.length === 0}>
|
||||
{data.session ? 'Continue browsing' : 'Browse all'}
|
||||
</Button>
|
||||
</Link>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Deck options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{ai.data?.ready && cards.length > 0 && (
|
||||
<>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', deckId: deck.id, sourceLabel: deck.title })}>
|
||||
Make a quiz from this
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
|
||||
Rename
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
|
||||
Move
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<Copy />}
|
||||
onSelect={async () => {
|
||||
const res = await api.post<{ deck: { id: string } }>(`/api/decks/${deck.id}/duplicate`, {}).catch((e) => (toast.error(errorMessage(e)), null));
|
||||
if (res) {
|
||||
await refresh();
|
||||
navigate(`/decks/${res.deck.id}`);
|
||||
toast.success('Duplicated');
|
||||
}
|
||||
}}
|
||||
>
|
||||
Duplicate
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
|
||||
Share
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/decks/${deck.id}/export`)}>
|
||||
Export JSON
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Stamp />} onSelect={() => act(() => api.post('/api/templates/from', { kind: 'deck', id: deck.id }), 'Saved as a template')}>
|
||||
Save as template
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<RotateCcw />} onSelect={resetDeck}>
|
||||
Reset review progress
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={deleteDeck}>
|
||||
Delete deck
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{stats.total > 0 && (
|
||||
<div className="card mb-6 p-4">
|
||||
<div className="flex h-2.5 overflow-hidden rounded-full bg-ink/8" role="img" aria-label={segments.map((s) => `${s.n} ${s.label.toLowerCase()}`).join(', ')}>
|
||||
{segments.map((s) => (s.n > 0 ? <div key={s.label} className={s.cls} style={{ width: `${(s.n / active) * 100}%` }} /> : null))}
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-x-5 gap-y-1.5 text-[13px]">
|
||||
{segments.map((s) => (
|
||||
<span key={s.label} className="flex items-center gap-1.5 text-ink-2">
|
||||
<span className={cx('size-2.5 rounded-[3px]', s.cls)} />
|
||||
{s.label} <span className="num font-semibold text-ink">{s.n}</span>
|
||||
</span>
|
||||
))}
|
||||
{stats.suspended > 0 && (
|
||||
<span className="flex items-center gap-1.5 text-ink-3">
|
||||
<EyeOff className="size-3.5" /> Suspended <span className="num font-semibold">{stats.suspended}</span>
|
||||
</span>
|
||||
)}
|
||||
<Tooltip label="Mature cards have an interval of 21 days or more. New cards are introduced a few per day (set the limit in Settings).">
|
||||
<button type="button" className="ml-auto text-xs text-ink-3 underline decoration-dotted underline-offset-2">
|
||||
What do these mean?
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<h2 className="eyebrow">Cards</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
{cards.length > 6 && (
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
|
||||
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Find a card" aria-label="Find a card" className="h-9 w-40 pl-8 sm:w-56" />
|
||||
</div>
|
||||
)}
|
||||
<Button size="sm" variant="ghost" icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
|
||||
Paste several
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cards.length === 0 ? (
|
||||
<div className="card mb-3 border-dashed">
|
||||
<EmptyState icon={<Layers />} title="No cards yet">
|
||||
Add your first card below, paste a list, or generate cards from your class documents.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="card mb-3 divide-y divide-line overflow-hidden">
|
||||
{shown.map((card) => {
|
||||
const label = dueLabel(card);
|
||||
return (
|
||||
<li key={card.id} id={`card-${card.id}`} className={cx('scroll-mt-24', params.get('card') === card.id && 'bg-marker/20')}>
|
||||
{editing === card.id ? (
|
||||
<div className="p-4">
|
||||
<CardEditor value={draft} onChange={setDraft} autoFocus onSubmit={saveEdit} />
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={() => setEditing(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" disabled={!draft.front.trim() || !draft.back.trim()} onClick={saveEdit}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className={cx('flex items-start gap-3 px-4 py-3', card.suspended && 'opacity-55')}>
|
||||
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-1 sm:grid-cols-2">
|
||||
<Markdown className="max-h-28 overflow-hidden text-[14.5px] font-medium">{card.front}</Markdown>
|
||||
<Markdown className="max-h-28 overflow-hidden text-[14.5px] text-ink-2">{card.back}</Markdown>
|
||||
</div>
|
||||
<Badge tone={label.tone} className="mt-0.5 hidden sm:inline-flex">
|
||||
{label.text}
|
||||
</Badge>
|
||||
<div className="flex shrink-0">
|
||||
<IconButton
|
||||
label="Edit card"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setDraft({ front: card.front, back: card.back, hint: card.hint, tags: card.tags });
|
||||
setEditing(card.id);
|
||||
}}
|
||||
>
|
||||
<Pencil />
|
||||
</IconButton>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Card options" size="sm" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={card.suspended ? <Eye /> : <EyeOff />} onSelect={() => act(() => api.patch(`/api/cards/${card.id}`, { suspended: !card.suspended }))}>
|
||||
{card.suspended ? 'Unsuspend' : 'Suspend'}
|
||||
</MenuItem>
|
||||
<MenuItem icon={<RotateCcw />} disabled={card.state === 0} onSelect={() => act(() => api.patch(`/api/cards/${card.id}`, { reset: true }), 'Card reset to new')}>
|
||||
Reset progress
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={() => act(() => api.del(`/api/cards/${card.id}`))}>
|
||||
Delete
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
{shown.length === 0 && <li className="px-4 py-8 text-center text-sm text-ink-3">No cards match "{filter}".</li>}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<div ref={addRef} className="card p-4">
|
||||
<div className="eyebrow mb-3 flex items-center gap-1.5">
|
||||
<Plus className="size-3.5" /> Add a card
|
||||
</div>
|
||||
<CardEditor value={fresh} onChange={setFresh} onSubmit={addCard} />
|
||||
<div className="mt-4 flex items-center justify-end gap-3">
|
||||
<span className="hidden text-xs text-ink-3 sm:block">Ctrl+Enter adds the card and starts the next one</span>
|
||||
<Button variant="primary" icon={<Plus />} loading={adding} disabled={!fresh.front.trim() || !fresh.back.trim()} onClick={addCard}>
|
||||
Add card
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BulkAddDialog open={bulkOpen} onClose={() => setBulkOpen(false)} kind="deck" onAdd={(items) => act(() => api.post(`/api/decks/${deck.id}/cards`, { cards: items }), `Added ${plural(items.length, 'card')}`)} />
|
||||
<RenameDialog target={rename ? { kind: 'deck', id: deck.id, title: deck.title, description: deck.description } : null} onClose={() => setRename(false)} />
|
||||
<MoveDialog target={move ? { kind: 'deck', id: deck.id, title: deck.title, classId: deck.classId, folderId: deck.folderId } : null} onClose={() => setMove(false)} />
|
||||
<ShareDialog target={share ? { kind: 'deck', id: deck.id, title: deck.title } : null} onClose={() => setShare(false)} />
|
||||
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={deck.classId} folderId={deck.folderId} preset={generate ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
347
web/src/pages/DocumentPage.tsx
Normal file
347
web/src/pages/DocumentPage.tsx
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, ChevronRight, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
|
||||
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { assistant, useAssistantContext } from '@/lib/assistantStore';
|
||||
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
|
||||
import type { ClassInfo, DocChunk, DocumentInfo, Share } from '@/lib/types';
|
||||
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Spinner, useConfirm } from '@/ui';
|
||||
|
||||
interface Detail {
|
||||
document: DocumentInfo;
|
||||
class: ClassInfo;
|
||||
outline: { seq: number; heading: string; page: number | null }[];
|
||||
share: Share | null;
|
||||
}
|
||||
interface ChunkPage {
|
||||
chunks: DocChunk[];
|
||||
total: number;
|
||||
offset: number;
|
||||
nextOffset: number | null;
|
||||
}
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { pdf: 'PDF', docx: 'Word document', pptx: 'PowerPoint', text: 'Text', markdown: 'Markdown', image: 'Image' };
|
||||
|
||||
export default function DocumentPage() {
|
||||
const { docId = '' } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const focusChunk = Number(params.get('chunk')) || null;
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const [view, setView] = useState<'text' | 'original'>('text');
|
||||
const [rename, setRename] = useState(false);
|
||||
const [move, setMove] = useState(false);
|
||||
const [share, setShare] = useState(false);
|
||||
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
|
||||
|
||||
const q = useQuery({
|
||||
queryKey: qk.document(docId),
|
||||
queryFn: () => api.get<Detail>(`/api/documents/${docId}`),
|
||||
refetchInterval: (query) => (['pending', 'processing'].includes(query.state.data?.document.status ?? '') ? 1200 : false),
|
||||
});
|
||||
const doc = q.data?.document;
|
||||
useDocumentTitle(doc?.title);
|
||||
useAssistantContext(doc?.classId, doc?.title, doc ? [doc.id] : []);
|
||||
const ready = doc?.status === 'ready';
|
||||
|
||||
const chunks = useInfiniteQuery({
|
||||
queryKey: ['document-chunks', docId, focusChunk, doc?.updatedAt],
|
||||
queryFn: ({ pageParam }) => api.get<ChunkPage>(`/api/documents/${docId}/chunks?limit=30&${pageParam === null && focusChunk ? `around=${focusChunk}` : `offset=${pageParam ?? 0}`}`),
|
||||
initialPageParam: null as number | null,
|
||||
getNextPageParam: (last) => last.nextOffset,
|
||||
enabled: ready && (doc?.chunkCount ?? 0) > 0,
|
||||
});
|
||||
const firstOffset = chunks.data?.pages[0]?.offset ?? 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (focusChunk && chunks.data) setTimeout(() => document.getElementById(`chunk-${focusChunk}`)?.scrollIntoView({ block: 'center' }), 80);
|
||||
}, [focusChunk, chunks.data?.pages.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
if (q.isError) return <ErrorState title="Document not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!q.data || !doc) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-10 w-96 max-w-full" />
|
||||
<Skeleton className="h-96" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const cls = q.data.class;
|
||||
const busy = doc.status === 'pending' || doc.status === 'processing';
|
||||
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image';
|
||||
const fileUrl = `/api/documents/${doc.id}/file`;
|
||||
|
||||
const reprocess = async (ocr: boolean) => {
|
||||
try {
|
||||
await api.post(`/api/documents/${doc.id}/reprocess`, { ocr });
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const remove = async () => {
|
||||
if (!(await confirm({ title: 'Delete this document?', message: `"${doc.title}" and its uploaded file will be permanently deleted. Quizzes and cards already generated from it are kept.`, confirmLabel: 'Delete', danger: true }))) return;
|
||||
try {
|
||||
await api.del(`/api/documents/${doc.id}`);
|
||||
await refresh();
|
||||
navigate(`/classes/${doc.classId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const all = chunks.data?.pages.flatMap((p) => p.chunks) ?? [];
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${cls.color}`)}>
|
||||
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
|
||||
<Link to={`/classes/${cls.id}`} className="flex items-center gap-1.5 hover:text-ink">
|
||||
<ClassDot color={cls.color} />
|
||||
{cls.name}
|
||||
</Link>
|
||||
<ChevronRight className="size-3.5" />
|
||||
<span>Document</span>
|
||||
</nav>
|
||||
|
||||
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
|
||||
<div className="min-w-0">
|
||||
<h1 className="display text-[28px] sm:text-[34px]">{doc.title}</h1>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-ink-2">
|
||||
<span>{KIND_LABEL[doc.docKind]}</span>
|
||||
{doc.pageCount ? <span>{plural(doc.pageCount, doc.docKind === 'pptx' ? 'slide' : 'page')}</span> : null}
|
||||
<span>{formatBytes(doc.size)}</span>
|
||||
{ready && doc.tokenCount > 0 && <span>about {formatTokens(doc.tokenCount)} tokens</span>}
|
||||
{q.data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="primary" icon={<Sparkles />} disabled={!ready || doc.chunkCount === 0} onClick={() => setGenerate({ documentIds: [doc.id] })}>
|
||||
Generate
|
||||
</Button>
|
||||
<Button icon={<MessageSquare />} disabled={!ready || doc.chunkCount === 0} onClick={() => assistant.open({ documentIds: [doc.id], classId: doc.classId, newChat: true })}>
|
||||
Ask
|
||||
</Button>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Document options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{ready && doc.chunkCount > 0 && (
|
||||
<>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', documentIds: [doc.id] })}>
|
||||
Quiz from this
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', documentIds: [doc.id] })}>
|
||||
Flashcards from this
|
||||
</MenuItem>
|
||||
<MenuItem icon={<NotebookPen />} onSelect={() => setGenerate({ kind: 'note', documentIds: [doc.id] })}>
|
||||
Study guide from this
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
|
||||
Rename
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
|
||||
Move
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
|
||||
Share
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`${fileUrl}?download=1`)}>
|
||||
Download original
|
||||
</MenuItem>
|
||||
<MenuItem icon={<RefreshCw />} disabled={busy} onSelect={() => reprocess(false)}>
|
||||
Read the file again
|
||||
</MenuItem>
|
||||
{(doc.docKind === 'pdf' || doc.docKind === 'image') && (
|
||||
<MenuItem icon={<ScanText />} disabled={busy || !ai.data?.ready} onSelect={() => reprocess(true)}>
|
||||
Read with AI vision
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
|
||||
Delete
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{busy && (
|
||||
<Callout tone="accent" icon={<Spinner className="size-[18px] text-accent" />} title={doc.status === 'pending' ? 'Waiting to be read' : 'Reading the file'} className="mb-5">
|
||||
Text is being extracted and indexed for search and AI. This page updates on its own.
|
||||
<ProgressBar value={doc.progress} className="mt-2.5 max-w-sm" label="Processing" />
|
||||
</Callout>
|
||||
)}
|
||||
{doc.status === 'failed' && (
|
||||
<Callout
|
||||
tone="bad"
|
||||
icon={<TriangleAlert />}
|
||||
title="This file could not be read"
|
||||
className="mb-5"
|
||||
action={
|
||||
<Button size="sm" onClick={() => reprocess(false)}>
|
||||
Try again
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{doc.error}
|
||||
</Callout>
|
||||
)}
|
||||
{ready && doc.needsOcr && (
|
||||
<Callout
|
||||
tone="warn"
|
||||
icon={<ScanText />}
|
||||
title={doc.docKind === 'image' ? 'This image has not been read yet' : 'No selectable text was found'}
|
||||
className="mb-5"
|
||||
action={
|
||||
ai.data?.ready ? (
|
||||
<Button size="sm" variant="primary" onClick={() => reprocess(true)}>
|
||||
Read with AI
|
||||
</Button>
|
||||
) : (
|
||||
<Link to="/settings/ai">
|
||||
<Button size="sm">Set up AI</Button>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
>
|
||||
{doc.docKind === 'image' ? 'An AI model with vision can transcribe it so it becomes searchable and usable for generation.' : 'It looks like a scan. An AI model with vision and PDF support can transcribe it.'}
|
||||
</Callout>
|
||||
)}
|
||||
{ready &&
|
||||
doc.warnings
|
||||
.filter((w) => !(doc.needsOcr && /AI model/.test(w)))
|
||||
.map((w, i) => (
|
||||
<Callout key={i} tone="warn" icon={<TriangleAlert />} className="mb-3 py-2.5">
|
||||
{w}
|
||||
</Callout>
|
||||
))}
|
||||
|
||||
{hasOriginal && (
|
||||
<div className="mb-4">
|
||||
<Segmented
|
||||
label="View"
|
||||
value={view}
|
||||
onChange={setView}
|
||||
options={[
|
||||
{ value: 'text', label: 'Extracted text', icon: <FileText /> },
|
||||
{ value: 'original', label: 'Original', icon: <ScanText /> },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{view === 'original' && hasOriginal ? (
|
||||
doc.docKind === 'image' ? (
|
||||
<div className="card grid place-items-center p-4">
|
||||
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
|
||||
</div>
|
||||
) : (
|
||||
<iframe src={fileUrl} title={doc.title} className="card h-[82vh] w-full" />
|
||||
)
|
||||
) : !ready ? null : doc.chunkCount === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<FileText />} title="No text to show">
|
||||
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
|
||||
<div className="min-w-0">
|
||||
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
|
||||
<article className="card divide-y divide-line">
|
||||
{chunks.isLoading && (
|
||||
<div className="space-y-3 p-6">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
</div>
|
||||
)}
|
||||
{all.map((ch, i) => {
|
||||
const prev = all[i - 1];
|
||||
const showHeading = ch.heading && ch.heading !== prev?.heading;
|
||||
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
|
||||
return (
|
||||
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
|
||||
{(showHeading || showPage) && (
|
||||
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
|
||||
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
|
||||
{showPage && (
|
||||
<span className="num text-[11px] text-ink-3">
|
||||
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
|
||||
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</article>
|
||||
{chunks.hasNextPage && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
|
||||
Show more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{q.data.outline.length > 1 && (
|
||||
<aside className="hidden lg:block">
|
||||
<div className="sticky top-8">
|
||||
<div className="eyebrow mb-2">Outline</div>
|
||||
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
|
||||
{q.data.outline.map((o) => (
|
||||
<li key={o.seq}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
// Load forward until the section is on the page, then scroll to it.
|
||||
let pages = chunks.data?.pages ?? [];
|
||||
let guard = 0;
|
||||
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
|
||||
const res = await chunks.fetchNextPage();
|
||||
pages = res.data?.pages ?? [];
|
||||
guard += 1;
|
||||
}
|
||||
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
|
||||
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
}}
|
||||
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
|
||||
title={o.heading}
|
||||
>
|
||||
{o.heading}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<RenameDialog target={rename ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setRename(false)} />
|
||||
<MoveDialog target={move ? { kind: 'document', id: doc.id, title: doc.title, classId: doc.classId, folderId: doc.folderId } : null} onClose={() => setMove(false)} />
|
||||
<ShareDialog target={share ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setShare(false)} />
|
||||
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={doc.classId} folderId={doc.folderId} preset={generate ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
514
web/src/pages/DraftPage.tsx
Normal file
514
web/src/pages/DraftPage.tsx
Normal file
|
|
@ -0,0 +1,514 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { BookOpen, Check, ChevronRight, CircleAlert, Eye, FileText, Layers, NotebookPen, Pencil, Plus, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { blankCard, blankQuestion, optionLetter, QUESTION_TYPE_LABEL, validateDraft, validateDraftCard, validateDraftQuestion, type ContentDraft, type DraftCard, type DraftQuestion } from '@shared/content';
|
||||
import { CardEditor, QuestionEditor } from '@/features/editors';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk, useClass, useClasses, useQuiz, useRefresh } from '@/lib/queries';
|
||||
import type { Draft } from '@/lib/types';
|
||||
import { cx, plural, useDocumentTitle } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, EmptyState, ErrorState, Field, IconButton, Input, PageLoading, ProgressBar, Segmented, Select, Textarea, useConfirm } from '@/ui';
|
||||
|
||||
const KIND = { quiz: { label: 'Quiz', icon: <BookOpen />, url: 'quizzes' }, deck: { label: 'Flashcards', icon: <Layers />, url: 'decks' }, note: { label: 'Note', icon: <NotebookPen />, url: 'notes' } } as const;
|
||||
|
||||
function QuestionPreview({ q }: { q: DraftQuestion }) {
|
||||
return (
|
||||
<>
|
||||
<Markdown serif className="text-[17px]">
|
||||
{q.stem || '*No question text*'}
|
||||
</Markdown>
|
||||
<ul className="mt-3 space-y-1.5">
|
||||
{q.options.map((o, i) => (
|
||||
<li key={i} className="flex items-start gap-2.5 text-[15px]">
|
||||
<span className={cx('num mt-0.5 grid size-6 shrink-0 place-items-center text-xs font-semibold', q.type === 'single' ? 'rounded-full' : 'rounded-md', o.correct ? 'bg-good text-white dark:text-[#10241a]' : 'bg-sunken text-ink-3')}>
|
||||
{o.correct ? <Check className="size-3.5" strokeWidth={3} /> : optionLetter(i)}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Markdown className={o.correct ? 'font-medium' : 'text-ink-2'}>{o.text || '*empty*'}</Markdown>
|
||||
{o.why && <div className="mt-0.5 text-[13px] text-ink-3">{o.why}</div>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{q.rationale && (
|
||||
<div className="mt-3 rounded-xl bg-sunken px-4 py-3">
|
||||
<div className="eyebrow mb-1">Rationale</div>
|
||||
<Markdown className="text-[14.5px]">{q.rationale}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{q.source && (
|
||||
<div className="mt-2 flex items-center gap-1.5 text-xs text-ink-3">
|
||||
<FileText className="size-3.5" /> {q.source}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DraftPage() {
|
||||
const { draftId = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const classes = useClasses();
|
||||
const query = useQuery({
|
||||
queryKey: qk.draft(draftId),
|
||||
queryFn: () => api.get<{ draft: Draft }>(`/api/drafts/${draftId}`).then((r) => r.draft),
|
||||
refetchInterval: (q) => (q.state.data?.status === 'generating' ? 1000 : false),
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const draft = query.data;
|
||||
|
||||
const [payload, setPayload] = useState<ContentDraft | null>(null);
|
||||
const [classId, setClassId] = useState('');
|
||||
const [folderId, setFolderId] = useState('');
|
||||
const [mode, setMode] = useState<'new' | 'append' | 'replace'>('new');
|
||||
const [targetId, setTargetId] = useState('');
|
||||
const [editing, setEditing] = useState<number | null>(null);
|
||||
const [preview, setPreview] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const loaded = useRef('');
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const dirty = useRef(false);
|
||||
|
||||
const cls = useClass(classId || undefined);
|
||||
const original = useQuiz(draft?.meta.origin === 'improve' ? draft.meta.targetId : undefined);
|
||||
useDocumentTitle(draft ? `Review: ${draft.title || 'draft'}` : 'Draft');
|
||||
|
||||
// Adopt the server copy once generation has finished.
|
||||
useEffect(() => {
|
||||
if (!draft || draft.status === 'generating') return;
|
||||
const key = `${draft.id}:${draft.status}`;
|
||||
if (loaded.current === key) return;
|
||||
loaded.current = key;
|
||||
setPayload(draft.payload);
|
||||
setClassId(draft.classId ?? '');
|
||||
setFolderId(draft.folderId ?? '');
|
||||
setMode(draft.meta.origin === 'improve' ? 'replace' : 'new');
|
||||
setTargetId(draft.meta.targetId ?? '');
|
||||
}, [draft]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!classId && classes.data?.length && draft && draft.status === 'ready') setClassId(classes.data.find((c) => !c.archived)?.id ?? classes.data[0].id);
|
||||
}, [classId, classes.data, draft]);
|
||||
|
||||
const persist = (next: ContentDraft) => {
|
||||
setPayload(next);
|
||||
dirty.current = true;
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => void flush(next), 900);
|
||||
};
|
||||
const flush = async (next: ContentDraft) => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = null;
|
||||
if (!dirty.current) return;
|
||||
dirty.current = false;
|
||||
await api.put(`/api/drafts/${draftId}`, { payload: next, classId: classId || null, folderId: folderId || null }).catch(() => {
|
||||
dirty.current = true;
|
||||
});
|
||||
};
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const issues = useMemo(() => (payload ? validateDraft(payload) : []), [payload]);
|
||||
const errors = issues.filter((i) => i.level === 'error');
|
||||
const badItems = new Set(errors.filter((i) => i.index !== undefined).map((i) => i.index));
|
||||
const sameKindItems = (cls.data?.items ?? []).filter((i) => i.kind === draft?.kind);
|
||||
|
||||
if (query.isError) return <ErrorState title="Draft not found" message={errorMessage(query.error)} />;
|
||||
if (!draft) return <PageLoading />;
|
||||
|
||||
const discard = async (ask = true) => {
|
||||
if (ask && !(await confirm({ title: 'Discard this draft?', message: 'The generated content will be thrown away.', confirmLabel: 'Discard', danger: true }))) return;
|
||||
await api.del(`/api/drafts/${draft.id}`).catch(() => undefined);
|
||||
void refresh();
|
||||
navigate(draft.classId ? `/classes/${draft.classId}` : '/');
|
||||
};
|
||||
|
||||
/* ---------- generating ---------- */
|
||||
if (draft.status === 'generating') {
|
||||
const partial = draft.itemCount;
|
||||
return (
|
||||
<div className="mx-auto max-w-xl pt-10 text-center sm:pt-20">
|
||||
<div className="mx-auto mb-5 grid size-14 animate-pulse place-items-center rounded-2xl bg-accent-soft text-accent">
|
||||
<Sparkles className="size-7" />
|
||||
</div>
|
||||
<h1 className="display text-[30px]">Writing your {draft.kind === 'quiz' ? 'quiz' : draft.kind === 'deck' ? 'flashcards' : 'study guide'}</h1>
|
||||
<p className="mt-2 text-[15px] text-ink-2" aria-live="polite">
|
||||
{draft.progressLabel || 'Getting started'}
|
||||
{draft.meta.model ? ` · ${draft.meta.model}` : ''}
|
||||
</p>
|
||||
<ProgressBar value={Math.max(0.04, draft.progress)} className="mx-auto mt-6 h-2 max-w-sm" label="Generation progress" />
|
||||
{draft.kind !== 'note' && partial > 0 && <p className="mt-3 text-sm text-ink-3">{plural(partial, draft.kind === 'quiz' ? 'question' : 'card')} so far</p>}
|
||||
<p className="mt-6 text-[13px] text-ink-3">You can leave this page. The draft keeps generating and will be waiting here.</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="mt-4"
|
||||
onClick={async () => {
|
||||
await api.post(`/api/drafts/${draft.id}/cancel`).catch(() => undefined);
|
||||
void query.refetch();
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- failed / gone ---------- */
|
||||
if (draft.status === 'failed' && draft.itemCount === 0) {
|
||||
return (
|
||||
<div className="mx-auto max-w-xl pt-10">
|
||||
<ErrorState title="Generation did not finish" message={draft.error || 'Something went wrong.'} />
|
||||
<div className="flex justify-center gap-2">
|
||||
<Button variant="primary" onClick={() => navigate(draft.classId ? `/classes/${draft.classId}` : '/')}>
|
||||
Back to class
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => discard(false)}>
|
||||
Discard
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (draft.status === 'saved' || draft.status === 'discarded') {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={<Check />}
|
||||
title={draft.status === 'saved' ? 'This draft was saved' : 'This draft was discarded'}
|
||||
action={
|
||||
draft.status === 'saved' && draft.savedId && draft.savedKind ? (
|
||||
<Button variant="primary" onClick={() => navigate(`/${KIND[draft.savedKind as keyof typeof KIND].url}/${draft.savedId}`)}>
|
||||
Open it
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => navigate('/')}>Go to Today</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!payload) return <PageLoading />;
|
||||
|
||||
const isImprove = draft.meta.origin === 'improve';
|
||||
const save = async () => {
|
||||
if (errors.length > 0) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
dirty.current = true;
|
||||
await flush(payload);
|
||||
const res = await api.post<{ saved: { kind: keyof typeof KIND; id: string; count: number } }>(`/api/drafts/${draft.id}/save`, {
|
||||
classId: classId || undefined,
|
||||
folderId: folderId || null,
|
||||
mode,
|
||||
targetId: mode === 'new' ? undefined : targetId || undefined,
|
||||
});
|
||||
await refresh();
|
||||
qc.removeQueries({ queryKey: qk.draft(draft.id) });
|
||||
toast.success(mode === 'replace' ? 'Revisions applied' : mode === 'append' ? 'Added' : 'Saved to your library');
|
||||
navigate(`/${KIND[res.saved.kind].url}/${res.saved.id}`, { replace: true });
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const setQuestions = (questions: DraftQuestion[]) => payload.kind === 'quiz' && persist({ ...payload, questions });
|
||||
const setCards = (cards: DraftCard[]) => payload.kind === 'deck' && persist({ ...payload, cards });
|
||||
const count = payload.kind === 'quiz' ? payload.questions.length : payload.kind === 'deck' ? payload.cards.length : 0;
|
||||
const noun = payload.kind === 'quiz' ? 'question' : 'card';
|
||||
const removeInvalid = () => {
|
||||
if (payload.kind === 'quiz') setQuestions(payload.questions.filter((_, i) => !badItems.has(i)));
|
||||
else if (payload.kind === 'deck') setCards(payload.cards.filter((_, i) => !badItems.has(i)));
|
||||
setEditing(null);
|
||||
};
|
||||
const topics = payload.kind === 'quiz' ? [...new Set(payload.questions.map((q) => q.topic).filter(Boolean))] : [];
|
||||
const canSave = errors.length === 0 && (mode === 'new' ? Boolean(classId) : Boolean(targetId));
|
||||
|
||||
return (
|
||||
<div className="animate-in pb-28">
|
||||
<header className="mb-6">
|
||||
<div className="eyebrow mb-2 flex flex-wrap items-center gap-2">
|
||||
<span className="flex items-center gap-1.5 [&>svg]:size-3.5">
|
||||
{KIND[draft.kind].icon} Draft {KIND[draft.kind].label.toLowerCase()}
|
||||
</span>
|
||||
{draft.meta.model && (
|
||||
<Badge tone="accent">
|
||||
<Sparkles /> {draft.meta.model}
|
||||
</Badge>
|
||||
)}
|
||||
{draft.meta.origin === 'import' && <Badge>Import</Badge>}
|
||||
</div>
|
||||
<Input
|
||||
value={payload.title}
|
||||
onChange={(e) => persist({ ...payload, title: e.target.value })}
|
||||
placeholder="Give it a title"
|
||||
aria-label="Title"
|
||||
aria-invalid={!payload.title.trim()}
|
||||
className="display h-auto border-transparent bg-transparent px-0 py-1 text-[28px] shadow-none hover:border-line-strong focus:px-2 sm:text-[34px]"
|
||||
readOnly={isImprove}
|
||||
/>
|
||||
<p className="mt-1 text-[15px] text-ink-2">
|
||||
{isImprove ? 'Review the revised questions. The original quiz changes only when you apply them.' : 'Review and edit before saving. Nothing is in your library yet.'}
|
||||
{draft.meta.sources?.length ? ` Based on ${draft.meta.sources.map((s) => s.title).join(', ')}.` : ''}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{draft.status === 'failed' && (
|
||||
<Callout tone="warn" icon={<TriangleAlert />} title="Generation stopped early" className="mb-4">
|
||||
{draft.error} What was written before that is below.
|
||||
</Callout>
|
||||
)}
|
||||
{(draft.meta.notes ?? []).map((n, i) => (
|
||||
<Callout key={i} tone="warn" icon={<TriangleAlert />} className="mb-4 py-2.5">
|
||||
{n}
|
||||
</Callout>
|
||||
))}
|
||||
{badItems.size > 0 && (
|
||||
<Callout
|
||||
tone="bad"
|
||||
icon={<CircleAlert />}
|
||||
className="mb-4"
|
||||
title={`${plural(badItems.size, noun)} ${badItems.size === 1 ? 'needs' : 'need'} fixing before you can save`}
|
||||
action={
|
||||
<Button size="sm" onClick={removeInvalid}>
|
||||
Remove {badItems.size === 1 ? 'it' : 'them'}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
They are marked below. Edit each one, or remove them.
|
||||
</Callout>
|
||||
)}
|
||||
|
||||
{/* destination */}
|
||||
{!isImprove && (
|
||||
<div className="card mb-6 grid gap-4 p-4 sm:grid-cols-3">
|
||||
<Field label="Class">
|
||||
<Select
|
||||
value={classId}
|
||||
onChange={(e) => {
|
||||
setClassId(e.target.value);
|
||||
setFolderId('');
|
||||
setTargetId('');
|
||||
}}
|
||||
>
|
||||
{!classId && <option value="">Choose a class</option>}
|
||||
{(classes.data ?? []).map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
{payload.kind !== 'note' ? (
|
||||
<Field label="Save as">
|
||||
<Select
|
||||
value={mode === 'append' ? targetId : ''}
|
||||
onChange={(e) => {
|
||||
setMode(e.target.value ? 'append' : 'new');
|
||||
setTargetId(e.target.value);
|
||||
}}
|
||||
>
|
||||
<option value="">A new {payload.kind}</option>
|
||||
{sameKindItems.length > 0 && (
|
||||
<optgroup label={`Add to an existing ${payload.kind}`}>
|
||||
{sameKindItems.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.title}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
</Select>
|
||||
</Field>
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
{mode === 'new' && (
|
||||
<Field label="Folder">
|
||||
<Select value={folderId} onChange={(e) => setFolderId(e.target.value)}>
|
||||
<option value="">No folder</option>
|
||||
{(cls.data?.folders ?? []).map((f) => (
|
||||
<option key={f.id} value={f.id}>
|
||||
{f.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* content */}
|
||||
{payload.kind === 'note' ? (
|
||||
<div>
|
||||
<div className="mb-3 flex justify-end">
|
||||
<Segmented
|
||||
size="sm"
|
||||
label="View"
|
||||
value={preview ? 'preview' : 'edit'}
|
||||
onChange={(v) => setPreview(v === 'preview')}
|
||||
options={[
|
||||
{ value: 'preview', label: 'Preview', icon: <Eye /> },
|
||||
{ value: 'edit', label: 'Edit', icon: <Pencil /> },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
{preview ? (
|
||||
<article className="card px-5 py-6 sm:px-10 sm:py-9">
|
||||
<Markdown serif>{payload.content}</Markdown>
|
||||
</article>
|
||||
) : (
|
||||
<Textarea value={payload.content} onChange={(e) => persist({ ...payload, content: e.target.value })} rows={28} className="num text-[13.5px] leading-relaxed" aria-label="Note content (Markdown)" />
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h2 className="eyebrow">{plural(count, noun)}</h2>
|
||||
</div>
|
||||
<ol className="space-y-3">
|
||||
{payload.kind === 'quiz'
|
||||
? payload.questions.map((q, i) => {
|
||||
const own = validateDraftQuestion(q, i);
|
||||
const bad = own.some((x) => x.level === 'error');
|
||||
const before = isImprove ? original.data?.questions.find((x) => x.id === draft.meta.replaceQuestionIds?.[i]) : undefined;
|
||||
return (
|
||||
<li key={i} className={cx('card p-4 sm:p-5', bad && 'border-bad/60 ring-1 ring-bad/30')}>
|
||||
<div className="mb-2.5 flex flex-wrap items-center gap-1.5">
|
||||
<span className="num text-xs font-semibold text-ink-3">{String(i + 1).padStart(2, '0')}</span>
|
||||
<Badge>{QUESTION_TYPE_LABEL[q.type]}</Badge>
|
||||
{q.topic && <Badge tone="accent">{q.topic}</Badge>}
|
||||
{q.difficulty !== 'medium' && <Badge>{q.difficulty}</Badge>}
|
||||
{bad && (
|
||||
<Badge tone="bad">
|
||||
<CircleAlert /> Needs fixing
|
||||
</Badge>
|
||||
)}
|
||||
<span className="ml-auto flex">
|
||||
<IconButton label={editing === i ? 'Done editing' : 'Edit question'} size="sm" active={editing === i} onClick={() => setEditing(editing === i ? null : i)}>
|
||||
{editing === i ? <Check /> : <Pencil />}
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Remove question"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setQuestions(payload.questions.filter((_, k) => k !== i));
|
||||
setEditing(null);
|
||||
}}
|
||||
>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
</span>
|
||||
</div>
|
||||
{editing === i ? (
|
||||
<QuestionEditor value={q} onChange={(next) => setQuestions(payload.questions.map((x, k) => (k === i ? next : x)))} issues={own} topics={topics} onSubmit={() => setEditing(null)} />
|
||||
) : (
|
||||
<>
|
||||
<QuestionPreview q={q} />
|
||||
{bad && <ul className="mt-3 space-y-0.5 text-[13px] text-bad">{own.filter((x) => x.level === 'error').map((x, k) => <li key={k}>• {x.message}</li>)}</ul>}
|
||||
</>
|
||||
)}
|
||||
{before && (
|
||||
<details className="mt-3 rounded-xl border border-line">
|
||||
<summary className="flex items-center gap-1 px-3 py-2 text-[13px] font-medium text-ink-2 hover:text-ink">
|
||||
<ChevronRight className="size-3.5" /> Original question
|
||||
</summary>
|
||||
<div className="border-t border-line p-3 opacity-80">
|
||||
<QuestionPreview q={{ ...before, options: before.options.map((o) => ({ text: o.text, correct: o.correct, why: o.why })), source: undefined }} />
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})
|
||||
: payload.cards.map((c, i) => {
|
||||
const own = validateDraftCard(c, i);
|
||||
const bad = own.length > 0;
|
||||
return (
|
||||
<li key={i} className={cx('card p-4', bad && 'border-bad/60 ring-1 ring-bad/30')}>
|
||||
{editing === i ? (
|
||||
<>
|
||||
<CardEditor value={c} onChange={(next) => setCards(payload.cards.map((x, k) => (k === i ? next : x)))} issues={own} autoFocus onSubmit={() => setEditing(null)} />
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button size="sm" variant="primary" onClick={() => setEditing(null)}>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="num mt-0.5 text-xs font-semibold text-ink-3">{String(i + 1).padStart(2, '0')}</span>
|
||||
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-1.5 sm:grid-cols-2">
|
||||
<Markdown className="text-[14.5px] font-medium">{c.front || '*empty*'}</Markdown>
|
||||
<div>
|
||||
<Markdown className="text-[14.5px] text-ink-2">{c.back || '*empty*'}</Markdown>
|
||||
{c.hint && <div className="mt-1 text-xs text-ink-3">Hint: {c.hint}</div>}
|
||||
</div>
|
||||
</div>
|
||||
<span className="flex shrink-0">
|
||||
<IconButton label="Edit card" size="sm" onClick={() => setEditing(i)}>
|
||||
<Pencil />
|
||||
</IconButton>
|
||||
<IconButton label="Remove card" size="sm" onClick={() => setCards(payload.cards.filter((_, k) => k !== i))}>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{!isImprove && (
|
||||
<Button
|
||||
className="mt-3"
|
||||
icon={<Plus />}
|
||||
onClick={() => {
|
||||
if (payload.kind === 'quiz') setQuestions([...payload.questions, blankQuestion()]);
|
||||
else setCards([...payload.cards, blankCard()]);
|
||||
setEditing(count);
|
||||
}}
|
||||
>
|
||||
Add {noun}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* save bar */}
|
||||
<div className="safe-bottom fixed inset-x-0 bottom-14 z-30 border-t border-line bg-paper/95 backdrop-blur lg:bottom-0 lg:left-[252px]">
|
||||
<div className="mx-auto flex h-16 max-w-[1080px] items-center gap-2 px-4 sm:px-8">
|
||||
<div className="min-w-0 flex-1 text-[13px]" aria-live="polite">
|
||||
{errors.length > 0 ? (
|
||||
<span className="flex items-center gap-1.5 font-medium text-bad">
|
||||
<CircleAlert className="size-4 shrink-0" />
|
||||
<span className="truncate">{badItems.size > 0 ? `${plural(badItems.size, noun)} to fix` : errors[0].message}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5 text-good">
|
||||
<Check className="size-4" /> Ready to save
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="ghost" onClick={() => discard()}>
|
||||
Discard
|
||||
</Button>
|
||||
<Button variant="primary" loading={saving} disabled={!canSave} onClick={save}>
|
||||
{isImprove ? `Apply ${plural(count, 'revision')}` : mode === 'append' ? `Add ${plural(count, noun)}` : payload.kind === 'note' ? 'Save note' : `Save ${plural(count, noun)}`}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
311
web/src/pages/Home.tsx
Normal file
311
web/src/pages/Home.tsx
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
import { ArrowRight, BookOpen, CircleCheck, FileUp, Flame, GraduationCap, Layers, Play, Plus, RotateCcw, Sparkles, Target } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { ClassDialog } from '@/app/Shell';
|
||||
import { AccuracyBar, Heatmap, Ring } from '@/features/charts';
|
||||
import { useStartSession } from '@/features/study';
|
||||
import { assistant } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useClasses, useOverview } from '@/lib/queries';
|
||||
import type { AttemptSummary } from '@/lib/types';
|
||||
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
|
||||
import { Badge, Button, ClassDot, ErrorState, ProgressBar, Section, Skeleton } from '@/ui';
|
||||
|
||||
function greeting(): string {
|
||||
const h = new Date().getHours();
|
||||
if (h < 5) return 'Burning the midnight oil';
|
||||
if (h < 12) return 'Good morning';
|
||||
if (h < 18) return 'Good afternoon';
|
||||
return 'Good evening';
|
||||
}
|
||||
|
||||
function Onboarding({ hasClass, aiReady, onNewClass }: { hasClass: boolean; aiReady: boolean; onNewClass: () => void }) {
|
||||
const steps = [
|
||||
{ done: hasClass, title: 'Create a class', body: 'One for each course. Everything else lives inside it.', action: <Button size="sm" variant="primary" icon={<Plus />} onClick={onNewClass}>New class</Button> },
|
||||
{ done: false, title: 'Add material', body: 'Import quizzes and flashcards, write your own, or upload lecture slides and notes.', action: hasClass ? <span className="text-[13px] text-ink-3">Open a class to add material</span> : null },
|
||||
{ done: aiReady, title: 'Connect an AI model', body: 'Optional. Lets Study Desk write questions from your documents and explain answers.', action: <Link to="/settings/ai" className="text-[13px] font-medium text-accent hover:underline">Open AI settings</Link> },
|
||||
];
|
||||
return (
|
||||
<div className="card overflow-hidden">
|
||||
<div className="border-b border-line bg-sunken/60 px-5 py-4 sm:px-6">
|
||||
<h2 className="display text-2xl">Set up your desk</h2>
|
||||
<p className="mt-1 text-sm text-ink-2">Three steps and you are studying.</p>
|
||||
</div>
|
||||
<ol className="divide-y divide-line">
|
||||
{steps.map((s, i) => (
|
||||
<li key={s.title} className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-4 sm:px-6">
|
||||
<span className={cx('num grid size-8 shrink-0 place-items-center rounded-full text-sm font-semibold', s.done ? 'bg-good-soft text-good' : 'bg-ink text-paper')}>{s.done ? <CircleCheck className="size-4" /> : i + 1}</span>
|
||||
<div className="min-w-0 flex-1 basis-52">
|
||||
<div className={cx('font-medium', s.done && 'text-ink-3 line-through')}>{s.title}</div>
|
||||
<div className="text-[13px] text-ink-2">{s.body}</div>
|
||||
</div>
|
||||
{!s.done && s.action}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResumeRow({ a }: { a: AttemptSummary }) {
|
||||
return (
|
||||
<Link to={`/session/${a.id}`} className="group flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-accent-soft text-accent">
|
||||
<Play className="size-4 fill-current" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium">{a.title}</span>
|
||||
<span className="mt-1 flex items-center gap-2">
|
||||
<ProgressBar value={a.questionCount ? a.answeredCount / a.questionCount : 0} className="w-24" />
|
||||
<span className="num text-xs text-ink-3">
|
||||
{a.answeredCount}/{a.questionCount}
|
||||
</span>
|
||||
<span className="text-xs text-ink-3">· {a.mode === 'exam' ? 'Exam' : 'Practice'} · {timeAgo(a.updatedAt)}</span>
|
||||
</span>
|
||||
</span>
|
||||
<ArrowRight className="size-4 text-ink-3 transition-transform group-hover:translate-x-0.5" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
useDocumentTitle('Today');
|
||||
const overview = useOverview();
|
||||
const classes = useClasses();
|
||||
const ai = useAiStatus();
|
||||
const { start, starting } = useStartSession();
|
||||
const [classDialog, setClassDialog] = useState(false);
|
||||
|
||||
if (overview.isError) return <ErrorState message="Could not load your overview." onRetry={() => overview.refetch()} />;
|
||||
const o = overview.data;
|
||||
const list = (classes.data ?? []).filter((c) => !c.archived);
|
||||
const loading = overview.isLoading || classes.isLoading;
|
||||
const hasContent = list.some((c) => c.counts.quizzes + c.counts.decks + c.counts.documents + c.counts.notes > 0);
|
||||
const isNew = !loading && !hasContent;
|
||||
const due = o?.due.total ?? 0;
|
||||
const today = new Date().toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
|
||||
|
||||
return (
|
||||
<div className="animate-in">
|
||||
<header className="mb-7">
|
||||
<div className="eyebrow mb-1.5">{today}</div>
|
||||
<h1 className="display text-[32px] sm:text-[40px]">{greeting()}.</h1>
|
||||
{o && !isNew && (
|
||||
<p className="mt-2 text-[15px] text-ink-2">
|
||||
{due > 0 ? (
|
||||
<>
|
||||
You have <span className="marker font-semibold text-ink">{plural(due, 'card')}</span> to review
|
||||
</>
|
||||
) : (
|
||||
'Your flashcards are all caught up'
|
||||
)}
|
||||
{o.activeAttempts.length > 0 ? ` and ${plural(o.activeAttempts.length, 'session')} in progress` : ''}.
|
||||
</p>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{loading ? (
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Skeleton className="h-44 md:col-span-2" />
|
||||
<Skeleton className="h-44" />
|
||||
<Skeleton className="h-40 md:col-span-3" />
|
||||
</div>
|
||||
) : isNew ? (
|
||||
<Onboarding hasClass={list.length > 0} aiReady={Boolean(ai.data?.ready)} onNewClass={() => setClassDialog(true)} />
|
||||
) : (
|
||||
o && (
|
||||
<>
|
||||
<div className="mb-8 grid gap-4 lg:grid-cols-[1.35fr_1fr]">
|
||||
{/* Review */}
|
||||
<div className="card relative overflow-hidden p-5 sm:p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
||||
<Layers className="size-3.5" /> Flashcard review
|
||||
</div>
|
||||
{due > 0 ? (
|
||||
<>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="display num text-[56px] leading-none font-medium tracking-tight">{due}</span>
|
||||
<span className="text-ink-2">due today</span>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
{o.due.learning > 0 && <Badge tone="warn">{o.due.learning} learning</Badge>}
|
||||
{o.due.review > 0 && <Badge tone="good">{o.due.review} review</Badge>}
|
||||
{o.due.new > 0 && <Badge tone="accent">{o.due.new} new</Badge>}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="display mt-1 text-[28px]">All caught up</div>
|
||||
<p className="mt-1 max-w-xs text-sm text-ink-2">
|
||||
{o.forecast[1] > 0 ? `${plural(o.forecast[1], 'card')} come due tomorrow.` : 'Nothing is scheduled for tomorrow yet. Add cards to a deck to start building memory.'}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Ring value={o.streak.goal ? o.streak.todayTotal / o.streak.goal : 0} size={76} stroke={7} tone={o.streak.todayDone ? 'good' : 'accent'}>
|
||||
<div className="text-center leading-none">
|
||||
<div className="num text-[17px] font-semibold">{o.streak.todayTotal}</div>
|
||||
<div className="mt-0.5 text-[10px] text-ink-3">of {o.streak.goal}</div>
|
||||
</div>
|
||||
</Ring>
|
||||
</div>
|
||||
<div className="mt-5 flex flex-wrap gap-2">
|
||||
{due > 0 ? (
|
||||
<Link to="/review">
|
||||
<Button variant="primary" size="lg" icon={<Play className="fill-current" />}>
|
||||
Start review
|
||||
</Button>
|
||||
</Link>
|
||||
) : null}
|
||||
{o.missedCount > 0 && (
|
||||
<Button size="lg" icon={<RotateCcw />} loading={starting} onClick={() => start({ source: { type: 'missed' }, count: Math.min(20, o.missedCount) })}>
|
||||
Redo {Math.min(20, o.missedCount)} missed questions
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Streak */}
|
||||
<div className="card flex flex-col p-5 sm:p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="eyebrow flex items-center gap-1.5">
|
||||
<Flame className="size-3.5" /> Streak
|
||||
</div>
|
||||
<Link to="/insights" className="text-xs font-medium text-accent hover:underline">
|
||||
Insights
|
||||
</Link>
|
||||
</div>
|
||||
<div className="mt-2 flex items-baseline gap-2">
|
||||
<span className="display num text-[40px] leading-none">{o.streak.current}</span>
|
||||
<span className="text-sm text-ink-2">{o.streak.current === 1 ? 'day' : 'days'}</span>
|
||||
{o.streak.longest > o.streak.current && <span className="ml-auto text-xs text-ink-3">Best {o.streak.longest}</span>}
|
||||
</div>
|
||||
<p className="mt-1 text-[13px] text-ink-3">
|
||||
{o.streak.todayDone ? 'Today counts. Nice work.' : `${Math.max(0, o.streak.goal - o.streak.todayTotal)} more ${o.streak.goal - o.streak.todayTotal === 1 ? 'item' : 'items'} today to ${o.streak.current > 0 ? 'keep it going' : 'start one'}.`}
|
||||
</p>
|
||||
<Heatmap days={o.activity} goal={o.streak.goal} weeks={18} className="mt-auto pt-4" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{o.activeAttempts.length > 0 && (
|
||||
<Section title="Pick up where you left off">
|
||||
<div className="card divide-y divide-line overflow-hidden">
|
||||
{o.activeAttempts.map((a) => (
|
||||
<ResumeRow key={a.id} a={a} />
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<div className="grid gap-x-6 lg:grid-cols-2">
|
||||
<Section
|
||||
title="Needs work"
|
||||
action={
|
||||
ai.data?.ready && o.weakTopics.length > 0 ? (
|
||||
<button type="button" className="flex items-center gap-1 text-xs font-medium text-accent hover:underline" onClick={() => assistant.open({ prompt: 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts.', autoSend: true, newChat: true })}>
|
||||
<Sparkles className="size-3.5" /> New questions on these
|
||||
</button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{o.weakTopics.length === 0 ? (
|
||||
<div className="card px-5 py-6 text-sm text-ink-2">
|
||||
<Target className="mb-2 size-5 text-ink-3" />
|
||||
Topics you score under 75% on will show up here once you have answered a few questions.
|
||||
</div>
|
||||
) : (
|
||||
<div className="card divide-y divide-line">
|
||||
{o.weakTopics.map((t) => (
|
||||
<div key={`${t.classId}:${t.topic}`} className="flex items-center gap-3 px-4 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<ClassDot color={t.classColor} />
|
||||
<span className="truncate text-sm font-medium">{t.topic}</span>
|
||||
</div>
|
||||
<AccuracyBar value={t.accuracy} className="mt-1.5" />
|
||||
</div>
|
||||
{t.classId && (
|
||||
<Button size="sm" onClick={() => start({ source: { type: 'topics', classId: t.classId!, topics: [t.topic] } })}>
|
||||
Practice
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="Recent results">
|
||||
{o.recentAttempts.length === 0 ? (
|
||||
<div className="card px-5 py-6 text-sm text-ink-2">
|
||||
<BookOpen className="mb-2 size-5 text-ink-3" />
|
||||
Finished quizzes appear here with your score.
|
||||
</div>
|
||||
) : (
|
||||
<div className="card divide-y divide-line">
|
||||
{o.recentAttempts.map((a) => {
|
||||
const p = pct(a.score, a.maxScore);
|
||||
const tone = gradeTone(p);
|
||||
return (
|
||||
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
|
||||
<span className={cx('num grid h-9 w-12 shrink-0 place-items-center rounded-[10px] text-sm font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium">{a.title}</span>
|
||||
<span className="text-xs text-ink-3">
|
||||
{plural(a.questionCount, 'question')} · {timeAgo(a.completedAt)}
|
||||
</span>
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
)}
|
||||
|
||||
{!loading && list.length > 0 && (
|
||||
<Section
|
||||
title="Classes"
|
||||
className="mt-2"
|
||||
action={
|
||||
<Button size="sm" variant="ghost" icon={<Plus />} onClick={() => setClassDialog(true)}>
|
||||
New class
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{list.map((c) => (
|
||||
<Link key={c.id} to={`/classes/${c.id}`} className={cx('card group relative overflow-hidden p-4 pl-5 transition-shadow hover:shadow-2', `tab-${c.color}`)}>
|
||||
<span aria-hidden className="absolute inset-y-0 left-0 w-1.5 bg-tab" />
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
{c.code && <div className="num mb-0.5 text-[11px] text-ink-3">{c.code}</div>}
|
||||
<div className="display truncate text-[19px]">{c.name}</div>
|
||||
</div>
|
||||
{c.due > 0 && <Badge tone="marker">{c.due} due</Badge>}
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-x-3 gap-y-1 text-xs text-ink-3">
|
||||
<span className="flex items-center gap-1"><BookOpen className="size-3.5" />{c.counts.quizzes}</span>
|
||||
<span className="flex items-center gap-1"><Layers className="size-3.5" />{c.counts.decks}</span>
|
||||
<span className="flex items-center gap-1"><FileUp className="size-3.5" />{c.counts.documents}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{!loading && list.length === 0 && !isNew && (
|
||||
<div className="card p-6 text-center">
|
||||
<GraduationCap className="mx-auto mb-2 size-6 text-ink-3" />
|
||||
<Button variant="primary" onClick={() => setClassDialog(true)}>New class</Button>
|
||||
</div>
|
||||
)}
|
||||
<ClassDialog open={classDialog} onOpenChange={setClassDialog} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
203
web/src/pages/InsightsPage.tsx
Normal file
203
web/src/pages/InsightsPage.tsx
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ChartColumn, Flame, RotateCcw, Sparkles, Target } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { AccuracyBar, AccuracyChart, ForecastBars, Heatmap } from '@/features/charts';
|
||||
import { useStartSession } from '@/features/study';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { assistant } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useClasses } from '@/lib/queries';
|
||||
import type { Insights } from '@/lib/types';
|
||||
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
|
||||
import { Button, ClassDot, EmptyState, ErrorState, PageHeader, Section, Segmented, Select, Skeleton } from '@/ui';
|
||||
|
||||
function Stat({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: 'good' | 'warn' | 'bad' | 'none' }) {
|
||||
return (
|
||||
<div className="card p-4">
|
||||
<div className="eyebrow">{label}</div>
|
||||
<div className={cx('display num mt-1.5 text-[30px] leading-none', tone === 'good' && 'text-good', tone === 'warn' && 'text-warn', tone === 'bad' && 'text-bad')}>{value}</div>
|
||||
{sub && <div className="mt-1.5 text-xs text-ink-3">{sub}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function InsightsPage() {
|
||||
useDocumentTitle('Insights');
|
||||
const classes = useClasses();
|
||||
const ai = useAiStatus();
|
||||
const { start, starting } = useStartSession();
|
||||
const [classId, setClassId] = useState('');
|
||||
const [days, setDays] = useState<'7' | '30' | '90'>('30');
|
||||
const q = useQuery({ queryKey: ['insights', classId, days], queryFn: () => api.get<Insights>(`/api/insights?days=${days}${classId ? `&classId=${classId}` : ''}`), placeholderData: (prev) => prev });
|
||||
const d = q.data;
|
||||
|
||||
if (q.isError) return <ErrorState message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
const acc = d?.totals.accuracy ?? null;
|
||||
const accPct = acc === null ? null : Math.round(acc * 100);
|
||||
const topics = (d?.topics ?? []).filter((t) => t.seen >= 2);
|
||||
const empty = d && d.totals.questionsAnswered === 0 && d.totals.cardsReviewed === 0 && d.activity.every((a) => a.total === 0);
|
||||
|
||||
return (
|
||||
<div className="animate-in">
|
||||
<PageHeader
|
||||
title="Insights"
|
||||
description="How your studying is going, and where to spend the next hour."
|
||||
actions={
|
||||
<>
|
||||
<Select value={classId} onChange={(e) => setClassId(e.target.value)} aria-label="Class" className="w-48">
|
||||
<option value="">All classes</option>
|
||||
{(classes.data ?? []).map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<Segmented
|
||||
label="Period"
|
||||
value={days}
|
||||
onChange={setDays}
|
||||
options={[
|
||||
{ value: '7', label: '7 days' },
|
||||
{ value: '30', label: '30 days' },
|
||||
{ value: '90', label: '90 days' },
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{!d ? (
|
||||
<div className="grid gap-4 sm:grid-cols-4">
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-24" />
|
||||
))}
|
||||
<Skeleton className="h-56 sm:col-span-4" />
|
||||
</div>
|
||||
) : empty ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<ChartColumn />} title="Nothing to chart yet">
|
||||
Take a quiz or review some flashcards and your progress will start to appear here.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className={cx('transition-opacity', q.isFetching && 'opacity-70')}>
|
||||
<div className="mb-8 grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<Stat label="Accuracy" value={accPct === null ? '—' : `${accPct}%`} sub={`${plural(d.totals.questionsAnswered, 'question')} answered`} tone={gradeTone(accPct)} />
|
||||
<Stat label="Card retention" value={d.totals.retention === null ? '—' : `${Math.round(d.totals.retention * 100)}%`} sub={`${plural(d.totals.cardsReviewed, 'card')} reviewed`} tone={d.totals.retention === null ? 'none' : gradeTone(Math.round(d.totals.retention * 100))} />
|
||||
<Stat label="Study days" value={`${d.totals.studyDays}`} sub={`of the last ${d.range}`} />
|
||||
<Stat label="Streak" value={`${d.streak.current}`} sub={`Best ${d.streak.longest} · goal ${d.streak.goal}/day`} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-x-6 lg:grid-cols-[1.5fr_1fr]">
|
||||
<Section title="Quiz accuracy by day">
|
||||
<div className="card p-4">
|
||||
<AccuracyChart points={d.accuracy} />
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="Reviews coming up">
|
||||
<div className="card p-4">
|
||||
<ForecastBars values={d.forecast} />
|
||||
<p className="mt-3 text-xs text-ink-3">
|
||||
{d.due.total > 0 ? (
|
||||
<>
|
||||
{plural(d.due.total, 'card')} ready now.{' '}
|
||||
<Link to={classId ? `/review?classId=${classId}` : '/review'} className="font-medium text-accent hover:underline">
|
||||
Start review
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
'Nothing due right now.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<Section
|
||||
title="Activity"
|
||||
action={
|
||||
<span className="flex items-center gap-1.5 text-xs text-ink-3">
|
||||
<Flame className="size-3.5" /> A day counts toward your streak at {d.streak.goal} items
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="card p-4 sm:p-5">
|
||||
<Heatmap days={d.activity} goal={d.streak.goal} weeks={53} />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Topics, weakest first"
|
||||
action={
|
||||
<div className="flex gap-2">
|
||||
{d.missedCount > 0 && (
|
||||
<Button size="sm" icon={<RotateCcw />} loading={starting} onClick={() => start({ source: { type: 'missed', classId: classId || undefined }, count: Math.min(25, d.missedCount) })}>
|
||||
Redo missed ({Math.min(25, d.missedCount)})
|
||||
</Button>
|
||||
)}
|
||||
{ai.data?.ready && topics.length > 0 && (
|
||||
<Button size="sm" icon={<Sparkles />} onClick={() => assistant.open({ prompt: 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts.', autoSend: true, newChat: true, classId: classId || null })}>
|
||||
New questions on weak areas
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{topics.length === 0 ? (
|
||||
<div className="card px-5 py-6 text-sm text-ink-2">
|
||||
<Target className="mb-2 size-5 text-ink-3" />
|
||||
Give your questions a topic and answer a few of them. Accuracy by topic will show up here.
|
||||
</div>
|
||||
) : (
|
||||
<div className="card divide-y divide-line">
|
||||
{topics.map((t) => (
|
||||
<div key={`${t.classId}:${t.topic}`} className="grid grid-cols-[1fr_auto] items-center gap-x-4 gap-y-1 px-4 py-3 sm:grid-cols-[1.2fr_1fr_auto]">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<ClassDot color={t.classColor} />
|
||||
<span className="truncate text-sm font-medium">{t.topic}</span>
|
||||
</div>
|
||||
<div className="mt-0.5 pl-[18px] text-xs text-ink-3">
|
||||
{t.className ? `${t.className} · ` : ''}
|
||||
{plural(t.seen, 'answer')}
|
||||
</div>
|
||||
</div>
|
||||
<AccuracyBar value={t.accuracy} className="col-span-2 sm:col-span-1" />
|
||||
{t.classId && t.questions > 0 ? (
|
||||
<Button size="sm" className="col-start-2 row-start-1 sm:col-start-3" onClick={() => start({ source: { type: 'topics', classId: t.classId!, topics: [t.topic] } })}>
|
||||
Practice
|
||||
</Button>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{d.recentAttempts.length > 0 && (
|
||||
<Section title="Recent sessions">
|
||||
<div className="card divide-y divide-line">
|
||||
{d.recentAttempts.map((a) => {
|
||||
const p = pct(a.score, a.maxScore);
|
||||
const tone = gradeTone(p);
|
||||
return (
|
||||
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-2.5 hover:bg-ink/4">
|
||||
<span className={cx('num grid h-8 w-12 shrink-0 place-items-center rounded-[9px] text-[13px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">{a.title}</span>
|
||||
<span className="shrink-0 text-xs text-ink-3">
|
||||
{a.mode === 'exam' ? 'Exam · ' : ''}
|
||||
{timeAgo(a.completedAt)}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
233
web/src/pages/NotePage.tsx
Normal file
233
web/src/pages/NotePage.tsx
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { MoveDialog, ShareDialog } from '@/features/dialogs';
|
||||
import { MarkdownArea } from '@/features/editors';
|
||||
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useAssistantContext } from '@/lib/assistantStore';
|
||||
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
|
||||
import type { ClassInfo, NoteInfo, Share } from '@/lib/types';
|
||||
import { cx, downloadText, timeAgo, useDocumentTitle } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, useConfirm } from '@/ui';
|
||||
|
||||
export default function NotePage() {
|
||||
const { noteId = '' } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const q = useQuery({ queryKey: qk.note(noteId), queryFn: () => api.get<{ note: NoteInfo; class: ClassInfo; share: Share | null }>(`/api/notes/${noteId}`), refetchOnWindowFocus: false });
|
||||
const note = q.data?.note;
|
||||
useDocumentTitle(note?.title);
|
||||
useAssistantContext(note?.classId, note?.title);
|
||||
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [status, setStatus] = useState<'saved' | 'saving' | 'dirty' | 'error'>('saved');
|
||||
const [move, setMove] = useState(false);
|
||||
const [share, setShare] = useState(false);
|
||||
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
|
||||
const loaded = useRef('');
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const latest = useRef({ title: '', content: '' });
|
||||
|
||||
useEffect(() => {
|
||||
if (note && loaded.current !== note.id) {
|
||||
loaded.current = note.id;
|
||||
setTitle(note.title);
|
||||
setContent(note.content);
|
||||
latest.current = { title: note.title, content: note.content };
|
||||
setEditing(Boolean(params.get('edit')) || note.content.trim() === '');
|
||||
if (params.get('edit')) setParams({}, { replace: true });
|
||||
}
|
||||
}, [note, params, setParams]);
|
||||
|
||||
const saveNow = async () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
setStatus('saving');
|
||||
try {
|
||||
await api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content });
|
||||
setStatus('saved');
|
||||
} catch {
|
||||
setStatus('error');
|
||||
}
|
||||
};
|
||||
const change = (patch: Partial<{ title: string; content: string }>) => {
|
||||
latest.current = { ...latest.current, ...patch };
|
||||
if (patch.title !== undefined) setTitle(patch.title);
|
||||
if (patch.content !== undefined) setContent(patch.content);
|
||||
setStatus('dirty');
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => void saveNow(), 900);
|
||||
};
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) {
|
||||
clearTimeout(timer.current);
|
||||
void api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }).catch(() => undefined);
|
||||
}
|
||||
},
|
||||
[noteId],
|
||||
);
|
||||
|
||||
if (q.isError) return <ErrorState title="Note not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!q.data || !note) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-10 w-96 max-w-full" />
|
||||
<Skeleton className="h-96" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const cls = q.data.class;
|
||||
const remove = async () => {
|
||||
if (!(await confirm({ title: 'Delete this note?', message: `"${note.title}" will be permanently deleted.`, confirmLabel: 'Delete', danger: true }))) return;
|
||||
try {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
await api.del(`/api/notes/${note.id}`);
|
||||
await refresh();
|
||||
navigate(`/classes/${note.classId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${cls.color}`)}>
|
||||
<nav aria-label="Breadcrumb" className="no-print mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
|
||||
<Link to={`/classes/${cls.id}`} className="flex items-center gap-1.5 hover:text-ink">
|
||||
<ClassDot color={cls.color} />
|
||||
{cls.name}
|
||||
</Link>
|
||||
<ChevronRight className="size-3.5" />
|
||||
<span>{note.kind === 'guide' ? 'Study guide' : 'Note'}</span>
|
||||
</nav>
|
||||
|
||||
<header className="mb-5 flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
|
||||
<div className="min-w-0 flex-1 basis-80">
|
||||
{editing ? (
|
||||
<Input value={title} onChange={(e) => change({ title: e.target.value })} aria-label="Title" maxLength={200} className="display h-auto border-transparent bg-transparent px-0 py-1 text-[28px] shadow-none hover:border-line-strong focus:px-2 sm:text-[34px]" />
|
||||
) : (
|
||||
<h1 className="display text-[28px] sm:text-[34px]">{title}</h1>
|
||||
)}
|
||||
<div className="no-print mt-1.5 flex flex-wrap items-center gap-2 text-[13px] text-ink-3">
|
||||
<span>Edited {timeAgo(note.updatedAt)}</span>
|
||||
{editing && (
|
||||
<span className={cx('flex items-center gap-1', status === 'error' && 'text-bad')} aria-live="polite">
|
||||
{status === 'saved' ? (
|
||||
<>
|
||||
<Check className="size-3.5" /> Saved
|
||||
</>
|
||||
) : status === 'error' ? (
|
||||
'Could not save. Check your connection.'
|
||||
) : (
|
||||
'Saving…'
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{q.data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="no-print flex items-center gap-2">
|
||||
<Segmented
|
||||
label="Mode"
|
||||
value={editing ? 'edit' : 'read'}
|
||||
onChange={(v) => {
|
||||
if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId)));
|
||||
setEditing(v === 'edit');
|
||||
}}
|
||||
options={[
|
||||
{ value: 'read', label: 'Read', icon: <Eye /> },
|
||||
{ value: 'edit', label: 'Edit', icon: <Pencil /> },
|
||||
]}
|
||||
/>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Note options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{ai.data?.ready && content.trim().length > 40 && (
|
||||
<>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', noteId: note.id, sourceLabel: title })}>
|
||||
Quiz from this note
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', noteId: note.id, sourceLabel: title })}>
|
||||
Flashcards from this note
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
|
||||
Move
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
|
||||
Share
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadText(`${title.replace(/[^\w\- ]+/g, '').trim() || 'note'}.md`, `# ${title}\n\n${content}`, 'text/markdown')}>
|
||||
Download as Markdown
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Printer />} onSelect={() => (setEditing(false), setTimeout(() => window.print(), 150))}>
|
||||
Print
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
|
||||
Delete
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{editing ? (
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<div>
|
||||
<MarkdownArea label="Note content (Markdown)" value={content} onChange={(v) => change({ content: v })} rows={22} placeholder={'Write in Markdown.\n\n## Heading\n- bullet\n**bold**, tables, and pasted images all work.'} className="[&_textarea]:min-h-[60vh] [&_textarea]:font-mono [&_textarea]:text-[13.5px]" />
|
||||
<p className="mt-1.5 text-xs text-ink-3">Markdown. Paste or drop an image to embed it. Changes save automatically.</p>
|
||||
</div>
|
||||
<article className="card hidden max-h-[80vh] overflow-y-auto px-7 py-6 xl:block">
|
||||
<div className="eyebrow mb-3 flex items-center gap-1.5">
|
||||
<Eye className="size-3.5" /> Preview
|
||||
</div>
|
||||
<Markdown serif>{content || '*Nothing yet.*'}</Markdown>
|
||||
</article>
|
||||
</div>
|
||||
) : content.trim() ? (
|
||||
<article className="card px-5 py-6 sm:px-12 sm:py-10 print:border-0 print:p-0 print:shadow-none">
|
||||
<Markdown serif className="mx-auto max-w-[70ch]">
|
||||
{content}
|
||||
</Markdown>
|
||||
</article>
|
||||
) : (
|
||||
<div className="card">
|
||||
<EmptyState
|
||||
icon={<Sparkles />}
|
||||
title="This note is empty"
|
||||
action={
|
||||
<Button variant="primary" icon={<Pencil />} onClick={() => setEditing(true)}>
|
||||
Start writing
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MoveDialog target={move ? { kind: 'note', id: note.id, title, classId: note.classId, folderId: note.folderId } : null} onClose={() => setMove(false)} />
|
||||
<ShareDialog target={share ? { kind: 'note', id: note.id, title } : null} onClose={() => setShare(false)} />
|
||||
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={note.classId} folderId={note.folderId} preset={generate ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
679
web/src/pages/QuizPage.tsx
Normal file
679
web/src/pages/QuizPage.tsx
Normal file
|
|
@ -0,0 +1,679 @@
|
|||
import { ArrowDown, ArrowUp, BookOpen, Check, ChevronRight, ClipboardList, Copy, Download, FolderInput, History, Layers, ListPlus, MoreHorizontal, Pencil, Play, Plus, RotateCcw, Search, Share2, Sparkles, Stamp, Timer, Trash2, WandSparkles } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { blankQuestion, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content';
|
||||
import { parseImport } from '@shared/importer';
|
||||
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
|
||||
import { QuestionEditor } from '@/features/editors';
|
||||
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
||||
import { useStartSession } from '@/features/study';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useAssistantContext } from '@/lib/assistantStore';
|
||||
import { useAiStatus, useQuiz, useRefresh } from '@/lib/queries';
|
||||
import { cx, downloadFile, formatDateTime, formatMinutes, gradeTone, pct, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui';
|
||||
|
||||
interface StartPrefs {
|
||||
mode: 'practice' | 'exam';
|
||||
shuffleQuestions: boolean;
|
||||
shuffleOptions: boolean;
|
||||
}
|
||||
|
||||
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) {
|
||||
const { start, starting } = useStartSession();
|
||||
const [prefs, setPrefs] = useLocalStorage<StartPrefs>('sd.startPrefs', { mode: 'practice', shuffleQuestions: true, shuffleOptions: true });
|
||||
const [count, setCount] = useState(total);
|
||||
const [timed, setTimed] = useState(false);
|
||||
const [minutes, setMinutes] = useState(30);
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setCount(total);
|
||||
setMinutes(Math.max(5, Math.round(total * 1.2)));
|
||||
setTimed(false);
|
||||
}
|
||||
}, [open, total]);
|
||||
const go = () =>
|
||||
start({
|
||||
mode: prefs.mode,
|
||||
source: { type: 'quiz', quizId },
|
||||
shuffleQuestions: prefs.shuffleQuestions,
|
||||
shuffleOptions: prefs.shuffleOptions,
|
||||
count: count < total ? count : undefined,
|
||||
timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null,
|
||||
});
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Start a session"
|
||||
description={title}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" icon={<Play className="fill-current" />} loading={starting} onClick={go}>
|
||||
Start
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-5">
|
||||
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
|
||||
{(
|
||||
[
|
||||
{ v: 'practice', title: 'Practice', body: 'Check each answer as you go and read the rationale right away.' },
|
||||
{ v: 'exam', title: 'Exam', body: 'No feedback until you submit. Flag questions and come back to them.' },
|
||||
] as const
|
||||
).map((m) => (
|
||||
<button
|
||||
key={m.v}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={prefs.mode === m.v}
|
||||
onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))}
|
||||
className={cx('rounded-xl border p-3.5 text-left transition-colors', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}
|
||||
>
|
||||
<div className="font-semibold">{m.title}</div>
|
||||
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.body}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<Field label={`Questions: ${count === total ? `all ${total}` : `${count} of ${total}`}`}>
|
||||
<input type="range" min={1} max={total} value={count} onChange={(e) => setCount(Number(e.target.value))} className="mt-1 w-full accent-[var(--accent)]" disabled={total <= 1} />
|
||||
</Field>
|
||||
<div className="space-y-4 rounded-xl border border-line p-4">
|
||||
<Switch checked={prefs.shuffleQuestions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQuestions: v }))} label="Shuffle questions" />
|
||||
<Switch checked={prefs.shuffleOptions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleOptions: v }))} label="Shuffle answer choices" description='"All of the above" style choices stay last.' />
|
||||
{prefs.mode === 'exam' && (
|
||||
<>
|
||||
<Switch checked={timed} onChange={setTimed} label="Time limit" description="The exam submits itself when time runs out." />
|
||||
{timed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Timer className="size-4 text-ink-3" />
|
||||
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setMinutes(Math.max(1, Math.min(600, Number(e.target.value) || 1)))} className="w-24" aria-label="Minutes" />
|
||||
<span className="text-sm text-ink-2">minutes</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** Paste several questions (or cards) as text or JSON and add them to an existing item. */
|
||||
export function BulkAddDialog({ open, onClose, kind, onAdd }: { open: boolean; onClose: () => void; kind: 'quiz' | 'deck'; onAdd: (items: unknown[]) => Promise<void> }) {
|
||||
const [text, setText] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (open) setText('');
|
||||
}, [open]);
|
||||
const parsed = useMemo(() => (text.trim() ? parseImport(text, { prefer: kind }) : null), [text, kind]);
|
||||
const all: (DraftQuestion | DraftCard)[] = (parsed?.items ?? []).flatMap((it): (DraftQuestion | DraftCard)[] => (kind === 'quiz' && it.kind === 'quiz' ? it.questions : kind === 'deck' && it.kind === 'deck' ? it.cards : []));
|
||||
const valid = all.filter((x) => ('stem' in x ? validateDraftQuestion(x, 0).every((i) => i.level !== 'error') : Boolean(x.front.trim() && x.back.trim())));
|
||||
const noun = kind === 'quiz' ? 'question' : 'card';
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Add several ${noun}s`}
|
||||
size="lg"
|
||||
footer={
|
||||
<>
|
||||
<span className="mr-auto text-[13px] text-ink-3" aria-live="polite">
|
||||
{parsed ? (all.length === 0 ? `No ${noun}s recognised yet` : `${valid.length} ready${all.length > valid.length ? `, ${all.length - valid.length} with problems will be skipped` : ''}`) : ''}
|
||||
</span>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={valid.length === 0}
|
||||
loading={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await onAdd(valid);
|
||||
onClose();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Add {valid.length > 0 ? plural(valid.length, noun) : ''}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Textarea
|
||||
autoFocus
|
||||
rows={14}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
spellCheck={false}
|
||||
className="num text-[13px]"
|
||||
aria-label={`Paste ${noun}s`}
|
||||
placeholder={
|
||||
kind === 'quiz'
|
||||
? '1. Which electrolyte imbalance causes peaked T waves?\nA. Hypokalemia\n*B. Hyperkalemia\nC. Hyponatremia\nRationale: High potassium speeds repolarisation.\nTopic: Electrolytes\n\n2. Next question…\n\nMark correct choices with * (or add a line "Answer: B, D"). JSON works too.'
|
||||
: 'Furosemide\tLoop diuretic; monitor potassium\nMetoprolol\tBeta-1 blocker; hold for HR under 60\n\nOne card per line: front, a tab (or " - " or "::"), then back. JSON works too.'
|
||||
}
|
||||
/>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function QuestionView({ q, index, stat }: { q: Question; index: number; stat?: { seen: number; correct: number; lastCorrect: boolean } }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const hasMore = Boolean(q.rationale) || q.options.some((o) => o.why);
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-1.5">
|
||||
<span className="num text-xs font-semibold text-ink-3">{String(index + 1).padStart(2, '0')}</span>
|
||||
<Badge>{QUESTION_TYPE_LABEL[q.type]}</Badge>
|
||||
{q.topic && <Badge tone="accent">{q.topic}</Badge>}
|
||||
{q.difficulty !== 'medium' && <Badge>{q.difficulty}</Badge>}
|
||||
{stat && stat.seen > 0 && (
|
||||
<Badge tone={stat.lastCorrect ? 'good' : 'bad'}>
|
||||
{stat.correct}/{stat.seen} correct
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Markdown serif className="text-[17px]">
|
||||
{q.stem}
|
||||
</Markdown>
|
||||
<ul className="mt-3 space-y-1.5">
|
||||
{q.options.map((o, i) => (
|
||||
<li key={o.id} className="flex items-start gap-2.5 text-[15px]">
|
||||
<span className={cx('num mt-0.5 grid size-6 shrink-0 place-items-center text-xs font-semibold', q.type === 'single' ? 'rounded-full' : 'rounded-md', o.correct ? 'bg-good text-white dark:text-[#10241a]' : 'bg-sunken text-ink-3')}>
|
||||
{o.correct ? <Check className="size-3.5" strokeWidth={3} /> : optionLetter(i)}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Markdown className={o.correct ? 'font-medium' : 'text-ink-2'}>{o.text}</Markdown>
|
||||
{open && o.why && <div className="mt-0.5 text-[13px] text-ink-3">{o.why}</div>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{hasMore && (
|
||||
<>
|
||||
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="mt-3 flex items-center gap-1 text-[13px] font-medium text-accent hover:underline">
|
||||
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
|
||||
{open ? 'Hide rationale' : 'Show rationale'}
|
||||
</button>
|
||||
{open && q.rationale && (
|
||||
<div className="mt-2 rounded-xl bg-sunken px-4 py-3">
|
||||
<Markdown className="text-[14.5px]">{q.rationale}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function QuizPage() {
|
||||
const { quizId = '' } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const q = useQuiz(quizId);
|
||||
const data = q.data;
|
||||
useDocumentTitle(data?.quiz.title);
|
||||
useAssistantContext(data?.quiz.classId, data?.quiz.title);
|
||||
const { start, starting } = useStartSession();
|
||||
|
||||
const [tab, setTab] = useState<'questions' | 'history'>('questions');
|
||||
const [editing, setEditing] = useState<string | 'new' | null>(null);
|
||||
const [draft, setDraft] = useState<DraftQuestion>(blankQuestion());
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [filter, setFilter] = useState('');
|
||||
const [onlyMissed, setOnlyMissed] = useState(false);
|
||||
const [startOpen, setStartOpen] = useState(false);
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
const [rename, setRename] = useState(false);
|
||||
const [move, setMove] = useState(false);
|
||||
const [share, setShare] = useState(false);
|
||||
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
|
||||
const newRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Deep links: ?start=1 opens the start dialog, ?edit=1 a blank question, ?q=<id> scrolls to a question.
|
||||
useEffect(() => {
|
||||
if (!data) return;
|
||||
const next = new URLSearchParams(params);
|
||||
if (params.get('start') && data.questions.length > 0) setStartOpen(true);
|
||||
if (params.get('edit')) {
|
||||
setDraft(blankQuestion());
|
||||
setEditing('new');
|
||||
}
|
||||
const target = params.get('q');
|
||||
if (target) setTimeout(() => document.getElementById(`q-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
|
||||
if (params.get('start') || params.get('edit')) {
|
||||
next.delete('start');
|
||||
next.delete('edit');
|
||||
setParams(next, { replace: true });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data?.quiz.id]);
|
||||
|
||||
const topics = useMemo(() => [...new Set((data?.questions ?? []).map((x) => x.topic).filter(Boolean))].sort(), [data]);
|
||||
const stats = data?.questionStats ?? {};
|
||||
const shown = useMemo(() => {
|
||||
const needle = filter.trim().toLowerCase();
|
||||
return (data?.questions ?? [])
|
||||
.map((question, index) => ({ question, index }))
|
||||
.filter(({ question }) => (!needle || question.stem.toLowerCase().includes(needle) || question.topic.toLowerCase().includes(needle)) && (!onlyMissed || stats[question.id]?.lastCorrect === false));
|
||||
}, [data, filter, onlyMissed, stats]);
|
||||
|
||||
if (q.isError) return <ErrorState title="Quiz not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-10 w-96 max-w-full" />
|
||||
<Skeleton className="h-24" />
|
||||
{[0, 1].map((i) => (
|
||||
<Skeleton key={i} className="h-48" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { quiz, questions, history } = data;
|
||||
const full = history.filter((h) => h.kind === 'full' && h.maxScore);
|
||||
const best = full.length ? Math.max(...full.map((h) => pct(h.score, h.maxScore) ?? 0)) : null;
|
||||
const last = full.length ? pct(full[0].score, full[0].maxScore) : null;
|
||||
const missedCount = Object.values(stats).filter((s) => !s.lastCorrect).length;
|
||||
const editingIssues = editing ? validateDraftQuestion(draft, 0) : [];
|
||||
const canSave = editingIssues.every((i) => i.level !== 'error');
|
||||
|
||||
const beginEdit = (question: Question) => {
|
||||
setDraft(questionToDraft(question));
|
||||
setEditing(question.id);
|
||||
};
|
||||
const beginNew = () => {
|
||||
setDraft({ ...blankQuestion(), topic: questions[questions.length - 1]?.topic ?? '' });
|
||||
setEditing('new');
|
||||
setTimeout(() => newRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 60);
|
||||
};
|
||||
const save = async (another = false) => {
|
||||
if (!canSave || !editing) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing === 'new') await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: [draft] });
|
||||
else await api.patch(`/api/questions/${editing}`, draft);
|
||||
await refresh();
|
||||
if (another && editing === 'new') {
|
||||
setDraft({ ...blankQuestion(draft.type), topic: draft.topic });
|
||||
setTimeout(() => newRef.current?.querySelector('textarea')?.focus(), 60);
|
||||
} else setEditing(null);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
const removeQuestion = async (question: Question) => {
|
||||
if (!(await confirm({ title: 'Delete this question?', message: 'It will be removed from the quiz. Past attempts keep their own copy.', confirmLabel: 'Delete', danger: true }))) return;
|
||||
await api.del(`/api/questions/${question.id}`).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
};
|
||||
const moveQuestion = async (index: number, delta: number) => {
|
||||
const ids = questions.map((x) => x.id);
|
||||
const to = index + delta;
|
||||
if (to < 0 || to >= ids.length) return;
|
||||
[ids[index], ids[to]] = [ids[to], ids[index]];
|
||||
await api.post(`/api/quizzes/${quiz.id}/questions/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
};
|
||||
const duplicateQuestion = async (question: Question, index: number) => {
|
||||
await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: [questionToDraft(question)], index: index + 1 }).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
};
|
||||
const deleteQuiz = async () => {
|
||||
if (!(await confirm({ title: 'Delete this quiz?', message: `"${quiz.title}" and its ${plural(questions.length, 'question')} will be permanently deleted.`, confirmLabel: 'Delete quiz', danger: true }))) return;
|
||||
try {
|
||||
await api.del(`/api/quizzes/${quiz.id}`);
|
||||
await refresh();
|
||||
navigate(`/classes/${quiz.classId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const improve = async (ids?: string[]) => {
|
||||
try {
|
||||
const res = await api.post<{ draftId: string }>('/api/ai/improve', { quizId: quiz.id, questionIds: ids });
|
||||
navigate(`/drafts/${res.draftId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
const editorFooter = (isNew: boolean) => (
|
||||
<div className="mt-5 flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
|
||||
<span className="mr-auto hidden text-xs text-ink-3 sm:block">Ctrl+Enter to save</span>
|
||||
<Button variant="ghost" onClick={() => setEditing(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
{isNew && (
|
||||
<Button disabled={!canSave} loading={saving} onClick={() => save(true)}>
|
||||
Save and add another
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="primary" disabled={!canSave} loading={saving} onClick={() => save(false)}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${data.class.color}`)}>
|
||||
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
|
||||
<Link to={`/classes/${data.class.id}`} className="flex items-center gap-1.5 hover:text-ink">
|
||||
<ClassDot color={data.class.color} />
|
||||
{data.class.name}
|
||||
</Link>
|
||||
<ChevronRight className="size-3.5" />
|
||||
<span>Quiz</span>
|
||||
</nav>
|
||||
|
||||
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
|
||||
<div className="min-w-0">
|
||||
<h1 className="display text-[30px] sm:text-[36px]">{quiz.title}</h1>
|
||||
{quiz.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{quiz.description}</p>}
|
||||
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-ink-2">
|
||||
<span>{plural(questions.length, 'question')}</span>
|
||||
{full.length > 0 && (
|
||||
<>
|
||||
<span>
|
||||
Last <strong className="num text-ink">{last}%</strong>
|
||||
</span>
|
||||
<span>
|
||||
Best <strong className="num text-ink">{best}%</strong>
|
||||
</span>
|
||||
<span>{plural(history.length, 'attempt')}</span>
|
||||
</>
|
||||
)}
|
||||
{data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{data.activeAttempt ? (
|
||||
<Link to={`/session/${data.activeAttempt.id}`}>
|
||||
<Button variant="marker" size="lg" icon={<Play className="fill-current" />}>
|
||||
Resume ({data.activeAttempt.answeredCount}/{data.activeAttempt.questionCount})
|
||||
</Button>
|
||||
</Link>
|
||||
) : null}
|
||||
<Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}>
|
||||
{data.activeAttempt ? 'Start new' : 'Start'}
|
||||
</Button>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Quiz options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{missedCount > 0 && (
|
||||
<MenuItem icon={<RotateCcw />} onSelect={() => start({ source: { type: 'missed', quizId: quiz.id } })}>
|
||||
Practice {missedCount} missed
|
||||
</MenuItem>
|
||||
)}
|
||||
{ai.data?.ready && questions.length > 0 && (
|
||||
<>
|
||||
<MenuItem icon={<WandSparkles />} onSelect={() => improve()}>
|
||||
Improve questions with AI
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', quizId: quiz.id, sourceLabel: quiz.title })}>
|
||||
Make flashcards from this
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
|
||||
Rename
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
|
||||
Move
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<Copy />}
|
||||
onSelect={async () => {
|
||||
const res = await api.post<{ quiz: { id: string } }>(`/api/quizzes/${quiz.id}/duplicate`, {}).catch((e) => (toast.error(errorMessage(e)), null));
|
||||
if (res) {
|
||||
await refresh();
|
||||
navigate(`/quizzes/${res.quiz.id}`);
|
||||
toast.success('Duplicated');
|
||||
}
|
||||
}}
|
||||
>
|
||||
Duplicate
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
|
||||
Share
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/quizzes/${quiz.id}/export`)}>
|
||||
Export JSON
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
icon={<Stamp />}
|
||||
onSelect={async () => {
|
||||
await api.post('/api/templates/from', { kind: 'quiz', id: quiz.id }).then(() => toast.success('Saved as a template')).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
}}
|
||||
>
|
||||
Save as template
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={deleteQuiz}>
|
||||
Delete quiz
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||
<Segmented
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
label="View"
|
||||
options={[
|
||||
{ value: 'questions', label: `Questions`, icon: <ClipboardList /> },
|
||||
{ value: 'history', label: `History${history.length ? ` (${history.length})` : ''}`, icon: <History /> },
|
||||
]}
|
||||
/>
|
||||
{tab === 'questions' && questions.length > 0 && (
|
||||
<div className="ml-auto flex flex-wrap items-center gap-2">
|
||||
{missedCount > 0 && (
|
||||
<button type="button" aria-pressed={onlyMissed} onClick={() => setOnlyMissed(!onlyMissed)} className={cx('h-9 rounded-full border px-3 text-[13px] font-medium', onlyMissed ? 'border-bad bg-bad-soft text-bad' : 'border-line-strong text-ink-2 hover:border-ink-3')}>
|
||||
Missed ({missedCount})
|
||||
</button>
|
||||
)}
|
||||
{questions.length > 5 && (
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
|
||||
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Find a question" aria-label="Find a question" className="h-9 w-44 pl-8 sm:w-56" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{tab === 'questions' ? (
|
||||
<>
|
||||
{questions.length === 0 && editing !== 'new' ? (
|
||||
<div className="card border-dashed">
|
||||
<EmptyState
|
||||
icon={<BookOpen />}
|
||||
title="No questions yet"
|
||||
action={
|
||||
<>
|
||||
<Button variant="primary" icon={<Plus />} onClick={beginNew}>
|
||||
Write a question
|
||||
</Button>
|
||||
<Button icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
|
||||
Paste several
|
||||
</Button>
|
||||
<Button icon={<Sparkles />} onClick={() => navigate(`/classes/${quiz.classId}`)}>
|
||||
Generate from documents
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
Write questions one at a time, paste a batch as text, or generate them from your class documents.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<ol className="space-y-3">
|
||||
{shown.map(({ question, index }) => (
|
||||
<li key={question.id} id={`q-${question.id}`} className={cx('card scroll-mt-24 p-4 sm:p-5', params.get('q') === question.id && 'ring-2 ring-marker')}>
|
||||
{editing === question.id ? (
|
||||
<>
|
||||
<QuestionEditor value={draft} onChange={setDraft} issues={editingIssues.filter((i) => draft.stem || i.field !== 'stem')} topics={topics} autoFocus onSubmit={() => save(false)} />
|
||||
{editorFooter(false)}
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<QuestionView q={question} index={index} stat={stats[question.id]} />
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col sm:flex-row">
|
||||
<IconButton label="Edit question" size="sm" onClick={() => beginEdit(question)}>
|
||||
<Pencil />
|
||||
</IconButton>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Question options" size="sm" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuItem icon={<Copy />} onSelect={() => duplicateQuestion(question, index)}>
|
||||
Duplicate
|
||||
</MenuItem>
|
||||
<MenuItem icon={<ArrowUp />} disabled={index === 0} onSelect={() => moveQuestion(index, -1)}>
|
||||
Move up
|
||||
</MenuItem>
|
||||
<MenuItem icon={<ArrowDown />} disabled={index === questions.length - 1} onSelect={() => moveQuestion(index, 1)}>
|
||||
Move down
|
||||
</MenuItem>
|
||||
{ai.data?.ready && (
|
||||
<MenuItem icon={<WandSparkles />} onSelect={() => improve([question.id])}>
|
||||
Improve with AI
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={() => removeQuestion(question)}>
|
||||
Delete
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{shown.length === 0 && questions.length > 0 && (
|
||||
<li className="card">
|
||||
<EmptyState icon={<Search />} title="No questions match" />
|
||||
</li>
|
||||
)}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<div ref={newRef} className="mt-3 scroll-mt-24">
|
||||
{editing === 'new' ? (
|
||||
<div className="card border-accent/40 p-4 ring-2 ring-accent/15 sm:p-5">
|
||||
<div className="eyebrow mb-4">New question</div>
|
||||
<QuestionEditor value={draft} onChange={setDraft} issues={[]} topics={topics} autoFocus onSubmit={() => save(true)} />
|
||||
{!canSave && draft.stem.trim() && <div className="mt-3 text-[13px] text-ink-3">{editingIssues.find((i) => i.level === 'error')?.message}</div>}
|
||||
{editorFooter(true)}
|
||||
</div>
|
||||
) : (
|
||||
questions.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button icon={<Plus />} onClick={beginNew}>
|
||||
Add question
|
||||
</Button>
|
||||
<Button variant="ghost" icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
|
||||
Paste several
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : history.length === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<History />} title="No attempts yet">
|
||||
Finished sessions are listed here with your score and time.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{full.length >= 2 && (
|
||||
<Callout className="mb-3" tone={last !== null && best !== null && last >= best ? 'good' : 'neutral'}>
|
||||
{last !== null && best !== null && last >= best ? `Your latest attempt (${last}%) is your best so far.` : `Latest ${last}%, best ${best}% across ${plural(full.length, 'full attempt')}.`}
|
||||
</Callout>
|
||||
)}
|
||||
<ul className="card divide-y divide-line">
|
||||
{history.map((h) => {
|
||||
const p = pct(h.score, h.maxScore);
|
||||
const tone = gradeTone(p);
|
||||
return (
|
||||
<li key={h.id}>
|
||||
<Link to={`/session/${h.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
|
||||
<span className={cx('num grid h-10 w-14 shrink-0 place-items-center rounded-[10px] text-[15px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium">
|
||||
{h.completedAt ? formatDateTime(h.completedAt) : ''}
|
||||
<span className="ml-2 font-normal text-ink-3">{timeAgo(h.completedAt)}</span>
|
||||
</span>
|
||||
<span className="text-xs text-ink-3">
|
||||
{h.mode === 'exam' ? 'Exam' : 'Practice'}
|
||||
{h.kind !== 'full' ? ' · missed only' : ''} · {h.maxScore ?? h.questionCount} scored{h.elapsedSec > 0 ? ` · ${formatMinutes(h.elapsedSec)}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight className="size-4 text-ink-3" />
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
|
||||
<StartSessionDialog open={startOpen} onClose={() => setStartOpen(false)} quizId={quiz.id} total={questions.length} title={quiz.title} />
|
||||
<BulkAddDialog
|
||||
open={bulkOpen}
|
||||
onClose={() => setBulkOpen(false)}
|
||||
kind="quiz"
|
||||
onAdd={async (items) => {
|
||||
try {
|
||||
await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: items });
|
||||
await refresh();
|
||||
toast.success(`Added ${plural(items.length, 'question')}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
throw e;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<RenameDialog target={rename ? { kind: 'quiz', id: quiz.id, title: quiz.title, description: quiz.description } : null} onClose={() => setRename(false)} />
|
||||
<MoveDialog target={move ? { kind: 'quiz', id: quiz.id, title: quiz.title, classId: quiz.classId, folderId: quiz.folderId } : null} onClose={() => setMove(false)} />
|
||||
<ShareDialog target={share ? { kind: 'quiz', id: quiz.id, title: quiz.title } : null} onClose={() => setShare(false)} />
|
||||
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={quiz.classId} folderId={quiz.folderId} preset={generate ?? undefined} />
|
||||
{starting && <span className="sr-only" role="status">Starting session</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
328
web/src/pages/ReviewPage.tsx
Normal file
328
web/src/pages/ReviewPage.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { CircleCheck, EyeOff, MoreHorizontal, Pencil, Undo2 } from 'lucide-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { CardEditor } from '@/features/editors';
|
||||
import { Explain } from '@/features/Explain';
|
||||
import { FlipCard, StudyTopBar } from '@/features/flashcards';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useAiStatus, useRefresh } from '@/lib/queries';
|
||||
import type { DueCounts, QueueCard } from '@/lib/types';
|
||||
import { cx, formatMinutes, plural, useDocumentTitle, useHotkeys } from '@/lib/util';
|
||||
import { Badge, Button, ClassDot, Dialog, ErrorState, IconButton, Kbd, Menu, MenuItem, PageLoading } from '@/ui';
|
||||
|
||||
interface QueueResponse {
|
||||
cards: QueueCard[];
|
||||
counts: DueCounts;
|
||||
}
|
||||
|
||||
const LEARN_AHEAD_MS = 20 * 60_000;
|
||||
const RATING_STYLE: Record<number, string> = {
|
||||
1: 'border-bad/40 text-bad hover:bg-bad-soft',
|
||||
2: 'border-warn/40 text-warn hover:bg-warn-soft',
|
||||
3: 'border-good/40 text-good hover:bg-good-soft',
|
||||
4: 'border-accent/40 text-accent hover:bg-accent-soft',
|
||||
};
|
||||
|
||||
/** Spaced-repetition review: due cards first, graded Again / Hard / Good / Easy and rescheduled by FSRS. */
|
||||
export default function ReviewPage() {
|
||||
const [params] = useSearchParams();
|
||||
const deckId = params.get('deckId') ?? '';
|
||||
const classId = params.get('classId') ?? '';
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const ai = useAiStatus();
|
||||
useDocumentTitle('Review');
|
||||
|
||||
const scope = deckId ? `deckId=${deckId}` : classId ? `classId=${classId}` : '';
|
||||
const query = useQuery({
|
||||
queryKey: ['review', scope],
|
||||
queryFn: () => api.get<QueueResponse>(`/api/review/queue?${scope}`),
|
||||
staleTime: Infinity,
|
||||
gcTime: 0,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const [queue, setQueue] = useState<QueueCard[] | null>(null);
|
||||
const [flipped, setFlipped] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [done, setDone] = useState({ reviewed: 0, again: 0 });
|
||||
const [last, setLast] = useState<{ cardId: string; snapshot: QueueCard[]; wasAgain: boolean } | null>(null);
|
||||
const [editing, setEditing] = useState<QueueCard | null>(null);
|
||||
const [draft, setDraft] = useState({ front: '', back: '', hint: '', tags: [] as string[] });
|
||||
const startedAt = useRef(Date.now());
|
||||
const scopeTitle = useRef('');
|
||||
|
||||
useEffect(() => {
|
||||
if (query.data && queue === null) {
|
||||
setQueue(query.data.cards);
|
||||
const first = query.data.cards[0];
|
||||
scopeTitle.current = deckId ? (first?.deckTitle ?? 'Deck') : classId ? (first?.className ?? 'Class') : 'All classes';
|
||||
}
|
||||
}, [query.data, queue, deckId, classId]);
|
||||
|
||||
const current = queue?.[0];
|
||||
useEffect(() => setFlipped(false), [current?.card.id]);
|
||||
|
||||
const rate = useCallback(
|
||||
async (rating: 1 | 2 | 3 | 4) => {
|
||||
if (!current || !queue || busy) return;
|
||||
setBusy(true);
|
||||
const snapshot = queue;
|
||||
try {
|
||||
const res = await api.post<{ result: QueueCard }>('/api/review/answer', { cardId: current.card.id, rating });
|
||||
const updated = res.result;
|
||||
const rest = queue.slice(1);
|
||||
const dueSoon = (updated.card.state === 1 || updated.card.state === 3) && (updated.card.due ?? 0) - Date.now() < LEARN_AHEAD_MS;
|
||||
if (dueSoon) {
|
||||
// Bring a learning card back after a few others, so it is not seen twice in a row.
|
||||
const at = Math.min(rest.length, rating === 1 ? 3 : 6);
|
||||
rest.splice(at, 0, updated);
|
||||
}
|
||||
setQueue(rest);
|
||||
setDone((d) => ({ reviewed: d.reviewed + 1, again: d.again + (rating === 1 ? 1 : 0) }));
|
||||
setLast({ cardId: current.card.id, snapshot, wasAgain: rating === 1 });
|
||||
if (rest.length === 0) {
|
||||
// The first load is capped; fetch anything that is still due.
|
||||
const more = await api.get<QueueResponse>(`/api/review/queue?${scope}`).catch(() => null);
|
||||
if (more && more.cards.length > 0) setQueue(more.cards);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[current, queue, busy, scope],
|
||||
);
|
||||
|
||||
const undo = useCallback(async () => {
|
||||
if (!last || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
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)));
|
||||
setDone((d) => ({ reviewed: Math.max(0, d.reviewed - 1), again: Math.max(0, d.again - (last.wasAgain ? 1 : 0)) }));
|
||||
setLast(null);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [last, busy]);
|
||||
|
||||
const suspend = async () => {
|
||||
if (!current || !queue) return;
|
||||
await api.patch(`/api/cards/${current.card.id}`, { suspended: true }).catch((e) => toast.error(errorMessage(e)));
|
||||
setQueue(queue.slice(1));
|
||||
toast('Card suspended. Unsuspend it from the deck page.');
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editing || !queue) return;
|
||||
try {
|
||||
await api.patch(`/api/cards/${editing.card.id}`, draft);
|
||||
setQueue(queue.map((c) => (c.card.id === editing.card.id ? { ...c, card: { ...c.card, ...draft } } : c)));
|
||||
setEditing(null);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
const exit = () => {
|
||||
void refresh();
|
||||
navigate(deckId ? `/decks/${deckId}` : classId ? `/classes/${classId}` : '/');
|
||||
};
|
||||
|
||||
useHotkeys({
|
||||
space: (e) => {
|
||||
e.preventDefault();
|
||||
if (current) setFlipped((f) => !f);
|
||||
},
|
||||
Enter: () => {
|
||||
if (!current) return;
|
||||
if (flipped) void rate(3);
|
||||
else setFlipped(true);
|
||||
},
|
||||
'1': () => flipped && void rate(1),
|
||||
'2': () => flipped && void rate(2),
|
||||
'3': () => flipped && void rate(3),
|
||||
'4': () => flipped && void rate(4),
|
||||
u: () => void undo(),
|
||||
'mod+z': (e) => {
|
||||
e.preventDefault();
|
||||
void undo();
|
||||
},
|
||||
e: () => {
|
||||
if (current) {
|
||||
setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags });
|
||||
setEditing(current);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (query.isError) return <ErrorState message={errorMessage(query.error)} onRetry={() => query.refetch()} className="pt-24" />;
|
||||
if (!queue) return <PageLoading />;
|
||||
|
||||
const remaining = queue.length;
|
||||
const counts = {
|
||||
learning: queue.filter((c) => c.card.state === 1 || c.card.state === 3).length,
|
||||
review: queue.filter((c) => c.card.state === 2).length,
|
||||
fresh: queue.filter((c) => c.card.state === 0).length,
|
||||
};
|
||||
const totalPlanned = done.reviewed + remaining;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh flex-col bg-paper">
|
||||
<StudyTopBar
|
||||
title="Review"
|
||||
subtitle={scopeTitle.current}
|
||||
onExit={exit}
|
||||
progress={totalPlanned ? done.reviewed / totalPlanned : 1}
|
||||
right={
|
||||
<>
|
||||
<div className="hidden items-center gap-1 sm:flex" aria-label="Cards remaining by type">
|
||||
<Badge tone="accent">{counts.fresh} new</Badge>
|
||||
<Badge tone="warn">{counts.learning} learning</Badge>
|
||||
<Badge tone="good">{counts.review} due</Badge>
|
||||
</div>
|
||||
<span className="num text-[13px] font-medium text-ink-2 sm:hidden">{remaining} left</span>
|
||||
<IconButton label="Undo last rating (U)" onClick={undo} disabled={!last || busy}>
|
||||
<Undo2 />
|
||||
</IconButton>
|
||||
{current && (
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Card options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<MenuItem
|
||||
icon={<Pencil />}
|
||||
hint="E"
|
||||
onSelect={() => {
|
||||
setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags });
|
||||
setEditing(current);
|
||||
}}
|
||||
>
|
||||
Edit card
|
||||
</MenuItem>
|
||||
<MenuItem icon={<EyeOff />} onSelect={suspend}>
|
||||
Suspend card
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<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">
|
||||
{!current ? (
|
||||
<div className="card m-auto w-full animate-in p-7 text-center sm:p-10">
|
||||
<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>
|
||||
<p className="mx-auto mt-2 max-w-sm text-[15px] text-ink-2">
|
||||
{done.reviewed > 0
|
||||
? `You reviewed ${plural(done.reviewed, 'card')} in ${formatMinutes((Date.now() - startedAt.current) / 1000)}${done.again > 0 ? `, with ${done.again} to see again soon` : ''}.`
|
||||
: 'Cards come back when you are about to forget them. Check in again later today or tomorrow.'}
|
||||
</p>
|
||||
<div className="mt-6 flex flex-wrap justify-center gap-2">
|
||||
<Button variant="primary" size="lg" onClick={exit}>
|
||||
Done
|
||||
</Button>
|
||||
{deckId && (
|
||||
<Button size="lg" onClick={() => navigate(`/decks/${deckId}/cram`)}>
|
||||
Browse the whole deck
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-3 flex items-center gap-2 text-xs text-ink-3">
|
||||
<ClassDot color={current.classColor} />
|
||||
<span className="truncate">
|
||||
{current.className} · {current.deckTitle}
|
||||
</span>
|
||||
<span className="ml-auto">{current.card.state === 0 ? <Badge tone="accent">New</Badge> : current.card.state === 2 ? <Badge tone="good">Review</Badge> : <Badge tone="warn">Learning</Badge>}</span>
|
||||
</div>
|
||||
<FlipCard
|
||||
cardKey={`${current.card.id}:${current.card.reps}`}
|
||||
front={current.card.front}
|
||||
back={current.card.back}
|
||||
hint={current.card.hint}
|
||||
flipped={flipped}
|
||||
onFlip={() => setFlipped((f) => !f)}
|
||||
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
|
||||
{current && (
|
||||
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
|
||||
<div className="mx-auto max-w-2xl px-3 py-3 sm:px-5">
|
||||
{flipped ? (
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{current.previews.map((p) => (
|
||||
<button
|
||||
key={p.rating}
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => rate(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="num text-[11px] opacity-80">{p.interval}</span>
|
||||
</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>
|
||||
</footer>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={editing !== null}
|
||||
onOpenChange={(o) => !o && setEditing(null)}
|
||||
title="Edit card"
|
||||
size="lg"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={() => setEditing(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" disabled={!draft.front.trim() || !draft.back.trim()} onClick={saveEdit}>
|
||||
Save
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<CardEditor value={draft} onChange={(c) => setDraft({ front: c.front, back: c.back, hint: c.hint ?? '', tags: c.tags })} onSubmit={saveEdit} showHint />
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
209
web/src/pages/SessionPage.tsx
Normal file
209
web/src/pages/SessionPage.tsx
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowLeft, RotateCcw, Trash2 } from 'lucide-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { Explain } from '@/features/Explain';
|
||||
import { QuizResults, QuizRunner } from '@/features/quiz';
|
||||
import { useStartSession } from '@/features/study';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
|
||||
import type { AnswerState, Attempt, SnapshotQuestion } from '@/lib/types';
|
||||
import { useDocumentTitle, useLatest } from '@/lib/util';
|
||||
import { Button, ErrorState, PageLoading, useConfirm } from '@/ui';
|
||||
|
||||
export default function SessionPage() {
|
||||
const { attemptId = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const { start, starting } = useStartSession();
|
||||
const query = useQuery({ queryKey: qk.attempt(attemptId), queryFn: () => api.get<{ attempt: Attempt }>(`/api/attempts/${attemptId}`).then((r) => r.attempt), staleTime: Infinity, refetchOnWindowFocus: false });
|
||||
const attempt = query.data;
|
||||
useDocumentTitle(attempt?.title);
|
||||
|
||||
// Local working copy: the UI never waits for the network.
|
||||
const [answers, setAnswers] = useState<Record<string, AnswerState>>({});
|
||||
const [flags, setFlags] = useState<string[]>([]);
|
||||
const [index, setIndex] = useState(0);
|
||||
const [finishing, setFinishing] = useState(false);
|
||||
const loaded = useRef('');
|
||||
const pending = useRef<{ answers: Record<string, { selected: string[]; checked: boolean }>; flags?: string[]; currentIndex?: number; elapsedSec?: number }>({ answers: {} });
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const inflight = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const warned = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (attempt && loaded.current !== attempt.id) {
|
||||
loaded.current = attempt.id;
|
||||
setAnswers(attempt.answers);
|
||||
setFlags(attempt.flags);
|
||||
setIndex(attempt.currentIndex);
|
||||
}
|
||||
}, [attempt]);
|
||||
|
||||
const flush = useCallback((): Promise<unknown> => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
const body = pending.current;
|
||||
if (Object.keys(body.answers).length === 0 && body.flags === undefined && body.currentIndex === undefined && body.elapsedSec === undefined) return inflight.current;
|
||||
pending.current = { answers: {} };
|
||||
const payload = { ...body, answers: Object.keys(body.answers).length ? body.answers : undefined };
|
||||
inflight.current = inflight.current
|
||||
.then(() => api.patch(`/api/attempts/${attemptId}`, payload))
|
||||
.then(() => {
|
||||
warned.current = false;
|
||||
})
|
||||
.catch((e) => {
|
||||
// Put the changes back so the next save retries them.
|
||||
pending.current = { ...payload, ...pending.current, answers: { ...(payload.answers ?? {}), ...pending.current.answers } };
|
||||
if (!warned.current) {
|
||||
warned.current = true;
|
||||
toast.error(`Progress is not being saved: ${errorMessage(e)}`);
|
||||
}
|
||||
});
|
||||
return inflight.current;
|
||||
}, [attemptId]);
|
||||
|
||||
const queue = useCallback(
|
||||
(patch: Partial<typeof pending.current>, immediate = false) => {
|
||||
pending.current = { ...pending.current, ...patch, answers: { ...pending.current.answers, ...(patch.answers ?? {}) } };
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
if (immediate) void flush();
|
||||
else timer.current = setTimeout(() => void flush(), 500);
|
||||
},
|
||||
[flush],
|
||||
);
|
||||
|
||||
const flushRef = useLatest(flush);
|
||||
useEffect(() => {
|
||||
const onHide = () => {
|
||||
if (document.visibilityState === 'hidden') void flushRef.current();
|
||||
};
|
||||
document.addEventListener('visibilitychange', onHide);
|
||||
window.addEventListener('pagehide', onHide);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', onHide);
|
||||
window.removeEventListener('pagehide', onHide);
|
||||
void flushRef.current();
|
||||
};
|
||||
}, [flushRef]);
|
||||
|
||||
if (query.isError) {
|
||||
return (
|
||||
<div className="pt-20">
|
||||
<ErrorState title="Session not found" message={errorMessage(query.error)} />
|
||||
<div className="flex justify-center">
|
||||
<Button onClick={() => navigate('/')}>Go to Today</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!attempt || loaded.current !== attempt.id) return <PageLoading />;
|
||||
|
||||
const back = attempt.quizId ? `/quizzes/${attempt.quizId}` : attempt.classId ? `/classes/${attempt.classId}` : '/';
|
||||
const exit = async () => {
|
||||
await flush();
|
||||
void refresh();
|
||||
navigate(back);
|
||||
};
|
||||
const renderExtra = ai.data?.ready
|
||||
? (q: SnapshotQuestion, selected: string[]) => <Explain body={{ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected, rationale: q.rationale }} />
|
||||
: undefined;
|
||||
|
||||
if (attempt.status === 'completed') {
|
||||
const missed = attempt.questions.filter((q) => attempt.results && !attempt.results[q.id]?.correct && (attempt.mode === 'exam' || attempt.results[q.id]?.answered)).length;
|
||||
return (
|
||||
<QuizResults
|
||||
title={attempt.title}
|
||||
mode={attempt.mode}
|
||||
questions={attempt.questions}
|
||||
answers={attempt.answers}
|
||||
flags={attempt.flags}
|
||||
elapsedSec={attempt.elapsedSec}
|
||||
sataScoring={attempt.settings.sataScoring}
|
||||
completedAt={attempt.completedAt}
|
||||
onExit={() => navigate(back)}
|
||||
renderExtra={renderExtra}
|
||||
actions={
|
||||
<>
|
||||
{missed > 0 && (
|
||||
<Button variant="primary" icon={<RotateCcw />} loading={starting} onClick={() => start({ source: { type: 'retake', attemptId: attempt.id } })}>
|
||||
Redo the {missed} missed
|
||||
</Button>
|
||||
)}
|
||||
{attempt.quizId && (
|
||||
<Button icon={<RotateCcw />} onClick={() => start({ mode: attempt.mode, source: { type: 'quiz', quizId: attempt.quizId! } })}>
|
||||
Take it again
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" icon={<ArrowLeft />} onClick={() => navigate(back)}>
|
||||
{attempt.quizId ? 'Back to quiz' : 'Done'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Trash2 />}
|
||||
className="sm:ml-auto"
|
||||
onClick={async () => {
|
||||
if (!(await confirm({ title: 'Delete this attempt?', message: 'It will be removed from your history and statistics.', confirmLabel: 'Delete', danger: true }))) return;
|
||||
await api.del(`/api/attempts/${attempt.id}`).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
navigate(back);
|
||||
}}
|
||||
>
|
||||
Delete attempt
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const finish = async (elapsedSec: number) => {
|
||||
setFinishing(true);
|
||||
try {
|
||||
await flush();
|
||||
const res = await api.post<{ attempt: Attempt }>(`/api/attempts/${attempt.id}/complete`, { elapsedSec });
|
||||
qc.setQueryData(qk.attempt(attempt.id), res.attempt);
|
||||
void refresh();
|
||||
window.scrollTo(0, 0);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setFinishing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<QuizRunner
|
||||
title={attempt.title}
|
||||
mode={attempt.mode}
|
||||
questions={attempt.questions}
|
||||
answers={answers}
|
||||
flags={flags}
|
||||
index={index}
|
||||
elapsedSec={attempt.elapsedSec}
|
||||
timeLimitSec={attempt.settings.timeLimitSec}
|
||||
sataScoring={attempt.settings.sataScoring}
|
||||
finishing={finishing}
|
||||
onAnswer={(qid, selected, checked) => {
|
||||
setAnswers((a) => ({ ...a, [qid]: { selected, checked } }));
|
||||
queue({ answers: { [qid]: { selected, checked } } }, checked);
|
||||
}}
|
||||
onFlags={(next) => {
|
||||
setFlags(next);
|
||||
queue({ flags: next });
|
||||
}}
|
||||
onIndex={(i) => {
|
||||
setIndex(i);
|
||||
queue({ currentIndex: i });
|
||||
}}
|
||||
onTick={(elapsedSec) => queue({ elapsedSec })}
|
||||
onFinish={finish}
|
||||
onExit={exit}
|
||||
renderExtra={renderExtra}
|
||||
/>
|
||||
);
|
||||
}
|
||||
626
web/src/pages/SettingsPage.tsx
Normal file
626
web/src/pages/SettingsPage.tsx
Normal file
|
|
@ -0,0 +1,626 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, Brain, Check, Copy, Database, Download, ExternalLink, FileUp, GraduationCap, HardDriveDownload, Layers, Link2, Lock, NotebookPen, RefreshCw, Share2, SlidersHorizontal, Sparkles, Stamp, Trash2, Upload } from 'lucide-react';
|
||||
import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { NavLink, useNavigate, useParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { shareUrl } from '@/features/dialogs';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk, useRefresh } from '@/lib/queries';
|
||||
import type { AppSettings, ShareListItem, Template } from '@/lib/types';
|
||||
import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
|
||||
|
||||
const AiSettings = lazy(() => import('@/features/AiSettings'));
|
||||
|
||||
const TABS = [
|
||||
{ id: 'study', label: 'Study', icon: <SlidersHorizontal /> },
|
||||
{ id: 'ai', label: 'AI', icon: <Sparkles /> },
|
||||
{ id: 'sharing', label: 'Sharing', icon: <Share2 /> },
|
||||
{ id: 'templates', label: 'Templates', icon: <Stamp /> },
|
||||
{ id: 'data', label: 'Data and backup', icon: <Database /> },
|
||||
{ id: 'security', label: 'Security', icon: <Lock /> },
|
||||
] as const;
|
||||
type TabId = (typeof TABS)[number]['id'];
|
||||
|
||||
interface SettingsResponse {
|
||||
settings: AppSettings;
|
||||
system: {
|
||||
version: string;
|
||||
node: string;
|
||||
dataDir: string;
|
||||
databaseBytes: number;
|
||||
uploadBytes: number;
|
||||
maxUploadMb: number;
|
||||
counts: Record<string, number>;
|
||||
timezones: string[];
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------ study ------------------------------ */
|
||||
|
||||
function StudySettings() {
|
||||
const refresh = useRefresh();
|
||||
const [theme, setTheme] = useTheme();
|
||||
const q = useQuery({ queryKey: qk.settings, queryFn: () => api.get<SettingsResponse>('/api/settings') });
|
||||
const [form, setForm] = useState<AppSettings | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
useEffect(() => {
|
||||
if (q.data && !form) setForm(q.data.settings);
|
||||
}, [q.data, form]);
|
||||
if (!q.data || !form) return <Skeleton className="h-80" />;
|
||||
|
||||
const save = async (patch: Partial<AppSettings>) => {
|
||||
const next = { ...form, ...patch };
|
||||
setForm(next);
|
||||
try {
|
||||
await api.put('/api/settings', patch);
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 1500);
|
||||
void refresh();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Section title="Appearance">
|
||||
<div className="card p-4">
|
||||
<Segmented
|
||||
label="Theme"
|
||||
value={theme}
|
||||
onChange={setTheme}
|
||||
options={[
|
||||
{ value: 'light', label: 'Light' },
|
||||
{ value: 'dark', label: 'Dark' },
|
||||
{ value: 'system', label: 'Match system' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="Flashcards" action={saved ? <span className="flex items-center gap-1 text-xs text-good"><Check className="size-3.5" /> Saved</span> : undefined}>
|
||||
<div className="card divide-y divide-line">
|
||||
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
|
||||
<div>
|
||||
<div className="text-sm font-medium">New cards per day</div>
|
||||
<div className="text-[13px] text-ink-3">How many never-seen cards are introduced each day, across all decks. Reviews of cards you already know are never limited.</div>
|
||||
</div>
|
||||
<Input type="number" min={0} max={500} value={form.newCardsPerDay} onChange={(e) => setForm({ ...form, newCardsPerDay: Number(e.target.value) })} onBlur={() => save({ newCardsPerDay: Math.max(0, Math.min(500, Math.round(form.newCardsPerDay) || 0)) })} aria-label="New cards per day" />
|
||||
</div>
|
||||
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
|
||||
<div>
|
||||
<div className="text-sm font-medium">Target retention: {Math.round(form.desiredRetention * 100)}%</div>
|
||||
<div className="text-[13px] text-ink-3">The chance of remembering a card when it comes back. Higher means more frequent reviews. 90% suits most people; try 93 to 95% before a big exam.</div>
|
||||
</div>
|
||||
<input type="range" min={0.8} max={0.97} step={0.01} value={form.desiredRetention} onChange={(e) => setForm({ ...form, desiredRetention: Number(e.target.value) })} onMouseUp={() => save({ desiredRetention: form.desiredRetention })} onTouchEnd={() => save({ desiredRetention: form.desiredRetention })} onKeyUp={() => save({ desiredRetention: form.desiredRetention })} className="w-full accent-[var(--accent)]" aria-label="Target retention" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-ink-3">Scheduling uses FSRS, the algorithm behind modern Anki. It adapts each card's interval to how well you remember it.</p>
|
||||
</Section>
|
||||
<Section title="Quizzes and goals">
|
||||
<div className="card divide-y divide-line">
|
||||
<div className="p-4">
|
||||
<Switch
|
||||
checked={form.sataScoring === 'partial'}
|
||||
onChange={(v) => save({ sataScoring: v ? 'partial' : 'strict' })}
|
||||
label="Partial credit for select-all-that-apply"
|
||||
description="On: NCLEX-style scoring, one point per correct choice and minus one per wrong choice, never below zero. Off: all or nothing. Applies to new sessions."
|
||||
/>
|
||||
</div>
|
||||
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
|
||||
<div>
|
||||
<div className="text-sm font-medium">Daily goal</div>
|
||||
<div className="text-[13px] text-ink-3">Cards reviewed plus questions answered that make a day count toward your streak.</div>
|
||||
</div>
|
||||
<Input type="number" min={1} max={1000} value={form.dailyGoal} onChange={(e) => setForm({ ...form, dailyGoal: Number(e.target.value) })} onBlur={() => save({ dailyGoal: Math.max(1, Math.min(1000, Math.round(form.dailyGoal) || 1)) })} aria-label="Daily goal" />
|
||||
</div>
|
||||
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_260px]">
|
||||
<div>
|
||||
<div className="text-sm font-medium">Timezone</div>
|
||||
<div className="text-[13px] text-ink-3">Decides when a study day starts and ends.</div>
|
||||
</div>
|
||||
<Select value={form.timezone} onChange={(e) => save({ timezone: e.target.value })} aria-label="Timezone">
|
||||
{!q.data.system.timezones.includes(form.timezone) && <option value={form.timezone}>{form.timezone}</option>}
|
||||
{q.data.system.timezones.map((tz) => (
|
||||
<option key={tz} value={tz}>
|
||||
{tz.replace(/_/g, ' ')}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ sharing ------------------------------ */
|
||||
|
||||
const SHARE_ICON: Record<ShareListItem['kind'], ReactNode> = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileUp />, folder: <Link2 />, class: <GraduationCap /> };
|
||||
|
||||
function SharingSettings() {
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const q = useQuery({ queryKey: qk.shares, queryFn: () => api.get<{ shares: ShareListItem[] }>('/api/shares').then((r) => r.shares) });
|
||||
const act = async (fn: () => Promise<unknown>, ok?: string) => {
|
||||
try {
|
||||
await fn();
|
||||
await refresh();
|
||||
if (ok) toast.success(ok);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
if (!q.data) return <Skeleton className="h-48" />;
|
||||
const live = q.data.filter((s) => s.enabled).length;
|
||||
return (
|
||||
<Section
|
||||
title={`Public links${q.data.length ? ` · ${live} active` : ''}`}
|
||||
action={
|
||||
live > 1 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={async () => {
|
||||
if (!(await confirm({ title: 'Turn off every link?', message: `${plural(live, 'link')} will stop working until you turn them back on.`, confirmLabel: 'Turn all off', danger: true }))) return;
|
||||
await act(() => Promise.all(q.data!.filter((s) => s.enabled).map((s) => api.patch(`/api/shares/${s.id}`, { enabled: false }))), 'All links are off');
|
||||
}}
|
||||
>
|
||||
Turn all off
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{q.data.length === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<Share2 />} title="Nothing is shared">
|
||||
Use "Share" on any quiz, deck, note, folder or class to create a public link. Friends can study without an account, and you can switch a link off at any time.
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="card divide-y divide-line">
|
||||
{q.data.map((s) => (
|
||||
<li key={s.id} className={cx('flex flex-wrap items-center gap-3 px-4 py-3', !s.enabled && 'opacity-60')}>
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-sunken text-ink-2 [&>svg]:size-4">{SHARE_ICON[s.kind]}</span>
|
||||
<div className="min-w-0 flex-1 basis-48">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-medium">{s.title}</span>
|
||||
<Badge>{s.kind}</Badge>
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-ink-3">
|
||||
{s.className && s.kind !== 'class' && (
|
||||
<span className="flex items-center gap-1">
|
||||
<ClassDot color={s.classColor} className="size-2" /> {s.className}
|
||||
</span>
|
||||
)}
|
||||
<span>{s.viewCount > 0 ? `Opened ${plural(s.viewCount, 'time')}, last ${timeAgo(s.lastViewedAt)}` : 'Never opened'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<IconButton label="Copy link" size="sm" disabled={!s.enabled} onClick={async () => (await copyText(shareUrl(s.token))) && toast.success('Link copied')}>
|
||||
<Copy />
|
||||
</IconButton>
|
||||
<a href={shareUrl(s.token)} target="_blank" rel="noreferrer" aria-label="Open link" className={cx('inline-grid size-8 place-items-center rounded-[9px] text-ink-2 hover:bg-ink/7', !s.enabled && 'pointer-events-none opacity-40')}>
|
||||
<ExternalLink className="size-[18px]" />
|
||||
</a>
|
||||
<IconButton label="Replace with a new link" size="sm" onClick={() => act(() => api.post(`/api/shares/${s.id}/rotate`), 'New link created. The old one no longer works.')}>
|
||||
<RefreshCw />
|
||||
</IconButton>
|
||||
<IconButton label="Delete link" size="sm" onClick={() => act(() => api.del(`/api/shares/${s.id}`), 'Link deleted')}>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
<input type="checkbox" role="switch" aria-label={`Link for ${s.title} is ${s.enabled ? 'on' : 'off'}`} checked={s.enabled} onChange={(e) => act(() => api.patch(`/api/shares/${s.id}`, { enabled: e.target.checked }))} className="ml-1.5 size-4 accent-[var(--accent)]" />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="mt-2.5 text-xs text-ink-3">Visitors can only read and study what a link points to. They cannot edit anything, see other content, or affect your progress. Uploaded documents are shared only when you share the document itself.</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ templates ------------------------------ */
|
||||
|
||||
function TemplateSettings() {
|
||||
const refresh = useRefresh();
|
||||
const q = useQuery({ queryKey: qk.templates, queryFn: () => api.get<{ templates: Template[] }>('/api/templates').then((r) => r.templates) });
|
||||
if (!q.data) return <Skeleton className="h-48" />;
|
||||
const groups: { kind: Template['kind']; title: string; blurb: string }[] = [
|
||||
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI.' },
|
||||
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.' },
|
||||
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.' },
|
||||
];
|
||||
return (
|
||||
<>
|
||||
{groups.map((g) => {
|
||||
const list = q.data!.filter((t) => t.kind === g.kind);
|
||||
return (
|
||||
<Section key={g.kind} title={g.title}>
|
||||
<ul className="card divide-y divide-line">
|
||||
{list.map((t) => (
|
||||
<li key={t.id} className="flex items-center gap-3 px-4 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-medium">{t.name}</span>
|
||||
{t.builtin ? <Badge>Built in</Badge> : <Badge tone="accent">Yours</Badge>}
|
||||
</div>
|
||||
{t.description && <div className="mt-0.5 line-clamp-2 text-[13px] text-ink-2">{t.description}</div>}
|
||||
{t.kind !== 'generation' && <div className="mt-0.5 text-xs text-ink-3">{t.kind === 'quiz' ? plural((t.payload.questions ?? []).length, 'question') : plural((t.payload.cards ?? []).length, 'card')}</div>}
|
||||
</div>
|
||||
{!t.builtin && (
|
||||
<IconButton
|
||||
label="Delete template"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
await api.del(`/api/templates/${t.id}`).catch((e) => toast.error(errorMessage(e)));
|
||||
await refresh();
|
||||
}}
|
||||
>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">None yet.</li>}
|
||||
</ul>
|
||||
<p className="mt-2 text-xs text-ink-3">{g.blurb}</p>
|
||||
</Section>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ data ------------------------------ */
|
||||
|
||||
interface V1Summary {
|
||||
classes: number;
|
||||
folders: number;
|
||||
decks: number;
|
||||
cards: number;
|
||||
quizzes: number;
|
||||
questions: number;
|
||||
attempts: number;
|
||||
scheduledCards: number;
|
||||
activityDays: number;
|
||||
skipped: string[];
|
||||
}
|
||||
|
||||
function DataSettings() {
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const settings = useQuery({ queryKey: qk.settings, queryFn: () => api.get<SettingsResponse>('/api/settings') });
|
||||
const backups = useQuery({ queryKey: ['backups'], queryFn: () => api.get<{ backups: { name: string; size: number; createdAt: number }[]; directory: string }>('/api/backups') });
|
||||
const bundleRef = useRef<HTMLInputElement>(null);
|
||||
const v1Ref = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState('');
|
||||
const [v1File, setV1File] = useState<File | null>(null);
|
||||
const [v1Preview, setV1Preview] = useState<V1Summary | null>(null);
|
||||
|
||||
const importBundle = async (file: File) => {
|
||||
setBusy('bundle');
|
||||
try {
|
||||
const json = JSON.parse(await file.text());
|
||||
const res = await api.post<{ summary: { classes: number; quizzes: number; decks: number; notes: number; skipped: string[] } }>('/api/import/bundle', json);
|
||||
await refresh();
|
||||
const s = res.summary;
|
||||
toast.success(`Restored ${plural(s.classes, 'class', 'classes')}, ${plural(s.quizzes, 'quiz', 'quizzes')}, ${plural(s.decks, 'deck')} and ${plural(s.notes, 'note')}${s.skipped.length ? `. ${s.skipped.length} problems skipped.` : ''}`);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof SyntaxError ? 'That file is not valid JSON.' : errorMessage(e));
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
const v1 = async (file: File, preview: boolean) => {
|
||||
setBusy(preview ? 'v1preview' : 'v1');
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await api.upload<{ summary: V1Summary }>(`/api/import/v1${preview ? '?preview=1' : ''}`, form);
|
||||
if (preview) {
|
||||
setV1File(file);
|
||||
setV1Preview(res.summary);
|
||||
} else {
|
||||
await refresh();
|
||||
setV1File(null);
|
||||
setV1Preview(null);
|
||||
toast.success(`Migrated ${plural(res.summary.classes, 'class', 'classes')} from V1`);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
const sys = settings.data?.system;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Section title="Export">
|
||||
<div className="card divide-y divide-line">
|
||||
<div className="flex flex-wrap items-center gap-3 p-4">
|
||||
<div className="min-w-0 flex-1 basis-64">
|
||||
<div className="text-sm font-medium">Everything as JSON</div>
|
||||
<div className="text-[13px] text-ink-3">All classes with their quizzes, flashcards and notes in one readable file. Portable: import it into another Study Desk. Does not include uploads or progress.</div>
|
||||
</div>
|
||||
<Button icon={<Download />} onClick={() => downloadFile('/api/export/all')}>
|
||||
Export JSON
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3 p-4">
|
||||
<div className="min-w-0 flex-1 basis-64">
|
||||
<div className="text-sm font-medium">Full backup</div>
|
||||
<div className="text-[13px] text-ink-3">A zip with the complete database (content, progress, history, settings) and every uploaded file. Use this to move servers or recover from a disaster.</div>
|
||||
</div>
|
||||
<Button variant="primary" icon={<HardDriveDownload />} onClick={() => downloadFile('/api/backup/download')}>
|
||||
Download backup
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Import">
|
||||
<div className="card divide-y divide-line">
|
||||
<div className="flex flex-wrap items-center gap-3 p-4">
|
||||
<div className="min-w-0 flex-1 basis-64">
|
||||
<div className="text-sm font-medium">Restore a JSON export</div>
|
||||
<div className="text-[13px] text-ink-3">Recreates the classes in an "Everything as JSON" file alongside what you already have. To import a single quiz or deck, use Add → Import inside a class.</div>
|
||||
</div>
|
||||
<input ref={bundleRef} type="file" accept=".json,application/json" hidden onChange={(e) => (e.target.files?.[0] && importBundle(e.target.files[0]), (e.target.value = ''))} />
|
||||
<Button icon={<Upload />} loading={busy === 'bundle'} onClick={() => bundleRef.current?.click()}>
|
||||
Choose file
|
||||
</Button>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="min-w-0 flex-1 basis-64">
|
||||
<div className="text-sm font-medium">Migrate from Study Desk V1</div>
|
||||
<div className="text-[13px] text-ink-3">
|
||||
Upload the V1 database file (<code className="num text-[12px]">study.db</code> from the old container's data folder). Classes, groups, decks, quizzes, attempt history, flashcard schedules and your activity are copied in. The V1 file is only read, never changed.
|
||||
</div>
|
||||
</div>
|
||||
<input ref={v1Ref} type="file" accept=".db,.sqlite,.sqlite3,application/octet-stream" hidden onChange={(e) => (e.target.files?.[0] && v1(e.target.files[0], true), (e.target.value = ''))} />
|
||||
<Button icon={<Upload />} loading={busy === 'v1preview'} onClick={() => v1Ref.current?.click()}>
|
||||
Choose study.db
|
||||
</Button>
|
||||
</div>
|
||||
{v1Preview && v1File && (
|
||||
<Callout tone="accent" className="mt-3" title={`Found in ${v1File.name}`}>
|
||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 text-[13px] sm:grid-cols-3">
|
||||
<span>{plural(v1Preview.classes, 'class', 'classes')}</span>
|
||||
<span>{plural(v1Preview.folders, 'group')} → folders</span>
|
||||
<span>{plural(v1Preview.quizzes, 'quiz', 'quizzes')} · {plural(v1Preview.questions, 'question')}</span>
|
||||
<span>{plural(v1Preview.decks, 'deck')} · {plural(v1Preview.cards, 'card')}</span>
|
||||
<span>{plural(v1Preview.attempts, 'quiz attempt')}</span>
|
||||
<span>{plural(v1Preview.scheduledCards, 'card schedule')}</span>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
loading={busy === 'v1'}
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: 'Migrate this V1 data?', message: 'Everything listed is added as new classes. A snapshot of the current database is taken first. Running the migration twice creates duplicates.', confirmLabel: 'Migrate' })) void v1(v1File, false);
|
||||
}}
|
||||
>
|
||||
Migrate now
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => (setV1Preview(null), setV1File(null))}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</Callout>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Database snapshots"
|
||||
action={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
icon={<FileUp />}
|
||||
loading={busy === 'snap'}
|
||||
onClick={async () => {
|
||||
setBusy('snap');
|
||||
await api.post('/api/backups').then(() => toast.success('Snapshot saved')).catch((e) => toast.error(errorMessage(e)));
|
||||
setBusy('');
|
||||
void backups.refetch();
|
||||
}}
|
||||
>
|
||||
Snapshot now
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="card">
|
||||
{!backups.data ? (
|
||||
<Skeleton className="m-4 h-16" />
|
||||
) : backups.data.backups.length === 0 ? (
|
||||
<p className="px-4 py-4 text-[13px] text-ink-2">No snapshots yet. One is written automatically each day once you have content, and before every upgrade that changes the database.</p>
|
||||
) : (
|
||||
<ul className="max-h-72 divide-y divide-line overflow-y-auto">
|
||||
{backups.data.backups.map((b) => (
|
||||
<li key={b.name} className="flex items-center gap-3 px-4 py-2.5">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="num truncate text-[13px] font-medium">{b.name}</div>
|
||||
<div className="text-xs text-ink-3">
|
||||
{formatDateTime(b.createdAt)} · {formatBytes(b.size)}
|
||||
</div>
|
||||
</div>
|
||||
<IconButton label={`Download ${b.name}`} size="sm" onClick={() => downloadFile(`/api/backups/${encodeURIComponent(b.name)}`)}>
|
||||
<Download />
|
||||
</IconButton>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-ink-3">
|
||||
Snapshots live in <code className="num">{backups.data?.directory ?? 'data/backups'}</code> on the server. Include your data folder in your Unraid backups to keep them off the machine too.
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
{sys && (
|
||||
<Section title="About this installation">
|
||||
<dl className="card grid grid-cols-2 gap-x-6 gap-y-3 p-4 text-[13px] sm:grid-cols-4">
|
||||
{[
|
||||
['Version', sys.version],
|
||||
['Database', formatBytes(sys.databaseBytes)],
|
||||
['Uploads', formatBytes(sys.uploadBytes)],
|
||||
['Upload limit', `${sys.maxUploadMb} MB per file`],
|
||||
['Classes', sys.counts.classes],
|
||||
['Questions', sys.counts.questions],
|
||||
['Flashcards', sys.counts.cards],
|
||||
['Documents', sys.counts.documents],
|
||||
].map(([k, v]) => (
|
||||
<div key={k as string}>
|
||||
<dt className="text-ink-3">{k}</dt>
|
||||
<dd className="num mt-0.5 font-medium">{typeof v === 'number' ? v.toLocaleString() : v}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ security ------------------------------ */
|
||||
|
||||
function SecuritySettings() {
|
||||
const [current, setCurrent] = useState('');
|
||||
const [next, setNext] = useState('');
|
||||
const [confirmPw, setConfirmPw] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const sessions = useQuery({ queryKey: ['sessions'], queryFn: () => api.get<{ sessions: { id: string; createdAt: number; lastSeenAt: number; userAgent: string; ip: string; current: boolean }[] }>('/api/auth/sessions').then((r) => r.sessions) });
|
||||
|
||||
const change = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (next.length < 8) return setError('Use at least 8 characters.');
|
||||
if (next !== confirmPw) return setError('The new passwords do not match.');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await api.post('/api/auth/password', { current, next });
|
||||
setCurrent('');
|
||||
setNext('');
|
||||
setConfirmPw('');
|
||||
toast.success('Password changed. Other devices were signed out.');
|
||||
void sessions.refetch();
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const device = (ua: string) => {
|
||||
const os = /iPhone|iPad/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'Unknown device';
|
||||
const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser';
|
||||
return `${browser} on ${os}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Section title="Change password">
|
||||
<form onSubmit={change} className="card max-w-md space-y-4 p-4">
|
||||
<Field label="Current password">
|
||||
<Input type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} required />
|
||||
</Field>
|
||||
<Field label="New password" hint="At least 8 characters.">
|
||||
<Input type="password" autoComplete="new-password" value={next} onChange={(e) => setNext(e.target.value)} required minLength={8} />
|
||||
</Field>
|
||||
<Field label="Confirm new password" error={error || undefined}>
|
||||
<Input type="password" autoComplete="new-password" value={confirmPw} onChange={(e) => setConfirmPw(e.target.value)} required />
|
||||
</Field>
|
||||
<Button type="submit" variant="primary" loading={busy}>
|
||||
Change password
|
||||
</Button>
|
||||
</form>
|
||||
<p className="mt-2 max-w-md text-xs text-ink-3">Forgot it? Set the RESET_ADMIN_PASSWORD environment variable on the container, restart once, then remove it.</p>
|
||||
</Section>
|
||||
<Section
|
||||
title="Signed-in devices"
|
||||
action={
|
||||
(sessions.data?.length ?? 0) > 1 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={async () => {
|
||||
await api.post('/api/auth/sessions/revoke-others').then(() => toast.success('Other devices signed out')).catch((e) => toast.error(errorMessage(e)));
|
||||
void sessions.refetch();
|
||||
}}
|
||||
>
|
||||
Sign out the others
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<ul className="card divide-y divide-line">
|
||||
{(sessions.data ?? []).map((s) => (
|
||||
<li key={s.id} className="flex items-center gap-3 px-4 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
{device(s.userAgent)}
|
||||
{s.current && <Badge tone="good">This device</Badge>}
|
||||
</div>
|
||||
<div className="text-xs text-ink-3">
|
||||
Active {timeAgo(s.lastSeenAt)} · signed in {timeAgo(s.createdAt)}
|
||||
{s.ip && s.ip !== 'unknown' ? ` · ${s.ip}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ page ------------------------------ */
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { tab } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const active = (TABS.find((t) => t.id === tab)?.id ?? 'study') as TabId;
|
||||
useDocumentTitle('Settings');
|
||||
useEffect(() => {
|
||||
if (tab && !TABS.some((t) => t.id === tab)) navigate('/settings', { replace: true });
|
||||
}, [tab, navigate]);
|
||||
|
||||
return (
|
||||
<div className="animate-in">
|
||||
<PageHeader title="Settings" />
|
||||
<div className="grid gap-x-10 gap-y-5 lg:grid-cols-[190px_1fr]">
|
||||
<nav aria-label="Settings sections" className="-mx-4 flex gap-1 overflow-x-auto px-4 pb-1 lg:mx-0 lg:flex-col lg:overflow-visible lg:px-0">
|
||||
{TABS.map((t) => (
|
||||
<NavLink
|
||||
key={t.id}
|
||||
to={t.id === 'study' ? '/settings' : `/settings/${t.id}`}
|
||||
end
|
||||
className={() => cx('flex h-9 shrink-0 items-center gap-2.5 rounded-[9px] px-3 text-sm font-medium whitespace-nowrap [&>svg]:size-4', active === t.id ? 'bg-ink text-paper lg:bg-ink/8 lg:text-ink' : 'text-ink-2 hover:bg-ink/5 hover:text-ink')}
|
||||
>
|
||||
{t.icon}
|
||||
{t.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<div className="min-w-0">
|
||||
{active === 'study' && <StudySettings />}
|
||||
{active === 'ai' && (
|
||||
<Suspense fallback={<PageLoading />}>
|
||||
<AiSettings />
|
||||
</Suspense>
|
||||
)}
|
||||
{active === 'sharing' && <SharingSettings />}
|
||||
{active === 'templates' && <TemplateSettings />}
|
||||
{active === 'data' && <DataSettings />}
|
||||
{active === 'security' && <SecuritySettings />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
402
web/src/pages/SharedPage.tsx
Normal file
402
web/src/pages/SharedPage.tsx
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
|
||||
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
|
||||
import { QuizResults, QuizRunner } from '@/features/quiz';
|
||||
import { api, ApiError } from '@/lib/api';
|
||||
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
|
||||
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useTheme } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, EmptyState, IconButton, PageLoading, Switch } from '@/ui';
|
||||
|
||||
/* ------------------------------ frame ------------------------------ */
|
||||
|
||||
function Frame({ children, back }: { children: ReactNode; back?: { to: string; label: string } }) {
|
||||
const [, setTheme] = useTheme();
|
||||
const dark = document.documentElement.dataset.theme === 'dark';
|
||||
return (
|
||||
<div className="min-h-dvh">
|
||||
<header className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-4 sm:px-5">
|
||||
{back ? (
|
||||
<Link to={back.to} className="-ml-2 flex h-9 items-center gap-1.5 rounded-lg px-2 text-sm font-medium text-ink-2 hover:bg-ink/6 hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> {back.label}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<img src="/icon.svg" alt="" className="size-7 rounded-lg" />
|
||||
<span className="display text-[18px]">Study Desk</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
<IconButton label={dark ? 'Switch to light theme' : 'Switch to dark theme'} onClick={() => setTheme(dark ? 'light' : 'dark')}>
|
||||
{dark ? <Sun /> : <Moon />}
|
||||
</IconButton>
|
||||
</header>
|
||||
<main className="mx-auto max-w-3xl animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8">{children}</main>
|
||||
<footer className="pb-8 text-center text-xs text-ink-3">Shared with Study Desk. Your progress is saved in this browser only.</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Unavailable() {
|
||||
return (
|
||||
<div className="grid min-h-dvh place-items-center px-6">
|
||||
<EmptyState icon={<Link2Off />} title="This link is no longer available">
|
||||
The owner may have turned sharing off or replaced the link. Ask them for a new one.
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ quiz ------------------------------ */
|
||||
|
||||
interface QuizState {
|
||||
mode: 'practice' | 'exam';
|
||||
order: string[];
|
||||
optionOrder: Record<string, string[]>;
|
||||
answers: Record<string, AnswerState>;
|
||||
flags: string[];
|
||||
index: number;
|
||||
elapsed: number;
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, only?: string[]): QuizState {
|
||||
const seed = (Math.random() * 2 ** 32) >>> 0;
|
||||
let ids = quiz.questions.map((q) => q.id).filter((id) => !only || only.includes(id));
|
||||
if (shuffleQ) ids = seededShuffle(ids, seed);
|
||||
const optionOrder: Record<string, string[]> = {};
|
||||
quiz.questions.forEach((q, i) => {
|
||||
const optionIds = q.options.map((o) => o.id);
|
||||
optionOrder[q.id] = shuffleO ? seededShuffle(optionIds, seed + i + 1) : optionIds;
|
||||
});
|
||||
return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false };
|
||||
}
|
||||
|
||||
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
|
||||
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 [running, setRunning] = useState(false);
|
||||
|
||||
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
|
||||
const questions = useMemo<SnapshotQuestion[]>(() => {
|
||||
if (!state) return [];
|
||||
const byId = new Map(quiz.questions.map((q) => [q.id, q]));
|
||||
return state.order
|
||||
.map((id) => byId.get(id))
|
||||
.filter((q): q is SnapshotQuestion => Boolean(q))
|
||||
.map((q) => {
|
||||
const order = state.optionOrder[q.id] ?? [];
|
||||
const sorted = [...q.options].sort((a, b) => (order.indexOf(a.id) + 1 || 99) - (order.indexOf(b.id) + 1 || 99));
|
||||
return { ...q, options: sorted };
|
||||
});
|
||||
}, [quiz, state]);
|
||||
|
||||
const begin = (only?: string[]) => {
|
||||
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, only));
|
||||
setRunning(true);
|
||||
window.scrollTo(0, 0);
|
||||
};
|
||||
|
||||
if (state && questions.length > 0 && state.done) {
|
||||
const missed = questions.filter((q) => !isFullyCorrect(scoreQuestion(q, state.answers[q.id]?.selected ?? [])) && (state.mode === 'exam' || (state.answers[q.id]?.selected.length ?? 0) > 0)).map((q) => q.id);
|
||||
return (
|
||||
<QuizResults
|
||||
title={quiz.title}
|
||||
mode={state.mode}
|
||||
questions={questions}
|
||||
answers={state.answers}
|
||||
flags={state.flags}
|
||||
elapsedSec={state.elapsed}
|
||||
sataScoring="partial"
|
||||
onExit={() => (setState(null), setRunning(false))}
|
||||
exitLabel="Back to start"
|
||||
footnote="This result is stored in your browser only. The person who shared the quiz cannot see it."
|
||||
actions={
|
||||
<>
|
||||
{missed.length > 0 && (
|
||||
<Button variant="primary" icon={<RotateCcw />} onClick={() => begin(missed)}>
|
||||
Redo the {missed.length} missed
|
||||
</Button>
|
||||
)}
|
||||
<Button icon={<RotateCcw />} onClick={() => begin()}>
|
||||
Take it again
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (state && questions.length > 0 && running) {
|
||||
return (
|
||||
<QuizRunner
|
||||
title={quiz.title}
|
||||
mode={state.mode}
|
||||
questions={questions}
|
||||
answers={state.answers}
|
||||
flags={state.flags}
|
||||
index={state.index}
|
||||
elapsedSec={state.elapsed}
|
||||
timeLimitSec={null}
|
||||
sataScoring="partial"
|
||||
exitLabel="Pause"
|
||||
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
|
||||
onFlags={(flags) => setState((s) => (s ? { ...s, flags } : s))}
|
||||
onIndex={(index) => setState((s) => (s ? { ...s, index } : s))}
|
||||
onTick={(elapsed) => setState((s) => (s ? { ...s, elapsed } : s))}
|
||||
onFinish={(elapsed) => {
|
||||
setState((s) => (s ? { ...s, elapsed, done: true } : s));
|
||||
window.scrollTo(0, 0);
|
||||
}}
|
||||
onExit={() => setRunning(false)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const inProgress = state && questions.length > 0 && !state.done;
|
||||
const answered = inProgress ? Object.values(state.answers).filter((a) => a.selected.length > 0).length : 0;
|
||||
return (
|
||||
<Frame back={back}>
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
||||
<BookOpen className="size-3.5" /> Shared quiz
|
||||
</div>
|
||||
<h1 className="display text-[32px] sm:text-[40px]">{quiz.title}</h1>
|
||||
{quiz.description && <p className="mt-2 text-[15px] text-ink-2">{quiz.description}</p>}
|
||||
<p className="mt-2 text-sm text-ink-3">{plural(quiz.questions.length, 'question')}</p>
|
||||
|
||||
{quiz.questions.length === 0 ? (
|
||||
<div className="card mt-6 p-6 text-sm text-ink-2">This quiz has no questions yet.</div>
|
||||
) : (
|
||||
<div className="card mt-6 p-5 sm:p-6">
|
||||
{inProgress && (
|
||||
<div className="mb-5 flex flex-wrap items-center gap-3 rounded-xl bg-accent-soft p-3.5">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-semibold">You have a session in progress</div>
|
||||
<div className="text-[13px] text-ink-2">
|
||||
{answered} of {questions.length} answered
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="primary" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
|
||||
Resume
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
|
||||
{(
|
||||
[
|
||||
{ v: 'practice', t: 'Practice', b: 'See the answer and rationale after each question.' },
|
||||
{ v: 'exam', t: 'Exam', b: 'Answers and score are shown at the end.' },
|
||||
] as const
|
||||
).map((m) => (
|
||||
<button key={m.v} type="button" role="radio" aria-checked={prefs.mode === m.v} onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))} className={cx('rounded-xl border p-3.5 text-left', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}>
|
||||
<div className="font-semibold">{m.t}</div>
|
||||
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.b}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<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.shuffleO} onChange={(v) => setPrefs((p) => ({ ...p, shuffleO: v }))} label="Shuffle answer choices" />
|
||||
</div>
|
||||
<Button variant={inProgress ? 'secondary' : 'primary'} size="lg" block className="mt-5" icon={<Play className="fill-current" />} onClick={() => begin()}>
|
||||
{inProgress ? 'Start over' : 'Start'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ deck ------------------------------ */
|
||||
|
||||
function SharedDeck({ deck, storageKey, back }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string } }) {
|
||||
const [saved, setSaved] = useLocalStorage<CramState | null>(storageKey, null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const state = useMemo(() => reconcileCramState(saved, deck.cards), [saved, deck.cards]);
|
||||
|
||||
if (running && state) {
|
||||
return <CramSession title={deck.title} subtitle="Shared flashcards" cards={deck.cards} state={state} onState={setSaved} onExit={() => setRunning(false)} exitLabel="Pause" />;
|
||||
}
|
||||
const seen = state ? Math.min(state.index, state.order.length) : 0;
|
||||
return (
|
||||
<Frame back={back}>
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
||||
<Layers className="size-3.5" /> Shared flashcards
|
||||
</div>
|
||||
<h1 className="display text-[32px] sm:text-[40px]">{deck.title}</h1>
|
||||
{deck.description && <p className="mt-2 text-[15px] text-ink-2">{deck.description}</p>}
|
||||
<p className="mt-2 text-sm text-ink-3">{plural(deck.cards.length, 'card')}</p>
|
||||
{deck.cards.length === 0 ? (
|
||||
<div className="card mt-6 p-6 text-sm text-ink-2">This deck has no cards yet.</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mt-6 flex flex-wrap gap-2">
|
||||
{state && seen > 0 && seen < state.order.length && (
|
||||
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
|
||||
Continue ({seen}/{state.order.length})
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant={state && seen > 0 && seen < state.order.length ? 'secondary' : 'primary'}
|
||||
size="lg"
|
||||
icon={<Play className="fill-current" />}
|
||||
onClick={() => {
|
||||
setSaved(freshCramState(deck.cards, false));
|
||||
setRunning(true);
|
||||
}}
|
||||
>
|
||||
Study in order
|
||||
</Button>
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={() => {
|
||||
setSaved(freshCramState(deck.cards, true));
|
||||
setRunning(true);
|
||||
}}
|
||||
>
|
||||
Shuffle
|
||||
</Button>
|
||||
</div>
|
||||
<h2 className="eyebrow mt-8 mb-2.5">All cards</h2>
|
||||
<ul className="card divide-y divide-line">
|
||||
{deck.cards.map((c) => (
|
||||
<li key={c.id} className="grid gap-x-5 gap-y-1 px-4 py-3 sm:grid-cols-2">
|
||||
<Markdown className="text-[14.5px] font-medium">{c.front}</Markdown>
|
||||
<Markdown className="text-[14.5px] text-ink-2">{c.back}</Markdown>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ note, document, collection ------------------------------ */
|
||||
|
||||
function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; label: string } }) {
|
||||
return (
|
||||
<Frame back={back}>
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
||||
<NotebookPen className="size-3.5" /> Shared note
|
||||
</div>
|
||||
<h1 className="display mb-6 text-[32px] sm:text-[40px]">{note.title}</h1>
|
||||
<article className="card px-5 py-6 sm:px-10 sm:py-9">
|
||||
<Markdown serif>{note.content || '*This note is empty.*'}</Markdown>
|
||||
</article>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
function SharedDocument({ doc, token }: { doc: PublicDocument; token: string }) {
|
||||
const url = `/api/public/${token}/file`;
|
||||
const inline = doc.docKind === 'pdf' || doc.docKind === 'image';
|
||||
return (
|
||||
<Frame>
|
||||
<div className="eyebrow mb-2 flex items-center gap-1.5">
|
||||
<FileText className="size-3.5" /> Shared document
|
||||
</div>
|
||||
<h1 className="display text-[30px] sm:text-[36px]">{doc.title}</h1>
|
||||
<p className="mt-2 text-sm text-ink-3">
|
||||
{doc.filename} · {formatBytes(doc.size)}
|
||||
{doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
|
||||
</p>
|
||||
<a href={url} download={inline ? undefined : doc.filename} target={inline ? '_blank' : undefined} rel="noreferrer" className="mt-5 inline-block">
|
||||
<Button variant="primary" size="lg" icon={<Download />}>
|
||||
{inline ? 'Open file' : 'Download'}
|
||||
</Button>
|
||||
</a>
|
||||
{doc.docKind === 'image' && <img src={url} alt={doc.title} className="card mt-6 max-w-full p-2" />}
|
||||
{doc.docKind === 'pdf' && <iframe src={url} title={doc.title} className="card mt-6 hidden h-[78vh] w-full sm:block" />}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||
|
||||
function SharedCollection({ data, token }: { data: PublicCollection; token: string }) {
|
||||
const groups = [{ id: null as string | null, name: '' }, ...data.folders].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0);
|
||||
return (
|
||||
<Frame>
|
||||
<div className={cx('border-l-[5px] border-tab pl-4', `tab-${data.color}`)}>
|
||||
<div className="eyebrow mb-1">{data.subtitle || 'Shared collection'}</div>
|
||||
<h1 className="display text-[32px] sm:text-[40px]">{data.title}</h1>
|
||||
{data.description && <p className="mt-2 text-[15px] text-ink-2">{data.description}</p>}
|
||||
</div>
|
||||
{groups.length === 0 ? (
|
||||
<div className="card mt-8 p-6 text-sm text-ink-2">Nothing has been added here yet.</div>
|
||||
) : (
|
||||
groups.map((g) => (
|
||||
<section key={g.id ?? 'none'} className="mt-7">
|
||||
{g.name && <h2 className="eyebrow mb-2.5">{g.name}</h2>}
|
||||
<ul className="card divide-y divide-line overflow-hidden">
|
||||
{g.items.map((i) => (
|
||||
<li key={`${i.kind}:${i.id}`}>
|
||||
<Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
|
||||
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[15px] font-medium">{i.title}</span>
|
||||
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : 'Note'}</span>
|
||||
</span>
|
||||
<ChevronRight className="size-4 text-ink-3" />
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ page ------------------------------ */
|
||||
|
||||
export default function SharedPage() {
|
||||
const { token = '', kind, itemId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const nested = Boolean(kind && itemId);
|
||||
const q = useQuery({
|
||||
queryKey: ['public', token, kind ?? '', itemId ?? ''],
|
||||
queryFn: ({ signal }) => api.pub<PublicPayload>(nested ? `/api/public/${token}/items/${kind}/${itemId}` : `/api/public/${token}`, signal),
|
||||
retry: (count, error) => !(error instanceof ApiError && error.status === 404) && count < 2,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const data = q.data;
|
||||
useDocumentTitle(data?.title);
|
||||
useEffect(() => {
|
||||
// A nested URL whose parent is not a collection makes no sense; send it to the root link.
|
||||
if (q.isError && nested && q.error instanceof ApiError && q.error.status === 404) navigate(`/s/${token}`, { replace: true });
|
||||
}, [q.isError, q.error, nested, navigate, token]);
|
||||
|
||||
if (q.isLoading) return <PageLoading />;
|
||||
if (q.isError || !data) {
|
||||
if (q.error instanceof ApiError && q.error.status !== 404) {
|
||||
return (
|
||||
<div className="grid min-h-dvh place-items-center px-6">
|
||||
<EmptyState title="Could not load this page" action={<Button onClick={() => q.refetch()}>Try again</Button>}>
|
||||
Check your connection and try again.
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <Unavailable />;
|
||||
}
|
||||
const back = nested ? { to: `/s/${token}`, label: 'All materials' } : undefined;
|
||||
const key = `sd.pub.${token.slice(0, 12)}.${data.kind}.${'id' in data ? data.id : ''}`;
|
||||
switch (data.kind) {
|
||||
case 'quiz':
|
||||
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} />;
|
||||
case 'deck':
|
||||
return <SharedDeck key={key} deck={data} storageKey={key} back={back} />;
|
||||
case 'note':
|
||||
return <SharedNote note={data} back={back} />;
|
||||
case 'document':
|
||||
return <SharedDocument doc={data} token={token} />;
|
||||
case 'collection':
|
||||
return <SharedCollection data={data} token={token} />;
|
||||
}
|
||||
}
|
||||
497
web/src/styles.css
Normal file
497
web/src/styles.css
Normal file
|
|
@ -0,0 +1,497 @@
|
|||
@import 'tailwindcss';
|
||||
@source inline("tab-{cobalt,teal,moss,amber,coral,rose,plum,slate}");
|
||||
@import '@fontsource-variable/instrument-sans';
|
||||
@import '@fontsource-variable/newsreader';
|
||||
@import '@fontsource-variable/newsreader/wght-italic.css';
|
||||
@import '@fontsource-variable/jetbrains-mono';
|
||||
|
||||
/*
|
||||
* Study Desk design language: "paper, ink and highlighter".
|
||||
* Warm paper surfaces, near-black ink, one cobalt accent for anything interactive,
|
||||
* and a highlighter yellow reserved for the few things that deserve emphasis.
|
||||
* Serif (Newsreader) carries content you read and think about; sans carries controls.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--paper: #fbfaf7;
|
||||
--surface: #ffffff;
|
||||
--sunken: #f3f1eb;
|
||||
--line: #e7e3d9;
|
||||
--line-strong: #d3cec1;
|
||||
--ink: #1b1a17;
|
||||
--ink-2: #57534a;
|
||||
--ink-3: #8b867a;
|
||||
--accent: #2747d8;
|
||||
--accent-hover: #1c37b5;
|
||||
--accent-ink: #ffffff;
|
||||
--accent-soft: #e9edfc;
|
||||
--marker: #ffe36e;
|
||||
--marker-ink: #1b1a17;
|
||||
--good: #1c7a4b;
|
||||
--good-soft: #e2f3e9;
|
||||
--bad: #c0362c;
|
||||
--bad-soft: #fbe8e5;
|
||||
--warn: #9a5b07;
|
||||
--warn-soft: #fbefd9;
|
||||
--shadow-1: 0 1px 2px rgb(27 26 23 / 0.05), 0 1px 1px rgb(27 26 23 / 0.03);
|
||||
--shadow-2: 0 4px 14px -4px rgb(27 26 23 / 0.1), 0 2px 4px -2px rgb(27 26 23 / 0.06);
|
||||
--shadow-3: 0 24px 60px -16px rgb(27 26 23 / 0.28), 0 8px 20px -8px rgb(27 26 23 / 0.14);
|
||||
|
||||
--c-cobalt: #2747d8;
|
||||
--c-teal: #0d7f86;
|
||||
--c-moss: #4f7a28;
|
||||
--c-amber: #b7790b;
|
||||
--c-coral: #d6552f;
|
||||
--c-rose: #c2386e;
|
||||
--c-plum: #7a45c2;
|
||||
--c-slate: #5d6673;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] {
|
||||
--paper: #151412;
|
||||
--surface: #1d1c19;
|
||||
--sunken: #100f0e;
|
||||
--line: #2f2d28;
|
||||
--line-strong: #46423a;
|
||||
--ink: #f3f0e9;
|
||||
--ink-2: #bcb7ab;
|
||||
--ink-3: #8a857a;
|
||||
--accent: #91a6ff;
|
||||
--accent-hover: #adbdff;
|
||||
--accent-ink: #0f1430;
|
||||
--accent-soft: #222949;
|
||||
--marker: #e9cb4b;
|
||||
--marker-ink: #1b1a17;
|
||||
--good: #5fc795;
|
||||
--good-soft: #15301f;
|
||||
--bad: #f1867d;
|
||||
--bad-soft: #3a1c19;
|
||||
--warn: #e5a94f;
|
||||
--warn-soft: #382911;
|
||||
--shadow-1: 0 1px 2px rgb(0 0 0 / 0.4);
|
||||
--shadow-2: 0 6px 18px -6px rgb(0 0 0 / 0.6);
|
||||
--shadow-3: 0 28px 70px -18px rgb(0 0 0 / 0.8);
|
||||
|
||||
--c-cobalt: #91a6ff;
|
||||
--c-teal: #4cc3c9;
|
||||
--c-moss: #9cc76d;
|
||||
--c-amber: #e8b44e;
|
||||
--c-coral: #f58a66;
|
||||
--c-rose: #f07ea9;
|
||||
--c-plum: #b893f2;
|
||||
--c-slate: #a0a9b6;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-paper: var(--paper);
|
||||
--color-surface: var(--surface);
|
||||
--color-sunken: var(--sunken);
|
||||
--color-line: var(--line);
|
||||
--color-line-strong: var(--line-strong);
|
||||
--color-ink: var(--ink);
|
||||
--color-ink-2: var(--ink-2);
|
||||
--color-ink-3: var(--ink-3);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-hover: var(--accent-hover);
|
||||
--color-accent-ink: var(--accent-ink);
|
||||
--color-accent-soft: var(--accent-soft);
|
||||
--color-marker: var(--marker);
|
||||
--color-marker-ink: var(--marker-ink);
|
||||
--color-good: var(--good);
|
||||
--color-good-soft: var(--good-soft);
|
||||
--color-bad: var(--bad);
|
||||
--color-bad-soft: var(--bad-soft);
|
||||
--color-warn: var(--warn);
|
||||
--color-warn-soft: var(--warn-soft);
|
||||
--color-tab: var(--tab, var(--c-cobalt));
|
||||
|
||||
--font-sans: 'Instrument Sans Variable', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
--font-serif: 'Newsreader Variable', 'Iowan Old Style', 'Palatino Linotype', Georgia, serif;
|
||||
--font-mono: 'JetBrains Mono Variable', ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
|
||||
|
||||
--shadow-1: var(--shadow-1);
|
||||
--shadow-2: var(--shadow-2);
|
||||
--shadow-3: var(--shadow-3);
|
||||
|
||||
--radius-card: 14px;
|
||||
--radius-control: 9px;
|
||||
|
||||
--animate-in: sd-in 180ms cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
--animate-pop: sd-pop 160ms cubic-bezier(0.2, 0.9, 0.3, 1.2);
|
||||
--animate-fade: sd-fade 140ms ease-out;
|
||||
--animate-sheet: sd-sheet 240ms cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
--animate-drawer: sd-drawer 240ms cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
--animate-shimmer: sd-shimmer 1.4s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes sd-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
}
|
||||
@keyframes sd-pop {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.96);
|
||||
}
|
||||
}
|
||||
@keyframes sd-fade {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@keyframes sd-sheet {
|
||||
from {
|
||||
transform: translateY(100%);
|
||||
}
|
||||
}
|
||||
@keyframes sd-drawer {
|
||||
from {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
@keyframes sd-shimmer {
|
||||
to {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
font-family: var(--font-sans);
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
-webkit-text-size-adjust: 100%;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-feature-settings: 'ss01', 'cv05';
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
body {
|
||||
min-height: 100dvh;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
#root {
|
||||
min-height: 100dvh;
|
||||
}
|
||||
::selection {
|
||||
background: var(--marker);
|
||||
color: var(--marker-ink);
|
||||
}
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
button,
|
||||
[role='button'],
|
||||
summary,
|
||||
label[for],
|
||||
select {
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
text-wrap: balance;
|
||||
}
|
||||
p {
|
||||
text-wrap: pretty;
|
||||
}
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
color: var(--ink-3);
|
||||
}
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--line-strong) transparent;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
::before,
|
||||
::after {
|
||||
animation-duration: 0.001ms !important;
|
||||
transition-duration: 0.001ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
/* Display type: serif, tight, slightly optical-size aware. */
|
||||
.display {
|
||||
font-family: var(--font-serif);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.015em;
|
||||
line-height: 1.12;
|
||||
font-variation-settings: 'opsz' 40;
|
||||
}
|
||||
.reading {
|
||||
font-family: var(--font-serif);
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.6;
|
||||
font-variation-settings: 'opsz' 16;
|
||||
}
|
||||
.eyebrow {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.09em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ink-3);
|
||||
}
|
||||
.num {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
/* Highlighter swipe behind a word or number. */
|
||||
.marker {
|
||||
background: linear-gradient(transparent 52%, var(--marker) 52%, var(--marker) 92%, transparent 92%);
|
||||
color: inherit;
|
||||
padding: 0 0.12em;
|
||||
margin: 0 -0.12em;
|
||||
border-radius: 2px;
|
||||
}
|
||||
:root[data-theme='dark'] .marker {
|
||||
background: linear-gradient(transparent 58%, color-mix(in srgb, var(--marker) 42%, transparent) 58%, color-mix(in srgb, var(--marker) 42%, transparent) 94%, transparent 94%);
|
||||
}
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius-card);
|
||||
box-shadow: var(--shadow-1);
|
||||
}
|
||||
.skeleton {
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(90deg, var(--sunken) 0%, color-mix(in srgb, var(--sunken) 55%, var(--surface)) 50%, var(--sunken) 100%);
|
||||
background-size: 200% 100%;
|
||||
animation: var(--animate-shimmer);
|
||||
}
|
||||
.kbd {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
padding: 3px 5px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-bottom-width: 2px;
|
||||
background: var(--surface);
|
||||
color: var(--ink-2);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Rendered Markdown (questions, cards, notes, assistant). */
|
||||
.md {
|
||||
line-height: 1.6;
|
||||
}
|
||||
.md > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.md > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.md p {
|
||||
margin: 0.65em 0;
|
||||
}
|
||||
.md h1,
|
||||
.md h2,
|
||||
.md h3,
|
||||
.md h4 {
|
||||
font-family: var(--font-serif);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
margin: 1.4em 0 0.5em;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
.md h1 {
|
||||
font-size: 1.6em;
|
||||
}
|
||||
.md h2 {
|
||||
font-size: 1.32em;
|
||||
padding-bottom: 0.25em;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.md h3 {
|
||||
font-size: 1.14em;
|
||||
}
|
||||
.md h4 {
|
||||
font-size: 1em;
|
||||
}
|
||||
.md ul,
|
||||
.md ol {
|
||||
margin: 0.6em 0;
|
||||
padding-left: 1.4em;
|
||||
}
|
||||
.md ul {
|
||||
list-style: disc;
|
||||
}
|
||||
.md ol {
|
||||
list-style: decimal;
|
||||
}
|
||||
.md li {
|
||||
margin: 0.22em 0;
|
||||
}
|
||||
.md li::marker {
|
||||
color: var(--ink-3);
|
||||
}
|
||||
.md strong {
|
||||
font-weight: 650;
|
||||
}
|
||||
.md a {
|
||||
color: var(--accent);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.md code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.88em;
|
||||
background: var(--sunken);
|
||||
padding: 0.12em 0.36em;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.md pre {
|
||||
background: var(--sunken);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0.8em 1em;
|
||||
border-radius: 10px;
|
||||
overflow-x: auto;
|
||||
margin: 0.8em 0;
|
||||
}
|
||||
.md pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
.md blockquote {
|
||||
border-left: 3px solid var(--line-strong);
|
||||
padding-left: 0.9em;
|
||||
color: var(--ink-2);
|
||||
margin: 0.8em 0;
|
||||
}
|
||||
.md hr {
|
||||
border: 0;
|
||||
border-top: 1px solid var(--line);
|
||||
margin: 1.4em 0;
|
||||
}
|
||||
.md img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 8px;
|
||||
margin: 0.5em 0;
|
||||
}
|
||||
.md .table-wrap {
|
||||
overflow-x: auto;
|
||||
margin: 0.8em 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
}
|
||||
.md table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.md th,
|
||||
.md td {
|
||||
text-align: left;
|
||||
padding: 0.5em 0.75em;
|
||||
border-bottom: 1px solid var(--line);
|
||||
vertical-align: top;
|
||||
}
|
||||
.md tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.md th {
|
||||
background: var(--sunken);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.md mark {
|
||||
background: var(--marker);
|
||||
color: var(--marker-ink);
|
||||
padding: 0 0.15em;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* Flashcard flip */
|
||||
.flip {
|
||||
perspective: 1600px;
|
||||
}
|
||||
.flip-inner {
|
||||
display: grid;
|
||||
transform-style: preserve-3d;
|
||||
transition: transform 420ms cubic-bezier(0.3, 0.8, 0.3, 1);
|
||||
}
|
||||
.flip-inner[data-flipped='true'] {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
.flip-face {
|
||||
grid-area: 1 / 1;
|
||||
backface-visibility: hidden;
|
||||
-webkit-backface-visibility: hidden;
|
||||
}
|
||||
.flip-back {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
/* Hidden face must not be reachable by keyboard or screen reader. */
|
||||
.flip-inner[data-flipped='true'] .flip-front,
|
||||
.flip-inner[data-flipped='false'] .flip-back {
|
||||
visibility: hidden;
|
||||
transition: visibility 0s linear 210ms;
|
||||
}
|
||||
.flip-inner[data-flipped='false'] .flip-front,
|
||||
.flip-inner[data-flipped='true'] .flip-back {
|
||||
visibility: visible;
|
||||
transition: visibility 0s linear 210ms;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.flip-inner {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@utility tab-cobalt {
|
||||
--tab: var(--c-cobalt);
|
||||
}
|
||||
@utility tab-teal {
|
||||
--tab: var(--c-teal);
|
||||
}
|
||||
@utility tab-moss {
|
||||
--tab: var(--c-moss);
|
||||
}
|
||||
@utility tab-amber {
|
||||
--tab: var(--c-amber);
|
||||
}
|
||||
@utility tab-coral {
|
||||
--tab: var(--c-coral);
|
||||
}
|
||||
@utility tab-rose {
|
||||
--tab: var(--c-rose);
|
||||
}
|
||||
@utility tab-plum {
|
||||
--tab: var(--c-plum);
|
||||
}
|
||||
@utility tab-slate {
|
||||
--tab: var(--c-slate);
|
||||
}
|
||||
@utility safe-bottom {
|
||||
padding-bottom: max(env(safe-area-inset-bottom), 0px);
|
||||
}
|
||||
|
||||
@media print {
|
||||
.no-print {
|
||||
display: none !important;
|
||||
}
|
||||
html,
|
||||
body {
|
||||
background: #fff;
|
||||
}
|
||||
}
|
||||
109
web/src/ui/Markdown.tsx
Normal file
109
web/src/ui/Markdown.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { memo, type ReactNode } from 'react';
|
||||
import ReactMarkdown, { type Components } from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { cx } from '@/lib/util';
|
||||
|
||||
export interface Citation {
|
||||
ref: string;
|
||||
label: string;
|
||||
documentId: string;
|
||||
chunkId: number;
|
||||
}
|
||||
|
||||
const BASE: Components = {
|
||||
a: ({ href, children }) => (
|
||||
<a href={href} target={href?.startsWith('/') ? undefined : '_blank'} rel="noreferrer noopener">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
table: ({ children }) => (
|
||||
<div className="table-wrap">
|
||||
<table>{children}</table>
|
||||
</div>
|
||||
),
|
||||
img: ({ src, alt }) => <img src={typeof src === 'string' ? src : undefined} alt={alt ?? ''} loading="lazy" />,
|
||||
};
|
||||
|
||||
/** Splits text on [c12] / [c12, c13] markers and swaps them for numbered citation chips. */
|
||||
function withCitations(children: ReactNode, cites: Map<string, { n: number; cite: Citation }>, onCite?: (c: Citation) => void): ReactNode {
|
||||
const walk = (node: ReactNode, key: string): ReactNode => {
|
||||
if (typeof node === 'string') {
|
||||
const parts = node.split(/(\[c\d+(?:\s*,\s*c\d+)*\])/g);
|
||||
if (parts.length === 1) return node;
|
||||
return parts.map((part, i) => {
|
||||
if (!/^\[c\d/.test(part)) return part;
|
||||
const refs = part.slice(1, -1).split(',').map((r) => r.trim());
|
||||
return (
|
||||
<span key={`${key}-${i}`} className="whitespace-nowrap">
|
||||
{refs.map((ref) => {
|
||||
const hit = cites.get(ref);
|
||||
if (!hit) return null;
|
||||
return (
|
||||
<button
|
||||
key={ref}
|
||||
type="button"
|
||||
title={hit.cite.label}
|
||||
onClick={() => onCite?.(hit.cite)}
|
||||
className="num mx-0.5 inline-grid h-[18px] min-w-[18px] -translate-y-px place-items-center rounded-[5px] bg-accent-soft px-1 align-middle text-[10.5px] font-semibold text-accent hover:bg-accent hover:text-accent-ink"
|
||||
>
|
||||
{hit.n}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
}
|
||||
if (Array.isArray(node)) return node.map((n, i) => walk(n, `${key}.${i}`));
|
||||
return node;
|
||||
};
|
||||
return walk(children, 'c');
|
||||
}
|
||||
|
||||
export const Markdown = memo(function Markdown({
|
||||
children,
|
||||
className,
|
||||
citations,
|
||||
onCite,
|
||||
serif,
|
||||
}: {
|
||||
children: string;
|
||||
className?: string;
|
||||
citations?: Citation[];
|
||||
onCite?: (c: Citation) => void;
|
||||
/** Use the reading serif (questions, cards, notes). */
|
||||
serif?: boolean;
|
||||
}) {
|
||||
let components = BASE;
|
||||
if (citations && citations.length > 0) {
|
||||
// Number citations in order of first appearance in the text.
|
||||
const order = new Map<string, { n: number; cite: Citation }>();
|
||||
const byRef = new Map(citations.map((c) => [c.ref, c]));
|
||||
for (const m of children.matchAll(/c\d+/g)) {
|
||||
const cite = byRef.get(m[0]);
|
||||
if (cite && !order.has(m[0])) order.set(m[0], { n: order.size + 1, cite });
|
||||
}
|
||||
const wrap =
|
||||
(Tag: 'p' | 'li' | 'td' | 'strong' | 'em' | 'h1' | 'h2' | 'h3' | 'h4' | 'blockquote') =>
|
||||
({ children: kids }: { children?: ReactNode }) => <Tag>{withCitations(kids, order, onCite)}</Tag>;
|
||||
components = { ...BASE, p: wrap('p'), li: wrap('li'), td: wrap('td'), strong: wrap('strong'), em: wrap('em'), h1: wrap('h1'), h2: wrap('h2'), h3: wrap('h3'), h4: wrap('h4'), blockquote: wrap('blockquote') };
|
||||
}
|
||||
return (
|
||||
<div className={cx('md', serif && 'reading', className)}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
|
||||
{children}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
/** Ordered list of the sources actually cited in a piece of text. */
|
||||
export function citedSources(text: string, citations: Citation[]): { n: number; cite: Citation }[] {
|
||||
const byRef = new Map(citations.map((c) => [c.ref, c]));
|
||||
const out = new Map<string, { n: number; cite: Citation }>();
|
||||
for (const m of text.matchAll(/c\d+/g)) {
|
||||
const cite = byRef.get(m[0]);
|
||||
if (cite && !out.has(m[0])) out.set(m[0], { n: out.size + 1, cite });
|
||||
}
|
||||
return [...out.values()];
|
||||
}
|
||||
491
web/src/ui/index.tsx
Normal file
491
web/src/ui/index.tsx
Normal file
|
|
@ -0,0 +1,491 @@
|
|||
import { CircleAlert, Inbox, LoaderCircle, X } from 'lucide-react';
|
||||
import { AlertDialog, Dialog as RDialog, DropdownMenu, Popover as RPopover, Switch as RSwitch, Tooltip as RTooltip } from 'radix-ui';
|
||||
import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useRef, useState, type ButtonHTMLAttributes, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes, type TextareaHTMLAttributes } from 'react';
|
||||
import { cx } from '@/lib/util';
|
||||
|
||||
/* ------------------------------ Button ------------------------------ */
|
||||
|
||||
type Variant = 'primary' | 'secondary' | 'ghost' | 'danger' | 'marker';
|
||||
type Size = 'sm' | 'md' | 'lg';
|
||||
|
||||
const VARIANT: Record<Variant, string> = {
|
||||
primary: 'bg-ink text-paper hover:bg-ink/88 active:bg-ink shadow-1',
|
||||
secondary: 'bg-surface text-ink border border-line-strong hover:bg-sunken active:bg-sunken shadow-1',
|
||||
ghost: 'text-ink-2 hover:bg-ink/6 hover:text-ink active:bg-ink/10',
|
||||
danger: 'bg-bad text-white hover:bg-bad/90 shadow-1 dark:text-[#1b1a17]',
|
||||
marker: 'bg-marker text-marker-ink hover:brightness-95 active:brightness-90 shadow-1',
|
||||
};
|
||||
const SIZE: Record<Size, string> = {
|
||||
sm: 'h-8 px-2.5 text-[13px] gap-1.5 rounded-[8px]',
|
||||
md: 'h-10 px-3.5 text-sm gap-2 rounded-[10px]',
|
||||
lg: 'h-12 px-5 text-[15px] gap-2 rounded-[12px]',
|
||||
};
|
||||
|
||||
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: Variant;
|
||||
size?: Size;
|
||||
loading?: boolean;
|
||||
icon?: ReactNode;
|
||||
block?: boolean;
|
||||
}
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
|
||||
{ variant = 'secondary', size = 'md', loading, icon, block, className, children, disabled, type = 'button', ...rest },
|
||||
ref,
|
||||
) {
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
type={type}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading || undefined}
|
||||
className={cx(
|
||||
'inline-flex shrink-0 select-none items-center justify-center font-medium whitespace-nowrap transition-[background,color,filter,transform] duration-100 active:scale-[0.985] disabled:pointer-events-none disabled:opacity-50',
|
||||
VARIANT[variant],
|
||||
SIZE[size],
|
||||
block && 'w-full',
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
>
|
||||
{loading ? <LoaderCircle className="size-4 animate-spin" aria-hidden /> : icon ? <span className="grid shrink-0 place-items-center [&>svg]:size-4" aria-hidden>{icon}</span> : null}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
|
||||
export const IconButton = forwardRef<HTMLButtonElement, ButtonHTMLAttributes<HTMLButtonElement> & { label: string; size?: 'sm' | 'md'; active?: boolean; tooltip?: boolean }>(function IconButton(
|
||||
{ label, size = 'md', active, tooltip = true, className, children, type = 'button', ...rest },
|
||||
ref,
|
||||
) {
|
||||
const button = (
|
||||
<button
|
||||
ref={ref}
|
||||
type={type}
|
||||
aria-label={label}
|
||||
className={cx(
|
||||
'inline-grid shrink-0 place-items-center rounded-[9px] text-ink-2 transition-colors hover:bg-ink/7 hover:text-ink disabled:pointer-events-none disabled:opacity-40 [&>svg]:size-[18px]',
|
||||
size === 'sm' ? 'size-8' : 'size-10',
|
||||
active && 'bg-ink/8 text-ink',
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
return tooltip ? <Tooltip label={label}>{button}</Tooltip> : button;
|
||||
});
|
||||
|
||||
/* ------------------------------ Tooltip ------------------------------ */
|
||||
|
||||
export function Tooltip({ label, children, side = 'bottom' }: { label: ReactNode; children: ReactNode; side?: 'top' | 'bottom' | 'left' | 'right' }) {
|
||||
return (
|
||||
<RTooltip.Root>
|
||||
<RTooltip.Trigger asChild>{children}</RTooltip.Trigger>
|
||||
<RTooltip.Portal>
|
||||
<RTooltip.Content side={side} sideOffset={6} className="z-[80] max-w-xs animate-fade rounded-md bg-ink px-2 py-1 text-xs font-medium text-paper shadow-2">
|
||||
{label}
|
||||
</RTooltip.Content>
|
||||
</RTooltip.Portal>
|
||||
</RTooltip.Root>
|
||||
);
|
||||
}
|
||||
export const TooltipProvider = RTooltip.Provider;
|
||||
|
||||
/* ------------------------------ Form controls ------------------------------ */
|
||||
|
||||
const CONTROL =
|
||||
'w-full rounded-[10px] border border-line-strong bg-surface px-3 text-sm text-ink shadow-1 outline-none transition-colors placeholder:text-ink-3 hover:border-ink-3 focus:border-accent focus:ring-2 focus:ring-accent/20 disabled:opacity-60 aria-[invalid=true]:border-bad aria-[invalid=true]:ring-bad/15';
|
||||
|
||||
export const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(function Input({ className, ...rest }, ref) {
|
||||
return <input ref={ref} className={cx(CONTROL, 'h-10', className)} {...rest} />;
|
||||
});
|
||||
|
||||
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement> & { autoGrow?: boolean; maxRows?: number }>(function Textarea(
|
||||
{ className, autoGrow, maxRows = 16, onChange, value, rows = 3, ...rest },
|
||||
ref,
|
||||
) {
|
||||
const inner = useRef<HTMLTextAreaElement | null>(null);
|
||||
const resize = useCallback(() => {
|
||||
const el = inner.current;
|
||||
if (!el || !autoGrow) return;
|
||||
el.style.height = 'auto';
|
||||
const line = parseFloat(getComputedStyle(el).lineHeight) || 22;
|
||||
el.style.height = `${Math.min(el.scrollHeight + 2, line * maxRows + 20)}px`;
|
||||
}, [autoGrow, maxRows]);
|
||||
useEffect(resize, [resize, value]);
|
||||
return (
|
||||
<textarea
|
||||
ref={(el) => {
|
||||
inner.current = el;
|
||||
if (typeof ref === 'function') ref(el);
|
||||
else if (ref) ref.current = el;
|
||||
}}
|
||||
rows={rows}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
onChange?.(e);
|
||||
resize();
|
||||
}}
|
||||
className={cx(CONTROL, 'resize-y py-2 leading-relaxed', autoGrow && 'resize-none overflow-y-auto', className)}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
export const Select = forwardRef<HTMLSelectElement, SelectHTMLAttributes<HTMLSelectElement>>(function Select({ className, children, ...rest }, ref) {
|
||||
return (
|
||||
<select
|
||||
ref={ref}
|
||||
className={cx(
|
||||
CONTROL,
|
||||
'h-10 appearance-none bg-[length:16px] bg-[right_10px_center] bg-no-repeat pr-9',
|
||||
"bg-[url('data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22 fill=%22none%22 stroke=%22%238b867a%22 stroke-width=%222.2%22 stroke-linecap=%22round%22 stroke-linejoin=%22round%22><path d=%22m6 9 6 6 6-6%22/></svg>')]",
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
);
|
||||
});
|
||||
|
||||
export function Field({ label, hint, error, children, className, optional }: { label: ReactNode; hint?: ReactNode; error?: ReactNode; children: ReactNode; className?: string; optional?: boolean }) {
|
||||
return (
|
||||
<label className={cx('block', className)}>
|
||||
<span className="mb-1.5 flex items-baseline justify-between gap-2 text-[13px] font-medium text-ink">
|
||||
<span>{label}</span>
|
||||
{optional && <span className="text-xs font-normal text-ink-3">Optional</span>}
|
||||
</span>
|
||||
{children}
|
||||
{error ? <span className="mt-1.5 flex items-start gap-1 text-[13px] text-bad"><CircleAlert className="mt-0.5 size-3.5 shrink-0" aria-hidden />{error}</span> : hint ? <span className="mt-1.5 block text-[13px] text-ink-3">{hint}</span> : null}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function Switch({ checked, onChange, label, description, disabled }: { checked: boolean; onChange: (v: boolean) => void; label: ReactNode; description?: ReactNode; disabled?: boolean }) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<label htmlFor={id} className="min-w-0">
|
||||
<span className="block text-sm font-medium text-ink">{label}</span>
|
||||
{description && <span className="mt-0.5 block text-[13px] text-ink-3">{description}</span>}
|
||||
</label>
|
||||
<RSwitch.Root
|
||||
id={id}
|
||||
checked={checked}
|
||||
onCheckedChange={onChange}
|
||||
disabled={disabled}
|
||||
className="relative mt-0.5 h-6 w-10 shrink-0 rounded-full bg-line-strong transition-colors data-[state=checked]:bg-accent disabled:opacity-50"
|
||||
>
|
||||
<RSwitch.Thumb className="block size-5 translate-x-0.5 rounded-full bg-white shadow-1 transition-transform data-[state=checked]:translate-x-[18px]" />
|
||||
</RSwitch.Root>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Segmented control for 2-4 mutually exclusive choices. */
|
||||
export function Segmented<T extends string>({ value, onChange, options, size = 'md', className, label }: { value: T; onChange: (v: T) => void; options: { value: T; label: ReactNode; icon?: ReactNode }[]; size?: 'sm' | 'md'; className?: string; label?: string }) {
|
||||
return (
|
||||
<div role="radiogroup" aria-label={label} className={cx('inline-flex rounded-[11px] bg-sunken p-1', className)}>
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={value === o.value}
|
||||
onClick={() => onChange(o.value)}
|
||||
className={cx(
|
||||
'inline-flex flex-1 items-center justify-center gap-1.5 rounded-[8px] font-medium whitespace-nowrap text-ink-2 transition-colors [&>svg]:size-4',
|
||||
size === 'sm' ? 'h-7 px-2.5 text-[13px]' : 'h-8 px-3 text-sm',
|
||||
value === o.value ? 'bg-surface text-ink shadow-1' : 'hover:text-ink',
|
||||
)}
|
||||
>
|
||||
{o.icon}
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ Feedback ------------------------------ */
|
||||
|
||||
export function Spinner({ className, label = 'Loading' }: { className?: string; label?: string }) {
|
||||
return <LoaderCircle role="status" aria-label={label} className={cx('size-5 animate-spin text-ink-3', className)} />;
|
||||
}
|
||||
|
||||
export function Badge({ children, tone = 'neutral', className }: { children: ReactNode; tone?: 'neutral' | 'accent' | 'good' | 'bad' | 'warn' | 'marker'; className?: string }) {
|
||||
const tones = {
|
||||
neutral: 'bg-ink/6 text-ink-2',
|
||||
accent: 'bg-accent-soft text-accent',
|
||||
good: 'bg-good-soft text-good',
|
||||
bad: 'bg-bad-soft text-bad',
|
||||
warn: 'bg-warn-soft text-warn',
|
||||
marker: 'bg-marker text-marker-ink',
|
||||
};
|
||||
return <span className={cx('inline-flex h-[22px] items-center gap-1 rounded-full px-2 text-xs font-medium whitespace-nowrap [&>svg]:size-3', tones[tone], className)}>{children}</span>;
|
||||
}
|
||||
|
||||
export function ProgressBar({ value, tone = 'accent', className, label }: { value: number; tone?: 'accent' | 'good' | 'ink' | 'tab'; className?: string; label?: string }) {
|
||||
const v = Math.max(0, Math.min(1, value));
|
||||
const tones = { accent: 'bg-accent', good: 'bg-good', ink: 'bg-ink', tab: 'bg-tab' };
|
||||
return (
|
||||
<div role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(v * 100)} className={cx('h-1.5 overflow-hidden rounded-full bg-ink/8', className)}>
|
||||
<div className={cx('h-full rounded-full transition-[width] duration-300', tones[tone])} style={{ width: `${v * 100}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Skeleton({ className }: { className?: string }) {
|
||||
return <div aria-hidden className={cx('skeleton', className)} />;
|
||||
}
|
||||
|
||||
export function PageLoading({ label = 'Loading' }: { label?: string }) {
|
||||
return (
|
||||
<div className="grid min-h-[40vh] place-items-center" role="status" aria-label={label}>
|
||||
<Spinner className="size-6" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({ icon, title, children, action, className }: { icon?: ReactNode; title: string; children?: ReactNode; action?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cx('mx-auto flex max-w-md flex-col items-center px-6 py-12 text-center', className)}>
|
||||
<div className="mb-4 grid size-12 place-items-center rounded-2xl bg-sunken text-ink-3 [&>svg]:size-6">{icon ?? <Inbox />}</div>
|
||||
<h3 className="display text-xl text-ink">{title}</h3>
|
||||
{children && <p className="mt-2 text-sm leading-relaxed text-ink-2">{children}</p>}
|
||||
{action && <div className="mt-5 flex flex-wrap justify-center gap-2">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorState({ title = 'Something went wrong', message, onRetry, className }: { title?: string; message?: string; onRetry?: () => void; className?: string }) {
|
||||
return (
|
||||
<div role="alert" className={cx('mx-auto flex max-w-md flex-col items-center px-6 py-12 text-center', className)}>
|
||||
<div className="mb-4 grid size-12 place-items-center rounded-2xl bg-bad-soft text-bad">
|
||||
<CircleAlert className="size-6" />
|
||||
</div>
|
||||
<h3 className="display text-xl">{title}</h3>
|
||||
{message && <p className="mt-2 text-sm text-ink-2">{message}</p>}
|
||||
{onRetry && (
|
||||
<Button className="mt-5" onClick={onRetry}>
|
||||
Try again
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Callout({ tone = 'neutral', icon, title, children, action, className }: { tone?: 'neutral' | 'accent' | 'good' | 'bad' | 'warn'; icon?: ReactNode; title?: ReactNode; children?: ReactNode; action?: ReactNode; className?: string }) {
|
||||
const tones = {
|
||||
neutral: 'bg-sunken border-line text-ink-2',
|
||||
accent: 'bg-accent-soft border-accent/20 text-ink',
|
||||
good: 'bg-good-soft border-good/20 text-ink',
|
||||
bad: 'bg-bad-soft border-bad/25 text-ink',
|
||||
warn: 'bg-warn-soft border-warn/25 text-ink',
|
||||
};
|
||||
const iconTone = { neutral: 'text-ink-3', accent: 'text-accent', good: 'text-good', bad: 'text-bad', warn: 'text-warn' };
|
||||
return (
|
||||
<div className={cx('flex items-start gap-3 rounded-xl border px-3.5 py-3 text-sm', tones[tone], className)}>
|
||||
{icon && <span className={cx('mt-0.5 shrink-0 [&>svg]:size-[18px]', iconTone[tone])}>{icon}</span>}
|
||||
<div className="min-w-0 flex-1">
|
||||
{title && <div className="font-medium text-ink">{title}</div>}
|
||||
{children && <div className={cx('leading-relaxed', title && 'mt-0.5 text-ink-2')}>{children}</div>}
|
||||
</div>
|
||||
{action && <div className="shrink-0">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Kbd({ children }: { children: ReactNode }) {
|
||||
return <kbd className="kbd">{children}</kbd>;
|
||||
}
|
||||
|
||||
/* ------------------------------ Dialog ------------------------------ */
|
||||
|
||||
export function Dialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
footer,
|
||||
size = 'md',
|
||||
bare,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl';
|
||||
/** No padding around the body (for lists and custom layouts). */
|
||||
bare?: boolean;
|
||||
}) {
|
||||
const widths = { sm: 'sm:max-w-sm', md: 'sm:max-w-lg', lg: 'sm:max-w-2xl', xl: 'sm:max-w-4xl' };
|
||||
return (
|
||||
<RDialog.Root open={open} onOpenChange={onOpenChange}>
|
||||
<RDialog.Portal>
|
||||
<RDialog.Overlay className="fixed inset-0 z-50 animate-fade bg-[#12110f]/45 backdrop-blur-[2px]" />
|
||||
<RDialog.Content
|
||||
aria-describedby={description ? undefined : undefined}
|
||||
className={cx(
|
||||
'fixed z-50 flex max-h-[92dvh] w-full flex-col bg-surface shadow-3 outline-none',
|
||||
'inset-x-0 bottom-0 animate-sheet rounded-t-[20px] border-t border-line',
|
||||
'sm:inset-x-auto sm:bottom-auto sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:animate-pop sm:rounded-[18px] sm:border',
|
||||
widths[size],
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-3 px-5 pt-5 pb-3 sm:px-6">
|
||||
<div className="min-w-0 flex-1">
|
||||
<RDialog.Title className="display text-[22px] text-ink">{title}</RDialog.Title>
|
||||
{description ? <RDialog.Description className="mt-1 text-sm text-ink-2">{description}</RDialog.Description> : <RDialog.Description className="sr-only">{typeof title === 'string' ? title : 'Dialog'}</RDialog.Description>}
|
||||
</div>
|
||||
<RDialog.Close asChild>
|
||||
<IconButton label="Close" size="sm" tooltip={false} className="-mt-1 -mr-2">
|
||||
<X />
|
||||
</IconButton>
|
||||
</RDialog.Close>
|
||||
</div>
|
||||
<div className={cx('min-h-0 flex-1 overflow-y-auto', !bare && 'px-5 pb-5 sm:px-6')}>{children}</div>
|
||||
{footer && <div className="safe-bottom flex flex-wrap items-center justify-end gap-2 border-t border-line bg-paper/60 px-5 py-3 sm:rounded-b-[18px] sm:px-6">{footer}</div>}
|
||||
</RDialog.Content>
|
||||
</RDialog.Portal>
|
||||
</RDialog.Root>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ Confirm ------------------------------ */
|
||||
|
||||
interface ConfirmOptions {
|
||||
title: string;
|
||||
message?: ReactNode;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
danger?: boolean;
|
||||
}
|
||||
const ConfirmContext = createContext<(opts: ConfirmOptions) => Promise<boolean>>(() => Promise.resolve(false));
|
||||
|
||||
export function ConfirmProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<(ConfirmOptions & { resolve: (v: boolean) => void }) | null>(null);
|
||||
const confirm = useCallback((opts: ConfirmOptions) => new Promise<boolean>((resolve) => setState({ ...opts, resolve })), []);
|
||||
const close = (v: boolean) => {
|
||||
state?.resolve(v);
|
||||
setState(null);
|
||||
};
|
||||
return (
|
||||
<ConfirmContext.Provider value={confirm}>
|
||||
{children}
|
||||
<AlertDialog.Root open={state !== null} onOpenChange={(o) => !o && close(false)}>
|
||||
<AlertDialog.Portal>
|
||||
<AlertDialog.Overlay className="fixed inset-0 z-[70] animate-fade bg-[#12110f]/45 backdrop-blur-[2px]" />
|
||||
<AlertDialog.Content className="fixed top-1/2 left-1/2 z-[70] w-[calc(100vw-2rem)] max-w-sm -translate-x-1/2 -translate-y-1/2 animate-pop rounded-[18px] border border-line bg-surface p-5 shadow-3 outline-none">
|
||||
<AlertDialog.Title className="display text-xl">{state?.title}</AlertDialog.Title>
|
||||
<AlertDialog.Description asChild>
|
||||
<div className="mt-2 text-sm leading-relaxed text-ink-2">{state?.message ?? 'This cannot be undone.'}</div>
|
||||
</AlertDialog.Description>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<AlertDialog.Cancel asChild>
|
||||
<Button variant="ghost">{state?.cancelLabel ?? 'Cancel'}</Button>
|
||||
</AlertDialog.Cancel>
|
||||
<AlertDialog.Action asChild>
|
||||
<Button variant={state?.danger ? 'danger' : 'primary'} onClick={() => close(true)}>
|
||||
{state?.confirmLabel ?? 'Confirm'}
|
||||
</Button>
|
||||
</AlertDialog.Action>
|
||||
</div>
|
||||
</AlertDialog.Content>
|
||||
</AlertDialog.Portal>
|
||||
</AlertDialog.Root>
|
||||
</ConfirmContext.Provider>
|
||||
);
|
||||
}
|
||||
export const useConfirm = () => useContext(ConfirmContext);
|
||||
|
||||
/* ------------------------------ Menu ------------------------------ */
|
||||
|
||||
export function Menu({ trigger, children, align = 'end', side = 'bottom' }: { trigger: ReactNode; children: ReactNode; align?: 'start' | 'end' | 'center'; side?: 'top' | 'bottom' }) {
|
||||
return (
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Trigger asChild>{trigger}</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content align={align} side={side} sideOffset={6} collisionPadding={10} className="z-[60] max-h-[70vh] min-w-[200px] animate-pop overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-2 outline-none">
|
||||
{children}
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
</DropdownMenu.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export function MenuItem({ children, icon, onSelect, danger, disabled, hint }: { children: ReactNode; icon?: ReactNode; onSelect?: () => void; danger?: boolean; disabled?: boolean; hint?: ReactNode }) {
|
||||
return (
|
||||
<DropdownMenu.Item
|
||||
disabled={disabled}
|
||||
onSelect={onSelect}
|
||||
className={cx(
|
||||
'flex h-9 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-sm outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-45 data-[highlighted]:bg-ink/7 [&>svg]:size-4 [&>svg]:shrink-0',
|
||||
danger ? 'text-bad [&>svg]:text-bad' : 'text-ink [&>svg]:text-ink-3',
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
<span className="flex-1 truncate">{children}</span>
|
||||
{hint && <span className="text-xs text-ink-3">{hint}</span>}
|
||||
</DropdownMenu.Item>
|
||||
);
|
||||
}
|
||||
export function MenuSeparator() {
|
||||
return <DropdownMenu.Separator className="my-1.5 h-px bg-line" />;
|
||||
}
|
||||
export function MenuLabel({ children }: { children: ReactNode }) {
|
||||
return <DropdownMenu.Label className="eyebrow px-2.5 pt-1.5 pb-1">{children}</DropdownMenu.Label>;
|
||||
}
|
||||
|
||||
/* ------------------------------ Popover ------------------------------ */
|
||||
|
||||
export function Popover({ trigger, children, align = 'start', className, open, onOpenChange }: { trigger: ReactNode; children: ReactNode; align?: 'start' | 'end' | 'center'; className?: string; open?: boolean; onOpenChange?: (o: boolean) => void }) {
|
||||
return (
|
||||
<RPopover.Root open={open} onOpenChange={onOpenChange}>
|
||||
<RPopover.Trigger asChild>{trigger}</RPopover.Trigger>
|
||||
<RPopover.Portal>
|
||||
<RPopover.Content align={align} sideOffset={8} collisionPadding={10} className={cx('z-[60] w-80 max-w-[calc(100vw-1.5rem)] animate-pop rounded-xl border border-line bg-surface p-4 shadow-2 outline-none', className)}>
|
||||
{children}
|
||||
</RPopover.Content>
|
||||
</RPopover.Portal>
|
||||
</RPopover.Root>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ Layout bits ------------------------------ */
|
||||
|
||||
export function PageHeader({ eyebrow, title, description, actions, className }: { eyebrow?: ReactNode; title: ReactNode; description?: ReactNode; actions?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<header className={cx('mb-6 flex flex-wrap items-end justify-between gap-x-6 gap-y-4', className)}>
|
||||
<div className="min-w-0">
|
||||
{eyebrow && <div className="eyebrow mb-1.5 flex items-center gap-1.5">{eyebrow}</div>}
|
||||
<h1 className="display text-[30px] text-ink sm:text-[36px]">{title}</h1>
|
||||
{description && <p className="mt-2 max-w-2xl text-[15px] text-ink-2">{description}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export function Section({ title, action, children, className }: { title: ReactNode; action?: ReactNode; children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<section className={cx('mb-8', className)}>
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<h2 className="eyebrow">{title}</h2>
|
||||
{action}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small coloured dot / spine used to identify a class. */
|
||||
export function ClassDot({ color, className }: { color: string; className?: string }) {
|
||||
return <span aria-hidden className={cx('inline-block size-2.5 shrink-0 rounded-[3px] bg-tab', `tab-${color}`, className)} />;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue