Files
Andrew S Erwin 3fe953c14d Mobile-friendly UI: responsive shell, phone layouts, drawer navigation
The UI was desktop-first: no viewport meta (phones rendered at ~980px CSS
width, killing every breakpoint), an always-inline 240px sidebar squeezing
phone content, fixed p-6/100vh chrome, a 6-column bookmarks table, fixed
w-60/w-72 rails on collections/tags/contacts, a 12-tab settings strip that
overflowed, and w-72 kanban columns. This pass makes every screen usable on
a phone while leaving the desktop layout intact.

- layout.tsx: viewport meta (width=device-width, initial-scale=1).
- app-shell/sidebar: below lg the sidebar is an overlay drawer (closed by
  default, hamburger opens, backdrop/navigation/resize-to-desktop closes);
  at lg+ it is the static expand/collapse rail exactly as before. Separate
  mobileOpen state so closing the drawer never collapses the desktop rail.
  h-screen -> h-dvh; main p-6 -> p-3 sm:p-6.
- lib/use-media-query.ts: hydration-safe useSyncExternalStore media hook
  (server snapshot false) so surfaces swap whole layouts without duplicating
  hidden DOM that would break the suites' strict text locators.
- bookmarks: table swaps to tappable cards below sm (title/host/status/tags/
  updated + open/trash); shared trash handler; detail sheet unchanged.
- collections/tags/contacts: rails become master-detail on phones — full-width
  list first, tap into detail, Back returns; collections no longer auto-jump
  into the first item on mobile; phone padding.
- settings: tab strip scrolls horizontally (triggers shrink-0) instead of
  overflowing the page.
- kanban/collection boards: columns w-[85vw] max-w-72/64 with a peek of the
  next column; dvh heights.
- calendar: compact cells + single-letter weekday headers on phones.
- ui/dialog: max-h-[calc(100dvh-2rem)] + internal scroll + phone width guard
  so tall forms never clip; ui/tabs triggers shrink-0.
- top-bar: alerts panel fits 320px; theme/avatar collapse on the smallest
  widths; hamburger gains an accessible name.
- connector settings (MCP/WebDAV/CalDAV/CardDAV): connection rows wrap and the
  name gets a width floor — the action cluster previously squeezed the name to
  zero width on phones (a real bug the new mobile test caught).

Verification: new mobile regression suite (390x844 context) proves drawer
open/close-on-nav, bookmark cards + sheet, tags master-detail + Back,
scrollable settings tabs reaching WebDAV, kanban column fits, and zero
horizontal overflow on all eight screens; all 19 existing desktop tests still
pass (20/20). Real-stack e2e fully passing. yarn lint / SSR eslint / build:
0 errors.
2026-11-16 21:05:40 -06:00

677 lines
34 KiB
TypeScript

