Library sidebar: folders, pinned-top, per-page menus, and an all-pages view

- Page.isFolder (migration 027): folders are content-less pages reusing
  parentId; folder delete reparents children one level up
- Sidebar: Pages group becomes Library; Pinned at top; folder tree; page
  menu (duplicate/pin/copy link/rename/move/trash); folder menu
- /pages index: filterable Library table (all/recent/pinned/untagged) with
  folder path + last edit (components/library-index.tsx)
- Docs: API.md isFolder + folder-delete semantics
This commit is contained in:
Andrew S Erwin
2026-12-01 06:07:12 -06:00
parent 50c89c1653
commit 9dbf9fa3ea
9 changed files with 541 additions and 231 deletions
+157
View File
@@ -0,0 +1,157 @@
'use client'
// Library index (the /pages "All pages" view from the library-sidebar mockup):
// a filterable table of every non-folder page with its folder path and last
// edit. Folders are content-less Page rows (isFolder) and are counted but not
// listed as documents. Client-only after mount to keep relative dates
// hydration-safe.
import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { BookOpen, FileText, Link2, MoreHorizontal, Pin, PinOff, Plus, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { toast } from 'sonner'
import { PAGES_CHANGED, type PageSummary } from '@/lib/pages'
import { SafeDate } from '@/components/safe-format'
import { useMounted } from '@/components/client-only'
import { cn } from '@/lib/utils'
type Filter = 'all' | 'recent' | 'pinned' | 'untagged'
const FILTERS: { key: Filter; label: string }[] = [
{ key: 'all', label: 'All' },
{ key: 'recent', label: 'Recent' },
{ key: 'pinned', label: 'Pinned' },
{ key: 'untagged', label: 'Untagged' },
]
export function LibraryIndex() {
const router = useRouter()
const mounted = useMounted()
const [pages, setPages] = useState<PageSummary[]>([])
const [recentIds, setRecentIds] = useState<Set<string>>(new Set())
const [filter, setFilter] = useState<Filter>('all')
const load = useCallback(() => {
fetch('/api/pages').then((r) => (r.ok ? r.json() : [])).then((d) => {
const list: PageSummary[] = Array.isArray(d) ? d : []
setPages(list)
// Recency is computed here (in the fetch callback), not during render,
// so the render path stays pure and hydration-safe.
const now = Date.now()
setRecentIds(new Set(list.filter((p) => p.updatedAt && now - new Date(p.updatedAt).getTime() < 2 * 24 * 60 * 60 * 1000).map((p) => p.id)))
}).catch(() => {})
}, [])
useEffect(() => {
load()
window.addEventListener(PAGES_CHANGED, load)
return () => window.removeEventListener(PAGES_CHANGED, load)
}, [load])
const folders = pages.filter((p) => p.isFolder)
const leaves = pages.filter((p) => !p.isFolder)
const folderById = new Map(folders.map((f) => [f.id, f]))
const folderPath = (p: PageSummary): string => {
const parts: string[] = []
let cur = p.parentId
const seen = new Set<string>()
while (cur && folderById.has(cur) && !seen.has(cur)) {
seen.add(cur)
parts.unshift(folderById.get(cur)!.title)
cur = folderById.get(cur)!.parentId
}
return parts.join(' / ')
}
const rows = leaves.filter((p) =>
filter === 'all' ? true :
filter === 'pinned' ? p.pinned :
filter === 'untagged' ? !(p.tags && p.tags.length) :
recentIds.has(p.id))
const createPage = async () => {
const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Untitled page' }) })
if (!res.ok) { toast.error('Could not create page'); return }
const p = await res.json()
window.dispatchEvent(new Event(PAGES_CHANGED))
router.push(`/pages?id=${p.id}`)
}
const patch = async (id: string, body: Record<string, unknown>) => {
const res = await fetch(`/api/pages/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
if (!res.ok) { toast.error('Could not update page'); return }
load()
window.dispatchEvent(new Event(PAGES_CHANGED))
}
const trash = async (p: PageSummary) => {
if (!confirm(`Move page "${p.title}" to the trash? Bookmarks are kept and it can be restored.`)) return
const res = await fetch(`/api/pages/${p.id}`, { method: 'DELETE' })
if (!res.ok) { toast.error('Could not delete page'); return }
load()
window.dispatchEvent(new Event(PAGES_CHANGED))
}
if (!mounted) return <div className="flex-1" />
return (
<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-3 flex items-center gap-2">
<BookOpen className="h-5 w-5 text-muted-foreground" />
<h2 className="font-display text-lg font-semibold">Library</h2>
<span className="text-xs text-muted-foreground">{leaves.length} pages · {folders.length} folders</span>
<Button size="sm" className="ml-auto" onClick={createPage}><Plus className="mr-1 h-4 w-4" />New page</Button>
</div>
<div className="mb-3 flex flex-wrap gap-1.5">
{FILTERS.map((f) => (
<button
key={f.key}
onClick={() => setFilter(f.key)}
className={cn(
'rounded-md border px-2.5 py-1 text-xs transition-colors',
filter === f.key ? 'border-primary bg-accent font-medium text-accent-foreground' : 'border-border text-muted-foreground hover:bg-accent/50'
)}
>
{f.label}
</button>
))}
</div>
<div className="grid grid-cols-[minmax(0,1fr)_110px_90px_28px] gap-2 border-b px-1 py-1.5 text-[11px] text-muted-foreground">
<span>Name</span><span>Folder</span><span>Edited</span><span />
</div>
{rows.length === 0 ? (
<p className="px-1 py-4 text-sm text-muted-foreground">No pages match this filter.</p>
) : rows.map((p) => (
<div key={p.id} className="grid grid-cols-[minmax(0,1fr)_110px_90px_28px] items-center gap-2 border-b px-1 py-2 text-sm">
<button onClick={() => router.push(`/pages?id=${p.id}`)} className="flex min-w-0 items-center gap-1.5 text-left hover:underline">
{p.pinned && <Pin className="h-3 w-3 shrink-0 text-muted-foreground" />}
<span className="truncate">{p.title}</span>
{(p.tags ?? []).map((t) => (
<span key={t.tag.id} className="shrink-0 rounded px-1.5 text-[10px]" style={{ backgroundColor: `${t.tag.color}22`, color: t.tag.color }}>{t.tag.name}</span>
))}
</button>
<span className="truncate text-xs text-muted-foreground">{folderPath(p) || '—'}</span>
<span className="text-xs text-muted-foreground">{p.updatedAt ? <SafeDate date={p.updatedAt} localize /> : '—'}</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button aria-label={`Actions for ${p.title}`} className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"><MoreHorizontal className="h-4 w-4" /></button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem onClick={() => router.push(`/pages?id=${p.id}`)}><FileText className="mr-2 h-3.5 w-3.5" />Open</DropdownMenuItem>
<DropdownMenuItem onClick={() => patch(p.id, { pinned: !p.pinned })}>{p.pinned ? <PinOff className="mr-2 h-3.5 w-3.5" /> : <Pin className="mr-2 h-3.5 w-3.5" />}{p.pinned ? 'Unpin' : 'Pin'}</DropdownMenuItem>
<DropdownMenuItem onClick={() => { void navigator.clipboard?.writeText(`${window.location.origin}/pages?id=${p.id}`); toast.success('Link copied') }}><Link2 className="mr-2 h-3.5 w-3.5" />Copy link</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => trash(p)}><Trash2 className="mr-2 h-3.5 w-3.5" />Move to trash</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))}
</div>
)
}