All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
- Malformed model JSON is sent back for repair, then retried; a failed job starts over once before it fails. Visitors can dismiss failed sets. - Generated sets get a short distinct name and description; flashcards are atomic and have no hints; standard study shows known/learning counts. - Share links: "In progress" list, finished sets join the normal lists with a "New" tag, plain progress steps, newest exam first. - Share-link AI expires after a week, can be limited to the US or Arizona (DB-IP Lite or Cloudflare headers) and is locked by abuse protection (migration 8). - The assistant never answers from general knowledge; MCP and web search tools load without a manual test. - Plain-text copy, no question count in exam mode, filler text removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
988 lines
42 KiB
TypeScript
988 lines
42 KiB
TypeScript
import {
|
|
Archive,
|
|
ArrowDownAZ,
|
|
ArrowLeft,
|
|
ArrowRight,
|
|
BookOpen,
|
|
ChevronDown,
|
|
Clock,
|
|
Copy,
|
|
Download,
|
|
FileImage,
|
|
FileText,
|
|
FileUp,
|
|
Folder as FolderIcon,
|
|
FolderInput,
|
|
FolderPlus,
|
|
GripVertical,
|
|
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, ITEM_DRAG_TYPE, 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 { SortableList, type SortableRenderProps } from '@/ui/Sortable';
|
|
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
|
|
import { letterGrade } from '@shared/content';
|
|
|
|
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 {letterGrade(q.lastPercent ?? 0)} · {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);
|
|
|
|
/**
|
|
* The exam (folder) in view: a class is divided into exams, each with its own material.
|
|
* 'all' shows everything, 'none' what is in no exam. Remembered per class; new visitors start
|
|
* on the latest exam.
|
|
*/
|
|
const [examChoice, setExamChoice] = useLocalStorage<string>(`sd.exam.${classId}`, '');
|
|
const exams = data?.folders ?? [];
|
|
const examView = examChoice === 'all' || examChoice === 'none' || exams.some((f) => f.id === examChoice) ? examChoice : exams.length ? exams[exams.length - 1].id : 'all';
|
|
const currentExam = exams.find((f) => f.id === examView) ?? null;
|
|
const groupLabel = data?.class.groupLabel ?? 'Exam';
|
|
useAssistantContext(classId, currentExam ? `${data?.class.name} · ${currentExam.name}` : data?.class.name, [], currentExam?.id ?? null);
|
|
|
|
const [filter, setFilter] = useState<Filter>('all');
|
|
const [query, setQuery] = useState('');
|
|
const [sort, setSort] = useLocalStorage<'manual' | 'recent' | 'title'>('sd.classSort', 'manual');
|
|
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);
|
|
if (currentExam) form.append('folderId', currentExam.id);
|
|
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)));
|
|
}
|
|
}
|
|
};
|
|
|
|
/** Items of the exam in view. */
|
|
const scoped = useMemo(() => {
|
|
const items = data?.items ?? [];
|
|
const known = new Set((data?.folders ?? []).map((f) => f.id));
|
|
if (examView === 'all') return items;
|
|
if (examView === 'none') return items.filter((i) => !i.folderId || !known.has(i.folderId));
|
|
return items.filter((i) => i.folderId === examView);
|
|
}, [data, examView]);
|
|
const looseCount = useMemo(() => {
|
|
const known = new Set((data?.folders ?? []).map((f) => f.id));
|
|
return (data?.items ?? []).filter((i) => !i.folderId || !known.has(i.folderId)).length;
|
|
}, [data]);
|
|
|
|
const counts = useMemo(() => {
|
|
const c = { all: 0, quiz: 0, deck: 0, document: 0, note: 0 };
|
|
for (const i of scoped) {
|
|
c.all += 1;
|
|
c[i.kind] += 1;
|
|
}
|
|
return c;
|
|
}, [scoped]);
|
|
|
|
const visible = useMemo(() => {
|
|
const needle = query.trim().toLowerCase();
|
|
const list = scoped.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 }) : sort === 'recent' ? b.updatedAt - a.updatedAt : a.sortOrder - b.sortOrder || a.createdAt - b.createdAt,
|
|
);
|
|
}, [scoped, 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) => {
|
|
const noun = groupLabel.toLowerCase();
|
|
if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${f.name}" will be removed. Everything in it stays in the class, outside any ${noun}.`, confirmLabel: `Delete ${noun}`, danger: true }))) return;
|
|
await api.del(`/api/folders/${f.id}`).catch((e) => toast.error(errorMessage(e)));
|
|
if (examChoice === f.id) setExamChoice('');
|
|
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 (
|
|
<Button to={`/session/${z.activeAttemptId}`} size="sm" variant="marker" icon={<Play className="fill-current" />}>
|
|
Resume
|
|
</Button>
|
|
);
|
|
if (z.questionCount > 0)
|
|
return (
|
|
<Button to={`/quizzes/${z.id}?start=1`} size="sm" icon={<Play className="fill-current" />}>
|
|
Start
|
|
</Button>
|
|
);
|
|
return null;
|
|
}
|
|
if (item.kind === 'deck') {
|
|
const d = item as DeckItem;
|
|
if (d.dueCount + Math.min(d.newCount, 20) > 0 && d.cardCount > 0)
|
|
return (
|
|
<Button to={`/review?deckId=${d.id}`} size="sm" variant={d.dueCount > 0 ? 'marker' : 'secondary'} icon={<Play className="fill-current" />}>
|
|
{d.dueCount > 0 ? `Review ${d.dueCount}` : 'Learn'}
|
|
</Button>
|
|
);
|
|
if (d.cardCount > 0)
|
|
return (
|
|
<Button to={`/decks/${d.id}/cram`} size="sm">Browse</Button>
|
|
);
|
|
}
|
|
return null;
|
|
};
|
|
|
|
const row = (item: Item, sortable?: SortableRenderProps) => {
|
|
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}`}
|
|
ref={sortable?.ref}
|
|
style={sortable?.style}
|
|
className={cx('group relative flex items-center gap-3 bg-surface px-3 py-2.5 hover:bg-ink/[0.035] sm:px-4', sortable && 'pl-1 sm:pl-1.5', sortable?.dragging && 'shadow-3')}
|
|
>
|
|
{sortable?.handle}
|
|
<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"
|
|
onDragStart={(e) => {
|
|
// Dropping this onto the assistant adds it to the chat.
|
|
e.dataTransfer.setData(ITEM_DRAG_TYPE, JSON.stringify({ kind: item.kind, id: item.id, title: item.title }));
|
|
e.dataTransfer.effectAllowed = 'copyLink';
|
|
}}
|
|
>
|
|
{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>
|
|
);
|
|
};
|
|
|
|
// Inside each section, items are grouped under a subheading per type.
|
|
const KIND_ORDER = ['quiz', 'deck', 'note', 'document'] as const;
|
|
const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', document: 'Class Materials', note: 'Notes' } as const;
|
|
const KIND_HEADING_ICON = { quiz: <BookOpen />, deck: <Layers />, document: <FileText />, note: <NotebookPen /> } as const;
|
|
const canSort = sort === 'manual' && !query.trim();
|
|
const persistOrder = (kind: Item['kind']) => async (ids: string[]) => {
|
|
// Keys within one folder group; keep the rest of this kind in their current relative order.
|
|
const all = (data?.items ?? []).filter((i) => i.kind === kind).sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt - b.createdAt).map((i) => i.id);
|
|
const moved = new Set(ids);
|
|
let k = 0;
|
|
const merged = all.map((id) => (moved.has(id) ? ids[k++] : id));
|
|
try {
|
|
await api.post(`/api/classes/${classId}/items/reorder`, { kind, ids: merged });
|
|
await refresh();
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
await refresh();
|
|
}
|
|
};
|
|
const list = (items: Item[]) =>
|
|
canSort && items.length > 1 ? (
|
|
<SortableList
|
|
items={items}
|
|
getKey={(i) => i.id}
|
|
getLabel={(i) => i.title}
|
|
noun={items[0].kind === 'deck' ? 'deck' : items[0].kind}
|
|
onReorder={(ids) => void persistOrder(items[0].kind)(ids)}
|
|
render={(item, props) => row(item, props)}
|
|
/>
|
|
) : (
|
|
items.map((i) => row(i))
|
|
);
|
|
const section = (items: Item[]) => {
|
|
if (filter !== 'all') {
|
|
// One kind only; group by kind anyway so ordering stays within a kind.
|
|
return <ul className="card divide-y divide-line overflow-hidden">{list(items)}</ul>;
|
|
}
|
|
return (
|
|
<div className="card overflow-hidden">
|
|
{KIND_ORDER.filter((k) => items.some((i) => i.kind === k)).map((k, n) => {
|
|
const group = items.filter((i) => i.kind === k);
|
|
return (
|
|
<section key={k} aria-label={KIND_HEADING[k]}>
|
|
<h3 className={cx('eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5', n > 0 && 'border-t')}>
|
|
{KIND_HEADING_ICON[k]}
|
|
{KIND_HEADING[k]}
|
|
<span className="num font-normal">{group.length}</span>
|
|
</h3>
|
|
<ul className="divide-y divide-line">{list(group)}</ul>
|
|
</section>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
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>
|
|
}
|
|
>
|
|
{currentExam && <MenuLabel>Adding to {currentExam.name}</MenuLabel>}
|
|
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz', folderId: currentExam?.id ?? null })}>
|
|
New quiz
|
|
</MenuItem>
|
|
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck', folderId: currentExam?.id ?? null })}>
|
|
New flashcard deck
|
|
</MenuItem>
|
|
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note', folderId: currentExam?.id ?? null })}>
|
|
New note
|
|
</MenuItem>
|
|
<MenuItem icon={<FolderPlus />} onSelect={() => setNewKind({ kind: 'folder' })}>
|
|
New {groupLabel.toLowerCase()}
|
|
</MenuItem>
|
|
<MenuSeparator />
|
|
<MenuItem icon={<Upload />} onSelect={() => fileRef.current?.click()}>
|
|
Upload class materials
|
|
</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 && (
|
|
<Button to={`/review?classId=${cls.id}`} variant="marker" icon={<Play className="fill-current" />}>
|
|
Review {data.due.total}
|
|
</Button>
|
|
)}
|
|
<Button 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 class materials
|
|
</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>
|
|
) : (
|
|
<>
|
|
<ExamTabs
|
|
exams={exams}
|
|
items={data.items}
|
|
looseCount={looseCount}
|
|
view={examView}
|
|
label={groupLabel}
|
|
onView={setExamChoice}
|
|
onNew={() => setNewKind({ kind: 'folder' })}
|
|
onRename={(f) => setRename({ kind: 'folder', id: f.id, title: f.name })}
|
|
onShare={(f) => setShare({ kind: 'folder', id: f.id, title: f.name })}
|
|
onDelete={removeFolder}
|
|
onReorder={async (ids) => {
|
|
await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
|
|
await refresh();
|
|
}}
|
|
/>
|
|
<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'],
|
|
['note', 'Notes'],
|
|
['document', 'Class Materials'],
|
|
] 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: 'manual', label: <span className="sr-only">Your order (drag to rearrange)</span>, icon: <GripVertical /> },
|
|
{ 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">
|
|
{currentExam && !searching ? (
|
|
<EmptyState
|
|
title={`Nothing in ${currentExam.name} yet`}
|
|
icon={<FolderIcon />}
|
|
action={
|
|
<>
|
|
<Button variant="primary" icon={<Upload />} onClick={() => fileRef.current?.click()}>
|
|
Upload class materials
|
|
</Button>
|
|
<Button onClick={() => setGenerate({})}>
|
|
Generate
|
|
</Button>
|
|
</>
|
|
}
|
|
>
|
|
Add this {groupLabel.toLowerCase()}'s slides and notes, then generate quizzes and flashcards from them. Use Move on anything already in the class to bring it here.
|
|
</EmptyState>
|
|
) : (
|
|
<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>
|
|
) : examView !== 'all' ? (
|
|
section(visible)
|
|
) : (
|
|
<div className="space-y-4">
|
|
{loose.length > 0 && section(loose)}
|
|
<SortableList
|
|
items={data.folders}
|
|
getKey={(f) => f.id}
|
|
getLabel={(f) => f.name}
|
|
noun="folder"
|
|
liveAs="div"
|
|
disabled={!canSort || searching || data.folders.length < 2}
|
|
onReorder={async (ids) => {
|
|
await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
|
|
await refresh();
|
|
}}
|
|
render={(f, sortable) => {
|
|
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} ref={sortable.ref} style={sortable.style} className={cx(sortable.dragging && 'rounded-[14px] bg-paper shadow-3')}>
|
|
<div className="mb-1.5 flex items-center gap-1">
|
|
{sortable.handle}
|
|
<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 ? (
|
|
section(items)
|
|
) : (
|
|
<div className="rounded-[14px] border border-dashed border-line-strong px-4 py-4 text-[13px] text-ink-3">Empty. Use "Move" on any item to put it here.</div>
|
|
))}
|
|
</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} groupLabel={groupLabel} 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} folderId={currentExam?.id ?? null} />
|
|
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} folderId={currentExam?.id ?? null} preset={generate ?? undefined} />
|
|
<ClassDialog open={editClass} onOpenChange={setEditClass} existing={cls} />
|
|
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} folderId={currentExam?.id ?? null} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function PasteTextDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
|
|
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, folderId: folderId ?? null, 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"
|
|
|
|
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">
|
|
<Textarea rows={12} value={text} onChange={(e) => setText(e.target.value)} />
|
|
</Field>
|
|
</div>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ exams ------------------------------ */
|
|
|
|
/**
|
|
* The second level of a class: one tab per exam (or unit, module… as the class calls them),
|
|
* plus "All" and, when anything is outside every exam, "Not in an exam".
|
|
*/
|
|
function ExamTabs({
|
|
exams,
|
|
items,
|
|
looseCount,
|
|
view,
|
|
label,
|
|
onView,
|
|
onNew,
|
|
onRename,
|
|
onShare,
|
|
onDelete,
|
|
onReorder,
|
|
}: {
|
|
exams: Folder[];
|
|
items: Item[];
|
|
looseCount: number;
|
|
view: string;
|
|
label: string;
|
|
onView: (v: string) => void;
|
|
onNew: () => void;
|
|
onRename: (f: Folder) => void;
|
|
onShare: (f: Folder) => void;
|
|
onDelete: (f: Folder) => void;
|
|
onReorder: (ids: string[]) => void;
|
|
}) {
|
|
const noun = label.toLowerCase();
|
|
const count = (id: string) => items.filter((i) => i.folderId === id).length;
|
|
const move = (index: number, by: number) => {
|
|
const ids = exams.map((f) => f.id);
|
|
const [id] = ids.splice(index, 1);
|
|
ids.splice(Math.max(0, Math.min(ids.length, index + by)), 0, id);
|
|
onReorder(ids);
|
|
};
|
|
if (exams.length === 0) {
|
|
return (
|
|
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-[14px] border border-dashed border-line-strong px-4 py-3 text-[13.5px] text-ink-2">
|
|
<FolderIcon className="size-4 shrink-0 text-tab" />
|
|
<span className="min-w-0 flex-1">Divide this class into {noun}s so each keeps its own class materials, quizzes and flashcards, and generating uses only that {noun}'s material.</span>
|
|
<Button size="sm" icon={<Plus />} onClick={onNew}>
|
|
New {noun}
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
const tab = (key: string, text: ReactNode, n: number, extra?: ReactNode) => (
|
|
<div key={key} className={cx('flex shrink-0 items-center rounded-[11px] border transition-colors', view === key ? 'border-tab bg-surface shadow-1' : 'border-transparent hover:bg-ink/5')}>
|
|
<button type="button" role="tab" aria-selected={view === key} onClick={() => onView(key)} className={cx('flex h-10 items-center gap-2 pr-2 pl-3.5 text-sm', view === key ? 'font-semibold text-ink' : 'font-medium text-ink-2')}>
|
|
{text}
|
|
<span className="num text-xs font-normal text-ink-3">{n}</span>
|
|
</button>
|
|
{extra}
|
|
</div>
|
|
);
|
|
return (
|
|
<div className="mb-4 border-b border-line pb-3">
|
|
<div role="tablist" aria-label={`${label}s`} className="-mx-1 flex items-center gap-1 overflow-x-auto px-1 pb-1">
|
|
{exams.map((f, index) =>
|
|
tab(
|
|
f.id,
|
|
<>
|
|
<FolderIcon className="size-4 text-tab" />
|
|
<span className="max-w-48 truncate">{f.name}</span>
|
|
{f.shared && <Share2 className="size-3.5 text-accent" aria-label="Shared" />}
|
|
</>,
|
|
count(f.id),
|
|
view === f.id ? (
|
|
<Menu
|
|
trigger={
|
|
<IconButton label={`${label} options for ${f.name}`} size="sm" tooltip={false} className="mr-1">
|
|
<MoreHorizontal />
|
|
</IconButton>
|
|
}
|
|
>
|
|
<MenuItem icon={<Pencil />} onSelect={() => onRename(f)}>
|
|
Rename
|
|
</MenuItem>
|
|
<MenuItem icon={<Share2 />} onSelect={() => onShare(f)}>
|
|
Share this {noun}
|
|
</MenuItem>
|
|
{index > 0 && (
|
|
<MenuItem icon={<ArrowLeft />} onSelect={() => move(index, -1)}>
|
|
Move earlier
|
|
</MenuItem>
|
|
)}
|
|
{index < exams.length - 1 && (
|
|
<MenuItem icon={<ArrowRight />} onSelect={() => move(index, 1)}>
|
|
Move later
|
|
</MenuItem>
|
|
)}
|
|
<MenuSeparator />
|
|
<MenuItem icon={<Trash2 />} danger onSelect={() => onDelete(f)}>
|
|
Delete {noun}
|
|
</MenuItem>
|
|
</Menu>
|
|
) : null,
|
|
),
|
|
)}
|
|
{looseCount > 0 && tab('none', <span className="text-ink-2">Not in a{/^[aeiou]/i.test(noun) ? 'n' : ''} {noun}</span>, looseCount)}
|
|
{tab('all', <span>All</span>, items.length)}
|
|
<button type="button" onClick={onNew} className="ml-1 flex h-10 shrink-0 items-center gap-1.5 rounded-[11px] px-3 text-sm font-medium text-ink-3 hover:bg-ink/5 hover:text-ink">
|
|
<Plus className="size-4" /> New {noun}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|