Add the V2 web app: design system, shell, study flows, AI, settings, sharing

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:53:01 -07:00
parent eae109c166
commit 74a98ac1f1
52 changed files with 11976 additions and 1 deletions

147
web/src/lib/api.ts Normal file
View file

@ -0,0 +1,147 @@
/** Thin client for the Study Desk API: JSON in, JSON out, typed errors, CSRF header on every call. */
export class ApiError extends Error {
status: number;
code: string;
details?: unknown;
constructor(status: number, code: string, message: string, details?: unknown) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
this.details = details;
}
}
/** Set by the app shell: called when any request comes back 401 so the login screen can appear. */
let onUnauthorized: (() => void) | null = null;
export function setUnauthorizedHandler(fn: (() => void) | null): void {
onUnauthorized = fn;
}
const BASE_HEADERS = { 'X-Requested-With': 'studydesk' };
async function toError(res: Response): Promise<ApiError> {
let code = 'http_error';
let message = res.status >= 500 ? 'The server ran into a problem. Try again in a moment.' : `Request failed (${res.status})`;
let details: unknown;
try {
const body = await res.json();
if (body?.error) {
code = body.error.code ?? code;
message = body.error.message ?? message;
details = body.error.details;
}
} catch {
/* not JSON */
}
return new ApiError(res.status, code, message, details);
}
export async function request<T>(method: string, url: string, body?: unknown, init: { signal?: AbortSignal; publicCall?: boolean } = {}): Promise<T> {
let res: Response;
try {
res = await fetch(url, {
method,
credentials: 'same-origin',
signal: init.signal,
headers: body instanceof FormData ? BASE_HEADERS : body !== undefined ? { ...BASE_HEADERS, 'Content-Type': 'application/json' } : BASE_HEADERS,
body: body instanceof FormData ? body : body !== undefined ? JSON.stringify(body) : undefined,
});
} catch (e) {
if ((e as Error)?.name === 'AbortError') throw e;
throw new ApiError(0, 'network', 'Could not reach the server. Check your connection and try again.');
}
if (!res.ok) {
const err = await toError(res);
if (res.status === 401 && !init.publicCall && err.code === 'unauthorized') onUnauthorized?.();
throw err;
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
}
export const api = {
get: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal }),
post: <T>(url: string, body?: unknown) => request<T>('POST', url, body ?? {}),
put: <T>(url: string, body?: unknown) => request<T>('PUT', url, body ?? {}),
patch: <T>(url: string, body?: unknown) => request<T>('PATCH', url, body ?? {}),
del: <T>(url: string) => request<T>('DELETE', url),
upload: <T>(url: string, form: FormData) => request<T>('POST', url, form),
/** Public (share-link) calls never trigger the login screen. */
pub: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal, publicCall: true }),
};
export function errorMessage(e: unknown, fallback = 'Something went wrong.'): string {
if (e instanceof ApiError) return e.message;
if (e instanceof Error && e.message) return e.message;
return fallback;
}
/** Uploads with progress (fetch cannot report upload progress). */
export function uploadWithProgress<T>(url: string, form: FormData, onProgress: (fraction: number) => void): Promise<T> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('X-Requested-With', 'studydesk');
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(e.loaded / e.total);
};
xhr.onerror = () => reject(new ApiError(0, 'network', 'The upload was interrupted. Check your connection and try again.'));
xhr.onload = () => {
let body: any = null;
try {
body = JSON.parse(xhr.responseText);
} catch {
/* ignore */
}
if (xhr.status >= 200 && xhr.status < 300) resolve(body as T);
else {
if (xhr.status === 401) onUnauthorized?.();
reject(new ApiError(xhr.status, body?.error?.code ?? 'http_error', body?.error?.message ?? `Upload failed (${xhr.status})`, body?.error?.details));
}
};
xhr.send(form);
});
}
/** POSTs JSON and reads a server-sent event stream of JSON objects. */
export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> {
const res = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
body: JSON.stringify(body),
signal,
});
if (!res.ok || !res.body) {
const err = await toError(res);
if (res.status === 401) onUnauthorized?.();
throw err;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let idx: number;
while ((idx = buffer.search(/\r?\n\r?\n/)) >= 0) {
const block = buffer.slice(0, idx);
buffer = buffer.slice(idx).replace(/^\r?\n\r?\n/, '');
const data = block
.split(/\r?\n/)
.filter((l) => l.startsWith('data:'))
.map((l) => l.slice(5).trimStart())
.join('\n');
if (!data) continue;
try {
const event = JSON.parse(data) as T;
if (event.type !== 'ping') onEvent(event);
} catch {
/* skip malformed event */
}
}
}
}

