First revision: DeepSeek, numeric questions, background assistant, UI fixes
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s
Providers and pricing - Add a DeepSeek provider: thinking mode with low/high/max effort, reasoning_content replayed between tool steps, cache-hit usage, /models discovery and catalog prices. - Fix "does not support tool calling": a rejected forced tool_choice (DeepSeek thinking mode) now asks for the call in the prompt; only a genuine no-tools 400 is "unsupported". - Seven reasoning-effort levels (Off to Max) mapped per adapter. - Cached-input price per model, cache-write and DeepSeek off-peak aware cost estimates. - Built-in bge-small embedding model (transformers.js) as the semantic search default. Quizzes - Numeric (type-the-answer) questions: units ignored, optional ± tolerance; editor, runner, importer, templates and generation prompts. - Quiz start screen instead of showing answers; navigator ring no longer clipped and key legend removed; clock only for timed exams; 7-point letter grades. Assistant and generation - Assistant turns run on the server independently of the browser, with re-attach and an explicit stop; drafts tray shows generations in progress. - Per-chat model switcher, @-tagging of class materials, full-width assistant page and a smaller assistant button. - Editable generation instructions and built-in presets, separate from the chatbot import instructions. Other - Dialog footer padding, keyboard hints removed, copy buttons work over plain HTTP, class and folder shares include documents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ccdad9728b
commit
f0aabe4d5d
63 changed files with 3892 additions and 488 deletions
|
|
@ -5,7 +5,7 @@ import { toast } from 'sonner';
|
|||
import { api, errorMessage } from '@/lib/api';
|
||||
import { qk } from '@/lib/queries';
|
||||
import { SemanticSettings } from './SemanticSettings';
|
||||
import type { AdapterMeta, AiModel, AiStatus, Provider, ProviderKind, TaskConfig, TaskName, TaskSettings } from '@/lib/types';
|
||||
import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type 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';
|
||||
|
||||
|
|
@ -19,6 +19,7 @@ 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.',
|
||||
deepseek: 'DeepSeek Flash and Pro with a DeepSeek platform key.',
|
||||
openai_compatible: 'OpenRouter, Groq, Together, LM Studio, vLLM and other compatible servers.',
|
||||
ollama: 'Models running on your own machine or server.',
|
||||
};
|
||||
|
|
@ -182,6 +183,34 @@ function ProviderDialog({ open, onClose, adapters, existing, onSaved }: { open:
|
|||
|
||||
/* ------------------------------ model dialog ------------------------------ */
|
||||
|
||||
/** The discount a provider gives on cached input when a model has no cached price of its own (mirrors the server). */
|
||||
const CACHE_HINT: Record<ProviderKind, string> = {
|
||||
openai: "OpenAI's discount (90% off for GPT-5 and later)",
|
||||
anthropic: "Claude's cache-read rate (10% of input)",
|
||||
gemini: "Gemini's cache rate (10% of input)",
|
||||
deepseek: "DeepSeek's cache-hit rate",
|
||||
openai_compatible: 'the normal input price',
|
||||
ollama: 'the normal input price',
|
||||
};
|
||||
|
||||
function cachedGuess(model: AiModel): string {
|
||||
const id = model.model.slice(model.model.lastIndexOf('/') + 1);
|
||||
const ratio =
|
||||
model.providerKind === 'openai'
|
||||
? /^gpt-4\.1/.test(id)
|
||||
? 0.25
|
||||
: /^(gpt-4o|o\d)/.test(id)
|
||||
? 0.5
|
||||
: 0.1
|
||||
: model.providerKind === 'anthropic' || model.providerKind === 'gemini'
|
||||
? 0.1
|
||||
: model.providerKind === 'deepseek'
|
||||
? 0.02
|
||||
: 1;
|
||||
const v = (model.priceIn ?? 0) * ratio;
|
||||
return `$${v < 0.01 ? v.toFixed(4) : v.toFixed(3)}`;
|
||||
}
|
||||
|
||||
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 });
|
||||
|
|
@ -189,6 +218,7 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
|
|||
const [maxOut, setMaxOut] = useState('');
|
||||
const [priceIn, setPriceIn] = useState('');
|
||||
const [priceOut, setPriceOut] = useState('');
|
||||
const [priceCached, setPriceCached] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!model) return;
|
||||
|
|
@ -198,13 +228,14 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
|
|||
setMaxOut(model.maxOutput?.toString() ?? '');
|
||||
setPriceIn(model.priceIn?.toString() ?? '');
|
||||
setPriceOut(model.priceOut?.toString() ?? '');
|
||||
setPriceCached(model.priceCachedIn?.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) });
|
||||
await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut), priceCachedIn: num(priceCached) });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
|
|
@ -254,6 +285,9 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
|
|||
<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>
|
||||
<Field label="Cached input price" hint={`USD per million cached (cache-hit) input tokens. Blank uses ${model ? CACHE_HINT[model.providerKind] : 'the provider discount'}.`} className="col-span-2">
|
||||
<Input type="number" min={0} step="0.001" value={priceCached} onChange={(e) => setPriceCached(e.target.value)} placeholder={model?.priceIn != null ? `About ${cachedGuess(model)}` : 'Unknown'} />
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
|
|
@ -495,10 +529,11 @@ function TaskRow({ name, label, description, config, models, resolved, onChange
|
|||
<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>
|
||||
{REASONING_EFFORTS.map((e) => (
|
||||
<option key={e.value} value={e.value}>
|
||||
{e.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
|
||||
|
|
@ -536,13 +571,14 @@ function Usage() {
|
|||
<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">
|
||||
<div className="grid grid-cols-2 gap-px border-b border-line bg-line sm:grid-cols-4">
|
||||
{[
|
||||
['Estimated cost', formatCost(u.total.cost)],
|
||||
['Requests', u.total.calls.toLocaleString()],
|
||||
['Tokens in / out', `${formatTokens(u.total.input)} / ${formatTokens(u.total.output)}`],
|
||||
['Cached input', u.total.input ? `${formatTokens(u.total.cached)} (${Math.round((u.total.cached / u.total.input) * 100)}%)` : '0'],
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="px-4 py-3">
|
||||
<div key={k} className="bg-surface px-4 py-3">
|
||||
<div className="eyebrow">{k}</div>
|
||||
<div className="num mt-1 text-lg font-semibold">{v}</div>
|
||||
</div>
|
||||
|
|
@ -555,6 +591,7 @@ function Usage() {
|
|||
<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">Cached</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>
|
||||
|
|
@ -571,6 +608,7 @@ function Usage() {
|
|||
</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.cached)}</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>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
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 { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, 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 { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
|
||||
import type { AssistantEvent, ChatMessage, Mentionable, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
|
||||
import { cx, plural, timeAgo, useDebounced, useLocalStorage } from '@/lib/util';
|
||||
import { citedSources, Markdown, type Citation } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui';
|
||||
|
||||
|
|
@ -16,6 +16,7 @@ interface Conversation {
|
|||
title: string;
|
||||
classId: string | null;
|
||||
updatedAt: number;
|
||||
running?: boolean;
|
||||
}
|
||||
|
||||
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const;
|
||||
|
|
@ -172,6 +173,82 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
|
|||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ composer: model picker and @ tags ------------------------------ */
|
||||
|
||||
const TAG_ICON: Record<TagKind, ReactNode> = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText />, folder: <Folder /> };
|
||||
const TAG_NOUN: Record<TagKind, string> = { quiz: 'Quiz', deck: 'Flashcards', note: 'Note', document: 'Document', folder: 'Folder' };
|
||||
|
||||
function TagChip({ item, onRemove, inverted }: { item: TaggedItem; onRemove?: () => void; inverted?: boolean }) {
|
||||
return (
|
||||
<span className={cx('inline-flex h-6 max-w-full items-center gap-1 rounded-full pr-2 pl-1.5 text-xs font-medium [&>svg]:size-3 [&>svg]:shrink-0', inverted ? 'bg-paper/15 text-paper' : 'bg-accent-soft text-accent')}>
|
||||
{TAG_ICON[item.kind]}
|
||||
<span className="truncate">{item.title}</span>
|
||||
{onRemove && (
|
||||
<button type="button" aria-label={`Remove ${item.title}`} onClick={onRemove} className="-mr-1 grid size-4 place-items-center rounded-full hover:bg-accent/15">
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Model chooser for this chat. "Default" follows the Assistant model set in Settings. */
|
||||
function ModelPicker({ value, onChange, defaultLabel }: { value: string; onChange: (id: string) => void; defaultLabel?: string }) {
|
||||
const models = useAiModels();
|
||||
const usable = (models.data ?? []).filter((m) => m.available);
|
||||
const chosen = usable.find((m) => m.id === value);
|
||||
const providers = [...new Set(usable.map((m) => m.providerName))];
|
||||
return (
|
||||
<Menu
|
||||
align="start"
|
||||
trigger={
|
||||
<button type="button" className="flex max-w-full min-w-0 items-center gap-1 rounded-md text-xs text-ink-3 hover:text-ink" aria-label="Choose the model for this chat">
|
||||
<span className="truncate">{chosen ? chosen.label : defaultLabel ? `${defaultLabel}` : 'Default model'}</span>
|
||||
<ChevronDown className="size-3 shrink-0" />
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<MenuLabel>Model for this chat</MenuLabel>
|
||||
<MenuItem onSelect={() => onChange('')} hint={!chosen ? <Check className="size-3.5" /> : undefined}>
|
||||
Default{defaultLabel ? ` · ${defaultLabel}` : ''}
|
||||
</MenuItem>
|
||||
{providers.map((p) => (
|
||||
<div key={p}>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>{p}</MenuLabel>
|
||||
{usable
|
||||
.filter((m) => m.providerName === p)
|
||||
.map((m) => (
|
||||
<MenuItem key={m.id} onSelect={() => onChange(m.id)} hint={m.id === value ? <Check className="size-3.5" /> : !m.capabilities.tools ? 'no tools' : undefined}>
|
||||
{m.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
/** Finds an "@query" being typed just before the caret. */
|
||||
function mentionAt(text: string, caret: number): { start: number; query: string } | null {
|
||||
const before = text.slice(0, caret);
|
||||
const m = /(^|\s)@([^\s@]{0,40})$/.exec(before);
|
||||
return m ? { start: caret - m[2].length - 1, query: m[2] } : null;
|
||||
}
|
||||
|
||||
function useMentionables(classId: string | null, query: string, enabled: boolean) {
|
||||
const debounced = useDebounced(query, 150);
|
||||
// Inside a class: load its materials once and filter here. Elsewhere: search by title.
|
||||
const q = useQuery({
|
||||
queryKey: ['ai', 'mentionables', classId ?? '', classId ? '' : debounced],
|
||||
queryFn: () => api.get<{ items: Mentionable[] }>(`/api/ai/mentionables?${new URLSearchParams(classId ? { classId } : { q: debounced })}`).then((r) => r.items),
|
||||
enabled: enabled && (Boolean(classId) || debounced.length >= 1),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const needle = query.toLowerCase();
|
||||
return (q.data ?? []).filter((i) => !needle || i.title.toLowerCase().includes(needle) || (i.folderName ?? '').toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
|
||||
/* ------------------------------ panel ------------------------------ */
|
||||
|
||||
export default function AssistantPanel({
|
||||
|
|
@ -186,56 +263,166 @@ export default function AssistantPanel({
|
|||
onConversationChange?: (id: string | null) => void;
|
||||
}) {
|
||||
const ai = useAiStatus();
|
||||
const models = useAiModels();
|
||||
const classes = useClasses();
|
||||
const refresh = useRefresh();
|
||||
const qc = useQueryClient();
|
||||
const { seed, context } = useAssistantState();
|
||||
const [conversationId, setConversationId] = useState<string | null>(routeConversationId ?? null);
|
||||
const initialConversation = variant === 'page' ? (routeConversationId ?? null) : assistant.drawerConversation;
|
||||
const [conversationId, setConversationId] = useState<string | null>(initialConversation);
|
||||
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 [tags, setTags] = useState<TaggedItem[]>([]);
|
||||
const [mention, setMention] = useState<{ start: number; query: string } | null>(null);
|
||||
const [mentionIndex, setMentionIndex] = useState(0);
|
||||
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
|
||||
/** The connection to the running turn. Aborting it only detaches: the turn continues on the server. */
|
||||
const stream = useRef<AbortController | null>(null);
|
||||
const stopRequested = useRef(false);
|
||||
const conversationRef = useRef<string | null>(initialConversation);
|
||||
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 availableModel = (models.data ?? []).find((m) => m.id === modelId && m.available);
|
||||
const effectiveModelId = availableModel ? modelId : '';
|
||||
|
||||
const load = useCallback(async (id: string) => {
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
setMessages(res.messages);
|
||||
const setConversation = useCallback(
|
||||
(id: string | null) => {
|
||||
conversationRef.current = id;
|
||||
setConversationId(id);
|
||||
stick.current = true;
|
||||
} catch {
|
||||
setConversationId(null);
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
if (variant === 'drawer') assistant.rememberDrawerConversation(id);
|
||||
},
|
||||
[variant],
|
||||
);
|
||||
|
||||
/** Applies one streamed event to the pending assistant message. */
|
||||
const applyEvent = useCallback((pendingId: string, e: AssistantEvent) => {
|
||||
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
|
||||
if (e.type === 'start') 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 }));
|
||||
}, []);
|
||||
|
||||
/** Follows a turn (new or already running) until it finishes or this panel detaches. */
|
||||
const follow = useCallback(
|
||||
async (pendingId: string, run: (signal: AbortSignal, onEvent: (e: AssistantEvent) => void) => Promise<void>) => {
|
||||
stream.current?.abort();
|
||||
const controller = new AbortController();
|
||||
stream.current = controller;
|
||||
stopRequested.current = false;
|
||||
setBusy(true);
|
||||
let finished = false;
|
||||
let startedId: string | null = null;
|
||||
try {
|
||||
await run(controller.signal, (e) => {
|
||||
if (e.type === 'start') {
|
||||
startedId = e.conversationId;
|
||||
if (stopRequested.current) void api.post(`/api/ai/chat/${e.conversationId}/stop`).catch(() => undefined);
|
||||
if (e.conversationId !== conversationRef.current) {
|
||||
setConversation(e.conversationId);
|
||||
onConversationChange?.(e.conversationId);
|
||||
}
|
||||
}
|
||||
if (e.type === 'done') finished = true;
|
||||
applyEvent(pendingId, e);
|
||||
});
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name !== 'AbortError') setMessages((list) => list.map((m) => (m.id === pendingId ? { ...m, error: errorMessage(e) } : m)));
|
||||
} finally {
|
||||
if (stream.current === controller) {
|
||||
stream.current = null;
|
||||
setBusy(false);
|
||||
}
|
||||
// Detached (left the conversation): leave the turn running and the message as it is.
|
||||
if (finished || !controller.signal.aborted) {
|
||||
setMessages((list) =>
|
||||
list.map((m) =>
|
||||
m.id === pendingId
|
||||
? { ...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 : stopRequested.current ? '*(Stopped.)*' : m.text) }
|
||||
: m,
|
||||
),
|
||||
);
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
// Tools may have created drafts, classes or sessions.
|
||||
void refresh();
|
||||
}
|
||||
void startedId;
|
||||
}
|
||||
},
|
||||
[applyEvent, onConversationChange, qc, refresh, setConversation],
|
||||
);
|
||||
|
||||
const load = useCallback(
|
||||
async (id: string) => {
|
||||
stream.current?.abort();
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const res = await api.get<{ conversation: { id: string; running?: boolean }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
|
||||
setConversation(id);
|
||||
stick.current = true;
|
||||
if (!res.conversation.running) {
|
||||
setMessages(res.messages);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
// Still answering: show what is saved up to the question, then replay the live turn.
|
||||
const lastUser = res.messages.map((m) => m.role).lastIndexOf('user');
|
||||
const pendingId = `p${Date.now()}`;
|
||||
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
|
||||
setLoadingHistory(false);
|
||||
void follow(pendingId, (signal, onEvent) => streamEvents<AssistantEvent>(`/api/ai/chat/${id}/stream`, undefined, onEvent, signal));
|
||||
} catch {
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
},
|
||||
[follow, setConversation],
|
||||
);
|
||||
|
||||
// Open the remembered or routed conversation on mount.
|
||||
useEffect(() => {
|
||||
if (initialConversation) void load(initialConversation);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId);
|
||||
if (!routeConversationId && variant === 'page' && conversationId && !busy) {
|
||||
setConversationId(null);
|
||||
if (variant !== 'page') return;
|
||||
if (routeConversationId && routeConversationId !== conversationRef.current) void load(routeConversationId);
|
||||
if (!routeConversationId && conversationRef.current && !busy) {
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [routeConversationId]);
|
||||
|
||||
const newChat = useCallback(() => {
|
||||
abort.current?.abort();
|
||||
setConversationId(null);
|
||||
// Detach only: an answer still being written keeps going and is saved in its conversation.
|
||||
stream.current?.abort();
|
||||
setBusy(false);
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
setFocusDocs([]);
|
||||
setTags([]);
|
||||
onConversationChange?.(null);
|
||||
setTimeout(() => inputRef.current?.focus(), 30);
|
||||
}, [onConversationChange]);
|
||||
}, [onConversationChange, setConversation]);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
stopRequested.current = true;
|
||||
const id = conversationRef.current;
|
||||
if (id) void api.post(`/api/ai/chat/${id}/stop`).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds;
|
||||
const className = classes.data?.find((c) => c.id === context.classId)?.name;
|
||||
|
|
@ -244,47 +431,37 @@ export default function AssistantPanel({
|
|||
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);
|
||||
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationRef.current;
|
||||
const sentTags = tags;
|
||||
setInput('');
|
||||
setTags([]);
|
||||
setMention(null);
|
||||
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>(
|
||||
setMessages((m) => [
|
||||
...m,
|
||||
{ id: `u${Date.now()}`, role: 'user', text: message, tags: sentTags.length ? sentTags : undefined, tools: [], ui: [], createdAt: Date.now() },
|
||||
{ id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true },
|
||||
]);
|
||||
await follow(pendingId, (signal, onEvent) =>
|
||||
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 }));
|
||||
{
|
||||
conversationId: convo,
|
||||
message,
|
||||
modelId: effectiveModelId || undefined,
|
||||
context: {
|
||||
classId: opts.classId !== undefined ? opts.classId : context.classId,
|
||||
documentIds: opts.documentIds ?? activeDocs,
|
||||
items: sentTags.map((t) => ({ kind: t.kind, id: t.id })),
|
||||
},
|
||||
},
|
||||
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();
|
||||
}
|
||||
onEvent,
|
||||
signal,
|
||||
),
|
||||
);
|
||||
},
|
||||
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh],
|
||||
[busy, tags, follow, effectiveModelId, context.classId, activeDocs],
|
||||
);
|
||||
|
||||
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
|
||||
|
|
@ -293,8 +470,9 @@ export default function AssistantPanel({
|
|||
handledSeed.current = seed.id;
|
||||
assistant.consumeSeed();
|
||||
if (seed.newChat) {
|
||||
abort.current?.abort();
|
||||
setConversationId(null);
|
||||
stream.current?.abort();
|
||||
setBusy(false);
|
||||
setConversation(null);
|
||||
setMessages([]);
|
||||
onConversationChange?.(null);
|
||||
}
|
||||
|
|
@ -304,14 +482,15 @@ export default function AssistantPanel({
|
|||
if (seed.prompt) setInput(seed.prompt);
|
||||
setTimeout(() => inputRef.current?.focus(), 60);
|
||||
}
|
||||
}, [seed, ai.data, send, onConversationChange]);
|
||||
}, [seed, ai.data, send, onConversationChange, setConversation]);
|
||||
|
||||
// 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(), []);
|
||||
// Leaving only disconnects; the server finishes the answer and saves it.
|
||||
useEffect(() => () => stream.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)) })));
|
||||
|
|
@ -329,16 +508,54 @@ export default function AssistantPanel({
|
|||
}, [activeDocs.length, className]);
|
||||
|
||||
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
|
||||
const options = useMentionables(context.classId, mention?.query ?? '', mention !== null);
|
||||
const pickable = options.filter((o) => !tags.some((t) => t.kind === o.kind && t.id === o.id));
|
||||
|
||||
const updateMention = (text: string, caret: number) => {
|
||||
const next = mentionAt(text, caret);
|
||||
setMention(next);
|
||||
if (!next || next.query !== mention?.query) setMentionIndex(0);
|
||||
};
|
||||
const choose = (item: Mentionable) => {
|
||||
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t : [...t, { kind: item.kind, id: item.id, title: item.title }]));
|
||||
if (mention) {
|
||||
const caret = inputRef.current?.selectionStart ?? input.length;
|
||||
const next = `${input.slice(0, mention.start)}${input.slice(caret)}`.replace(/\s{2,}/g, ' ');
|
||||
setInput(next);
|
||||
setTimeout(() => {
|
||||
const el = inputRef.current;
|
||||
if (el) {
|
||||
el.focus();
|
||||
el.setSelectionRange(mention.start, mention.start);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
setMention(null);
|
||||
};
|
||||
const openPicker = () => {
|
||||
const el = inputRef.current;
|
||||
const caret = el?.selectionStart ?? input.length;
|
||||
const needsSpace = caret > 0 && !/\s/.test(input[caret - 1] ?? '');
|
||||
const next = `${input.slice(0, caret)}${needsSpace ? ' ' : ''}@${input.slice(caret)}`;
|
||||
setInput(next);
|
||||
const at = caret + (needsSpace ? 1 : 0) + 1;
|
||||
setMention({ start: at - 1, query: '' });
|
||||
setMentionIndex(0);
|
||||
setTimeout(() => {
|
||||
el?.focus();
|
||||
el?.setSelectionRange(at, at);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
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">
|
||||
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-5')}>
|
||||
<span className="grid size-8 shrink-0 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>
|
||||
{ai.data?.ready ? <ModelPicker value={effectiveModelId} onChange={setModelId} defaultLabel={ai.data.resolved.chat?.label} /> : <div className="truncate text-xs text-ink-3">{ai.data ? 'Not set up' : ''}</div>}
|
||||
</div>
|
||||
<IconButton label="New chat" size="sm" onClick={newChat}>
|
||||
<Plus />
|
||||
|
|
@ -354,7 +571,7 @@ export default function AssistantPanel({
|
|||
<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)}>
|
||||
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={c.running ? 'working…' : timeAgo(c.updatedAt)}>
|
||||
{c.title}
|
||||
</MenuItem>
|
||||
))}
|
||||
|
|
@ -365,7 +582,9 @@ export default function AssistantPanel({
|
|||
icon={<Trash2 />}
|
||||
danger
|
||||
onSelect={async () => {
|
||||
await api.del(`/api/ai/conversations/${conversationId}`).catch(() => undefined);
|
||||
const id = conversationId;
|
||||
stop();
|
||||
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
|
||||
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
|
||||
newChat();
|
||||
}}
|
||||
|
|
@ -385,7 +604,7 @@ export default function AssistantPanel({
|
|||
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')}
|
||||
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-6')}
|
||||
aria-live="polite"
|
||||
>
|
||||
{ai.isLoading || loadingHistory ? (
|
||||
|
|
@ -395,18 +614,18 @@ export default function AssistantPanel({
|
|||
) : !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.
|
||||
Add a provider such as OpenAI, Anthropic, Google Gemini, DeepSeek or a local model, then switch on a model.
|
||||
<div className="mt-3">
|
||||
<Button to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()} size="sm" variant="primary">
|
||||
Open AI settings
|
||||
</Button>
|
||||
Open AI settings
|
||||
</Button>
|
||||
</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>
|
||||
<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. Type @ to point me at a specific quiz, deck, note or document.</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">
|
||||
|
|
@ -421,7 +640,16 @@ export default function AssistantPanel({
|
|||
{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 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.tags?.length ? (
|
||||
<div className="mb-1.5 flex flex-wrap gap-1">
|
||||
{m.tags.map((t) => (
|
||||
<TagChip key={`${t.kind}:${t.id}`} item={t} inverted />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{m.text}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
|
||||
|
|
@ -432,8 +660,8 @@ export default function AssistantPanel({
|
|||
</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">
|
||||
<div className={cx('safe-pb-3 shrink-0 border-t border-line px-3 pt-2.5', variant === 'page' && 'lg:px-6')}>
|
||||
<div className="relative mx-auto max-w-2xl">
|
||||
{contextLabel && (
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<Badge tone="accent" className="max-w-full">
|
||||
|
|
@ -447,41 +675,104 @@ export default function AssistantPanel({
|
|||
)}
|
||||
</div>
|
||||
)}
|
||||
{mention && (
|
||||
<div role="listbox" aria-label="Tag a material" className="absolute inset-x-0 bottom-full z-30 mb-2 max-h-72 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-2">
|
||||
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : 'Your library'}</div>
|
||||
{pickable.length === 0 ? (
|
||||
<div className="px-2.5 py-2 text-[13px] text-ink-3">{context.classId || mention.query ? 'Nothing matches.' : 'Type to search your quizzes, decks, notes and documents.'}</div>
|
||||
) : (
|
||||
pickable.map((o, i) => (
|
||||
<button
|
||||
key={`${o.kind}:${o.id}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === mentionIndex}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onMouseMove={() => setMentionIndex(i)}
|
||||
onClick={() => choose(o)}
|
||||
className={cx('flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left', i === mentionIndex && 'bg-ink/7')}
|
||||
>
|
||||
<span className="grid size-7 shrink-0 place-items-center rounded-md bg-sunken text-ink-2 [&>svg]:size-3.5">{TAG_ICON[o.kind]}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm">{o.title}</span>
|
||||
<span className="block truncate text-[11px] text-ink-3">
|
||||
{TAG_NOUN[o.kind]}
|
||||
{o.folderName ? ` · ${o.folderName}` : ''}
|
||||
{!context.classId ? ` · ${o.className}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
</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"
|
||||
className="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();
|
||||
if (busy) stop();
|
||||
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>
|
||||
{tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 px-1.5 pt-1 pb-1.5">
|
||||
{tags.map((t) => (
|
||||
<TagChip key={`${t.kind}:${t.id}`} item={t} onRemove={() => setTags((list) => list.filter((x) => !(x.kind === t.kind && x.id === t.id)))} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-end gap-1.5">
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
rows={1}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
updateMention(e.target.value, e.target.selectionStart ?? e.target.value.length);
|
||||
e.target.style.height = 'auto';
|
||||
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
|
||||
}}
|
||||
onSelect={(e) => mention && updateMention(e.currentTarget.value, e.currentTarget.selectionStart ?? 0)}
|
||||
onBlur={() => setTimeout(() => setMention(null), 120)}
|
||||
onKeyDown={(e) => {
|
||||
if (mention && pickable.length > 0) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setMentionIndex((i) => (i + (e.key === 'ArrowDown' ? 1 : -1) + pickable.length) % pickable.length);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
choose(pickable[Math.min(mentionIndex, pickable.length - 1)]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (mention && e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setMention(null);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
if (!busy) void send(input);
|
||||
}
|
||||
}}
|
||||
placeholder={context.classId ? 'Ask anything. Type @ to tag a quiz, deck, note or document…' : '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"
|
||||
/>
|
||||
<IconButton label="Tag a material" size="sm" className="mb-0.5" onClick={openPicker}>
|
||||
<AtSign />
|
||||
</IconButton>
|
||||
<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>
|
||||
</div>
|
||||
</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>
|
||||
|
|
|
|||
114
web/src/features/DraftsTray.tsx
Normal file
114
web/src/features/DraftsTray.tsx
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, CircleAlert, Layers, NotebookPen, Sparkles } from 'lucide-react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { NavLink, useNavigate } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
import { qk, useRefresh } from '@/lib/queries';
|
||||
import type { DraftSummary } from '@/lib/types';
|
||||
import { cx, plural, timeAgo } from '@/lib/util';
|
||||
import { ProgressBar } from '@/ui';
|
||||
|
||||
const ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
|
||||
const NOUN = { quiz: 'quiz', deck: 'flashcards', note: 'study guide' };
|
||||
|
||||
/**
|
||||
* Drafts that still need attention: generations in progress (polled while running), drafts
|
||||
* ready for review, and recent failures. Generation runs on the server, so leaving the page
|
||||
* never loses it; this is how you get back to it.
|
||||
*/
|
||||
export function useOpenDrafts() {
|
||||
const q = useQuery({
|
||||
queryKey: qk.drafts,
|
||||
queryFn: ({ signal }) => api.get<{ drafts: DraftSummary[] }>('/api/drafts', signal).then((r) => r.drafts),
|
||||
refetchInterval: (query) => (query.state.data?.some((d) => d.status === 'generating') ? 2000 : 60_000),
|
||||
});
|
||||
const dayAgo = Date.now() - 86_400_000;
|
||||
const drafts = (q.data ?? []).filter((d) => d.status === 'generating' || d.status === 'ready' || (d.status === 'failed' && d.updatedAt > dayAgo));
|
||||
return { drafts, generating: drafts.filter((d) => d.status === 'generating') };
|
||||
}
|
||||
|
||||
/** Announces generations that finish while you are elsewhere in the app. */
|
||||
export function useDraftNotifications() {
|
||||
const { drafts } = useOpenDrafts();
|
||||
const refresh = useRefresh();
|
||||
const navigate = useNavigate();
|
||||
const seen = useRef<Map<string, string>>(new Map());
|
||||
useEffect(() => {
|
||||
const prev = seen.current;
|
||||
for (const d of drafts) {
|
||||
const before = prev.get(d.id);
|
||||
if (before === 'generating' && d.status !== 'generating') {
|
||||
const onPage = window.location.pathname === `/drafts/${d.id}`;
|
||||
if (!onPage) {
|
||||
if (d.status === 'ready') toast.success(`${d.title || 'Your draft'} is ready to review`, { action: { label: 'Review', onClick: () => navigate(`/drafts/${d.id}`) } });
|
||||
else toast.error(`${d.title || 'A draft'} did not finish`);
|
||||
}
|
||||
void refresh(qk.drafts);
|
||||
}
|
||||
}
|
||||
seen.current = new Map(drafts.map((d) => [d.id, d.status]));
|
||||
}, [drafts, refresh, navigate]);
|
||||
}
|
||||
|
||||
function DraftRow({ d, compact }: { d: DraftSummary; compact?: boolean }) {
|
||||
const status =
|
||||
d.status === 'generating'
|
||||
? d.progressLabel || 'Starting'
|
||||
: d.status === 'failed'
|
||||
? 'Did not finish'
|
||||
: d.kind === 'note'
|
||||
? 'Ready to review'
|
||||
: `Ready · ${plural(d.itemCount, d.kind === 'quiz' ? 'question' : 'card')}`;
|
||||
return (
|
||||
<NavLink
|
||||
to={`/drafts/${d.id}`}
|
||||
className={({ isActive }) => cx('block rounded-[9px] px-2.5 py-2 transition-colors', isActive ? 'bg-ink/8' : 'hover:bg-ink/5', !compact && 'border border-line bg-surface shadow-1')}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className={cx('grid shrink-0 place-items-center [&>svg]:size-3.5', d.status === 'failed' ? 'text-bad' : d.status === 'generating' ? 'text-accent' : 'text-ink-3')}>
|
||||
{d.status === 'failed' ? <CircleAlert /> : d.status === 'generating' ? <Sparkles className="animate-pulse" /> : ICON[d.kind]}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{d.title || `New ${NOUN[d.kind]}`}</span>
|
||||
{!compact && <span className="shrink-0 text-[11px] text-ink-3">{timeAgo(d.updatedAt)}</span>}
|
||||
</span>
|
||||
<span className={cx('mt-0.5 block truncate pl-[22px] text-[11px]', d.status === 'failed' ? 'text-bad' : 'text-ink-3')}>{status}</span>
|
||||
{d.status === 'generating' && <ProgressBar value={Math.max(0.04, d.progress)} className="mt-1.5 ml-[22px] h-1" label={`Generating ${d.title}`} />}
|
||||
</NavLink>
|
||||
);
|
||||
}
|
||||
|
||||
/** Sidebar section: only shown while something is generating or waiting for review. */
|
||||
export function SidebarDrafts() {
|
||||
const { drafts } = useOpenDrafts();
|
||||
if (drafts.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-5 px-3">
|
||||
<div className="mb-1.5 flex items-center justify-between px-2">
|
||||
<span className="eyebrow">Drafts</span>
|
||||
{drafts.length > 5 && <span className="text-[11px] text-ink-3">{drafts.length}</span>}
|
||||
</div>
|
||||
<div className="max-h-56 space-y-0.5 overflow-y-auto">
|
||||
{drafts.slice(0, 8).map((d) => (
|
||||
<DraftRow key={d.id} d={d} compact />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The same list for the Today page, where phones see it. */
|
||||
export function DraftsSection() {
|
||||
const { drafts } = useOpenDrafts();
|
||||
if (drafts.length === 0) return null;
|
||||
return (
|
||||
<section className="mb-8">
|
||||
<h2 className="eyebrow mb-3">Drafts</h2>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{drafts.slice(0, 6).map((d) => (
|
||||
<DraftRow key={d.id} d={d} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -86,6 +86,8 @@ function LlmInstructionsDialog({ open, onClose }: { open: boolean; onClose: () =
|
|||
setCopied(true);
|
||||
toast.success('Instructions copied');
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} else {
|
||||
toast.error('Your browser blocked copying. Select the text and copy it yourself.');
|
||||
}
|
||||
}}
|
||||
>
|
||||
|
|
@ -269,7 +271,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
|
|||
<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>
|
||||
<span>{filename ? filename : 'or drop a .json, .txt or .csv file here.'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -15,8 +15,11 @@ interface EmbeddingStatus {
|
|||
running: boolean;
|
||||
lastError: string;
|
||||
defaults: Record<ProviderKind, string | null>;
|
||||
local: { model: string; label: string; dimensions: number; downloaded: boolean; status: 'idle' | 'loading' | 'ready' | 'error'; error: string; enabledByDefault: boolean };
|
||||
}
|
||||
|
||||
const LOCAL = 'local';
|
||||
|
||||
const KEY = ['ai', 'embeddings'];
|
||||
|
||||
/**
|
||||
|
|
@ -33,7 +36,8 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
refetchInterval: (query) => (query.state.data?.running ? 1500 : false),
|
||||
});
|
||||
const data = q.data;
|
||||
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.enabled);
|
||||
// Anthropic and DeepSeek have no embeddings API.
|
||||
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.kind !== 'deepseek' && p.enabled);
|
||||
const [providerId, setProviderId] = useState('');
|
||||
const [model, setModel] = useState('');
|
||||
const [dimensions, setDimensions] = useState('');
|
||||
|
|
@ -47,9 +51,10 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
}, [data]);
|
||||
|
||||
if (!data) return null;
|
||||
const isLocal = providerId === LOCAL;
|
||||
const chosen = providers.find((p) => p.id === providerId);
|
||||
const suggested = chosen ? data.defaults[chosen.kind] : null;
|
||||
const dirty = providerId !== (data.settings.providerId ?? '') || model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : '');
|
||||
const suggested = isLocal ? data.local.label : chosen ? data.defaults[chosen.kind] : null;
|
||||
const dirty = providerId !== (data.settings.providerId ?? '') || (!isLocal && (model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : '')));
|
||||
const reload = () => qc.invalidateQueries({ queryKey: KEY });
|
||||
|
||||
const save = async () => {
|
||||
|
|
@ -59,7 +64,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
}
|
||||
setBusy('save');
|
||||
try {
|
||||
await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId ? model.trim() : '', dimensions: dimensions ? Number(dimensions) : null });
|
||||
await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId && !isLocal ? model.trim() : '', dimensions: dimensions && !isLocal ? Number(dimensions) : null });
|
||||
toast.success(providerId ? 'Semantic search is on. Indexing your documents…' : 'Semantic search is off');
|
||||
await reload();
|
||||
} catch (e) {
|
||||
|
|
@ -103,11 +108,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
Finds passages by meaning as well as by words, so "why do patients on Lasix need bananas?" finds the section on furosemide and potassium. Used by search, the assistant and
|
||||
focused generation. Keyword search keeps working without it.
|
||||
</p>
|
||||
{eligible.length === 0 ? (
|
||||
<Callout tone="accent" icon={<Sparkles />} className="mt-4" title="Needs an embeddings provider">
|
||||
Connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic does not offer embeddings.
|
||||
</Callout>
|
||||
) : (
|
||||
{(
|
||||
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
|
||||
<Field label="Provider">
|
||||
<Select
|
||||
|
|
@ -115,10 +116,12 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
onChange={(e) => {
|
||||
const next = providers.find((p) => p.id === e.target.value);
|
||||
setProviderId(e.target.value);
|
||||
if (next && (!model || !dirty)) setModel(data.defaults[next.kind] ?? '');
|
||||
if (e.target.value === LOCAL) setModel(data.local.model);
|
||||
else if (next && (!model || !dirty || model === data.local.model)) setModel(data.defaults[next.kind] ?? '');
|
||||
}}
|
||||
>
|
||||
<option value="">Off (keywords only)</option>
|
||||
<option value={LOCAL}>Built-in model (free, runs on this server)</option>
|
||||
{eligible.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
|
|
@ -127,16 +130,29 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
</Select>
|
||||
</Field>
|
||||
<Field label="Embedding model" hint={suggested ? `Suggested: ${suggested}` : chosen ? 'The model id your server uses for embeddings' : undefined}>
|
||||
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId} />
|
||||
<Input value={isLocal ? data.local.label : model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId || isLocal} />
|
||||
</Field>
|
||||
<Field label="Size" hint="Optional">
|
||||
<Input type="number" min={64} max={4096} step={64} value={dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId} className="sm:w-28" />
|
||||
<Input type="number" min={64} max={4096} step={64} value={isLocal ? String(data.local.dimensions) : dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId || isLocal} className="sm:w-28" />
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
{eligible.length > 0 && (
|
||||
{isLocal && (
|
||||
<p className="mt-2 text-[13px] text-ink-3">
|
||||
{data.local.downloaded
|
||||
? 'The model is on this server. Embeddings are computed on its processor at no cost.'
|
||||
: 'The model (about 35 MB) is downloaded from Hugging Face the first time it is used, then kept with your data. Embeddings are computed on this server at no cost.'}
|
||||
{data.local.status === 'loading' ? ' Loading the model now…' : ''}
|
||||
</p>
|
||||
)}
|
||||
{eligible.length === 0 && !isLocal && (
|
||||
<Callout tone="accent" icon={<Sparkles />} className="mt-3" title="Cloud embeddings need a provider">
|
||||
Use the built-in model, or connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic and DeepSeek do not offer embeddings.
|
||||
</Callout>
|
||||
)}
|
||||
{(
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !model.trim())} loading={busy === 'save'} onClick={save}>
|
||||
<Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !isLocal && !model.trim())} loading={busy === 'save'} onClick={save}>
|
||||
Save
|
||||
</Button>
|
||||
{data.configured && !dirty && (
|
||||
|
|
@ -174,7 +190,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
|
|||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-ink-3">Embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage. Local Ollama models are free.</p>
|
||||
<p className="mt-2 text-xs text-ink-3">The built-in model and local Ollama models are free. Cloud embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage.</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
338
web/src/features/TemplateSettings.tsx
Normal file
338
web/src/features/TemplateSettings.tsx
Normal file
|
|
@ -0,0 +1,338 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, Bot, ChevronRight, Layers, MessageSquareText, 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>
|
||||
<p className="mt-2 text-xs text-ink-3">
|
||||
What "AI instructions" in the Import window copies for ChatGPT, Claude or another chatbot you use yourself. They describe the import JSON format, so keep that part intact.
|
||||
</p>
|
||||
</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>
|
||||
<p className="mt-2 text-xs text-ink-3">
|
||||
Sent to your connected AI model when you use Generate or ask the assistant to make quizzes, flashcards or study guides. The output format is handled separately, so these only need to
|
||||
describe what good material looks like.
|
||||
</p>
|
||||
</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', '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="Style">
|
||||
<Select value={payload.style ?? 'nclex'} onChange={(e) => set({ style: e.target.value })}>
|
||||
<option value="nclex">NCLEX</option>
|
||||
<option value="standard">Standard</option>
|
||||
<option value="recall">Quick recall</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>
|
||||
);
|
||||
})}
|
||||
<p className="flex items-center gap-1.5 text-xs text-ink-3">
|
||||
<MessageSquareText className="size-3.5" /> Changes apply to new generations. Drafts that are already written are not affected.
|
||||
</p>
|
||||
<PresetDialog template={editing} onClose={() => setEditing(null)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -150,7 +150,7 @@ export function ForecastBars({ values, className }: { values: number[]; classNam
|
|||
/** 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';
|
||||
const tone = p >= 85 ? 'bg-good' : p >= 77 ? '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">
|
||||
|
|
|
|||
|
|
@ -280,8 +280,8 @@ const SHARE_BLURB: Record<ShareKind, string> = {
|
|||
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.',
|
||||
folder: 'Anyone with the link can study the quizzes, decks and notes in this folder and view or download its documents.',
|
||||
class: 'Anyone with the link can study every quiz, deck and note in this class and view or download its documents.',
|
||||
};
|
||||
|
||||
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
|
||||
|
|
@ -321,6 +321,8 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
|
|||
setCopied(true);
|
||||
toast.success('Link copied');
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} else {
|
||||
toast.error('Your browser blocked copying. Select the link and copy it yourself.');
|
||||
}
|
||||
};
|
||||
const on = Boolean(share?.enabled);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
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 { DIFFICULTIES, LIMITS, optionLetter, parseNumericAnswer, 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';
|
||||
|
|
@ -157,6 +157,19 @@ export function QuestionEditor({
|
|||
};
|
||||
|
||||
const setType = (type: QuestionType) => {
|
||||
if (type === value.type) return;
|
||||
if (type === 'numeric') {
|
||||
// Keep any marked answer that already is a number; otherwise start with one blank answer.
|
||||
const keep = value.options.filter((o) => o.correct && parseNumericAnswer(o.text) !== null).map((o) => ({ ...o, correct: true }));
|
||||
set({ type, options: keep.length ? keep : [{ text: '', correct: true, why: value.options.find((o) => o.correct)?.why ?? '' }] });
|
||||
return;
|
||||
}
|
||||
if (value.type === 'numeric') {
|
||||
const options = value.options.filter((o) => o.text.trim()).map((o, i) => ({ ...o, correct: type === 'multi' || i === 0 }));
|
||||
while (options.length < 4) options.push({ text: '', correct: false, why: '' });
|
||||
set({ type, options });
|
||||
return;
|
||||
}
|
||||
if (type === 'single') {
|
||||
// Keep only the first marked answer so the question stays valid.
|
||||
let seen = false;
|
||||
|
|
@ -178,9 +191,11 @@ export function QuestionEditor({
|
|||
label="Question type"
|
||||
value={value.type}
|
||||
onChange={setType}
|
||||
className="max-w-full overflow-x-auto"
|
||||
options={[
|
||||
{ value: 'single', label: 'Multiple choice' },
|
||||
{ value: 'multi', label: 'Select all that apply' },
|
||||
{ value: 'multi', label: 'Select all' },
|
||||
{ value: 'numeric', label: 'Numeric answer' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -190,6 +205,41 @@ export function QuestionEditor({
|
|||
<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>
|
||||
|
||||
{value.type === 'numeric' ? (
|
||||
<div>
|
||||
<FieldLabel>Correct answer</FieldLabel>
|
||||
<ul className="space-y-2">
|
||||
{value.options.map((o, i) => (
|
||||
<li key={i} className="flex items-start gap-2">
|
||||
<Input
|
||||
value={o.text}
|
||||
onChange={(e) => setOption(i, { text: e.target.value, correct: true })}
|
||||
aria-label={i === 0 ? 'Correct answer' : `Also accepted ${i}`}
|
||||
aria-invalid={Boolean(o.text.trim()) && parseNumericAnswer(o.text) === null}
|
||||
placeholder={i === 0 ? '12.5 mL' : 'Another accepted answer'}
|
||||
inputMode="decimal"
|
||||
className="num max-w-xs"
|
||||
/>
|
||||
{value.options.length > 1 && (
|
||||
<IconButton label="Remove this answer" size="sm" className="mt-1" onClick={() => set({ options: value.options.filter((_, k) => k !== i) })}>
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-1.5 text-[13px] text-ink-3">The student types a number. Units are ignored, so "12.5" and "12.5 mL" both count. Add a tolerance with ±, for example "12.5 ± 0.1 mL".</p>
|
||||
{value.options.length < LIMITS.options && (
|
||||
<button type="button" onClick={() => set({ options: [...value.options, { text: '', correct: true, why: '' }] })} className="mt-1 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" /> Accept another answer
|
||||
</button>
|
||||
)}
|
||||
<div className="mt-3">
|
||||
<FieldLabel>Working</FieldLabel>
|
||||
<Textarea autoGrow rows={1} value={value.options[0]?.why ?? ''} onChange={(e) => setOption(0, { why: e.target.value })} aria-label="Working" placeholder="How the answer is calculated (optional)" className="bg-sunken text-[13px]" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<FieldLabel>{value.type === 'single' ? 'Answer choices · mark the correct one' : 'Answer choices · mark every correct one'}</FieldLabel>
|
||||
<ul className="space-y-2">
|
||||
|
|
@ -230,6 +280,7 @@ export function QuestionEditor({
|
|||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<FieldLabel>Rationale</FieldLabel>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from
|
|||
import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Button, IconButton, Kbd, ProgressBar } from '@/ui';
|
||||
import { Button, IconButton, ProgressBar } from '@/ui';
|
||||
import { Ring } from './charts';
|
||||
|
||||
/* ------------------------------ streaks ------------------------------ */
|
||||
|
|
@ -163,7 +163,7 @@ export function FlipCard({
|
|||
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
|
||||
<div className="flex items-center justify-between px-6 pt-5">
|
||||
<span className="eyebrow">{label ?? 'Question'}</span>
|
||||
<span className="text-xs text-ink-3">Click or press Space to flip</span>
|
||||
<span className="text-xs text-ink-3">Tap the card to flip it</span>
|
||||
</div>
|
||||
<div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16">
|
||||
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
|
||||
|
|
@ -238,18 +238,6 @@ export function StudyFooter({ children }: { children: ReactNode }) {
|
|||
);
|
||||
}
|
||||
|
||||
export function KeyHints({ items }: { items: [ReactNode, string][] }) {
|
||||
return (
|
||||
<div className="mt-2 hidden flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] text-ink-3 md:flex">
|
||||
{items.map(([keys, label]) => (
|
||||
<span key={label} className="flex items-center gap-1">
|
||||
{keys} {label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SWIPE_MS = 230;
|
||||
|
||||
/* ------------------------------ browse / cram ------------------------------ */
|
||||
|
|
@ -433,7 +421,7 @@ export function CramSession({
|
|||
{!done && card && (
|
||||
<StudyFooter>
|
||||
<div className="flex items-center gap-2">
|
||||
<IconButton label="Previous card (Backspace)" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
|
||||
<IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
|
||||
<ArrowLeft />
|
||||
</IconButton>
|
||||
{seenAnswer ? (
|
||||
|
|
@ -450,17 +438,10 @@ export function CramSession({
|
|||
Show answer
|
||||
</Button>
|
||||
)}
|
||||
<IconButton label="Skip card (S)" onClick={() => move(1)} disabled={busy}>
|
||||
<IconButton label="Skip card" onClick={() => move(1)} disabled={busy}>
|
||||
<SkipForward />
|
||||
</IconButton>
|
||||
</div>
|
||||
<KeyHints
|
||||
items={[
|
||||
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
|
||||
[<Kbd>←</Kbd>, 'still learning'],
|
||||
[<Kbd>→</Kbd>, 'know it'],
|
||||
]}
|
||||
/>
|
||||
</StudyFooter>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
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 { isFullyCorrect, letterGrade, optionLetter, parseNumericAnswer, 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 { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
|
||||
import { Ring } from './charts';
|
||||
|
||||
/* ------------------------------ option list ------------------------------ */
|
||||
|
|
@ -71,6 +71,87 @@ function OptionList({
|
|||
);
|
||||
}
|
||||
|
||||
/* ------------------------------ numeric answer ------------------------------ */
|
||||
|
||||
/** The accepted answer(s) of a numeric question, for display. */
|
||||
function acceptedAnswers(question: SnapshotQuestion): string {
|
||||
return question.options
|
||||
.filter((o) => o.correct !== false)
|
||||
.map((o) => o.text)
|
||||
.join(' or ');
|
||||
}
|
||||
|
||||
/** A calculation: the student types the number. Units are optional; only the number is checked. */
|
||||
function NumericAnswer({
|
||||
question,
|
||||
value,
|
||||
revealed,
|
||||
onChange,
|
||||
onSubmit,
|
||||
autoFocus,
|
||||
}: {
|
||||
question: SnapshotQuestion;
|
||||
value: string;
|
||||
revealed: boolean;
|
||||
onChange?: (text: string) => void;
|
||||
onSubmit?: () => void;
|
||||
autoFocus?: boolean;
|
||||
}) {
|
||||
const right = revealed && isFullyCorrect(scoreQuestion(question, value ? [value] : []));
|
||||
const unreadable = value.trim() !== '' && parseNumericAnswer(value) === null;
|
||||
const why = question.options.find((o) => o.why)?.why;
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
<label className="block">
|
||||
<span className="sr-only">Your answer</span>
|
||||
<Input
|
||||
value={value}
|
||||
autoFocus={autoFocus}
|
||||
inputMode="decimal"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
readOnly={revealed || !onChange}
|
||||
onChange={(e) => onChange?.(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
onSubmit?.();
|
||||
}
|
||||
}}
|
||||
placeholder="Type your answer, e.g. 12.5"
|
||||
aria-invalid={unreadable || undefined}
|
||||
className={cx(
|
||||
'num h-14 max-w-sm rounded-[14px] px-4 text-[20px]',
|
||||
revealed && (right ? 'border-good bg-good-soft ring-1 ring-good' : 'border-bad bg-bad-soft ring-1 ring-bad'),
|
||||
)}
|
||||
/>
|
||||
</label>
|
||||
{!revealed && <p className="text-[13px] text-ink-3">{unreadable ? 'Enter a number. Units are optional.' : 'Only the number is checked, so units are optional.'}</p>}
|
||||
{revealed && (
|
||||
<div className="rounded-[14px] border border-good/60 border-dashed px-3.5 py-2.5">
|
||||
<div className="flex flex-wrap items-baseline gap-x-2 text-[15px]">
|
||||
<span className="text-[13px] font-medium text-good">Correct answer</span>
|
||||
<span className="num font-semibold">{acceptedAnswers(question)}</span>
|
||||
</div>
|
||||
{why && <div className="mt-1 text-[13.5px] leading-snug text-ink-2">{why}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the student answered, as text (for the AI explanation). */
|
||||
function answerTexts(question: SnapshotQuestion, selected: string[]): string[] {
|
||||
if (question.type === 'numeric') return selected.slice(0, 1);
|
||||
return question.options.filter((o) => selected.includes(o.id)).map((o) => o.text);
|
||||
}
|
||||
|
||||
/** Tone for a percentage on the 7-point scale: A and B good, C passing, D and F failing. */
|
||||
export function gradeToneFor(percent: number): 'good' | 'warn' | 'bad' {
|
||||
const letter = letterGrade(percent);
|
||||
return letter === 'A' || letter === 'B' ? 'good' : letter === 'C' ? 'warn' : 'bad';
|
||||
}
|
||||
|
||||
/** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */
|
||||
function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null {
|
||||
if (question.type !== 'multi') return null;
|
||||
|
|
@ -194,12 +275,21 @@ export function QuizRunner(p: RunnerProps) {
|
|||
topRef.current?.scrollIntoView({ block: 'start' });
|
||||
}, [index]);
|
||||
|
||||
const numeric = question.type === 'numeric';
|
||||
const toggle = (id: string) => {
|
||||
if (checked) return;
|
||||
if (checked || numeric) 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 typed = numeric ? (selected[0] ?? '') : '';
|
||||
const setTyped = (text: string) => !checked && p.onAnswer(question.id, text.trim() ? [text] : [], false);
|
||||
const canCheck = numeric ? parseNumericAnswer(typed) !== null : selected.length > 0;
|
||||
const check = () => {
|
||||
if (!canCheck) return;
|
||||
// Let the typed answer show its correct/incorrect colour instead of the focus ring.
|
||||
if (numeric) (document.activeElement as HTMLElement | null)?.blur();
|
||||
p.onAnswer(question.id, numeric ? [typed.trim()] : 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]);
|
||||
|
||||
|
|
@ -223,8 +313,8 @@ export function QuizRunner(p: RunnerProps) {
|
|||
};
|
||||
|
||||
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)])),
|
||||
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)]))),
|
||||
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)]))),
|
||||
Enter: primary,
|
||||
ArrowRight: () => go(index + 1),
|
||||
ArrowLeft: () => go(index - 1),
|
||||
|
|
@ -253,7 +343,7 @@ export function QuizRunner(p: RunnerProps) {
|
|||
</div>
|
||||
{live && (
|
||||
<div
|
||||
className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', live.percent >= 80 ? 'bg-good-soft text-good' : live.percent >= 60 ? 'bg-warn-soft text-warn' : 'bg-bad-soft text-bad')}
|
||||
className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', { good: 'bg-good-soft text-good', warn: 'bg-warn-soft text-warn', bad: 'bg-bad-soft text-bad' }[gradeToneFor(live.percent)])}
|
||||
aria-label={`Score so far: ${fmtPoints(live.points)} of ${live.n} correct, ${live.percent} percent`}
|
||||
>
|
||||
<span className="hidden sm:inline">
|
||||
|
|
@ -262,10 +352,13 @@ export function QuizRunner(p: RunnerProps) {
|
|||
{live.percent}%
|
||||
</div>
|
||||
)}
|
||||
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}>
|
||||
<Clock className="size-3.5" />
|
||||
{formatDuration(remaining ?? clock)}
|
||||
</div>
|
||||
{/* The clock is a timed-exam feature; untimed sessions track time quietly for the results. */}
|
||||
{remaining !== null && (
|
||||
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label="Time remaining">
|
||||
<Clock className="size-3.5" />
|
||||
{formatDuration(remaining)}
|
||||
</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}
|
||||
|
|
@ -289,8 +382,12 @@ export function QuizRunner(p: RunnerProps) {
|
|||
<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} />
|
||||
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : numeric ? 'Enter your answer.' : 'Choose one answer.'}</p>
|
||||
{numeric ? (
|
||||
<NumericAnswer key={question.id} question={question} value={typed} revealed={checked} onChange={setTyped} onSubmit={primary} />
|
||||
) : (
|
||||
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
|
||||
)}
|
||||
|
||||
{checked && (
|
||||
<div className="mt-5 animate-in space-y-4">
|
||||
|
|
@ -301,10 +398,7 @@ export function QuizRunner(p: RunnerProps) {
|
|||
<Markdown className="text-[15px]">{question.rationale}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{p.renderExtra?.(
|
||||
question,
|
||||
question.options.filter((o) => selected.includes(o.id)).map((o) => o.text),
|
||||
)}
|
||||
{p.renderExtra?.(question, answerTexts(question, selected))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -324,11 +418,8 @@ export function QuizRunner(p: RunnerProps) {
|
|||
<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">
|
||||
<Button size="lg" variant="primary" disabled={!canCheck} onClick={check} className="min-w-32">
|
||||
Check
|
||||
<span className="hidden sm:inline">
|
||||
<Kbd>↵</Kbd>
|
||||
</span>
|
||||
</Button>
|
||||
</>
|
||||
) : isLast ? (
|
||||
|
|
@ -361,7 +452,8 @@ export function QuizRunner(p: RunnerProps) {
|
|||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-6 gap-2 sm:grid-cols-8">
|
||||
{/* Padding keeps the current-question ring (and its offset) inside the scroll area. */}
|
||||
<div className="grid grid-cols-6 gap-2 p-1.5 sm:grid-cols-8">
|
||||
{p.questions.map((q, i) => {
|
||||
const s = statusOf(q);
|
||||
return (
|
||||
|
|
@ -383,21 +475,6 @@ export function QuizRunner(p: RunnerProps) {
|
|||
);
|
||||
})}
|
||||
</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>
|
||||
);
|
||||
|
|
@ -440,7 +517,8 @@ export function QuizResults(p: ResultsProps) {
|
|||
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 tone = gradeToneFor(percent);
|
||||
const grade = letterGrade(percent);
|
||||
|
||||
const topics = useMemo(() => {
|
||||
const map = new Map<string, { n: number; s: number }>();
|
||||
|
|
@ -455,7 +533,7 @@ export function QuizResults(p: ResultsProps) {
|
|||
}, [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';
|
||||
const headline = { A: 'Excellent work', B: 'Strong result', C: 'Passing', D: 'Just below passing', F: 'Worth another pass' }[grade];
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-paper">
|
||||
|
|
@ -471,13 +549,13 @@ export function QuizResults(p: ResultsProps) {
|
|||
<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 className="flex flex-col items-center leading-none">
|
||||
<span className="display text-[40px] font-medium">{grade}</span>
|
||||
<span className="num mt-1 text-[13px] font-medium text-ink-3">{percent}%</span>
|
||||
</div>
|
||||
</Ring>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
|
||||
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'} · grade {grade}</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">{fmtPoints(points)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
|
||||
|
|
@ -506,7 +584,7 @@ export function QuizResults(p: ResultsProps) {
|
|||
<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 className={cx('h-full rounded-full', { good: 'bg-good', warn: 'bg-warn', bad: 'bg-bad' }[gradeToneFor(pc)])} style={{ width: `${Math.max(4, pc)}%` }} />
|
||||
</div>
|
||||
<span className="num w-10 text-right text-[13px] font-medium">{pc}%</span>
|
||||
</div>
|
||||
|
|
@ -550,7 +628,7 @@ export function QuizResults(p: ResultsProps) {
|
|||
<Markdown serif className="mb-3.5 text-[17px]">
|
||||
{r.q.stem}
|
||||
</Markdown>
|
||||
<OptionList question={r.q} selected={r.selected} revealed />
|
||||
{r.q.type === 'numeric' ? <NumericAnswer question={r.q} value={r.selected[0] ?? ''} revealed /> : <OptionList question={r.q} selected={r.selected} revealed />}
|
||||
{r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && <p className="mt-2.5 text-[13px] text-ink-2">{creditDetail(r.q, r.selected, p.sataScoring)}</p>}
|
||||
{r.q.rationale && (
|
||||
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
|
||||
|
|
@ -560,10 +638,7 @@ export function QuizResults(p: ResultsProps) {
|
|||
)}
|
||||
{p.renderExtra && (
|
||||
<div className="mt-3">
|
||||
{p.renderExtra(
|
||||
r.q,
|
||||
r.q.options.filter((o) => r.selected.includes(o.id)).map((o) => o.text),
|
||||
)}
|
||||
{p.renderExtra(r.q, answerTexts(r.q, r.selected))}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue