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>
327 lines
14 KiB
TypeScript
327 lines
14 KiB
TypeScript
import { useQuery } from '@tanstack/react-query';
|
|
import { BookOpen, Bot, ChevronRight, Layers, NotebookPen, Pencil, RotateCcw, Trash2 } from 'lucide-react';
|
|
import { useEffect, useState, type ReactNode } from 'react';
|
|
import { toast } from 'sonner';
|
|
import { api, errorMessage } from '@/lib/api';
|
|
import { qk, useRefresh } from '@/lib/queries';
|
|
import type { Template } from '@/lib/types';
|
|
import { cx, plural } from '@/lib/util';
|
|
import { Badge, Button, Dialog, Field, IconButton, Input, Section, Segmented, Select, Skeleton, Textarea, useConfirm } from '@/ui';
|
|
|
|
/* ------------------------------ shared text editor ------------------------------ */
|
|
|
|
/** A collapsible row holding one block of instructions, with save and reset. */
|
|
function InstructionRow({ label, text, builtin, customized, onSave }: { label: string; text: string; builtin: string; customized: boolean; onSave: (text: string | null) => Promise<void> }) {
|
|
const [open, setOpen] = useState(false);
|
|
const [value, setValue] = useState(text);
|
|
const [busy, setBusy] = useState(false);
|
|
useEffect(() => setValue(text), [text]);
|
|
const dirty = value.trim() !== text.trim();
|
|
const save = async (next: string | null) => {
|
|
setBusy(true);
|
|
try {
|
|
await onSave(next);
|
|
toast.success(next === null ? 'Back to the built-in wording' : 'Saved');
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
return (
|
|
<li>
|
|
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex w-full items-center gap-2.5 px-4 py-3 text-left hover:bg-ink/4">
|
|
<ChevronRight className={cx('size-4 shrink-0 text-ink-3 transition-transform', open && 'rotate-90')} />
|
|
<span className="min-w-0 flex-1 truncate text-sm font-medium">{label}</span>
|
|
{customized ? <Badge tone="accent">Edited</Badge> : <Badge>Built in</Badge>}
|
|
</button>
|
|
{open && (
|
|
<div className="px-4 pb-4">
|
|
<Textarea value={value} onChange={(e) => setValue(e.target.value)} rows={12} spellCheck={false} aria-label={label} className="num text-[12.5px] leading-relaxed" />
|
|
<div className="mt-2 flex flex-wrap items-center gap-2">
|
|
<Button size="sm" variant="primary" disabled={!dirty || value.trim().length < 10} loading={busy} onClick={() => save(value)}>
|
|
Save
|
|
</Button>
|
|
{dirty && (
|
|
<Button size="sm" variant="ghost" onClick={() => setValue(text)}>
|
|
Undo changes
|
|
</Button>
|
|
)}
|
|
{(customized || value.trim() !== builtin.trim()) && (
|
|
<Button size="sm" variant="ghost" icon={<RotateCcw />} className="ml-auto" disabled={busy} onClick={() => save(null)}>
|
|
Reset to built-in
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</li>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ import (outside chatbot) instructions ------------------------------ */
|
|
|
|
interface LlmInstructions {
|
|
quiz: string;
|
|
deck: string;
|
|
customized: { quiz: boolean; deck: boolean };
|
|
builtin?: { quiz: string; deck: string };
|
|
}
|
|
|
|
function ImportInstructions() {
|
|
const q = useQuery({ queryKey: ['llm-instructions'], queryFn: () => api.get<LlmInstructions>('/api/llm-instructions') });
|
|
if (!q.data) return <Skeleton className="h-28" />;
|
|
const save = (kind: 'quiz' | 'deck') => async (text: string | null) => {
|
|
await api.put('/api/llm-instructions', { kind, text });
|
|
await q.refetch();
|
|
};
|
|
return (
|
|
<Section title="Import instructions (manual generation)">
|
|
<ul className="card divide-y divide-line overflow-hidden">
|
|
<InstructionRow label="Quiz questions" text={q.data.quiz} builtin={q.data.builtin?.quiz ?? q.data.quiz} customized={q.data.customized.quiz} onSave={save('quiz')} />
|
|
<InstructionRow label="Flashcards" text={q.data.deck} builtin={q.data.builtin?.deck ?? q.data.deck} customized={q.data.customized.deck} onSave={save('deck')} />
|
|
</ul>
|
|
</Section>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ built-in generator instructions ------------------------------ */
|
|
|
|
interface GenerationInstruction {
|
|
key: string;
|
|
group: string;
|
|
label: string;
|
|
text: string;
|
|
builtin: string;
|
|
customized: boolean;
|
|
}
|
|
|
|
function GeneratorInstructions() {
|
|
const q = useQuery({ queryKey: ['ai', 'instructions'], queryFn: () => api.get<{ instructions: GenerationInstruction[] }>('/api/ai/instructions').then((r) => r.instructions) });
|
|
if (!q.data) return <Skeleton className="h-40" />;
|
|
const groups = [...new Set(q.data.map((i) => i.group))];
|
|
const save = (key: string) => async (text: string | null) => {
|
|
await api.put('/api/ai/instructions', { key, text });
|
|
await q.refetch();
|
|
};
|
|
return (
|
|
<Section title="AI generation instructions (automatic generation)">
|
|
<div className="space-y-3">
|
|
{groups.map((g) => (
|
|
<div key={g}>
|
|
<div className="mb-1.5 text-xs font-medium text-ink-3">{g}</div>
|
|
<ul className="card divide-y divide-line overflow-hidden">
|
|
{q.data!
|
|
.filter((i) => i.group === g)
|
|
.map((i) => (
|
|
<InstructionRow key={i.key} label={i.label} text={i.text} builtin={i.builtin} customized={i.customized} onSave={save(i.key)} />
|
|
))}
|
|
</ul>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</Section>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ generation presets ------------------------------ */
|
|
|
|
type PresetKind = 'quiz' | 'deck' | 'note';
|
|
|
|
function PresetDialog({ template, onClose }: { template: Template | null; onClose: () => void }) {
|
|
const refresh = useRefresh();
|
|
const [name, setName] = useState('');
|
|
const [description, setDescription] = useState('');
|
|
const [payload, setPayload] = useState<Record<string, any>>({});
|
|
const [busy, setBusy] = useState(false);
|
|
useEffect(() => {
|
|
if (!template) return;
|
|
setName(template.name);
|
|
setDescription(template.description);
|
|
setPayload({ ...template.payload });
|
|
}, [template]);
|
|
const set = (patch: Record<string, unknown>) => setPayload((p) => ({ ...p, ...patch }));
|
|
const kind: PresetKind = payload.kind ?? 'quiz';
|
|
const save = async () => {
|
|
if (!template) return;
|
|
setBusy(true);
|
|
try {
|
|
const clean = { ...payload };
|
|
if (kind !== 'quiz') ['style', 'format', 'difficulty', 'sataShare'].forEach((k) => delete clean[k]);
|
|
if (kind !== 'deck') delete clean.cardStyle;
|
|
if (kind !== 'note') delete clean.noteStyle;
|
|
if (kind === 'note') delete clean.count;
|
|
if (!String(clean.instructions ?? '').trim()) delete clean.instructions;
|
|
await api.patch(`/api/templates/${template.id}`, { name, description, payload: clean });
|
|
await refresh();
|
|
toast.success('Preset saved');
|
|
onClose();
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
return (
|
|
<Dialog
|
|
open={template !== null}
|
|
onOpenChange={(o) => !o && onClose()}
|
|
title="Edit preset"
|
|
description={template?.builtin ? 'A built-in preset. Your changes are kept, and you can reset it later.' : undefined}
|
|
footer={
|
|
<>
|
|
<Button variant="ghost" onClick={onClose}>
|
|
Cancel
|
|
</Button>
|
|
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={save}>
|
|
Save
|
|
</Button>
|
|
</>
|
|
}
|
|
>
|
|
<div className="space-y-4">
|
|
<Field label="Name">
|
|
<Input value={name} onChange={(e) => setName(e.target.value)} maxLength={120} />
|
|
</Field>
|
|
<Field label="Description" optional>
|
|
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={1000} />
|
|
</Field>
|
|
<Segmented<PresetKind>
|
|
label="Creates"
|
|
value={kind}
|
|
onChange={(k) => set({ kind: k })}
|
|
options={[
|
|
{ value: 'quiz', label: 'Quiz', icon: <BookOpen /> },
|
|
{ value: 'deck', label: 'Flashcards', icon: <Layers /> },
|
|
{ value: 'note', label: 'Study guide', icon: <NotebookPen /> },
|
|
]}
|
|
/>
|
|
{kind !== 'note' && (
|
|
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'}>
|
|
<Input type="number" min={1} max={200} value={payload.count ?? (kind === 'quiz' ? 15 : 30)} onChange={(e) => set({ count: Math.max(1, Math.min(200, Number(e.target.value) || 1)) })} className="w-28" />
|
|
</Field>
|
|
)}
|
|
{kind === 'quiz' && (
|
|
<div className="grid gap-3 sm:grid-cols-3">
|
|
<Field label="Set">
|
|
<Select value={payload.format ?? 'practice'} onChange={(e) => set({ format: e.target.value, style: 'nclex', ...(e.target.value === 'exam' && !payload.count ? { count: 50 } : {}) })}>
|
|
<option value="practice">Practice set</option>
|
|
<option value="exam">Practice exam</option>
|
|
</Select>
|
|
</Field>
|
|
<Field label="Difficulty">
|
|
<Select value={payload.difficulty ?? 'mixed'} onChange={(e) => set({ difficulty: e.target.value })}>
|
|
<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: ${Math.round((payload.sataShare ?? 0.3) * 100)}%`}>
|
|
<input type="range" min={0} max={100} step={5} value={Math.round((payload.sataShare ?? 0.3) * 100)} onChange={(e) => set({ sataShare: Number(e.target.value) / 100 })} className="mt-3 w-full accent-[var(--accent)]" />
|
|
</Field>
|
|
</div>
|
|
)}
|
|
{kind === 'deck' && (
|
|
<Field label="Card style">
|
|
<Select value={payload.cardStyle ?? 'concise'} onChange={(e) => set({ cardStyle: e.target.value })}>
|
|
<option value="concise">Concise</option>
|
|
<option value="detailed">Detailed</option>
|
|
<option value="medication">Medication</option>
|
|
<option value="definition">Term and definition</option>
|
|
</Select>
|
|
</Field>
|
|
)}
|
|
{kind === 'note' && (
|
|
<Field label="Guide style">
|
|
<Select value={payload.noteStyle ?? 'study_guide'} onChange={(e) => set({ noteStyle: e.target.value })}>
|
|
<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>
|
|
)}
|
|
<Field label="Extra instructions" optional hint="Added to the AI generation instructions whenever this preset is used.">
|
|
<Textarea rows={4} value={payload.instructions ?? ''} onChange={(e) => set({ instructions: e.target.value })} />
|
|
</Field>
|
|
</div>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------ page ------------------------------ */
|
|
|
|
export function TemplateSettings() {
|
|
const refresh = useRefresh();
|
|
const confirm = useConfirm();
|
|
const [editing, setEditing] = useState<Template | null>(null);
|
|
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; icon: ReactNode }[] = [
|
|
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI. Built-in presets can be edited and reset.', icon: <Bot /> },
|
|
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.', icon: <BookOpen /> },
|
|
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.', icon: <Layers /> },
|
|
];
|
|
const act = async (fn: () => Promise<unknown>, message: string) => {
|
|
try {
|
|
await fn();
|
|
await refresh();
|
|
toast.success(message);
|
|
} catch (e) {
|
|
toast.error(errorMessage(e));
|
|
}
|
|
};
|
|
return (
|
|
<>
|
|
<GeneratorInstructions />
|
|
<ImportInstructions />
|
|
{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.edited ? <Badge tone="accent">Edited</Badge> : 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.kind === 'generation' && (
|
|
<IconButton label="Edit preset" size="sm" onClick={() => setEditing(t)}>
|
|
<Pencil />
|
|
</IconButton>
|
|
)}
|
|
{t.edited && (
|
|
<IconButton label="Reset to built-in" size="sm" onClick={() => act(() => api.post(`/api/templates/${t.id}/reset`), 'Preset reset')}>
|
|
<RotateCcw />
|
|
</IconButton>
|
|
)}
|
|
{!t.builtin && (
|
|
<IconButton
|
|
label="Delete template"
|
|
size="sm"
|
|
onClick={async () => {
|
|
if (!(await confirm({ title: 'Delete this template?', message: `"${t.name}" will be removed.`, confirmLabel: 'Delete', danger: true }))) return;
|
|
await act(() => api.del(`/api/templates/${t.id}`), 'Template deleted');
|
|
}}
|
|
>
|
|
<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 flex items-center gap-1.5 text-xs text-ink-3">{g.blurb}</p>
|
|
</Section>
|
|
);
|
|
})}
|
|
<PresetDialog template={editing} onClose={() => setEditing(null)} />
|
|
</>
|
|
);
|
|
}
|