View file

@ -0,0 +1,67 @@
import { useEffect, useSyncExternalStore } from 'react';
export interface AssistantSeed {
id: number;
prompt?: string;
autoSend?: boolean;
newChat?: boolean;
classId?: string | null;
documentIds?: string[];
}
interface State {
open: boolean;
seed: AssistantSeed | null;
/** What the user is currently looking at; supplied by pages. */
context: { classId: string | null; documentIds: string[]; label: string };
}
let state: State = { open: false, seed: null, context: { classId: null, documentIds: [], label: '' } };
const listeners = new Set<() => void>();
const set = (patch: Partial<State>) => {
state = { ...state, ...patch };
listeners.forEach((fn) => fn());
};
let seedId = 0;
export const assistant = {
/** Opens the assistant, optionally with a prepared prompt. */
open(seed: Omit<AssistantSeed, 'id'> = {}) {
seedId += 1;
set({ open: true, seed: { id: seedId, ...seed } });
},
close() {
set({ open: false });
},
toggle() {
set({ open: !state.open });
},
consumeSeed() {
if (state.seed) set({ seed: null });
},
setContext(context: State['context']) {
const cur = state.context;
if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return;
set({ context });
},
};
export function useAssistantState(): State {
return useSyncExternalStore(
(fn) => {
listeners.add(fn);
return () => listeners.delete(fn);
},
() => state,
() => state,
);
}
/** Pages call this so the assistant knows which class or document "this" refers to. */
export function useAssistantContext(classId: string | null | undefined, label = '', documentIds: string[] = []): void {
const key = documentIds.join(',');
useEffect(() => {
assistant.setContext({ classId: classId ?? null, documentIds: key ? key.split(',') : [], label });
return () => assistant.setContext({ classId: null, documentIds: [], label: '' });
}, [classId, label, key]);
}

54
web/src/lib/queries.ts Normal file
View file

@ -0,0 +1,54 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback } from 'react';
import { api } from './api';
import type { AiModel, AiStatus, ClassDetail, ClassListItem, DeckDetail, Overview, QuizDetail } from './types';
export const qk = {
auth: ['auth'] as const,
classes: ['classes'] as const,
class: (id: string) => ['class', id] as const,
quiz: (id: string) => ['quiz', id] as const,
deck: (id: string) => ['deck', id] as const,
note: (id: string) => ['note', id] as const,
document: (id: string) => ['document', id] as const,
attempt: (id: string) => ['attempt', id] as const,
draft: (id: string) => ['draft', id] as const,
drafts: ['drafts'] as const,
overview: ['overview'] as const,
aiStatus: ['ai', 'status'] as const,
aiModels: ['ai', 'models'] as const,
aiProviders: ['ai', 'providers'] as const,
shares: ['shares'] as const,
templates: ['templates'] as const,
settings: ['settings'] as const,
};
export const useClasses = () => useQuery({ queryKey: qk.classes, queryFn: ({ signal }) => api.get<{ classes: ClassListItem[] }>('/api/classes', signal).then((r) => r.classes) });
export const useClass = (id: string | undefined, refetchInterval?: number | false) =>
useQuery({ queryKey: qk.class(id ?? ''), queryFn: ({ signal }) => api.get<ClassDetail>(`/api/classes/${id}`, signal), enabled: Boolean(id), refetchInterval });
export const useQuiz = (id: string | undefined) => useQuery({ queryKey: qk.quiz(id ?? ''), queryFn: ({ signal }) => api.get<QuizDetail>(`/api/quizzes/${id}`, signal), enabled: Boolean(id) });
export const useDeck = (id: string | undefined) => useQuery({ queryKey: qk.deck(id ?? ''), queryFn: ({ signal }) => api.get<DeckDetail>(`/api/decks/${id}`, signal), enabled: Boolean(id) });
export const useOverview = () => useQuery({ queryKey: qk.overview, queryFn: ({ signal }) => api.get<Overview>('/api/overview', signal) });
export const useAiStatus = () => useQuery({ queryKey: qk.aiStatus, queryFn: ({ signal }) => api.get<AiStatus>('/api/ai/status', signal), staleTime: 60_000 });
export const useAiModels = () => useQuery({ queryKey: qk.aiModels, queryFn: ({ signal }) => api.get<{ models: AiModel[] }>('/api/ai/models', signal).then((r) => r.models), staleTime: 60_000 });
/**
* After a change, refresh everything that could show it. The whole dataset is small and
* requests are local, so correctness beats precision here.
*/
export function useRefresh() {
const qc = useQueryClient();
return useCallback(
(...only: (readonly unknown[])[]) => {
if (only.length > 0) return Promise.all(only.map((queryKey) => qc.invalidateQueries({ queryKey })));
return qc.invalidateQueries({ predicate: (q) => q.queryKey[0] !== 'auth' && q.queryKey[0] !== 'public' });
},
[qc],
);
}

