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:
parent
eae109c166
commit
74a98ac1f1
52 changed files with 11976 additions and 1 deletions
347
web/src/pages/DocumentPage.tsx
Normal file
347
web/src/pages/DocumentPage.tsx
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, ChevronRight, Download, FileText, FolderInput, Layers, MessageSquare, MoreHorizontal, NotebookPen, Pencil, RefreshCw, ScanText, Share2, Sparkles, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
|
||||
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { assistant, useAssistantContext } from '@/lib/assistantStore';
|
||||
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
|
||||
import type { ClassInfo, DocChunk, DocumentInfo, Share } from '@/lib/types';
|
||||
import { cx, downloadFile, formatBytes, formatTokens, plural, useDocumentTitle } from '@/lib/util';
|
||||
import { Markdown } from '@/ui/Markdown';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, ErrorState, IconButton, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Spinner, useConfirm } from '@/ui';
|
||||
|
||||
interface Detail {
|
||||
document: DocumentInfo;
|
||||
class: ClassInfo;
|
||||
outline: { seq: number; heading: string; page: number | null }[];
|
||||
share: Share | null;
|
||||
}
|
||||
interface ChunkPage {
|
||||
chunks: DocChunk[];
|
||||
total: number;
|
||||
offset: number;
|
||||
nextOffset: number | null;
|
||||
}
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { pdf: 'PDF', docx: 'Word document', pptx: 'PowerPoint', text: 'Text', markdown: 'Markdown', image: 'Image' };
|
||||
|
||||
export default function DocumentPage() {
|
||||
const { docId = '' } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const focusChunk = Number(params.get('chunk')) || null;
|
||||
const navigate = useNavigate();
|
||||
const refresh = useRefresh();
|
||||
const confirm = useConfirm();
|
||||
const ai = useAiStatus();
|
||||
const [view, setView] = useState<'text' | 'original'>('text');
|
||||
const [rename, setRename] = useState(false);
|
||||
const [move, setMove] = useState(false);
|
||||
const [share, setShare] = useState(false);
|
||||
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
|
||||
|
||||
const q = useQuery({
|
||||
queryKey: qk.document(docId),
|
||||
queryFn: () => api.get<Detail>(`/api/documents/${docId}`),
|
||||
refetchInterval: (query) => (['pending', 'processing'].includes(query.state.data?.document.status ?? '') ? 1200 : false),
|
||||
});
|
||||
const doc = q.data?.document;
|
||||
useDocumentTitle(doc?.title);
|
||||
useAssistantContext(doc?.classId, doc?.title, doc ? [doc.id] : []);
|
||||
const ready = doc?.status === 'ready';
|
||||
|
||||
const chunks = useInfiniteQuery({
|
||||
queryKey: ['document-chunks', docId, focusChunk, doc?.updatedAt],
|
||||
queryFn: ({ pageParam }) => api.get<ChunkPage>(`/api/documents/${docId}/chunks?limit=30&${pageParam === null && focusChunk ? `around=${focusChunk}` : `offset=${pageParam ?? 0}`}`),
|
||||
initialPageParam: null as number | null,
|
||||
getNextPageParam: (last) => last.nextOffset,
|
||||
enabled: ready && (doc?.chunkCount ?? 0) > 0,
|
||||
});
|
||||
const firstOffset = chunks.data?.pages[0]?.offset ?? 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (focusChunk && chunks.data) setTimeout(() => document.getElementById(`chunk-${focusChunk}`)?.scrollIntoView({ block: 'center' }), 80);
|
||||
}, [focusChunk, chunks.data?.pages.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
if (q.isError) return <ErrorState title="Document not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!q.data || !doc) {
|
||||
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 busy = doc.status === 'pending' || doc.status === 'processing';
|
||||
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image';
|
||||
const fileUrl = `/api/documents/${doc.id}/file`;
|
||||
|
||||
const reprocess = async (ocr: boolean) => {
|
||||
try {
|
||||
await api.post(`/api/documents/${doc.id}/reprocess`, { ocr });
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const remove = async () => {
|
||||
if (!(await confirm({ title: 'Delete this document?', message: `"${doc.title}" and its uploaded file will be permanently deleted. Quizzes and cards already generated from it are kept.`, confirmLabel: 'Delete', danger: true }))) return;
|
||||
try {
|
||||
await api.del(`/api/documents/${doc.id}`);
|
||||
await refresh();
|
||||
navigate(`/classes/${doc.classId}`);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
}
|
||||
};
|
||||
const all = chunks.data?.pages.flatMap((p) => p.chunks) ?? [];
|
||||
|
||||
return (
|
||||
<div className={cx('animate-in', `tab-${cls.color}`)}>
|
||||
<nav aria-label="Breadcrumb" className="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>Document</span>
|
||||
</nav>
|
||||
|
||||
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
|
||||
<div className="min-w-0">
|
||||
<h1 className="display text-[28px] sm:text-[34px]">{doc.title}</h1>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-ink-2">
|
||||
<span>{KIND_LABEL[doc.docKind]}</span>
|
||||
{doc.pageCount ? <span>{plural(doc.pageCount, doc.docKind === 'pptx' ? 'slide' : 'page')}</span> : null}
|
||||
<span>{formatBytes(doc.size)}</span>
|
||||
{ready && doc.tokenCount > 0 && <span>about {formatTokens(doc.tokenCount)} tokens</span>}
|
||||
{q.data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="primary" icon={<Sparkles />} disabled={!ready || doc.chunkCount === 0} onClick={() => setGenerate({ documentIds: [doc.id] })}>
|
||||
Generate
|
||||
</Button>
|
||||
<Button icon={<MessageSquare />} disabled={!ready || doc.chunkCount === 0} onClick={() => assistant.open({ documentIds: [doc.id], classId: doc.classId, newChat: true })}>
|
||||
Ask
|
||||
</Button>
|
||||
<Menu
|
||||
trigger={
|
||||
<IconButton label="Document options" tooltip={false}>
|
||||
<MoreHorizontal />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{ready && doc.chunkCount > 0 && (
|
||||
<>
|
||||
<MenuItem icon={<BookOpen />} onSelect={() => setGenerate({ kind: 'quiz', documentIds: [doc.id] })}>
|
||||
Quiz from this
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', documentIds: [doc.id] })}>
|
||||
Flashcards from this
|
||||
</MenuItem>
|
||||
<MenuItem icon={<NotebookPen />} onSelect={() => setGenerate({ kind: 'note', documentIds: [doc.id] })}>
|
||||
Study guide from this
|
||||
</MenuItem>
|
||||
<MenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
|
||||
Rename
|
||||
</MenuItem>
|
||||
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
|
||||
Move
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
|
||||
Share
|
||||
</MenuItem>
|
||||
<MenuItem icon={<Download />} onSelect={() => downloadFile(`${fileUrl}?download=1`)}>
|
||||
Download original
|
||||
</MenuItem>
|
||||
<MenuItem icon={<RefreshCw />} disabled={busy} onSelect={() => reprocess(false)}>
|
||||
Read the file again
|
||||
</MenuItem>
|
||||
{(doc.docKind === 'pdf' || doc.docKind === 'image') && (
|
||||
<MenuItem icon={<ScanText />} disabled={busy || !ai.data?.ready} onSelect={() => reprocess(true)}>
|
||||
Read with AI vision
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
<MenuItem icon={<Trash2 />} danger onSelect={remove}>
|
||||
Delete
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{busy && (
|
||||
<Callout tone="accent" icon={<Spinner className="size-[18px] text-accent" />} title={doc.status === 'pending' ? 'Waiting to be read' : 'Reading the file'} className="mb-5">
|
||||
Text is being extracted and indexed for search and AI. This page updates on its own.
|
||||
<ProgressBar value={doc.progress} className="mt-2.5 max-w-sm" label="Processing" />
|
||||
</Callout>
|
||||
)}
|
||||
{doc.status === 'failed' && (
|
||||
<Callout
|
||||
tone="bad"
|
||||
icon={<TriangleAlert />}
|
||||
title="This file could not be read"
|
||||
className="mb-5"
|
||||
action={
|
||||
<Button size="sm" onClick={() => reprocess(false)}>
|
||||
Try again
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{doc.error}
|
||||
</Callout>
|
||||
)}
|
||||
{ready && doc.needsOcr && (
|
||||
<Callout
|
||||
tone="warn"
|
||||
icon={<ScanText />}
|
||||
title={doc.docKind === 'image' ? 'This image has not been read yet' : 'No selectable text was found'}
|
||||
className="mb-5"
|
||||
action={
|
||||
ai.data?.ready ? (
|
||||
<Button size="sm" variant="primary" onClick={() => reprocess(true)}>
|
||||
Read with AI
|
||||
</Button>
|
||||
) : (
|
||||
<Link to="/settings/ai">
|
||||
<Button size="sm">Set up AI</Button>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
>
|
||||
{doc.docKind === 'image' ? 'An AI model with vision can transcribe it so it becomes searchable and usable for generation.' : 'It looks like a scan. An AI model with vision and PDF support can transcribe it.'}
|
||||
</Callout>
|
||||
)}
|
||||
{ready &&
|
||||
doc.warnings
|
||||
.filter((w) => !(doc.needsOcr && /AI model/.test(w)))
|
||||
.map((w, i) => (
|
||||
<Callout key={i} tone="warn" icon={<TriangleAlert />} className="mb-3 py-2.5">
|
||||
{w}
|
||||
</Callout>
|
||||
))}
|
||||
|
||||
{hasOriginal && (
|
||||
<div className="mb-4">
|
||||
<Segmented
|
||||
label="View"
|
||||
value={view}
|
||||
onChange={setView}
|
||||
options={[
|
||||
{ value: 'text', label: 'Extracted text', icon: <FileText /> },
|
||||
{ value: 'original', label: 'Original', icon: <ScanText /> },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{view === 'original' && hasOriginal ? (
|
||||
doc.docKind === 'image' ? (
|
||||
<div className="card grid place-items-center p-4">
|
||||
<img src={fileUrl} alt={doc.title} className="max-h-[80vh] max-w-full rounded-lg" />
|
||||
</div>
|
||||
) : (
|
||||
<iframe src={fileUrl} title={doc.title} className="card h-[82vh] w-full" />
|
||||
)
|
||||
) : !ready ? null : doc.chunkCount === 0 ? (
|
||||
<div className="card">
|
||||
<EmptyState icon={<FileText />} title="No text to show">
|
||||
{doc.needsOcr ? 'Use "Read with AI" above to transcribe this file.' : 'Nothing readable was found in this file.'}
|
||||
</EmptyState>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_220px]">
|
||||
<div className="min-w-0">
|
||||
{firstOffset > 0 && <div className="mb-3 rounded-xl border border-dashed border-line-strong px-4 py-2.5 text-[13px] text-ink-3">Showing from section {firstOffset + 1}. <Link to={`/documents/${doc.id}`} className="font-medium text-accent hover:underline">Start from the beginning</Link></div>}
|
||||
<article className="card divide-y divide-line">
|
||||
{chunks.isLoading && (
|
||||
<div className="space-y-3 p-6">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
</div>
|
||||
)}
|
||||
{all.map((ch, i) => {
|
||||
const prev = all[i - 1];
|
||||
const showHeading = ch.heading && ch.heading !== prev?.heading;
|
||||
const showPage = ch.pageStart !== null && ch.pageStart !== prev?.pageStart;
|
||||
return (
|
||||
<section key={ch.id} id={`chunk-${ch.id}`} className={cx('scroll-mt-24 px-5 py-4 sm:px-8', focusChunk === ch.id && 'bg-marker/25')}>
|
||||
{(showHeading || showPage) && (
|
||||
<div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
|
||||
{showHeading ? <h2 className="display text-[19px]">{ch.heading}</h2> : <span />}
|
||||
{showPage && (
|
||||
<span className="num text-[11px] text-ink-3">
|
||||
{doc.docKind === 'pptx' ? 'Slide' : 'Page'} {ch.pageStart}
|
||||
{ch.pageEnd && ch.pageEnd !== ch.pageStart ? `–${ch.pageEnd}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Markdown className="text-[15px] text-ink">{ch.text}</Markdown>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</article>
|
||||
{chunks.hasNextPage && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button loading={chunks.isFetchingNextPage} onClick={() => chunks.fetchNextPage()}>
|
||||
Show more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{q.data.outline.length > 1 && (
|
||||
<aside className="hidden lg:block">
|
||||
<div className="sticky top-8">
|
||||
<div className="eyebrow mb-2">Outline</div>
|
||||
<ul className="max-h-[70vh] space-y-0.5 overflow-y-auto text-[13px]">
|
||||
{q.data.outline.map((o) => (
|
||||
<li key={o.seq}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
// Load forward until the section is on the page, then scroll to it.
|
||||
let pages = chunks.data?.pages ?? [];
|
||||
let guard = 0;
|
||||
while (!pages.some((p) => p.chunks.some((c) => c.seq === o.seq)) && pages[pages.length - 1]?.nextOffset !== null && guard < 40) {
|
||||
const res = await chunks.fetchNextPage();
|
||||
pages = res.data?.pages ?? [];
|
||||
guard += 1;
|
||||
}
|
||||
const hit = pages.flatMap((p) => p.chunks).find((c) => c.seq === o.seq);
|
||||
if (hit) document.getElementById(`chunk-${hit.id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
}}
|
||||
className="block w-full truncate rounded-md px-2 py-1 text-left text-ink-2 hover:bg-ink/5 hover:text-ink"
|
||||
title={o.heading}
|
||||
>
|
||||
{o.heading}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<RenameDialog target={rename ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setRename(false)} />
|
||||
<MoveDialog target={move ? { kind: 'document', id: doc.id, title: doc.title, classId: doc.classId, folderId: doc.folderId } : null} onClose={() => setMove(false)} />
|
||||
<ShareDialog target={share ? { kind: 'document', id: doc.id, title: doc.title } : null} onClose={() => setShare(false)} />
|
||||
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={doc.classId} folderId={doc.folderId} preset={generate ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue