Files
superbrain/web/components/sidebar.tsx
T
Andrew S Erwin 060a8115ec Automations workspace phase 1: sidebar groups, detail view, recompile-to-edit, named runs
Promotes Automations to a top-level sidebar group (below Bookmarks) with
user-defined AgentGroup folders (migration 025, FK SET NULL on delete).
The /automations page becomes master-detail: overview (composer + grouped
list + named global runs) and per-task detail (original prompt, group
assignment, run-now/pause/delete, per-task run timeline with true/false/
error pills). Editing recompiles through /api/agent/compile and confirms
the proposal before a versioned PATCH applies spec+prompt — the model
never writes. Tasks store prompt+groupId; projections add runCount/
errorCount; runs carry taskName. The engine is untouched: groups/prompt
are metadata, the validated spec remains the only thing it executes.
Chaining, refinements and dry-run stay phase 2.

Verified: full DB integration suite under -race, db-converge + migration
atomicity, web lint/SSR/build, and a rewritten browser regression covering
the sidebar folder, detail prompt, per-task runs, recompile-to-edit and
named global runs.
2026-11-25 14:16:45 -06:00

781 lines
37 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,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
} 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 }: {
label: string
expanded: boolean
onToggle: () => void
action?: { label: string; onClick: () => void }
}) {
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>
{action && (
<button
onClick={action.onClick}
title={action.label}
aria-label={action.label}
className="shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/header:opacity-100 focus-visible:opacity-100"
>
<Plus className="h-3.5 w-3.5" />
</button>
)}
</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 [allPagesExpanded, setAllPagesExpanded] = usePersistentState('superbrain:sidebar:allpages', true)
const [pinnedExpanded, setPinnedExpanded] = usePersistentState('superbrain:sidebar:pinned', false)
const [untaggedExpanded, setUntaggedExpanded] = usePersistentState('superbrain:sidebar:untagged', false)
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') }
}
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) => {
if (!confirm(`Move page "${p.title}" to the trash? Bookmarks are kept and it can be restored.`)) return
try {
const res = await fetch(`/api/pages/${p.id}`, { method: 'DELETE' })
if (!res.ok) { toast.error('Could not delete page'); return }
load()
notifyPagesChanged()
} catch { toast.error('Could not delete page') }
}
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
})
}
// Flatten the owner's page tree for display. The server already orders the
// list (pinned first, then position); preserving that order per parent keeps
// pinned pages predictable while nested children follow their parent.
const pageRows: { page: PageSummary; depth: number; hasChildren: boolean }[] = []
{
const known = new Set(pages.map((p) => p.id))
const byParent = new Map<string | null, PageSummary[]>()
for (const p of pages) {
const key = p.parentId && known.has(p.parentId) ? p.parentId : null
const list = byParent.get(key) ?? []
list.push(p)
byParent.set(key, list)
}
const visited = new Set<string>()
const visit = (parent: string | null, depth: number) => {
for (const p of byParent.get(parent) ?? []) {
if (visited.has(p.id)) continue
visited.add(p.id)
const children = byParent.get(p.id) ?? []
pageRows.push({ page: p, depth, hasChildren: children.length > 0 })
if (!collapsedPages.has(p.id)) visit(p.id, depth + 1)
}
}
visit(null, 0)
// Defensive: a corrupt/cyclic pre-existing hierarchy must still render
// every page once rather than disappear from the sidebar.
for (const p of pages) {
if (!visited.has(p.id)) pageRows.push({ page: p, depth: 0, hasChildren: (byParent.get(p.id) ?? []).length > 0 })
}
}
const pinnedPages = pages.filter((p) => p.pinned)
const untaggedPages = pages.filter((p) => !(p.tags && p.tags.length))
// Collapsed desktop rail: a flat icon list (grouping is an expanded affordance).
if (!open) {
const rail = [
{ href: '/pages', icon: FileText, label: 'Pages' },
{ 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">
<GroupHeader label="Pages" expanded={pagesExpanded} onToggle={() => setPagesExpanded(!pagesExpanded)} action={{ label: 'New page', onClick: () => void createPage() }} />
{pagesExpanded && (
<>
<NavSection icon={FileText} label="All Pages" href="/pages" expanded={allPagesExpanded} onToggle={() => setAllPagesExpanded(!allPagesExpanded)} count={pages.length}>
{pageRows.map(({ page: p, depth, hasChildren }) => {
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 page ${p.title}`}
/>
</div>
)
}
return (
<div
key={p.id}
data-page-id={p.id}
onDragOver={(e) => {
// Event handler, not render: reading the drag source is safe.
// eslint-disable-next-line react-hooks/refs
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 })
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setPageDrop(null)
}}
onDrop={(e) => {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
// Event handler, not render: reading the drag source is safe.
// eslint-disable-next-line react-hooks/refs
dropPage(draggedPageRef.current, p, e.clientY > rect.top + rect.height / 2)
}}
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'
)}
>
{hasChildren ? (
<button
type="button"
onClick={() => toggleCollapsed(p.id)}
aria-label={collapsedPages.has(p.id) ? `Expand ${p.title}` : `Collapse ${p.title}`}
aria-expanded={!collapsedPages.has(p.id)}
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', collapsedPages.has(p.id) && '-rotate-90')} />
</button>
) : <span className="w-4 shrink-0" aria-hidden />}
<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 page"
aria-label={`Drag page ${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">
{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">
<button
onClick={() => void createPage(p.id)}
title="New subpage"
aria-label={`New subpage under ${p.title}`}
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
>
<Plus className="h-3.5 w-3.5" />
</button>
<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>
<DropdownMenuContent align="start" className="w-44">
<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 to sidebar'}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => startRename(p)}>
<Pencil className="mr-2 h-3.5 w-3.5" />
Rename
</DropdownMenuItem>
<DropdownMenuItem onClick={() => void createPage(p.id)}>
<Plus className="mr-2 h-3.5 w-3.5" />
New subpage
</DropdownMenuItem>
{p.parentId && (
<DropdownMenuItem onClick={() => patchPage(p.id, { parentId: null })}>
<ChevronRight className="mr-2 h-3.5 w-3.5" />
Move to top level
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => removePage(p)}>
<Trash2 className="mr-2 h-3.5 w-3.5" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)
})}
{pages.length === 0 && <p className="px-3 py-1 text-xs text-muted-foreground/70">No pages yet</p>}
</NavSection>
<NavSection icon={Pin} label="Pinned Pages" expanded={pinnedExpanded} onToggle={() => setPinnedExpanded(!pinnedExpanded)} count={pinnedPages.length}>
{pinnedPages.map((p) => (
<ChildLink key={p.id} href={`/pages?id=${p.id}`} label={p.title} active={pathname === '/pages' && activePageId === p.id} />
))}
{pinnedPages.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No pinned pages</p>}
</NavSection>
<NavSection icon={FileText} label="Untagged Pages" expanded={untaggedExpanded} onToggle={() => setUntaggedExpanded(!untaggedExpanded)} count={untaggedPages.length}>
{untaggedPages.map((p) => (
<div
key={p.id}
draggable
onDragStart={(e) => {
e.dataTransfer.setData(PAGE_DRAG_MIME, p.id)
e.dataTransfer.effectAllowed = 'copy'
}}
className="group/un flex cursor-grab items-center rounded-md active:cursor-grabbing"
title={`Drag ${p.title} onto a tag to tag it`}
>
<GripVertical className="h-3 w-3 shrink-0 text-muted-foreground/40 opacity-0 group-hover/un:opacity-100" />
<Link href={`/pages?id=${p.id}`} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1 text-sm text-muted-foreground hover:text-foreground">
<FileText className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">{p.title}</span>
</Link>
</div>
))}
{untaggedPages.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">Every page has a tag</p>}
</NavSection>
</>
)}
<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>
)
}