514
web/src/lib/types.ts Normal file
View file

@ -0,0 +1,514 @@
import type { Card, ClassColor, ContentDraft, Option, Question, QuestionType } from '@shared/content';
export type { Card, ClassColor, ContentDraft, Option, Question, QuestionType };
export interface ClassInfo {
id: string;
name: string;
code: string;
description: string;
color: ClassColor;
archived: boolean;
sortOrder: number;
createdAt: number;
updatedAt: number;
}
export interface ClassListItem extends ClassInfo {
counts: { quizzes: number; decks: number; documents: number; notes: number };
due: number;
}
export interface Folder {
id: string;
classId: string;
name: string;
sortOrder: number;
shared?: boolean;
}
export type ItemKind = 'quiz' | 'deck' | 'document' | 'note';
interface ItemBase {
id: string;
title: string;
description: string;
folderId: string | null;
createdAt: number;
updatedAt: number;
shared: boolean;
}
export interface QuizItem extends ItemBase {
kind: 'quiz';
questionCount: number;
attempts: number;
lastPercent: number | null;
lastStudiedAt: number | null;
activeAttemptId: string | null;
}
export interface DeckItem extends ItemBase {
kind: 'deck';
cardCount: number;
dueCount: number;
newCount: number;
learnedCount: number;
}
export interface DocumentItem extends ItemBase {
kind: 'document';
docKind: string;
filename: string;
size: number;
status: 'pending' | 'processing' | 'ready' | 'failed';
error: string;
progress: number;
pageCount: number | null;
tokenCount: number;
needsOcr: boolean;
}
export interface NoteItem extends ItemBase {
kind: 'note';
noteKind: string;
}
export type Item = QuizItem | DeckItem | DocumentItem | NoteItem;
export interface DueCounts {
learning: number;
review: number;
new: number;
total: number;
}
export interface Share {
id: string;
token: string;
enabled: boolean;
viewCount: number;
lastViewedAt: number | null;
createdAt: number;
}
export interface ClassDetail {
class: ClassInfo;
folders: Folder[];
items: Item[];
due: DueCounts;
share: Share | null;
}
export interface QuizInfo {
id: string;
classId: string;
folderId: string | null;
title: string;
description: string;
createdAt: number;
updatedAt: number;
}
export interface AttemptSummary {
id: string;
quizId: string | null;
classId: string | null;
title: string;
mode: 'practice' | 'exam';
kind: string;
status: 'active' | 'completed';
questionCount: number;
answeredCount: number;
currentIndex: number;
elapsedSec: number;
score: number | null;
maxScore: number | null;
startedAt: number;
updatedAt: number;
completedAt: number | null;
}
export interface SnapshotQuestion {
id: string;
quizId?: string | null;
quizTitle?: string;
type: QuestionType;
stem: string;
options: Option[];
rationale: string;
topic: string;
difficulty: string;
}
export interface AnswerState {
selected: string[];
checked: boolean;
at?: number;
}
export interface Attempt {
id: string;
quizId: string | null;
classId: string | null;
title: string;
mode: 'practice' | 'exam';
kind: string;
status: 'active' | 'completed';
settings: { shuffleQuestions: boolean; shuffleOptions: boolean; timeLimitSec: number | null; sataScoring: 'partial' | 'strict' };
questions: SnapshotQuestion[];
answers: Record<string, AnswerState>;
flags: string[];
currentIndex: number;
elapsedSec: number;
score: number | null;
maxScore: number | null;
startedAt: number;
updatedAt: number;
completedAt: number | null;
results: Record<string, { score: number; correct: boolean; answered: boolean }> | null;
}
export interface QuizDetail {
quiz: QuizInfo;
class: ClassInfo;
questions: Question[];
questionStats: Record<string, { seen: number; correct: number; lastCorrect: boolean }>;
history: AttemptSummary[];
activeAttempt: AttemptSummary | null;
share: Share | null;
}
export interface DeckStats {
total: number;
new: number;
learning: number;
young: number;
mature: number;
suspended: number;
dueNow: number;
}
export interface DeckDetail {
deck: QuizInfo;
class: ClassInfo;
cards: Card[];
stats: DeckStats;
due: DueCounts;
session: { state: unknown; updatedAt: number } | null;
share: Share | null;
}
export interface RatingPreview {
rating: 1 | 2 | 3 | 4;
label: string;
interval: string;
due: number;
}
export interface QueueCard {
card: Card;
deckTitle: string;
classId: string;
className: string;
classColor: ClassColor;
previews: RatingPreview[];
}
export interface DayActivity {
date: string;
cards: number;
questions: number;
total: number;
}
export interface Streak {
current: number;
longest: number;
todayDone: boolean;
todayTotal: number;
goal: number;
}
export interface TopicStat {
topic: string;
classId: string | null;
className: string;
classColor: ClassColor;
seen: number;
accuracy: number;
questions: number;
}
export interface Totals {
questionsAnswered: number;
accuracy: number | null;
cardsReviewed: number;
retention: number | null;
quizzesCompleted: number;
studyDays: number;
}
export interface AppSettings {
timezone: string;
newCardsPerDay: number;
desiredRetention: number;
sataScoring: 'partial' | 'strict';
dailyGoal: number;
}
export interface Overview {
settings: AppSettings;
due: DueCounts;
streak: Streak;
activity: DayActivity[];
activeAttempts: AttemptSummary[];
recentAttempts: AttemptSummary[];
weakTopics: TopicStat[];
missedCount: number;
totals: Totals;
forecast: number[];
}
export interface Insights {
range: number;
totals: Totals;
streak: Streak;
activity: DayActivity[];
accuracy: { date: string; answered: number; accuracy: number | null }[];
topics: TopicStat[];
forecast: number[];
due: DueCounts;
missedCount: number;
recentAttempts: AttemptSummary[];
}
export interface DocumentInfo {
id: string;
classId: string;
folderId: string | null;
title: string;
filename: string;
mime: string;
docKind: 'pdf' | 'docx' | 'pptx' | 'text' | 'markdown' | 'image';
size: number;
status: 'pending' | 'processing' | 'ready' | 'failed';
error: string;
progress: number;
pageCount: number | null;
charCount: number;
tokenCount: number;
chunkCount: number;
needsOcr: boolean;
warnings: string[];
createdAt: number;
updatedAt: number;
}
export interface DocChunk {
id: number;
seq: number;
text: string;
heading: string;
pageStart: number | null;
pageEnd: number | null;
label: string;
}
export interface NoteInfo {
id: string;
classId: string;
folderId: string | null;
title: string;
content: string;
kind: string;
source: Record<string, unknown>;
createdAt: number;
updatedAt: number;
}
export interface SearchHit {
kind: 'class' | 'quiz' | 'deck' | 'note' | 'document' | 'question' | 'card' | 'passage';
id: string;
title: string;
snippet: string;
classId: string;
className: string;
classColor: ClassColor;
parentId?: string;
page?: number | null;
}
export interface ShareListItem extends Share {
kind: 'quiz' | 'deck' | 'folder' | 'class' | 'note' | 'document';
targetId: string;
title: string;
classId: string | null;
className: string;
classColor: ClassColor;
}
/* ------------------------------ AI ------------------------------ */
export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'openai_compatible' | 'ollama';
export interface AdapterMeta {
kind: ProviderKind;
label: string;
defaultBaseUrl: string | null;
requiresApiKey: boolean;
requiresBaseUrl: boolean;
supportsDiscovery: boolean;
docsUrl: string;
keyHint: string;
}
export interface Provider {
id: string;
name: string;
kind: ProviderKind;
baseUrl: string | null;
hasKey: boolean;
keyPreview: string;
headerNames: string[];
enabled: boolean;
lastTestAt: number | null;
lastTestOk: boolean | null;
lastTestMessage: string;
createdAt: number;
}
export interface ModelCaps {
tools: boolean;
vision: boolean;
pdf: boolean;
reasoning: boolean;
temperature: boolean;
}
export interface AiModel {
id: string;
providerId: string;
providerName: string;
providerKind: ProviderKind;
model: string;
label: string;
source: string;
enabled: boolean;
available: boolean;
capabilities: ModelCaps;
contextWindow: number | null;
maxOutput: number | null;
priceIn: number | null;
priceOut: number | null;
}
export type TaskName = 'chat' | 'generate' | 'vision' | 'quick';
export interface TaskConfig {
modelId: string | null;
temperature: number | null;
reasoningEffort: 'none' | 'low' | 'medium' | 'high' | null;
maxOutputTokens: number | null;
}
export type TaskSettings = Record<TaskName | 'default', TaskConfig>;
export interface AiStatus {
ready: boolean;
modelCount: number;
tasks: TaskSettings;
resolved: Record<TaskName, { modelId: string; label: string; provider: string } | null>;
}
export interface DraftMeta {
origin?: string;
model?: string;
sources?: { documentId: string; title: string }[];
replaceQuestionIds?: string[];
targetKind?: 'quiz' | 'deck';
targetId?: string;
notes?: string[];
}
export interface Draft {
id: string;
kind: 'quiz' | 'deck' | 'note';
classId: string | null;
folderId: string | null;
title: string;
payload: ContentDraft;
meta: DraftMeta;
status: 'generating' | 'ready' | 'failed' | 'saved' | 'discarded';
progress: number;
progressLabel: string;
error: string;
savedKind: string | null;
savedId: string | null;
itemCount: number;
createdAt: number;
updatedAt: number;
}
export type DraftSummary = Omit<Draft, 'payload'>;
export type UiItem =
| { type: 'draft'; draftId: string; kind: 'quiz' | 'deck' | 'note'; title: string; count: number; status: string }
| { type: 'action'; actionId: string; summary: string; changes: string[]; status: 'pending' | 'confirmed' | 'cancelled' | 'failed'; result?: string }
| { type: 'sources'; items: { ref: string; chunkId: number; documentId: string; label: string }[] }
| { type: 'link'; kind: 'quiz' | 'deck' | 'note' | 'document' | 'class' | 'attempt'; id: string; title: string };
export interface ToolActivity {
id: string;
name: string;
label: string;
status: 'running' | 'done' | 'error';
summary?: string;
}
export interface ChatMessage {
id: number | string;
role: 'user' | 'assistant';
text: string;
tools: ToolActivity[];
ui: UiItem[];
model?: string;
error?: string;
createdAt: number;
pending?: boolean;
reasoning?: string;
}
export type AssistantEvent =
| { type: 'start'; conversationId: string; model: string }
| { type: 'text'; delta: string }
| { type: 'reasoning'; delta: string }
| { type: 'tool'; tool: ToolActivity }
| { type: 'ui'; item: UiItem }
| { type: 'error'; message: string; code: string; detail?: string }
| { type: 'done'; conversationId: string; title: string };
export interface Template {
id: string;
kind: 'quiz' | 'deck' | 'generation';
name: string;
description: string;
payload: Record<string, any>;
builtin: boolean;
updatedAt: number;
}
/* ------------------------------ public ------------------------------ */
export interface PublicQuiz {
kind: 'quiz';
id: string;
title: string;
description: string;
questions: SnapshotQuestion[];
}
export interface PublicDeck {
kind: 'deck';
id: string;
title: string;
description: string;
cards: { id: string; front: string; back: string; hint: string }[];
}
export interface PublicNote {
kind: 'note';
id: string;
title: string;
content: string;
updatedAt: number;
}
export interface PublicDocument {
kind: 'document';
id: string;
title: string;
filename: string;
docKind: string;
size: number;
pageCount: number | null;
}
export interface PublicCollection {
kind: 'collection';
title: string;
subtitle: string;
description?: string;
color: ClassColor;
folders: { id: string; name: string }[];
items: { kind: 'quiz' | 'deck' | 'note'; id: string; title: string; description: string; folderId: string | null; count: number }[];
}
export type PublicPayload = PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection;