'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, nextUntitledTitle,
notifyActivePage, notifyPagesChanged, pageLinkMarkdown, type PageSummary,
} from '@/lib/pages'
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<PageSummary[]>([])
const [activeId, setActiveId] = useState<string | null>(initialId)
const [page, setPage] = useState<PageDetail | null>(null)
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [saveStates, setSaveStates] = useState<Record<string, PageSaveState>>({})
const [linkQuery, setLinkQuery] = useState('')
const [results, setResults] = useState<LinkedBookmark[]>([])
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<PageRevisionSummary[]>([])
const [revision, setRevision] = useState<PageRevisionDetail | null>(null)
const [historyBusy, setHistoryBusy] = useState<string | null>(null)
const editorRef = useRef<PageEditorHandle>(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])
useEffect(() => {
const timer = setTimeout(() => loadPages().then((data) => {
if (!activePage.current && data.length) { activePage.current = data[0].id; setActiveId(data[0].id) }
}).catch((e) => console.error('Failed to load pages', e)), 0)
return () => clearTimeout(timer)
}, [loadPages])
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<string, unknown>) => {
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 createPage = async () => {
if (activePage.current && !await autosave.flush(activePage.current)) return
const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: nextUntitledTitle(pages.map((p) => p.title)) }) })
if (!res.ok) { toast.error('Could not create page'); return }
const p = await res.json()
await loadPages()
notify()
select(p.id)
}
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<string>())
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<string>()
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 (
<div className="flex h-full flex-col">
{!page || page.id !== activeId ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
<FileText className="h-10 w-10 text-muted-foreground" />
<h2 className="font-display text-xl font-semibold">{pages.length ? 'Select a page' : 'No pages yet'}</h2>
<p className="max-w-sm text-sm text-muted-foreground">Pages are Markdown notes that collect links into a workspace. A bookmark can live on many pages.</p>
<Button onClick={createPage}><Plus className="mr-1 h-4 w-4" />Create a page</Button>
</div>
) : (
<div className="mx-auto w-full max-w-4xl flex-1 overflow-y-auto px-3 py-4 sm:px-6 sm:py-8">
<div className="mb-6 flex flex-wrap items-center gap-2">
<input value={title} onChange={(e) => 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" />
<span className="text-xs text-muted-foreground">{saveState === 'saving' ? 'Saving…' : saveState === 'dirty' ? 'Unsaved' : saveState === 'conflict' ? 'Conflict' : 'Saved'}</span>
{saveState === 'dirty' && <Button size="sm" variant="outline" onClick={() => autosave.flush(page.id)}>Save now</Button>}
<Button variant="ghost" size="icon-sm" title={page.pinned ? 'Unpin' : 'Pin to sidebar'} onClick={togglePin}>{page.pinned ? <PinOff className="h-4 w-4" /> : <Pin className="h-4 w-4" />}</Button>
<Button variant="ghost" size="icon-sm" title="Download .md" onClick={download}><Download className="h-4 w-4" /></Button>
<Button variant="ghost" size="icon-sm" title="Version history" onClick={() => void openHistory()}><History className="h-4 w-4" /></Button>
<Button variant="ghost" size="icon-sm" title="Move to trash" onClick={remove}><Trash2 className="h-4 w-4 text-destructive" /></Button>
</div>
<div className="mb-4 flex flex-wrap items-center gap-2 text-sm">
<label className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
<CornerUpLeft className="h-3.5 w-3.5 shrink-0" />
<span className="shrink-0">Parent</span>
<select
value={page.parentId ?? ''}
onChange={(e) => void setParent(e.target.value)}
aria-label="Parent page"
className="h-8 max-w-[16rem] rounded-md border bg-background px-2 text-sm text-foreground"
>
<option value="">Top level</option>
{parentOptions.map((p) => <option key={p.id} value={p.id}>{p.title}</option>)}
</select>
</label>
<Popover open={pageLinkOpen} onOpenChange={(open) => { setPageLinkOpen(open); if (!open) setPageLinkQuery('') }}>
<PopoverTrigger asChild><Button size="sm" variant="outline"><FileText className="mr-1 h-3.5 w-3.5" />Link a page</Button></PopoverTrigger>
<PopoverContent align="start" className="w-80 max-w-[calc(100vw-2rem)] p-2">
<Input autoFocus value={pageLinkQuery} onChange={(e) => setPageLinkQuery(e.target.value)} placeholder="Find a page to link" className="h-8 text-sm" />
<div className="mt-2 max-h-64 overflow-y-auto">
{pageLinkOptions.map((p) => (
<button key={p.id} onClick={() => { insertSnippet(pageLinkMarkdown(p)); setPageLinkOpen(false) }} className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-muted">
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate">{p.title}</span>
</button>
))}
{pageLinkOptions.length === 0 && <p className="px-2 py-3 text-center text-xs text-muted-foreground">No matching pages</p>}
</div>
</PopoverContent>
</Popover>
<Popover open={embedOpen} onOpenChange={setEmbedOpen}>
<PopoverTrigger asChild><Button size="sm" variant="outline"><Layers className="mr-1 h-3.5 w-3.5" />Embed a collection</Button></PopoverTrigger>
<PopoverContent align="start" className="w-80 max-w-[calc(100vw-2rem)] p-2">
<div className="max-h-64 overflow-y-auto">
{collections.map((c) => (
<button key={c.id} onClick={() => { insertSnippet(collectionEmbedMarkdown(c.id, c.views?.[0]?.id)); setEmbedOpen(false) }} className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-muted">
<Layers className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate">{c.name}</span>
</button>
))}
{collections.length === 0 && <p className="px-2 py-3 text-center text-xs text-muted-foreground">No collections yet. Create one from Collections first.</p>}
</div>
</PopoverContent>
</Popover>
</div>
{saveState === 'conflict' && (
<div role="alert" className="mb-4 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm">
<p className="font-medium text-foreground">This page was changed elsewhere</p>
<p className="mt-1 text-muted-foreground">
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.
</p>
<div className="mt-3 flex flex-wrap gap-2">
<Button size="sm" variant="destructive" onClick={overwriteRemote}>Overwrite with my draft</Button>
<Button size="sm" variant="outline" onClick={copyDraft}>Save my draft as a new page</Button>
<Button size="sm" variant="outline" onClick={discardDraft}>Discard my draft and load latest</Button>
</div>
</div>
)}
<PageEditor
key={page.id}
ref={editorRef}
content={content}
embeds={page.embeds}
onContentChange={onContentChange}
onNavigatePage={(id) => { void select(id) }}
onAddUrl={(url) => { void saveUrlAsBookmark(url) }}
/>
<div className="mt-10 mb-3 flex items-center justify-between">
<h3 className="font-display text-lg font-semibold">Links on this page <span className="text-sm font-normal text-muted-foreground">({page.bookmarks.length})</span></h3>
<Popover open={linkOpen} onOpenChange={setLinkOpen}>
<PopoverTrigger asChild><Button size="sm" variant="outline"><Link2 className="mr-1 h-4 w-4" />Add link</Button></PopoverTrigger>
<PopoverContent align="end" className="w-80 max-w-[calc(100vw-2rem)] p-2">
<Input autoFocus value={linkQuery} onChange={(e) => setLinkQuery(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && looksLikeUrl && addUrl()} placeholder="Search bookmarks or paste a URL" className="h-8 text-sm" />
<div className="mt-2 max-h-64 overflow-y-auto">
{looksLikeUrl && (
<button onClick={addUrl} className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-muted"><Plus className="h-3.5 w-3.5" />Save &amp; add “{linkQuery.trim()}”</button>
)}
{results.filter((r) => !page.bookmarks.some((x) => x.bookmark.id === r.id)).map((r) => (
<button key={r.id} onClick={() => addBookmark(r.id)} className="flex w-full flex-col rounded px-2 py-1.5 text-left hover:bg-muted">
<span className="truncate text-sm">{r.title || r.ogTitle || r.url}</span>
<span className="truncate text-xs text-muted-foreground">{host(r.url)}</span>
</button>
))}
{!looksLikeUrl && results.length === 0 && <p className="px-2 py-3 text-center text-xs text-muted-foreground">No matching bookmarks</p>}
</div>
</PopoverContent>
</Popover>
</div>
{page.bookmarks.length === 0 ? (
<div className="rounded-lg bg-muted/40 p-8 text-center text-sm text-muted-foreground">No links yet. Add existing bookmarks or paste a new URL.</div>
) : (
<div className="grid gap-3 sm:grid-cols-2">
{page.bookmarks.map(({ bookmark: b }) => (
<div key={b.id} className="group relative flex gap-3 rounded-lg bg-card p-3 shadow-sm ring-1 ring-border/50 transition-shadow hover:shadow-md">
{b.ogImage ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={b.ogImage} alt={`Preview of ${b.title || host(b.url)}`} referrerPolicy="no-referrer" className="h-16 w-24 shrink-0 rounded object-cover bg-muted" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }} />
) : null}
<a href={b.url} target="_blank" rel="noopener noreferrer" className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
{b.favicon && (
// eslint-disable-next-line @next/next/no-img-element
<img src={b.favicon} alt="" referrerPolicy="no-referrer" className="h-3.5 w-3.5" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }} />
)}
<span className="truncate text-sm font-medium">{b.title || b.ogTitle || b.url}</span>
</div>
<p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{b.description || b.ogDescription || ''}</p>
<p className="mt-1 text-[11px] text-muted-foreground/80">{host(b.url)}</p>
</a>
<button onClick={() => removeBookmark(b.id)} title="Remove from page" className="absolute right-1.5 top-1.5 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-muted group-hover:opacity-100"><X className="h-3.5 w-3.5" /></button>
</div>
))}
</div>
)}
{page.backlinks.length > 0 && (
<section className="mt-8" aria-label="Pages linking here">
<h3 className="mb-2 font-display text-lg font-semibold">
Linked from <span className="text-sm font-normal text-muted-foreground">({page.backlinks.length})</span>
</h3>
<div className="flex flex-wrap gap-2">
{page.backlinks.map((b) => (
<button
key={b.id}
type="button"
onClick={() => void select(b.id)}
className="flex max-w-full items-center gap-1.5 rounded-md border bg-card px-2.5 py-1.5 text-sm transition-colors hover:bg-accent"
>
<CornerUpLeft className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate">{b.title}</span>
</button>
))}
</div>
</section>
)}
</div>
)}
<Dialog open={historyOpen} onOpenChange={(open) => { setHistoryOpen(open); if (!open) setRevision(null) }}>
<DialogContent className="max-w-3xl">
<DialogHeader><DialogTitle>Version history</DialogTitle></DialogHeader>
<p className="text-xs text-muted-foreground">
Every saved content version is kept. Restoring writes a new version, so nothing in history is ever rewritten.
</p>
<div className="grid gap-3 md:grid-cols-[15rem_1fr]">
<div className="max-h-[24rem] space-y-1 overflow-y-auto rounded-md border p-1">
{revisions.map((rev) => (
<div key={rev.id} className={cn('rounded-md px-2 py-1.5', revision?.id === rev.id ? 'bg-accent' : 'hover:bg-muted')}>
<button type="button" className="flex w-full items-center justify-between gap-2 text-left" onClick={() => void viewRevision(rev.id)}>
<span className="min-w-0">
<span className="block truncate text-sm font-medium">Version {rev.version}</span>
<span className="block text-xs text-muted-foreground">{new Date(rev.createdAt).toLocaleString('en-US', { timeZone: 'UTC' })}</span>
</span>
{revisions[0]?.id === rev.id && <span className="shrink-0 text-[10px] uppercase tracking-wide text-muted-foreground">Current</span>}
</button>
<button
type="button"
disabled={historyBusy === rev.id}
onClick={() => void restoreRevision(rev)}
className="mt-1 flex items-center gap-1 text-xs text-primary hover:underline disabled:opacity-50"
>
<RotateCcw className="h-3 w-3" /> Restore
</button>
</div>
))}
{revisions.length === 0 && <p className="px-2 py-6 text-center text-xs text-muted-foreground">No saved versions yet.</p>}
</div>
<div className="max-h-[24rem] overflow-y-auto rounded-md border bg-muted/20 p-3">
{revision ? (
<>
<p className="mb-2 text-sm font-medium">{revision.title}</p>
<pre className="whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground">{revision.content || '(empty page)'}</pre>
</>
) : (
<p className="py-10 text-center text-sm text-muted-foreground">Select a version to preview it.</p>
)}
</div>
</div>
</DialogContent>
</Dialog>
</div>
)
}