'use client' import { useCallback, useEffect, useRef, useState } from 'react' import { useRouter } from 'next/navigation' import { toast } from 'sonner' import { CornerUpLeft, Download, FileText, History, Layers, Link2, Pin, PinOff, Plus, RotateCcw, Trash2, X, } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/utils' import { PageAutosave, PageConflictError, type PageSaveState } from '@/lib/page-autosave' import { PAGES_CHANGED, collectionEmbedMarkdown, descendantPageIds, notifyActivePage, notifyPagesChanged, pageLinkMarkdown, type PageSummary, } from '@/lib/pages' import { LibraryIndex } from '@/components/library-index' import { PageEditor, type PageEditorHandle } from '@/components/page-editor' import { type PageEmbed, type LinkedBookmark } from '@/components/page-embed-card' import { LinkPreviewCard } from '@/components/link-preview-card' export { PAGES_CHANGED } type PageBacklink = { id: string; title: string; updatedAt: string } type PageDetail = PageSummary & { content: string; version: number bookmarks: { bookmark: LinkedBookmark }[] backlinks: PageBacklink[] links: { id: string; title: string }[] embeds: PageEmbed[] } type PageRevisionSummary = { id: string; version: number; title: string; createdAt: string; length: number } type PageRevisionDetail = PageRevisionSummary & { content: string; icon: string | null } const notify = notifyPagesChanged const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } } // Canonical form for URL identity: https:// implied, host lowercased, hash // dropped, trailing slash trimmed — so a re-pasted URL matches the bookmark // already in the library instead of minting a duplicate. const normalizeUrl = (raw: string) => { const trimmed = raw.trim() const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}` try { const u = new URL(withScheme) u.hash = '' return u.toString().replace(/\/$/, '') } catch { return withScheme } } export function PagesClient({ initialId }: { initialId: string | null }) { const router = useRouter() const [pages, setPages] = useState([]) const [activeId, setActiveId] = useState(initialId) const [page, setPage] = useState(null) const [title, setTitle] = useState('') const [content, setContent] = useState('') const [saveStates, setSaveStates] = useState>({}) const [linkQuery, setLinkQuery] = useState('') const [results, setResults] = useState([]) const [linkOpen, setLinkOpen] = useState(false) const [pageLinkOpen, setPageLinkOpen] = useState(false) const [pageLinkQuery, setPageLinkQuery] = useState('') const [embedOpen, setEmbedOpen] = useState(false) const [collections, setCollections] = useState<{ id: string; name: string; icon: string | null; views?: { id: string; name: string }[] }[]>([]) const [historyOpen, setHistoryOpen] = useState(false) const [revisions, setRevisions] = useState([]) const [revision, setRevision] = useState(null) const [historyBusy, setHistoryBusy] = useState(null) const editorRef = useRef(null) const activePage = useRef(initialId) const loadSequence = useRef(0) const selectionSequence = useRef(0) // Optimistic concurrency (review DATA-01): PageAutosave tracks the server // revision per page and sends it with content saves, so a newer save from // another tab or device answers 409 instead of being silently overwritten. const persistContent = useCallback(async (id: string, content: string, version: number | undefined) => { const body = JSON.stringify(typeof version === 'number' ? { content, version } : { content }) let res: Response try { res = await fetch(`/api/pages/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body, keepalive: new TextEncoder().encode(body).length < 60000, }) } catch (error) { toast.error('Could not save page. Your draft is kept in this tab; retry saving.') throw error } if (res.status === 409) { // Another session saved first. Review DATA-04: the queue enters a // paused conflict state instead of adopting the remote version, so // nothing overwrites the newer content until the user explicitly // chooses to overwrite, discard, or copy the draft. let serverVersion: number | undefined try { const latest = await fetch(`/api/pages/${id}`, { cache: 'no-store' }).then(r => (r.ok ? r.json() : null)) if (latest && typeof latest.version === 'number') serverVersion = latest.version } catch { /* keep the stale base; the conflict state pauses autosave either way */ } toast.error('This page was saved in another tab or device. Autosave is paused so nothing is overwritten until you resolve the conflict.') throw new PageConflictError(serverVersion) } if (!res.ok) { toast.error('Could not save page. Your draft is kept in this tab; retry saving.') throw new Error('Save failed') } const saved = await res.json().catch(() => null) return saved && typeof saved.version === 'number' ? saved.version : undefined }, []) const [autosave] = useState(() => new PageAutosave(persistContent, (id, state) => setSaveStates(previous => ({ ...previous, [id]: state })))) const saveState = activeId ? saveStates[activeId] ?? 'saved' : 'saved' useEffect(() => { const beforeUnload = (event: BeforeUnloadEvent) => { if (autosave.hasUnsaved()) { event.preventDefault(); event.returnValue = '' } } const flush = () => { void autosave.flushAll() } window.addEventListener('beforeunload', beforeUnload) window.addEventListener('pagehide', flush) return () => { window.removeEventListener('beforeunload', beforeUnload) window.removeEventListener('pagehide', flush) flush() } }, [autosave]) const loadPages = useCallback(async () => { const res = await fetch('/api/pages') if (!res.ok) return [] as PageSummary[] const data: PageSummary[] = await res.json() setPages(data) return data }, []) const loadPage = useCallback(async (id: string) => { const sequence = ++loadSequence.current const res = await fetch(`/api/pages/${id}`) if (sequence !== loadSequence.current || activePage.current !== id) return if (!res.ok) { setPage(null); notifyActivePage(null); return } const data: PageDetail = await res.json() if (sequence !== loadSequence.current || activePage.current !== id) return if (typeof data.version === 'number') autosave.setVersion(data.id, data.version) // Review DATA-03: recovery compares the draft's original base version // with the freshly fetched server version; a mismatch pauses autosave in // the conflict state instead of silently rebasing onto the newer save. const draft = autosave.restore(id, data.version) setPage(data) setTitle(data.title) setContent(draft ?? data.content) notifyActivePage(data.title) // The editor is uncontrolled (TipTap owns its document): every load must // explicitly paint what the user should see — the recovered draft, or the // fresh server content after a discard — or stale text stays on screen. editorRef.current?.resetContent(draft ?? data.content) }, [autosave]) // /pages with no ?id is the Library "All pages" info view (library-index); // it must NOT auto-open the first page, or the index would never be seen. useEffect(() => { const timer = setTimeout(() => { if (activeId) loadPage(activeId).catch((e) => console.error('Failed to load page', e)) else setPage(null) }, 0) return () => clearTimeout(timer) }, [activeId, loadPage]) const select = async (id: string) => { const sequence = ++selectionSequence.current if (activePage.current && !await autosave.flush(activePage.current)) return if (sequence !== selectionSequence.current) return activePage.current = id setActiveId(id) router.replace(`/pages?id=${id}`) } // The sidebar can create or open pages while this workspace stays mounted. useEffect(() => { if (!initialId || initialId === activePage.current) return void loadPages() void select(initialId) }, [initialId]) // Sidebar mutations (rename, pin, delete) announce themselves; keep the // page list in step and drop the detail view when the open page is gone. useEffect(() => { const reload = () => { void loadPages().then((data) => { if (activePage.current && !data.some((p) => p.id === activePage.current)) { activePage.current = null setActiveId(null) setPage(null) notifyActivePage(null) router.replace('/pages') } }) } window.addEventListener(PAGES_CHANGED, reload) return () => window.removeEventListener(PAGES_CHANGED, reload) }, [loadPages, router]) // Leaving the pages workspace clears the breadcrumb title. useEffect(() => () => { notifyActivePage(null) }, []) const patch = async (body: Record) => { if (!activeId || page?.id !== activeId) return null const res = await fetch(`/api/pages/${page.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) if (!res.ok) { toast.error('Could not save page'); return null } // Review CR-17: metadata responses (rename/pin/link changes) carry the // CURRENT content revision but never require or acknowledge a content // base — adopting it here would silently rebase an in-flight stale draft // onto another editor's save and authorize overwriting it. Only content // saves (persistContent) and fresh page loads may move the version map. return res } const onContentChange = (v: string) => { if (!page || page.id !== activeId) return setContent(v) autosave.edit(page.id, v) } // Insert generated Markdown at the caret (or at the end when the editor is // not focused). The content stays the source of truth: page links and // embeds are resolved by the server from this text. const insertSnippet = (snippet: string) => { if (!page || page.id !== activeId) return editorRef.current?.insertSnippet(snippet) } const setParent = async (value: string) => { if (!page) return const parentId = value || null if (await patch({ parentId })) { setPage((current) => current?.id === page.id ? { ...current, parentId } : current) await loadPages(); notify() } } const openHistory = async () => { if (!page) return setHistoryOpen(true) setRevision(null) try { const res = await fetch(`/api/pages/${page.id}/revisions`, { cache: 'no-store' }) setRevisions(res.ok ? await res.json() : []) if (!res.ok) toast.error('Could not load page history') } catch { toast.error('Could not load page history') } } const viewRevision = async (id: string) => { if (!page) return setHistoryBusy(id) try { const res = await fetch(`/api/pages/${page.id}/revisions/${id}`, { cache: 'no-store' }) if (res.ok) setRevision(await res.json()) else toast.error('Could not load this version') } catch { toast.error('Could not load this version') } finally { setHistoryBusy(null) } } const restoreRevision = async (rev: PageRevisionSummary) => { if (!page) return if (!confirm(`Restore version ${rev.version}? The current content is kept in history.`)) return setHistoryBusy(rev.id) try { if (!await autosave.flush(page.id)) { toast.error('Resolve the unsaved draft before restoring history'); return } const latest = await fetch(`/api/pages/${page.id}`, { cache: 'no-store' }) if (!latest.ok) { toast.error('Could not reload the page'); return } const current: PageDetail = await latest.json() const res = await fetch(`/api/pages/${page.id}/revisions/${rev.id}/restore`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ version: current.version }), }) if (res.status === 409) { toast.error('The page changed elsewhere. Reload it before restoring history.') await loadPage(page.id) return } if (!res.ok) { toast.error((await res.json().catch(() => null))?.error ?? 'Could not restore this version'); return } const restored: PageDetail = await res.json() autosave.discard(page.id) autosave.setVersion(page.id, restored.version) setPage(restored) setTitle(restored.title) setContent(restored.content) editorRef.current?.resetContent(restored.content) notifyActivePage(restored.title) setHistoryOpen(false) toast.success(`Restored version ${rev.version} as version ${restored.version}`) await loadPages(); notify() } catch { toast.error('Could not restore this version') } finally { setHistoryBusy(null) } } const saveTitle = async () => { if (!page) return const t = title.trim() // Keep the generated "Untitled N" name until the user gives a real one. if (!t) { setTitle(page.title); return } if (t === page.title) return if (await patch({ title: t })) { setPage(current => current?.id === page.id ? { ...current, title: t } : current) notifyActivePage(t) await loadPages(); notify() } } const togglePin = async () => { if (!page) return if (await patch({ pinned: !page.pinned })) { setPage(current => current?.id === page.id ? { ...current, pinned: !page.pinned } : current) await loadPages(); notify() } } const download = async () => { if (!activeId) return // A paused conflict can never flush; exporting the server copy is still // useful, so only ordinary save failures block the download. if (autosave.conflictVersion(activeId) === null && !await autosave.flush(activeId)) return const a = document.createElement('a') a.href = `/api/pages/${activeId}/markdown` a.download = '' document.body.appendChild(a); a.click(); a.remove() } // Explicit conflict resolutions (review DATA-04). Typing is never consent; // each path is a deliberate click. const overwriteRemote = async () => { if (!activeId) return if (await autosave.resolveOverwrite(activeId)) toast.success('Your draft replaced the newer version') else toast.error('Could not save page. Your draft is kept in this tab; retry saving.') } const discardDraft = async () => { if (!activeId) return autosave.discard(activeId) await loadPage(activeId) } const copyDraft = async () => { const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: `${page?.title ?? 'Untitled'} (draft copy)`, content }), }) if (!res.ok) { toast.error('Could not create the copy'); return } toast.success('Draft copied to a new page') await loadPages(); notify() } const remove = async () => { if (!page || !confirm(`Move page "${page.title}" to the trash? Bookmarks are kept and it can be restored.`)) return if (!await autosave.flush(page.id)) return const res = await fetch(`/api/pages/${page.id}`, { method: 'DELETE' }) if (!res.ok) { toast.error('Could not delete page'); return } autosave.forget(page.id) const data = await loadPages(); notify() if (data.length) select(data[0].id) else { activePage.current = null; setActiveId(null); router.replace('/pages') } } useEffect(() => { if (!embedOpen) return fetch('/api/collections') .then((res) => (res.ok ? res.json() : [])) .then((data) => setCollections(Array.isArray(data) ? data : [])) .catch(() => { /* transient; reopening retries */ }) }, [embedOpen]) useEffect(() => { if (!linkOpen) return const q = linkQuery.trim() const t = setTimeout(async () => { try { const params = new URLSearchParams({ limit: '8' }) if (q) params.set('search', q) const res = await fetch(`/api/bookmarks?${params}`) if (res.ok) setResults((await res.json()).slice(0, 8)) } catch { /* transient; retried on next keystroke */ } }, 250) return () => clearTimeout(t) }, [linkQuery, linkOpen]) const addBookmark = async (bookmarkId: string) => { if (!activeId) return false if (!await autosave.flush(activeId)) return false const res = await patch({ addBookmarkId: bookmarkId }) if (!res) return false // Reflect the server's fresh link list straight from the PATCH response // (pageView carries bookmarks/backlinks/embeds). No loadPage refetch: // an attach triggered from inside the editor must never risk resetting // content and moving the caret mid-typing, and per CR-17 the metadata // response must not feed its version into autosave anyway. const updated: PageDetail | null = await res.json().catch(() => null) if (updated && updated.id === activeId) setPage(updated) setLinkOpen(false); setLinkQuery('') await loadPages() return true } // Product invariant: a URL added to a page becomes a bookmark. Reuse the // bookmark that already carries this URL — attached to the page, or in the // library (search matches url server-side) — instead of minting a duplicate. const urlInFlight = useRef(new Set()) const saveUrlAsBookmark = async (raw: string) => { if (!page || page.id !== activeId) return const url = normalizeUrl(raw) if (page.bookmarks.some((x) => normalizeUrl(x.bookmark.url) === url)) return if (urlInFlight.current.has(url)) return urlInFlight.current.add(url) try { let existingId: string | undefined try { const found = await fetch(`/api/bookmarks?search=${encodeURIComponent(url)}&limit=8`) const rows: LinkedBookmark[] = found.ok ? await found.json() : [] existingId = rows.find((r) => normalizeUrl(r.url) === url)?.id } catch { /* transient; creating a fresh bookmark is the safe fallback */ } if (existingId) { if (await addBookmark(existingId)) toast.success('Link added') return } const res = await fetch('/api/bookmarks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }) }) if (!res.ok) { toast.error('Could not save URL'); return } const created: { id: string } = await res.json() if (await addBookmark(created.id)) toast.success('Link added') } finally { urlInFlight.current.delete(url) } } const addUrl = () => { if (linkQuery.trim()) void saveUrlAsBookmark(linkQuery) } const removeBookmark = async (bookmarkId: string) => { if (await patch({ removeBookmarkId: bookmarkId })) { if (page) setPage({ ...page, bookmarks: page.bookmarks.filter((x) => x.bookmark.id !== bookmarkId) }) await loadPages() } } // Notion-style paste (see PageEditor): a bare URL lands in the document // untouched and its preview offers a titled-link upgrade — nothing is // rewritten without an explicit click, so undo stays intact. The URL still // becomes a bookmark on this page via saveUrlAsBookmark. const looksLikeUrl = /^(https?:\/\/)?[\w-]+(\.[\w-]+)+/i.test(linkQuery.trim()) // A page may move under any page except itself or one of its descendants // (the server rejects that cycle even if a stale client tries it). const blockedParents = page ? descendantPageIds(pages, page.id) : new Set() const parentOptions = page ? pages.filter((p) => p.id !== page.id && !blockedParents.has(p.id)) : [] const pageLinkOptions = pages.filter((p) => p.id !== activeId && p.title.toLowerCase().includes(pageLinkQuery.toLowerCase())) return (
{!page || page.id !== activeId ? ( ) : (
setTitle(e.target.value)} onBlur={saveTitle} onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()} className="min-w-0 flex-1 bg-transparent font-display text-3xl font-bold outline-none" aria-label="Page title" /> {saveState === 'saving' ? 'Saving…' : saveState === 'dirty' ? 'Unsaved' : saveState === 'conflict' ? 'Conflict' : 'Saved'} {saveState === 'dirty' && }
{ setPageLinkOpen(open); if (!open) setPageLinkQuery('') }}> setPageLinkQuery(e.target.value)} placeholder="Find a page to link" className="h-8 text-sm" />
{pageLinkOptions.map((p) => ( ))} {pageLinkOptions.length === 0 &&

No matching pages

}
{collections.map((c) => ( ))} {collections.length === 0 &&

No collections yet. Create one from Collections first.

}
{saveState === 'conflict' && (

This page was changed elsewhere

Your local draft is based on an older version — or its base version is unknown — so autosave is paused and nothing is overwritten until you choose. Your draft stays in the editor below.

)} { void select(id) }} onAddUrl={(url) => { void saveUrlAsBookmark(url) }} />

