Files
superbrain/web/components/sidebar.tsx
T
Andrew S Erwin 80c037d346
release gate / check (push) Failing after 5m27s
Library: fix folder rename (render the inline input in folder rows)
startRename set state but only page rows rendered the rename input, so
folder Rename did nothing. Folder rows now show the same inline input.
2026-12-01 08:15:35 -06:00

872 lines
40 KiB
TypeScript

'use client'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { Suspense, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
// Release version baked into the client bundle at image build time
// (web/Dockerfile ARG SUPERBRAIN_VERSION; CI passes the tag, local builds
// keep "dev"). Shown in the sidebar footer so any deployment can be
// identified from the UI alone.
const APP_VERSION = process.env.NEXT_PUBLIC_SUPERBRAIN_VERSION || ''
import { cn } from '@/lib/utils'
import { BrandIcon } from '@/components/brand-icon'
import {
Calendar, Tags, Users, Kanban, Link2, Settings, ChevronLeft, ChevronRight, ChevronDown,
FileText, Pin, PinOff, Plus, Shield, Search, MoreHorizontal, Trash2, Pencil, Layers, GripVertical, X, Sparkles, Folder,
FolderOpen, FolderPlus, Copy, FolderInput, BookOpen,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger,
} from '@/components/ui/dropdown-menu'
import { toast } from 'sonner'
import { PAGES_CHANGED, nextUntitledTitle, notifyPagesChanged, type PageSummary } from '@/lib/pages'
import { AUTOMATIONS_CHANGED, notifyAutomationsChanged } from '@/lib/automations'
import { reorderPages } from '@/lib/page-order'
// Dragging a page from "Untagged Pages" onto a tag assigns that tag. A custom
// MIME keeps this distinct from the page-reorder drag (text/plain + ref).
const PAGE_DRAG_MIME = 'application/x-superbrain-page'
type TagRow = { id: string; name: string; color: string }
type ColumnRow = { id: string; label: string; color?: string }
type CollectionRow = { id: string; name: string; icon?: string | null }
type ContactRow = { id: string; displayName: string }
type AutomationRow = { id: string; name: string; status: string; enabled: boolean; groupId?: string | null }
type AutomationGroup = { id: string; name: string }
// Status dot for the Automations dropdown: enabled tasks show their engine
// status; a disabled task is muted regardless (it will not run).
function automationDot(t: AutomationRow): string {
if (!t.enabled) return '#9ca3af'
switch (t.status) {
case 'active': return '#10b981'
case 'done': return '#9ca3af'
case 'paused': return '#f59e0b'
default: return '#ef4444'
}
}
// Section collapse state persists per browser. useSyncExternalStore keeps it
// hydration-safe (server snapshot uses the default; the client snapshot reads
// localStorage after mount) without setState inside an effect.
const SECTION_STORE_EVENT = 'superbrain:sidebar-sections'
function readSection(key: string, fallback: boolean): boolean {
try {
const stored = window.localStorage.getItem(key)
return stored === '0' || stored === '1' ? stored === '1' : fallback
} catch { return fallback }
}
function usePersistentState(key: string, initial: boolean) {
const subscribe = useCallback((onChange: () => void) => {
window.addEventListener('storage', onChange)
window.addEventListener(SECTION_STORE_EVENT, onChange)
return () => {
window.removeEventListener('storage', onChange)
window.removeEventListener(SECTION_STORE_EVENT, onChange)
}
}, [])
const getSnapshot = useCallback(() => readSection(key, initial), [key, initial])
const getServerSnapshot = useCallback(() => initial, [initial])
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
const update = useCallback((next: boolean) => {
try { window.localStorage.setItem(key, next ? '1' : '0') } catch { /* non-fatal */ }
window.dispatchEvent(new Event(SECTION_STORE_EVENT))
}, [key])
return [value, update] as const
}
interface SidebarProps {
open: boolean
// Mobile (<lg): the sidebar is an overlay drawer driven by mobileOpen;
// `open` only governs the desktop rail's expanded/collapsed width.
mobileOpen?: boolean
onToggle: () => void
onCloseMobile?: () => void
onQuickFind: () => void
pathname: string
isAdmin?: boolean
}
export function Sidebar({ open, mobileOpen = false, onToggle, onCloseMobile, onQuickFind, pathname, isAdmin = false }: SidebarProps) {
// The drawer always shows full labels; the icon-only rail is a desktop
// affordance. Below lg the aside is fixed and slides; at lg+ it is the
// static rail exactly as before.
const expanded = open || mobileOpen
return (
<aside
className={cn(
'fixed inset-y-0 left-0 z-40 flex w-60 flex-col border-r bg-[hsl(var(--sidebar))] text-[hsl(var(--sidebar-foreground))] transition-transform duration-300 ease-in-out',
'lg:static lg:z-auto lg:translate-x-0 lg:transition-all',
mobileOpen ? 'translate-x-0' : '-translate-x-full',
open ? 'lg:w-60' : 'lg:w-16'
)}
>
<div className="flex items-center gap-2 px-3 py-3">
<Link href="/pages" className="flex min-w-0 items-center gap-2">
<BrandIcon className="h-6 w-6" />
{expanded && <span className="truncate font-display text-sm font-bold tracking-tight">superbrain</span>}
</Link>
<Button variant="ghost" size="icon-sm" className="ml-auto lg:hidden" onClick={onCloseMobile} aria-label="Close navigation">
<X className="h-4 w-4" />
</Button>
</div>
{/* Quick find sits at the top of the sidebar for one-tap access. */}
<div className="px-2 pb-1">
<button
onClick={onQuickFind}
title="Quick find (Ctrl/⌘ K)"
className="flex w-full items-center gap-2 rounded-lg border border-border/60 bg-muted/40 px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<Search className="h-4 w-4 shrink-0" />
{expanded && <span className="flex-1 text-left">Quick find</span>}
{expanded && <kbd className="rounded border bg-background px-1 text-[10px] font-medium text-muted-foreground">⌘K</kbd>}
</button>
</div>
<Suspense fallback={<div className="flex-1" />}>
<SidebarNav open={expanded} pathname={pathname} isAdmin={isAdmin} />
</Suspense>
<div className="space-y-0.5 border-t p-2">
<Link
href="/settings"
className={cn(
'flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-sm transition-colors',
pathname === '/settings' ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
)}
>
<Settings className="h-4 w-4 shrink-0" />
{expanded && <span>Settings</span>}
</Link>
<Button variant="ghost" size="icon-sm" onClick={onToggle} className="hidden w-full lg:flex" aria-label={open ? 'Collapse sidebar' : 'Expand sidebar'}>
{open ? <ChevronLeft className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</Button>
{expanded && APP_VERSION && (
<p className="px-3 pt-0.5 text-[10px] text-muted-foreground/70 select-none" title={`Superbrain ${APP_VERSION}`}>
{APP_VERSION === 'dev' ? 'dev build' : `v${APP_VERSION}`}
</p>
)}
</div>
</aside>
)
}
function GroupHeader({ label, expanded, onToggle, action, action2, alwaysVisibleActions = false }: {
label: string
expanded: boolean
onToggle: () => void
action?: { label: string; onClick: () => void; icon?: React.ComponentType<{ className?: string }> }
action2?: { label: string; onClick: () => void; icon?: React.ComponentType<{ className?: string }> }
alwaysVisibleActions?: boolean
}) {
const renderAction = (a?: { label: string; onClick: () => void; icon?: React.ComponentType<{ className?: string }> }) => {
if (!a) return null
const Icon = a.icon ?? Plus
return (
<button
onClick={a.onClick}
title={a.label}
aria-label={a.label}
className={cn(
'shrink-0 rounded p-1 text-muted-foreground transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100',
alwaysVisibleActions ? 'opacity-100' : 'opacity-0 group-hover/header:opacity-100'
)}
>
<Icon className="h-3.5 w-3.5" />
</button>
)
}
return (
<div className="group/header flex items-center gap-0.5 rounded-md pr-1 hover:bg-accent/40">
<button onClick={onToggle} className="flex flex-1 items-center gap-1 px-2 py-1 text-left" aria-expanded={expanded}>
<ChevronDown className={cn('h-3 w-3 shrink-0 text-muted-foreground transition-transform', !expanded && '-rotate-90')} />
<span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{label}</span>
</button>
{renderAction(action)}
{renderAction(action2)}
</div>
)
}
// A collapsible sub-section: caret + icon + label (optionally a link) + count,
// with an indented child list when expanded.
function NavSection({ icon: Icon, label, href, expanded, onToggle, count, children }: {
icon: React.ComponentType<{ className?: string }>
label: string
href?: string
expanded: boolean
onToggle: () => void
count?: number
children?: React.ReactNode
}) {
const inner = (
<>
<Icon className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">{label}</span>
{count != null && <span className="ml-auto text-[10px] text-muted-foreground/70">{count}</span>}
</>
)
return (
<div>
<div className="flex items-center gap-1 rounded-lg pr-1 hover:bg-accent/40">
<button onClick={onToggle} aria-expanded={expanded} aria-label={`${expanded ? 'Collapse' : 'Expand'} ${label}`} className="shrink-0 rounded p-1 text-muted-foreground hover:text-foreground">
<ChevronDown className={cn('h-3 w-3 transition-transform', !expanded && '-rotate-90')} />
</button>
{href ? (
<Link href={href} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground hover:text-foreground">{inner}</Link>
) : (
<button onClick={onToggle} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground hover:text-foreground">{inner}</button>
)}
</div>
{expanded && <div className="ml-3 space-y-0.5 border-l border-border/40 pl-2">{children}</div>}
</div>
)
}
function NavLink({ href, icon: Icon, label, active }: {
href: string
icon: React.ComponentType<{ className?: string }>
label: string
active?: boolean
}) {
return (
<Link
href={href}
className={cn(
'flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm transition-colors',
active ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
)}
>
<Icon className="h-4 w-4 shrink-0" />
<span className="truncate">{label}</span>
</Link>
)
}
function ChildLink({ href, label, dot, active, onDragOver, onDragLeave, onDrop, highlight }: {
href: string
label: string
dot?: string
active?: boolean
onDragOver?: (e: React.DragEvent) => void
onDragLeave?: (e: React.DragEvent) => void
onDrop?: (e: React.DragEvent) => void
highlight?: boolean
}) {
return (
<Link
href={href}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
className={cn(
'flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground',
active && 'bg-accent/60 font-medium text-accent-foreground',
highlight && 'bg-accent/40 ring-1 ring-primary/60'
)}
>
{dot && <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: dot }} />}
<span className="truncate">{label}</span>
</Link>
)
}
function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathname: string; isAdmin?: boolean }) {
const router = useRouter()
const searchParams = useSearchParams()
const [pages, setPages] = useState<PageSummary[]>([])
const [tags, setTags] = useState<TagRow[]>([])
const [columns, setColumns] = useState<ColumnRow[]>([])
const [collections, setCollections] = useState<CollectionRow[]>([])
const [contacts, setContacts] = useState<ContactRow[]>([])
const [automations, setAutomations] = useState<AutomationRow[]>([])
const [automationGroups, setAutomationGroups] = useState<AutomationGroup[]>([])
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({})
const [newGroupName, setNewGroupName] = useState<string | null>(null)
const [pagesExpanded, setPagesExpanded] = usePersistentState('superbrain:sidebar:pages', true)
const [bookmarksExpanded, setBookmarksExpanded] = usePersistentState('superbrain:sidebar:bookmarks', true)
const [pinnedExpanded, setPinnedExpanded] = usePersistentState('superbrain:sidebar:pinned', true)
const [tagsExpanded, setTagsExpanded] = usePersistentState('superbrain:sidebar:tags', false)
const [kanbanExpanded, setKanbanExpanded] = usePersistentState('superbrain:sidebar:kanban', false)
const [collectionsExpanded, setCollectionsExpanded] = usePersistentState('superbrain:sidebar:collections', false)
const [contactsExpanded, setContactsExpanded] = usePersistentState('superbrain:sidebar:contacts', false)
const [automationsExpanded, setAutomationsExpanded] = usePersistentState('superbrain:sidebar:automations', false)
const [renamingId, setRenamingId] = useState<string | null>(null)
const [renameValue, setRenameValue] = useState('')
const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null)
const [tagDrop, setTagDrop] = useState<string | null>(null)
const [collapsedPages, setCollapsedPages] = useState<Set<string>>(() => new Set())
const draggedPageRef = useRef<string | null>(null)
const activePageId = pathname === '/pages' ? searchParams.get('id') : null
const load = useCallback(() => {
fetch('/api/pages')
.then((r) => (r.ok ? r.json() : []))
.then((d: PageSummary[]) => setPages(d ?? []))
.catch((e) => console.error('Failed to load pages', e))
}, [])
useEffect(() => {
load()
window.addEventListener(PAGES_CHANGED, load)
return () => window.removeEventListener(PAGES_CHANGED, load)
}, [load])
// The Bookmarks group's carets list live entities; load them once alongside
// pages so expanding a caret is instant.
useEffect(() => {
const get = (path: string) => fetch(path).then((r) => (r.ok ? r.json() : [])).catch(() => [])
get('/api/tags').then((d) => setTags(Array.isArray(d) ? d : []))
get('/api/kanban/columns').then((d) => setColumns(Array.isArray(d) ? d : []))
get('/api/collections').then((d) => setCollections(Array.isArray(d) ? d : []))
get('/api/contacts').then((d) => setContacts(Array.isArray(d) ? d : []))
get('/api/agent/tasks').then((d) => setAutomations(Array.isArray(d) ? d : []))
get('/api/agent/groups').then((d) => setAutomationGroups(Array.isArray(d) ? d : []))
}, [])
// The automations workspace announces creates/toggles/deletes so the
// dropdown stays live without a navigation (the pages-changed pattern).
useEffect(() => {
const reloadAutomations = () => {
fetch('/api/agent/tasks')
.then((r) => (r.ok ? r.json() : []))
.then((d) => setAutomations(Array.isArray(d) ? d : []))
.catch(() => { /* non-fatal */ })
fetch('/api/agent/groups')
.then((r) => (r.ok ? r.json() : []))
.then((d) => setAutomationGroups(Array.isArray(d) ? d : []))
.catch(() => { /* non-fatal */ })
}
window.addEventListener(AUTOMATIONS_CHANGED, reloadAutomations)
return () => window.removeEventListener(AUTOMATIONS_CHANGED, reloadAutomations)
}, [])
const createGroup = async () => {
const name = (newGroupName ?? '').trim()
setNewGroupName(null)
if (!name) return
try {
const res = await fetch('/api/agent/groups', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
})
if (!res.ok) { toast.error('Could not create group'); return }
notifyAutomationsChanged()
} catch { toast.error('Could not create group') }
}
const createPage = async (parentId?: string | null) => {
const title = nextUntitledTitle(pages.map((p) => p.title))
try {
const res = await fetch('/api/pages', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(parentId ? { title, parentId } : { title }),
})
if (!res.ok) { toast.error('Could not create page'); return }
const p = await res.json()
if (parentId) setCollapsedPages((current) => { const next = new Set(current); next.delete(parentId); return next })
notifyPagesChanged()
router.push(`/pages?id=${p.id}`)
} catch { toast.error('Could not create page') }
}
// Library folders are content-less Page rows (isFolder) reusing parentId.
const createFolder = async (parentId?: string | null) => {
try {
const res = await fetch('/api/pages', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'New folder', isFolder: true, ...(parentId ? { parentId } : {}) }),
})
if (!res.ok) { toast.error('Could not create folder'); return }
if (parentId) setCollapsedPages((current) => { const next = new Set(current); next.delete(parentId); return next })
notifyPagesChanged()
toast.success('Folder created')
} catch { toast.error('Could not create folder') }
}
const duplicatePage = async (p: PageSummary) => {
try {
const src = await fetch(`/api/pages/${p.id}`).then((r) => (r.ok ? r.json() : null))
const res = await fetch('/api/pages', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: `${p.title} (copy)`,
content: src?.content ?? '',
...(p.parentId ? { parentId: p.parentId } : {}),
}),
})
if (!res.ok) { toast.error('Could not duplicate page'); return }
const copy = await res.json()
for (const t of p.tags ?? []) {
await fetch(`/api/pages/${copy.id}/tags`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tagId: t.tag.id }) }).catch(() => {})
}
notifyPagesChanged()
toast.success('Duplicated')
} catch { toast.error('Could not duplicate page') }
}
const copyLink = (p: PageSummary) => {
const url = `${window.location.origin}/pages?id=${p.id}`
void navigator.clipboard?.writeText(url).then(() => toast.success('Link copied')).catch(() => toast.error('Could not copy link'))
}
const patchPage = async (id: string, body: Record<string, unknown>) => {
try {
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()
notifyPagesChanged()
} catch { toast.error('Could not update page') }
}
const startRename = (p: PageSummary) => {
setRenamingId(p.id)
setRenameValue(p.title)
}
const commitRename = async (p: PageSummary) => {
const t = renameValue.trim()
setRenamingId(null)
if (!t || t === p.title) return
await patchPage(p.id, { title: t })
}
const removePage = async (p: PageSummary) => {
const msg = p.isFolder
? `Move folder "${p.title}" to the trash? Its pages and subfolders are kept and moved up one level.`
: `Move page "${p.title}" to the trash? Bookmarks are kept and it can be restored.`
if (!confirm(msg)) return
try {
const res = await fetch(`/api/pages/${p.id}`, { method: 'DELETE' })
if (!res.ok) { toast.error('Could not delete'); return }
load()
notifyPagesChanged()
} catch { toast.error('Could not delete') }
}
const savePageOrder = async (next: PageSummary[]) => {
setPages(next)
try {
const res = await fetch('/api/pages', {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ order: next.map((p) => p.id) }),
})
if (!res.ok) { toast.error('Could not reorder pages'); load(); return }
notifyPagesChanged()
} catch {
toast.error('Could not reorder pages')
load()
}
}
// The source id is passed in from the drop handler (reading the ref inside
// an event handler) so the compiler does not treat this helper as reading a
// ref during render.
const dropPage = (source: string | null, target: PageSummary, after: boolean) => {
draggedPageRef.current = null
setPageDrop(null)
if (!source) return
const next = reorderPages(pages, source, target.id, after)
if (next === 'blocked') { toast.error('Pinned and unpinned pages keep separate groups'); return }
if (next) void savePageOrder(next)
}
// Drag-a-page-onto-a-tag: assign the tag, then refresh so the page leaves
// the "Untagged" list.
const assignTag = async (pageId: string, tagId: string) => {
try {
const res = await fetch(`/api/pages/${pageId}/tags`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tagId }),
})
if (!res.ok) { toast.error('Could not tag page'); return }
toast.success('Page tagged')
load()
} catch { toast.error('Could not tag page') }
}
const toggleCollapsed = (id: string) => {
setCollapsedPages((current) => {
const next = new Set(current)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
// Library tree: folders (isFolder) and pages share the parentId hierarchy.
// The server orders the list (pinned first, then position); filtering per
// parent preserves that order. Folders render as containers, pages as leaves.
const knownIds = new Set(pages.map((p) => p.id))
const parentOf = (p: PageSummary): string | null => (p.parentId && knownIds.has(p.parentId) ? p.parentId : null)
const childrenOf = (id: string | null) => pages.filter((p) => parentOf(p) === id)
const folders = pages.filter((p) => p.isFolder)
const leafPages = pages.filter((p) => !p.isFolder)
const pinnedPages = leafPages.filter((p) => p.pinned)
const pageMenu = (p: PageSummary) => (
<DropdownMenuContent align="start" className="w-48">
<DropdownMenuItem onClick={() => void duplicatePage(p)}>
<Copy className="mr-2 h-3.5 w-3.5" /> Duplicate
</DropdownMenuItem>
<DropdownMenuItem onClick={() => patchPage(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={() => copyLink(p)}>
<Link2 className="mr-2 h-3.5 w-3.5" /> Copy link
</DropdownMenuItem>
<DropdownMenuItem onClick={() => startRename(p)}>
<Pencil className="mr-2 h-3.5 w-3.5" /> Rename
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<FolderInput className="mr-2 h-3.5 w-3.5" /> Move to
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-52">
<DropdownMenuItem onClick={() => patchPage(p.id, { parentId: null })}>
<BookOpen className="mr-2 h-3.5 w-3.5" /> Library (top level)
{p.parentId === null && <span className="ml-auto text-[10px]">✓</span>}
</DropdownMenuItem>
{folders.map((f) => (
<DropdownMenuItem key={f.id} onClick={() => patchPage(p.id, { parentId: f.id })}>
<Folder className="mr-2 h-3.5 w-3.5" /> {f.title}
{p.parentId === f.id && <span className="ml-auto text-[10px]">✓</span>}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={async () => {
const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'New folder', isFolder: true }) })
if (!res.ok) { toast.error('Could not create folder'); return }
const f = await res.json()
await patchPage(p.id, { parentId: f.id })
}}>
<FolderPlus className="mr-2 h-3.5 w-3.5" /> New folder…
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => removePage(p)}>
<Trash2 className="mr-2 h-3.5 w-3.5" /> Move to trash
</DropdownMenuItem>
</DropdownMenuContent>
)
const renderPageRow = (p: PageSummary, depth: number, pinIcon = false, allowDrag = true): React.ReactNode => {
const isActive = pathname === '/pages' && activePageId === p.id
if (renamingId === p.id) {
return (
<div key={p.id} className="px-1 py-0.5" style={{ paddingLeft: depth * 12 }}>
<Input
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onBlur={() => commitRename(p)}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
if (e.key === 'Escape') setRenamingId(null)
}}
className="h-7 text-sm"
aria-label={`Rename ${p.title}`}
/>
</div>
)
}
return (
<div
key={p.id}
data-page-id={allowDrag ? p.id : undefined}
onDragOver={allowDrag ? (e) => {
if (!draggedPageRef.current || draggedPageRef.current === p.id) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
const rect = e.currentTarget.getBoundingClientRect()
setPageDrop({ id: p.id, after: e.clientY > rect.top + rect.height / 2 })
} : undefined}
onDragLeave={allowDrag ? (e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setPageDrop(null) } : undefined}
onDrop={allowDrag ? (e) => {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
dropPage(draggedPageRef.current, p, e.clientY > rect.top + rect.height / 2)
} : undefined}
style={{ paddingLeft: depth * 12 }}
className={cn('group/row flex items-center rounded-lg pr-1 transition-colors', isActive ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50', pageDrop?.id === p.id && 'ring-1 ring-primary/50')}
>
{allowDrag && (
<span
data-page-drag-handle
draggable
onDragStart={(e) => { draggedPageRef.current = p.id; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', p.id) }}
onDragEnd={() => { draggedPageRef.current = null; setPageDrop(null) }}
className="ml-1 shrink-0 cursor-grab text-muted-foreground/40 opacity-0 transition-opacity hover:text-muted-foreground active:cursor-grabbing group-hover/row:opacity-100 focus-visible:opacity-100"
title="Drag to reorder"
aria-label={`Drag ${p.title}`}
>
<GripVertical className="h-3.5 w-3.5" />
</span>
)}
<Link href={`/pages?id=${p.id}`} className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-sm">
{pinIcon || p.pinned ? <Pin className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
<span className={cn('truncate', isActive ? 'font-medium' : 'text-muted-foreground')}>{p.title}</span>
</Link>
<div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/row:opacity-100">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button title="Page actions" aria-label={`Actions for ${p.title}`} className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
<MoreHorizontal className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
{pageMenu(p)}
</DropdownMenu>
</div>
</div>
)
}
const renderFolderRow = (f: PageSummary, depth: number): React.ReactNode => {
const open = !collapsedPages.has(f.id)
const kids = childrenOf(f.id)
if (renamingId === f.id) {
return (
<div key={f.id} className="px-1 py-0.5" style={{ paddingLeft: depth * 12 }}>
<Input
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onBlur={() => commitRename(f)}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
if (e.key === 'Escape') setRenamingId(null)
}}
className="h-7 text-sm"
aria-label={`Rename folder ${f.title}`}
/>
</div>
)
}
return (
<div key={f.id}>
<div className="group/row flex items-center rounded-lg pr-1 hover:bg-accent/50" style={{ paddingLeft: depth * 12 }}>
<button type="button" onClick={() => toggleCollapsed(f.id)} aria-expanded={open} aria-label={`${open ? 'Collapse' : 'Expand'} ${f.title}`} className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
<ChevronDown className={cn('h-3 w-3 transition-transform', !open && '-rotate-90')} />
</button>
<button type="button" onClick={() => toggleCollapsed(f.id)} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground hover:text-foreground">
{open ? <FolderOpen className="h-3.5 w-3.5 shrink-0" /> : <Folder className="h-3.5 w-3.5 shrink-0" />}
<span className="truncate">{f.title}</span>
<span className="ml-auto text-[10px] text-muted-foreground/70">{kids.length}</span>
</button>
<div className="flex shrink-0 items-center opacity-0 transition-opacity focus-within:opacity-100 group-hover/row:opacity-100">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button title="Folder actions" aria-label={`Actions for ${f.title}`} className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
<MoreHorizontal className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
<DropdownMenuItem onClick={() => void createPage(f.id)}>
<Plus className="mr-2 h-3.5 w-3.5" /> New page
</DropdownMenuItem>
<DropdownMenuItem onClick={() => void createFolder(f.id)}>
<FolderPlus className="mr-2 h-3.5 w-3.5" /> New subfolder
</DropdownMenuItem>
<DropdownMenuItem onClick={() => startRename(f)}>
<Pencil className="mr-2 h-3.5 w-3.5" /> Rename
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => removePage(f)}>
<Trash2 className="mr-2 h-3.5 w-3.5" /> Move to trash
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{open && renderTree(f.id, depth + 1)}
</div>
)
}
const renderTree = (parentId: string | null, depth: number): React.ReactNode => {
const kids = childrenOf(parentId)
const subFolders = kids.filter((k) => k.isFolder)
const subPages = kids.filter((k) => !k.isFolder)
return (
<>
{subFolders.map((f) => renderFolderRow(f, depth))}
{subPages.map((p) => renderPageRow(p, depth))}
</>
)
}
// Collapsed desktop rail: a flat icon list (grouping is an expanded affordance).
if (!open) {
const rail = [
{ href: '/pages', icon: BookOpen, label: 'Library' },
{ href: '/bookmarks', icon: Link2, label: 'All Bookmarks' },
{ href: '/calendar', icon: Calendar, label: 'Calendar' },
{ href: '/tags', icon: Tags, label: 'Tags' },
{ href: '/kanban', icon: Kanban, label: 'Kanban' },
{ href: '/collections', icon: Layers, label: 'Collections' },
{ href: '/contacts', icon: Users, label: 'Contacts' },
{ href: '/automations', icon: Sparkles, label: 'Automations' },
{ href: '/trash', icon: Trash2, label: 'Trash' },
...(isAdmin ? [{ href: '/admin', icon: Shield, label: 'Admin' }] : []),
]
return (
<nav className="flex-1 space-y-0.5 overflow-y-auto p-2">
{rail.map((it) => (
<Link
key={it.href}
href={it.href}
title={it.label}
aria-label={it.label}
className={cn('flex items-center justify-center rounded-lg px-2 py-1.5', pathname === it.href ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground')}
>
<it.icon className="h-4 w-4" />
</Link>
))}
</nav>
)
}
return (
<nav className="flex-1 space-y-0.5 overflow-y-auto p-2">
<NavSection icon={Pin} label="Pinned" expanded={pinnedExpanded} onToggle={() => setPinnedExpanded(!pinnedExpanded)} count={pinnedPages.length}>
{pinnedPages.map((p) => renderPageRow(p, 0, true, false))}
{pinnedPages.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No pinned pages</p>}
</NavSection>
<GroupHeader
label="Library"
expanded={pagesExpanded}
onToggle={() => setPagesExpanded(!pagesExpanded)}
action={{ label: 'New folder', onClick: () => void createFolder(), icon: FolderPlus }}
action2={{ label: 'New page', onClick: () => void createPage() }}
alwaysVisibleActions
/>
{pagesExpanded && (
<>
<Link
href="/pages"
className={cn(
'flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm transition-colors',
pathname === '/pages' && !activePageId ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
)}
>
<BookOpen className="h-4 w-4 shrink-0" />
<span className="truncate">All pages</span>
<span className="ml-auto text-[10px] text-muted-foreground/70">{leafPages.length}</span>
</Link>
{renderTree(null, 0)}
{pages.length === 0 && <p className="px-3 py-1 text-xs text-muted-foreground/70">No pages yet</p>}
</>
)}
<div className="pt-2">
<GroupHeader label="Bookmarks" expanded={bookmarksExpanded} onToggle={() => setBookmarksExpanded(!bookmarksExpanded)} />
{bookmarksExpanded && (
<>
<NavLink href="/bookmarks" icon={Link2} label="All Bookmarks" active={pathname === '/bookmarks'} />
<NavLink href="/calendar" icon={Calendar} label="Calendar" active={pathname === '/calendar'} />
<NavSection icon={Tags} label="Tags" href="/tags" expanded={tagsExpanded} onToggle={() => setTagsExpanded(!tagsExpanded)} count={tags.length}>
{tags.map((t) => (
<ChildLink
key={t.id}
href={`/tags?tag=${t.id}`}
label={t.name}
dot={t.color}
highlight={tagDrop === t.id}
onDragOver={(e) => {
if (e.dataTransfer.types.includes(PAGE_DRAG_MIME)) {
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
setTagDrop(t.id)
}
}}
onDragLeave={() => setTagDrop(null)}
onDrop={(e) => {
const pid = e.dataTransfer.getData(PAGE_DRAG_MIME)
setTagDrop(null)
if (pid) { e.preventDefault(); void assignTag(pid, t.id) }
}}
/>
))}
{tags.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No tags yet</p>}
</NavSection>
<NavSection icon={Kanban} label="Kanban" href="/kanban" expanded={kanbanExpanded} onToggle={() => setKanbanExpanded(!kanbanExpanded)} count={columns.length}>
{columns.map((c) => (
<ChildLink key={c.id} href={`/kanban?column=${c.id}`} label={c.label} dot={c.color} />
))}
{columns.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No columns yet</p>}
</NavSection>
<NavSection icon={Layers} label="Collections" href="/collections" expanded={collectionsExpanded} onToggle={() => setCollectionsExpanded(!collectionsExpanded)} count={collections.length}>
{collections.map((c) => (
<ChildLink key={c.id} href={`/collections?id=${c.id}`} label={c.name} />
))}
{collections.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No collections yet</p>}
</NavSection>
<NavSection icon={Users} label="Contacts" href="/contacts" expanded={contactsExpanded} onToggle={() => setContactsExpanded(!contactsExpanded)} count={contacts.length}>
{contacts.map((c) => (
<ChildLink key={c.id} href={`/contacts?open=${c.id}`} label={c.displayName} />
))}
{contacts.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No contacts yet</p>}
</NavSection>
</>
)}
</div>
<div className="pt-2">
<GroupHeader label="Automations" expanded={automationsExpanded} onToggle={() => setAutomationsExpanded(!automationsExpanded)} action={{ label: 'New automation', onClick: () => router.push('/automations') }} />
{automationsExpanded && (
<>
{automationGroups.map((g) => {
const members = automations.filter((t) => t.groupId === g.id)
const isOpen = openGroups[g.id] !== false
return (
<NavSection key={g.id} icon={Folder} label={g.name} expanded={isOpen} onToggle={() => setOpenGroups((s) => ({ ...s, [g.id]: !isOpen }))} count={members.length}>
{members.map((t) => (
<ChildLink key={t.id} href={`/automations?task=${t.id}`} label={t.name} dot={automationDot(t)} active={pathname === '/automations' && searchParams.get('task') === t.id} />
))}
{members.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">Empty group</p>}
</NavSection>
)
})}
{automations.filter((t) => !t.groupId).map((t) => (
<ChildLink key={t.id} href={`/automations?task=${t.id}`} label={t.name} dot={automationDot(t)} active={pathname === '/automations' && searchParams.get('task') === t.id} />
))}
{automations.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No automations yet</p>}
{newGroupName !== null ? (
<div className="px-1 py-0.5">
<Input
autoFocus
value={newGroupName}
onChange={(e) => setNewGroupName(e.target.value)}
onBlur={createGroup}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
if (e.key === 'Escape') setNewGroupName(null)
}}
className="h-7 text-sm"
aria-label="New group name"
placeholder="Group name…"
/>
</div>
) : (
<button onClick={() => setNewGroupName('')} className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground">
<Plus className="h-3.5 w-3.5" /> New group
</button>
)}
</>
)}
</div>
<div className="pt-2">
<NavLink href="/trash" icon={Trash2} label="Trash" active={pathname === '/trash'} />
{isAdmin && <NavLink href="/admin" icon={Shield} label="Admin" active={pathname === '/admin'} />}
</div>
</nav>
)
}