import { useQuery } from '@tanstack/react-query'; import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react'; import { useEffect, useRef, useState } from 'react'; import { Link, useNavigate, useParams, useSearchParams } from 'react-router'; import { toast } from 'sonner'; import { MoveDialog, ShareDialog } from '@/features/dialogs'; import { MarkdownArea } from '@/features/editors'; import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog'; import { api, errorMessage } from '@/lib/api'; import { useAssistantContext } from '@/lib/assistantStore'; import { qk, useAiStatus, useRefresh } from '@/lib/queries'; import type { ClassInfo, NoteInfo, Share } from '@/lib/types'; import { cx, downloadText, timeAgo, useDocumentTitle } from '@/lib/util'; import { Markdown } from '@/ui/Markdown'; import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, useConfirm } from '@/ui'; export default function NotePage() { const { noteId = '' } = useParams(); const [params, setParams] = useSearchParams(); const navigate = useNavigate(); const refresh = useRefresh(); const confirm = useConfirm(); const ai = useAiStatus(); const q = useQuery({ queryKey: qk.note(noteId), queryFn: () => api.get<{ note: NoteInfo; class: ClassInfo; share: Share | null }>(`/api/notes/${noteId}`), refetchOnWindowFocus: false }); const note = q.data?.note; useDocumentTitle(note?.title); useAssistantContext(note?.classId, note?.title); const [editing, setEditing] = useState(false); const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const [status, setStatus] = useState<'saved' | 'saving' | 'dirty' | 'error'>('saved'); const [move, setMove] = useState(false); const [share, setShare] = useState(false); const [generate, setGenerate] = useState(null); const loaded = useRef(''); const timer = useRef | null>(null); const latest = useRef({ title: '', content: '' }); useEffect(() => { if (note && loaded.current !== note.id) { loaded.current = note.id; setTitle(note.title); setContent(note.content); latest.current = { title: note.title, content: note.content }; setEditing(Boolean(params.get('edit')) || note.content.trim() === ''); if (params.get('edit')) setParams({}, { replace: true }); } }, [note, params, setParams]); const saveNow = async () => { if (timer.current) clearTimeout(timer.current); timer.current = null; setStatus('saving'); try { await api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }); setStatus('saved'); } catch { setStatus('error'); } }; const change = (patch: Partial<{ title: string; content: string }>) => { latest.current = { ...latest.current, ...patch }; if (patch.title !== undefined) setTitle(patch.title); if (patch.content !== undefined) setContent(patch.content); setStatus('dirty'); if (timer.current) clearTimeout(timer.current); timer.current = setTimeout(() => void saveNow(), 900); }; useEffect( () => () => { if (timer.current) { clearTimeout(timer.current); void api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }).catch(() => undefined); } }, [noteId], ); if (q.isError) return q.refetch()} />; if (!q.data || !note) { return (
); } const cls = q.data.class; const remove = async () => { if (!(await confirm({ title: 'Delete this note?', message: `"${note.title}" will be permanently deleted.`, confirmLabel: 'Delete', danger: true }))) return; try { if (timer.current) clearTimeout(timer.current); timer.current = null; await api.del(`/api/notes/${note.id}`); await refresh(); navigate(`/classes/${note.classId}`); } catch (e) { toast.error(errorMessage(e)); } }; return (
{editing ? ( change({ title: e.target.value })} aria-label="Title" maxLength={200} className="display h-auto border-transparent bg-transparent px-0 py-1 text-[28px] shadow-none hover:border-line-strong focus:px-2 sm:text-[34px]" /> ) : (

{title}

)}
Edited {timeAgo(note.updatedAt)} {editing && ( {status === 'saved' ? ( <> Saved ) : status === 'error' ? ( 'Could not save. Check your connection.' ) : ( 'Saving…' )} )} {q.data.share?.enabled && ( Shared )}
{ if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId))); setEditing(v === 'edit'); }} options={[ { value: 'read', label: 'Read', icon: }, { value: 'edit', label: 'Edit', icon: }, ]} /> } > {ai.data?.ready && content.trim().length > 40 && ( <> } onSelect={() => setGenerate({ kind: 'quiz', noteId: note.id, sourceLabel: title })}> Quiz from this note } onSelect={() => setGenerate({ kind: 'deck', noteId: note.id, sourceLabel: title })}> Flashcards from this note )} } onSelect={() => setMove(true)}> Move } onSelect={() => setShare(true)}> Share } onSelect={() => downloadText(`${title.replace(/[^\w\- ]+/g, '').trim() || 'note'}.md`, `# ${title}\n\n${content}`, 'text/markdown')}> Download as Markdown } onSelect={() => (setEditing(false), setTimeout(() => window.print(), 150))}> Print } danger onSelect={remove}> Delete
{editing ? (
change({ content: v })} rows={22} placeholder={'Write in Markdown.\n\n## Heading\n- bullet\n**bold**, tables, and pasted images all work.'} className="[&_textarea]:min-h-[60vh] [&_textarea]:font-mono [&_textarea]:text-[13.5px]" />

Markdown. Paste or drop an image to embed it. Changes save automatically.

Preview
{content || '*Nothing yet.*'}
) : content.trim() ? (
{content}
) : (
} title="This note is empty" action={ } />
)} setMove(false)} /> setShare(false)} /> setGenerate(null)} classId={note.classId} folderId={note.folderId} preset={generate ?? undefined} />
); }