Links on this page ({page.bookmarks.length})

setLinkQuery(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && looksLikeUrl && addUrl()} placeholder="Search bookmarks or paste a URL" className="h-8 text-sm" />
{looksLikeUrl && ( )} {results.filter((r) => !page.bookmarks.some((x) => x.bookmark.id === r.id)).map((r) => ( ))} {!looksLikeUrl && results.length === 0 &&

No matching bookmarks

}
{page.bookmarks.length === 0 ? (
No links yet. Add existing bookmarks or paste a new URL.
) : (
{page.bookmarks.map(({ bookmark: b }) => (
{b.ogImage ? ( // eslint-disable-next-line @next/next/no-img-element {`Preview { (e.target as HTMLImageElement).style.display = 'none' }} /> ) : null}
{b.favicon && ( // eslint-disable-next-line @next/next/no-img-element { (e.target as HTMLImageElement).style.display = 'none' }} /> )} {b.title || b.ogTitle || b.url}

{b.description || b.ogDescription || ''}

{host(b.url)}

))}
)} {page.backlinks.length > 0 && (

Linked from ({page.backlinks.length})

{page.backlinks.map((b) => ( ))}
)}
)} { setHistoryOpen(open); if (!open) setRevision(null) }}> Version history

Every saved content version is kept. Restoring writes a new version, so nothing in history is ever rewritten.

{revisions.map((rev) => (
))} {revisions.length === 0 &&

No saved versions yet.

}
{revision ? ( <>

{revision.title}

{revision.content || '(empty page)'}
) : (

Select a version to preview it.

)}
) }