288
web/src/lib/util.ts Normal file
View file

@ -0,0 +1,288 @@
import clsx, { type ClassValue } from 'clsx';
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
export const cx = (...v: ClassValue[]) => clsx(v);
/* ------------------------------ formatting ------------------------------ */
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
export function timeAgo(ts: number | null | undefined, nowTs = Date.now()): string {
if (!ts) return 'never';
const diff = ts - nowTs;
const abs = Math.abs(diff);
if (abs < 45_000) return 'just now';
if (abs < 3_600_000) return rtf.format(Math.round(diff / 60_000), 'minute');
if (abs < 86_400_000) return rtf.format(Math.round(diff / 3_600_000), 'hour');
if (abs < 7 * 86_400_000) return rtf.format(Math.round(diff / 86_400_000), 'day');
return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: new Date(ts).getFullYear() === new Date(nowTs).getFullYear() ? undefined : 'numeric' });
}
export function formatDate(ts: number): string {
return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
export function formatDateTime(ts: number): string {
return new Date(ts).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
}
export function formatDuration(totalSec: number): string {
const s = Math.max(0, Math.round(totalSec));
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
const sec = s % 60;
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
return `${m}:${String(sec).padStart(2, '0')}`;
}
export function formatMinutes(totalSec: number): string {
if (totalSec < 60) return `${Math.round(totalSec)}s`;
const m = Math.round(totalSec / 60);
if (m < 60) return `${m} min`;
return `${Math.floor(m / 60)}h ${m % 60}m`;
}
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)} KB`;
if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(1)} MB`;
return `${(bytes / 1073741824).toFixed(2)} GB`;
}
export function plural(n: number, one: string, many = `${one}s`): string {
return `${n.toLocaleString()} ${n === 1 ? one : many}`;
}
export function pct(score: number | null | undefined, max: number | null | undefined): number | null {
if (score === null || score === undefined || !max) return null;
return Math.round((score / max) * 100);
}
export function formatTokens(n: number | null | undefined): string {
if (!n) return '0';
if (n < 1000) return String(n);
if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`;
return `${(n / 1_000_000).toFixed(1)}M`;
}
export function formatCost(n: number | null | undefined): string {
if (n === null || n === undefined) return '—';
if (n === 0) return '$0.00';
if (n < 0.01) return '<$0.01';
return `$${n.toFixed(2)}`;
}
export function gradeTone(percent: number | null): 'good' | 'warn' | 'bad' | 'none' {
if (percent === null) return 'none';
if (percent >= 80) return 'good';
if (percent >= 60) return 'warn';
return 'bad';
}
export function downloadFile(url: string): void {
const a = document.createElement('a');
a.href = url;
a.rel = 'noopener';
a.download = '';
document.body.appendChild(a);
a.click();
a.remove();
}
export function downloadText(filename: string, text: string, mime = 'application/json'): void {
const url = URL.createObjectURL(new Blob([text], { type: mime }));
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return ok;
} catch {
return false;
}
}
}
export function shuffle<T>(items: readonly T[]): T[] {
const out = [...items];
for (let i = out.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[out[i], out[j]] = [out[j], out[i]];
}
return out;
}
/* ------------------------------ theme ------------------------------ */
export type ThemeChoice = 'light' | 'dark' | 'system';
const themeListeners = new Set<() => void>();
function readTheme(): ThemeChoice {
try {
const v = localStorage.getItem('sd.theme');
return v === 'light' || v === 'dark' ? v : 'system';
} catch {
return 'system';
}
}
function applyTheme(choice: ThemeChoice): void {
const dark = choice === 'dark' || (choice === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
}
export function setTheme(choice: ThemeChoice): void {
try {
localStorage.setItem('sd.theme', choice);
} catch {
/* private mode */
}
applyTheme(choice);
themeListeners.forEach((fn) => fn());
}
if (typeof window !== 'undefined') {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
applyTheme(readTheme());
themeListeners.forEach((fn) => fn());
});
}
export function useTheme(): [ThemeChoice, (c: ThemeChoice) => void] {
const choice = useSyncExternalStore(
(fn) => {
themeListeners.add(fn);
return () => themeListeners.delete(fn);
},
readTheme,
() => 'system' as ThemeChoice,
);
return [choice, setTheme];
}
/* ------------------------------ hooks ------------------------------ */
export function useMediaQuery(query: string): boolean {
return useSyncExternalStore(
(fn) => {
const mq = window.matchMedia(query);
mq.addEventListener('change', fn);
return () => mq.removeEventListener('change', fn);
},
() => window.matchMedia(query).matches,
() => false,
);
}
export const useIsDesktop = () => useMediaQuery('(min-width: 1024px)');
export function isTypingTarget(target: EventTarget | null): boolean {
const el = target as HTMLElement | null;
if (!el || !el.tagName) return false;
return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable;
}
/**
* Global keyboard shortcuts. Keys are matched on `event.key` (lower-cased), optionally
* prefixed with "mod+" (Ctrl or Cmd) or "shift+". Shortcuts never fire while typing
* unless they use the modifier.
*/
export function useHotkeys(map: Record<string, (e: KeyboardEvent) => void>, enabled = true): void {
const ref = useRef(map);
ref.current = map;
useEffect(() => {
if (!enabled) return;
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || e.isComposing) return;
const mod = e.metaKey || e.ctrlKey;
if (e.altKey) return;
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
const combo = `${mod ? 'mod+' : ''}${e.shiftKey && key.length > 1 ? 'shift+' : ''}${key === ' ' ? 'space' : key}`;
const handler = ref.current[combo];
if (!handler) return;
if (!mod && isTypingTarget(e.target)) return;
// Leave Enter/Space alone when a button or link has focus so it activates normally.
const tag = (e.target as HTMLElement | null)?.tagName;
if (!mod && (key === 'Enter' || key === ' ') && (tag === 'BUTTON' || tag === 'A' || tag === 'SUMMARY')) return;
if (document.querySelector('[role="dialog"][data-state="open"], [role="menu"][data-state="open"], [role="listbox"]') && !mod) {
// A dialog or menu is open: page shortcuts stay out of the way.
if (!(e.target as HTMLElement | null)?.closest('[data-hotkeys="allow"]')) return;
}
handler(e);
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [enabled]);
}
export function useDebounced<T>(value: T, ms: number): T {
const [v, setV] = useState(value);
useEffect(() => {
const t = setTimeout(() => setV(value), ms);
return () => clearTimeout(t);
}, [value, ms]);
return v;
}
export function useLocalStorage<T>(key: string, initial: T): [T, (v: T | ((prev: T) => T)) => void] {
const [value, setValue] = useState<T>(() => {
try {
const raw = localStorage.getItem(key);
return raw ? (JSON.parse(raw) as T) : initial;
} catch {
return initial;
}
});
const set = useCallback(
(v: T | ((prev: T) => T)) => {
setValue((prev) => {
const next = typeof v === 'function' ? (v as (p: T) => T)(prev) : v;
try {
localStorage.setItem(key, JSON.stringify(next));
} catch {
/* storage full or unavailable */
}
return next;
});
},
[key],
);
return [value, set];
}
export function useDocumentTitle(title: string | undefined | null): void {
useEffect(() => {
if (title) document.title = `${title} · Study Desk`;
return () => {
document.title = 'Study Desk';
};
}, [title]);
}
/** Keeps the latest callback without re-subscribing effects. */
export function useLatest<T>(value: T) {
const ref = useRef(value);
ref.current = value;
return ref;
}
export const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform ?? '');
export const modKey = isMac ? '⌘' : 'Ctrl';