'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 ( 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 ( ) } function GroupHeader({ label, expanded, onToggle, action, action2 }: { 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 }> } }) { const renderAction = (a?: { label: string; onClick: () => void; icon?: React.ComponentType<{ className?: string }> }) => { if (!a) return null const Icon = a.icon ?? Plus return ( ) } return (
{renderAction(action)} {renderAction(action2)}
) } // 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 = ( <> {label} {count != null && {count}} ) return (
{href ? ( {inner} ) : ( )}
{expanded &&
{children}
}
) } function NavLink({ href, icon: Icon, label, active }: { href: string icon: React.ComponentType<{ className?: string }> label: string active?: boolean }) { return ( {label} ) } 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 ( {dot && } {label} ) } function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathname: string; isAdmin?: boolean }) { const router = useRouter() const searchParams = useSearchParams() const [pages, setPages] = useState([]) const [tags, setTags] = useState([]) const [columns, setColumns] = useState([]) const [collections, setCollections] = useState([]) const [contacts, setContacts] = useState([]) const [automations, setAutomations] = useState([]) const [automationGroups, setAutomationGroups] = useState([]) const [openGroups, setOpenGroups] = useState>({}) const [newGroupName, setNewGroupName] = useState(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(null) const [renameValue, setRenameValue] = useState('') const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null) const [tagDrop, setTagDrop] = useState(null) const [collapsedPages, setCollapsedPages] = useState>(() => new Set()) const draggedPageRef = useRef(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) => { 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) => ( void duplicatePage(p)}> Duplicate patchPage(p.id, { pinned: !p.pinned })}> {p.pinned ? : } {p.pinned ? 'Unpin' : 'Pin'} copyLink(p)}> Copy link startRename(p)}> Rename Move to patchPage(p.id, { parentId: null })}> Library (top level) {p.parentId === null && ✓} {folders.map((f) => ( patchPage(p.id, { parentId: f.id })}> {f.title} {p.parentId === f.id && ✓} ))} { 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 }) }}> New folder… removePage(p)}> Move to trash ) const renderPageRow = (p: PageSummary, depth: number, pinIcon = false, allowDrag = true): React.ReactNode => { const isActive = pathname === '/pages' && activePageId === p.id if (renamingId === p.id) { return (
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}`} />
) } return (
{ 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 && ( { 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}`} > )} {pinIcon || p.pinned ? : } {p.title}
{pageMenu(p)}
) } const renderFolderRow = (f: PageSummary, depth: number): React.ReactNode => { const open = !collapsedPages.has(f.id) const kids = childrenOf(f.id) return (
void createPage(f.id)}> New page void createFolder(f.id)}> New subfolder startRename(f)}> Rename removePage(f)}> Move to trash
{open && renderTree(f.id, depth + 1)}
) } 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 ( ) } return ( ) }