233 lines
10 KiB
TypeScript
233 lines
10 KiB
TypeScript
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<GeneratePreset | null>(null);
|
|
const loaded = useRef('');
|
|
const timer = useRef<ReturnType<typeof setTimeout> | 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 <ErrorState title="Note not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
|
if (!q.data || !note) {
|
|
return (
|
|
<div className="space-y-4">
|
|
<Skeleton className="h-5 w-40" />
|
|
<Skeleton className="h-10 w-96 max-w-full" />
|
|
<Skeleton className="h-96" />
|
|
</div>
|
|
);
|
|
}
|
|
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 (
|
|
<div className={cx('animate-in', `tab-${cls.color}`)}>
|
|
<nav aria-label="Breadcrumb" className="no-print mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
|
|
<Link to={`/classes/${cls.id}`} className="flex items-center gap-1.5 hover:text-ink">
|
|
<ClassDot color={cls.color} />
|
|
{cls.name}
|
|
</Link>
|
|
<ChevronRight className="size-3.5" />
|
|
<span>{note.kind === 'guide' ? 'Study guide' : 'Note'}</span>
|
|
</nav>
|
|
|
|
<header className="mb-5 flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
|
|
<div className="min-w-0 flex-1 basis-80">
|
|
{editing ? (
|
|
<Input value={title} onChange={(e) => 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]" />
|
|
) : (
|
|
<h1 className="display text-[28px] sm:text-[34px]">{title}</h1>
|
|
)}
|
|
<div className="no-print mt-1.5 flex flex-wrap items-center gap-2 text-[13px] text-ink-3">
|
|
<span>Edited {timeAgo(note.updatedAt)}</span>
|
|
{editing && (
|
|
<span className={cx('flex items-center gap-1', status === 'error' && 'text-bad')} aria-live="polite">
|
|
{status === 'saved' ? (
|
|
<>
|
|
<Check className="size-3.5" /> Saved
|
|
</>
|
|
) : status === 'error' ? (
|
|
'Could not save. Check your connection.'
|
|
) : (
|
|
'Saving…'
|
|
)}
|
|
</span>
|
|
)}
|
|
{q.data.share?.enabled && (
|
|
<Badge tone="accent">
|
|
<Share2 /> Shared
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<div className="no-print flex items-center gap-2">
|
|
<Segmented
|
|
label="Mode"
|
|
value={editing ? 'edit' : 'read'}
|
|
onChange={(v) => {
|
|
if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId)));
|
|
setEditing(v === 'edit');
|
|
}}
|
|
options={[
|
|
{ value: 'read', label: 'Read', icon: <Eye /> },
|
|
{ value: 'edit', label: 'Edit', icon: <Pencil /> },
|
|
]}
|
|
/>
|
|
<Menu
|
|
trigger={
|
|
<IconButton label="Note options" tooltip={false}>
|
|
<MoreHorizontal />
|
|
</IconButton>
|
|
}
|
|
>
|
|
{ai.data?.ready && content.trim().length > 40 && (
|
|
<>
|
|
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', noteId: note.id, sourceLabel: title })}>
|
|
Quiz from this note
|
|
</MenuItem>
|
|
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', noteId: note.id, sourceLabel: title })}>
|
|
Flashcards from this note
|
|
</MenuItem>
|
|
<MenuSeparator />
|
|
</>
|
|
)}
|
|
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
|
|
Move
|
|
</MenuItem>
|
|
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
|
|
Share
|
|
</MenuItem>
|
|
<MenuItem icon={<Download />} onSelect={() => downloadText(`${title.replace(/[^\w\- ]+/g, '').trim() || 'note'}.md`, `# ${title}\n\n${content}`, 'text/markdown')}>
|
|
Download as Markdown
|
|
</MenuItem>
|
|
<MenuItem icon={<Printer />} onSelect={() => (setEditing(false), setTimeout(() => window.print(), 150))}>
|
|
Print
|
|
</MenuItem>
|
|
<MenuSeparator />
|
|
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
|
|
Delete
|
|
</MenuItem>
|
|
</Menu>
|
|
</div>
|
|
</header>
|
|
|
|
{editing ? (
|
|
<div className="grid gap-4 xl:grid-cols-2">
|
|
<div>
|
|
<MarkdownArea label="Note content (Markdown)" value={content} onChange={(v) => 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]" />
|
|
<p className="mt-1.5 text-xs text-ink-3">Markdown. Paste or drop an image to embed it. Changes save automatically.</p>
|
|
</div>
|
|
<article className="card hidden max-h-[80vh] overflow-y-auto px-7 py-6 xl:block">
|
|
<div className="eyebrow mb-3 flex items-center gap-1.5">
|
|
<Eye className="size-3.5" /> Preview
|
|
</div>
|
|
<Markdown serif>{content || '*Nothing yet.*'}</Markdown>
|
|
</article>
|
|
</div>
|
|
) : content.trim() ? (
|
|
<article className="card px-5 py-6 sm:px-12 sm:py-10 print:border-0 print:p-0 print:shadow-none">
|
|
<Markdown serif className="mx-auto max-w-[70ch]">
|
|
{content}
|
|
</Markdown>
|
|
</article>
|
|
) : (
|
|
<div className="card">
|
|
<EmptyState
|
|
icon={<Sparkles />}
|
|
title="This note is empty"
|
|
action={
|
|
<Button variant="primary" icon={<Pencil />} onClick={() => setEditing(true)}>
|
|
Start writing
|
|
</Button>
|
|
}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
<MoveDialog target={move ? { kind: 'note', id: note.id, title, classId: note.classId, folderId: note.folderId } : null} onClose={() => setMove(false)} />
|
|
<ShareDialog target={share ? { kind: 'note', id: note.id, title } : null} onClose={() => setShare(false)} />
|
|
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={note.classId} folderId={note.folderId} preset={generate ?? undefined} />
|
|
</div>
|
|
);
|
|
}
|