release gate / check (push) Canceled after 1m2s
- Remove the auto-select-first-page effect so the Library index (filters, folder path, relative edited label, click-to-edit) is actually reachable - Edited column uses Today/Yesterday/Mon D labels computed in the fetch callback - Update mobile regression + e2e to the new /pages landing (index, not editor)
170 lines
8.0 KiB
TypeScript
170 lines
8.0 KiB
TypeScript
'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 { 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 [editedLabels, setEditedLabels] = useState<Record<string, string>>({})
|
|
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 + relative edit labels are computed here (in the fetch
|
|
// callback), not during render, so the render path stays pure and
|
|
// hydration-safe.
|
|
const now = Date.now()
|
|
const startOfToday = new Date(); startOfToday.setHours(0, 0, 0, 0)
|
|
const recent = new Set<string>()
|
|
const labels: Record<string, string> = {}
|
|
for (const p of list) {
|
|
if (!p.updatedAt) continue
|
|
const t = new Date(p.updatedAt)
|
|
if (now - t.getTime() < 2 * 24 * 60 * 60 * 1000) recent.add(p.id)
|
|
const day = new Date(t); day.setHours(0, 0, 0, 0)
|
|
const days = Math.round((startOfToday.getTime() - day.getTime()) / (24 * 60 * 60 * 1000))
|
|
labels[p.id] = days === 0 ? 'Today' : days === 1 ? 'Yesterday' : t.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
|
|
}
|
|
setRecentIds(recent)
|
|
setEditedLabels(labels)
|
|
}).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">{editedLabels[p.id] ?? '—'}</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>
|
|
)
|
|
} |