# All files / src/components Sidebar.tsx

68.79% Statements 97/141
52.43% Branches 43/82
70.37% Functions 38/54
70.75% Lines 75/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332

    2x

    16x

    261x
    138x
    5x
    1x

    5x
    5x

    64x
    254x
    64x

    64x
    512x
    512x

    64x
    254x
    4x
    8x

    64x
    1056x
    1056x
    1056x

    87x
    87x
    64x
    64x
    64x

    552x
    545x
    87x

    87x
    64x
    64x
    254x

    254x

    64x

    728x
    3766x
    728x

    728x

    12x

    87x
    34x

    87x

    87x

    87x

    2x

    87x
    87x
    87x
    87x
    87x

    87x
    87x
    87x

    87x
    87x
    87x

    87x
    87x
    87x

    87x
    87x
    87x

    87x
    12x

    87x

    87x

    87x

    87x

    87x

    87x

    1x

    5x

    699x

     import { useState, useMemo, useRef, useEffect, useCallback, memo } from 'react'
    import type { VaultEntry, SidebarSelection } from '../types'
    import { resolveIcon } from '../utils/iconRegistry'
    import { TypeCustomizePopover } from './TypeCustomizePopover'
    import { useSectionVisibility } from '../hooks/useSectionVisibility'
    import {
      DndContext, closestCenter, KeyboardSensor, PointerSensor,
      useSensor, useSensors, type DragEndEvent,
    } from '@dnd-kit/core'
    import {
      SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy,
    } from '@dnd-kit/sortable'
    import { CSS } from '@dnd-kit/utilities'
    import {
      FileText, Star, Wrench, Flask, Target, ArrowsClockwise,
      Users, CalendarBlank, Tag, TagSimple, Trash, StackSimple, Archive, CaretLeft, GitDiff,
    } from '@phosphor-icons/react'
    import { GitCommitHorizontal, SlidersHorizontal } from 'lucide-react'
    import {
      type SectionGroup, isSelectionActive,
      NavItem, SectionContent, type SectionContentProps, VisibilityPopover,
    } from './SidebarParts'

    interface SidebarProps {
      entries: VaultEntry[]
      selection: SidebarSelection
      onSelect: (selection: SidebarSelection) => void
      onSelectNote?: (entry: VaultEntry) => void
      onCreateType?: (type: string) => void
      onCreateNewType?: () => void
      onCustomizeType?: (typeName: string, icon: string, color: string) => void
      onReorderSections?: (orderedTypes: { typeName: string; order: number }[]) => void
      modifiedCount?: number
      onCommitPush?: () => void
      onCollapse?: () => void
    }

    const BUILT_IN_SECTION_GROUPS: SectionGroup[] = [
      { label: 'Projects', type: 'Project', Icon: Wrench },
      { label: 'Experiments', type: 'Experiment', Icon: Flask },
      { label: 'Responsibilities', type: 'Responsibility', Icon: Target },
      { label: 'Procedures', type: 'Procedure', Icon: ArrowsClockwise },
      { label: 'People', type: 'Person', Icon: Users },
      { label: 'Events', type: 'Event', Icon: CalendarBlank },
      { label: 'Topics', type: 'Topic', Icon: Tag },
      { label: 'Types', type: 'Type', Icon: StackSimple },
    ]

    const BUILT_IN_TYPES = new Set(BUILT_IN_SECTION_GROUPS.map((s) => s.type))

    // --- Hooks ---

    function useOutsideClick(ref: React.RefObject<HTMLElement | null>, isOpen: boolean, onClose: () => void) {
      useEffect(() => {
        if (!isOpen) return
        const handler = (e: MouseEvent) => {
          Eif (ref.current && !ref.current.contains(e.target as Node)) onClose()
        }
        document.addEventListener('mousedown', handler)
        return () => document.removeEventListener('mousedown', handler)
      }, [ref, isOpen, onClose])
    }

    function buildTypeEntryMap(entries: VaultEntry[]): Record<string, VaultEntry> {
      const map: Record<string, VaultEntry> = {}
      for (const e of entries) { if (e.isA === 'Type') map[e.title] = e }
      return map
    }

    function applyOverrides(typeEntryMap: Record<string, VaultEntry>): SectionGroup[] {
      return BUILT_IN_SECTION_GROUPS.map((sg) => {
        const te = typeEntryMap[sg.type]
        Eif (!te?.icon && !te?.color) return sg
        return { ...sg, Icon: te?.icon ? resolveIcon(te.icon) : sg.Icon, customColor: te?.color ?? null }
      })
    }

    function buildCustomSections(entries: VaultEntry[]): SectionGroup[] {
      return entries
        .filter((e) => e.isA === 'Type' && !BUILT_IN_TYPES.has(e.title))
        .sort((a, b) => a.title.localeCompare(b.title))
        .map((e) => ({ label: e.title + 's', type: e.title, Icon: resolveIcon(e.icon), customColor: e.color }))
    }

    function sortSections(groups: SectionGroup[], typeEntryMap: Record<string, VaultEntry>): SectionGroup[] {
      return [...groups].sort((a, b) => {
        const orderA = typeEntryMap[a.type]?.order ?? Infinity
        const orderB = typeEntryMap[b.type]?.order ?? Infinity
        return orderA !== orderB ? orderA - orderB : a.label.localeCompare(b.label)
      })
    }

    function useSidebarSections(entries: VaultEntry[], isSectionVisible: (type: string) => boolean) {
      const typeEntryMap = useMemo(() => buildTypeEntryMap(entries), [entries])
      const allSectionGroups = useMemo(() => {
        const built = applyOverrides(typeEntryMap)
        const custom = buildCustomSections(entries)
        return sortSections([...built, ...custom], typeEntryMap)
      }, [entries, typeEntryMap])
      const visibleSections = useMemo(() => allSectionGroups.filter((g) => isSectionVisible(g.type)), [allSectionGroups, isSectionVisible])
      const sectionIds = useMemo(() => visibleSections.map((g) => g.type), [visibleSections])
      return { typeEntryMap, allSectionGroups, visibleSections, sectionIds }
    }

    function useEntryCounts(entries: VaultEntry[]) {
      return useMemo(() => {
        let active = 0, archived = 0, trashed = 0
        for (const e of entries) {
          Iif (e.trashed) Itrashed++
          else if (e.archived) archived++
          else active++
        }
        return { activeCount: active, archivedCount: archived, trashedCount: trashed }
      }, [entries])
    }

    function computeReorder(sectionIds: string[], activeId: string, overId: string): string[] | null {
      const oldIndex = sectionIds.indexOf(activeId)
      const newIndex = sectionIds.indexOf(overId)
      if (oldIndex === -1 || newIndex === -1) return null
      const reordered = [...sectionIds]
      reordered.splice(oldIndex, 1)
      reordered.splice(newIndex, 0, activeId)
      return reordered
    }

    function buildCustomizeArgs(typeEntry: VaultEntry, prop: 'icon' | 'color', value: string): [string, string] {
      return [
        prop === 'icon' ? value : (typeEntry.icon ?? 'file-text'),
        prop === 'color' ? value : (typeEntry.color ?? 'blue'),
      ]
    }

    // --- Sub-components ---

    function SortableSection({ group, sectionProps }: {
      group: SectionGroup
      sectionProps: Omit<SectionContentProps, 'group' | 'items' | 'isCollapsed' | 'dragHandleProps' | 'onToggle'>
        & { entries: VaultEntry[]; collapsed: Record<string, boolean>; onToggle: (type: string) => void }
    }) {
      const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: group.type })
      const items = sectionProps.entries.filter((e) => e.isA === group.type && !e.archived && !e.trashed)
      const isCollapsed = sectionProps.collapsed[group.type] ?? true

      return (
        <div ref={setNodeRef} style={{ transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.5 : 1, padding: '4px 6px' }} {...attributes}>
          <SectionContent
            group={group} items={items} isCollapsed={isCollapsed}
            selection={sectionProps.selection} onSelect={sectionProps.onSelect}
            onSelectNote={sectionProps.onSelectNote} onCreateType={sectionProps.onCreateType}
            onCreateNewType={sectionProps.onCreateNewType} onContextMenu={sectionProps.onContextMenu}
            onToggle={() => sectionProps.onToggle(group.type)}
            dragHandleProps={listeners}
          />
        </div>
      )
    }

    function CommitButton({ modifiedCount, onClick }: { modifiedCount: number; onClick?: () => void }) {
      if (!onClick) return null
      return (
        <div className="shrink-0 border-t border-border" style={{ padding: 12 }}>
          <button className="flex w-full items-center justify-center bg-primary text-primary-foreground hover:bg-primary/90 transition-colors" style={{ borderRadius: 6, gap: 6, padding: '8px 16px', border: 'none', cursor: 'pointer' }} onClick={onClick}>
            <GitCommitHorizontal size={14} />
            <span className="text-[13px] font-medium">Commit & Push</span>
            {modifiedCount > 0 && (
              <span className="text-white font-semibold" style={{ background: '#ffffff40', borderRadius: 9, padding: '0 6px', fontSize: 10 }}>{modifiedCount}</span>
            )}
          </button>
        </div>
      )
    }

    function SidebarTitleBar({ onCollapse }: { onCollapse?: () => void }) {
      return (
        <div className="shrink-0 flex items-center justify-end border-b border-border" style={{ height: 38, WebkitAppRegion: 'drag', padding: '0 8px' } as React.CSSProperties} data-tauri-drag-region>
          {onCollapse && (
            <button
              className="flex shrink-0 cursor-pointer items-center justify-center rounded border-none bg-transparent p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
              style={{ width: 24, height: 24, WebkitAppRegion: 'no-drag' } as React.CSSProperties}
              onClick={onCollapse}
              aria-label="Collapse sidebar"
              title="Collapse sidebar"
            >
              <CaretLeft size={14} weight="bold" />
            </button>
          )}
        </div>
      )
    }

    function ContextMenuOverlay({ pos, type, innerRef, onOpenCustomize }: {
      pos: { x: number; y: number } | null; type: string | null
      innerRef: React.Ref<HTMLDivElement>
      onOpenCustomize: (type: string) => void
    }) {
      Eif (!pos || !type) return null
      return (
        <div ref={innerRef} className="fixed z-50 rounded-md border bg-popover p-1 shadow-md" style={{ left: pos.x, top: pos.y, minWidth: 180 }}>
          <button className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-sm cursor-default hover:bg-accent hover:text-accent-foreground transition-colors border-none bg-transparent text-left" onClick={() => onOpenCustomize(type)}>
            Customize icon & color…
          </button>
        </div>
      )
    }

    function CustomizeOverlay({ target, typeEntryMap, innerRef, onCustomize, onClose }: {
      target: string | null; typeEntryMap: Record<string, VaultEntry>
      innerRef: React.Ref<HTMLDivElement>
      onCustomize: (prop: 'icon' | 'color', value: string) => void
      onClose: () => void
    }) {
      Eif (!target) return null
      return (
        <div ref={innerRef} className="fixed z-50" style={{ left: 20, top: 100 }}>
          <TypeCustomizePopover
            currentIcon={typeEntryMap[target]?.icon ?? null}
            currentColor={typeEntryMap[target]?.color ?? null}
            onChangeIcon={(icon) => onCustomize('icon', icon)}
            onChangeColor={(color) => onCustomize('color', color)}
            onClose={onClose}
          />
        </div>
      )
    }

    // --- Main Sidebar ---

    export const Sidebar = memo(function Sidebar({
      entries, selection, onSelect, onSelectNote, onCreateType, onCreateNewType,
      onCustomizeType, onReorderSections, modifiedCount = 0, onCommitPush, onCollapse,
    }: SidebarProps) {
      const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
      const [customizeTarget, setCustomizeTarget] = useState<string | null>(null)
      const [contextMenuPos, setContextMenuPos] = useState<{ x: number; y: number } | null>(null)
      const [contextMenuType, setContextMenuType] = useState<string | null>(null)
      const [showCustomize, setShowCustomize] = useState(false)

      const contextMenuRef = useRef<HTMLDivElement>(null)
      const popoverRef = useRef<HTMLDivElement>(null)
      const customizeRef = useRef<HTMLDivElement>(null)

      const { toggleSection: toggleVisibility, isSectionVisible } = useSectionVisibility()
      const { typeEntryMap, allSectionGroups, visibleSections, sectionIds } = useSidebarSections(entries, isSectionVisible)
      const { activeCount, archivedCount, trashedCount } = useEntryCounts(entries)

      const closeContextMenu = useCallback(() => { setContextMenuPos(null); setContextMenuType(null) }, [])
      const closeCustomize = useCallback(() => setShowCustomize(false), [])
      const closeCustomizeTarget = useCallback(() => setCustomizeTarget(null), [])

      useOutsideClick(customizeRef, showCustomize, closeCustomize)
      useOutsideClick(contextMenuRef, !!contextMenuPos, closeContextMenu)
      useOutsideClick(popoverRef, !!customizeTarget, closeCustomizeTarget)

      const toggleSection = useCallback((type: string) => {
        setCollapsed((prev) => ({ ...prev, [type]: !(prev[type] ?? true) }))
      }, [])

      const sensors = useSensors(
        useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
        useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
      )

      const handleDragEnd = useCallback((event: DragEndEvent) => {
        const { active, over } = event
        if (!over || active.id === over.id) return
        const reordered = computeReorder(sectionIds, active.id as string, over.id as string)
        if (reordered) onReorderSections?.(reordered.map((typeName, i) => ({ typeName, order: i })))
      }, [sectionIds, onReorderSections])

      const handleContextMenu = useCallback((e: React.MouseEvent, type: string) => {
        e.preventDefault(); e.stopPropagation()
        setContextMenuPos({ x: e.clientX, y: e.clientY }); setContextMenuType(type)
      }, [])

      const handleCustomize = useCallback((prop: 'icon' | 'color', value: string) => {
        if (!customizeTarget || !onCustomizeType) return
        const te = typeEntryMap[customizeTarget]
        if (!te) return
        const [icon, color] = buildCustomizeArgs(te, prop, value)
        onCustomizeType(customizeTarget, icon, color)
      }, [customizeTarget, typeEntryMap, onCustomizeType])

      const sectionProps = {
        entries, collapsed, selection, onSelect, onSelectNote, onCreateType, onCreateNewType,
        onContextMenu: handleContextMenu, onToggle: toggleSection,
      }

      return (
        <aside className="flex h-full flex-col overflow-hidden border-r border-[var(--sidebar-border)] bg-sidebar text-sidebar-foreground">
          <SidebarTitleBar onCollapse={onCollapse} />
          <nav className="flex-1 overflow-y-auto">
            {/* Top nav */}
            <div className="border-b border-border" style={{ padding: '4px 6px' }}>
              <NavItem icon={FileText} label="All Notes" count={activeCount} isActive={isSelectionActive(selection, { kind: 'filter', filter: 'all' })} badgeClassName="bg-primary text-primary-foreground" onClick={() => onSelect({ kind: 'filter', filter: 'all' })} />
              <NavItem icon={Star} label="Favorites" isActive={isSelectionActive(selection, { kind: 'filter', filter: 'favorites' })} onClick={() => onSelect({ kind: 'filter', filter: 'favorites' })} />
              <NavItem icon={Archive} label="Archive" count={archivedCount} isActive={isSelectionActive(selection, { kind: 'filter', filter: 'archived' })} badgeClassName="text-muted-foreground" badgeStyle={{ background: 'var(--muted)' }} onClick={() => onSelect({ kind: 'filter', filter: 'archived' })} />
              <NavItem icon={TagSimple} label="Untagged" disabled />
              <NavItem icon={Trash} label="Trash" count={trashedCount} isActive={isSelectionActive(selection, { kind: 'filter', filter: 'trash' })} activeClassName="bg-destructive/10 text-destructive" badgeClassName="text-muted-foreground" badgeStyle={{ background: 'var(--muted)' }} onClick={() => onSelect({ kind: 'filter', filter: 'trash' })} />
              {modifiedCount > 0 && (
                <NavItem icon={GitDiff} label="Changes" count={modifiedCount} isActive={isSelectionActive(selection, { kind: 'filter', filter: 'changes' })} activeClassName="bg-[color:var(--accent-orange)]/10 text-[var(--accent-orange)]" badgeClassName="text-white" badgeStyle={{ background: 'var(--accent-orange)' }} onClick={() => onSelect({ kind: 'filter', filter: 'changes' })} />
              )}
            </div>

            {/* Sections header + visibility popover */}
            <div ref={customizeRef} style={{ position: 'relative', padding: '4px 6px 0' }}>
              <div className="flex w-full select-none items-center justify-between" style={{ padding: '4px 16px' }}>
                <span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">Sections</span>
                <button className="flex shrink-0 cursor-pointer items-center justify-center rounded border-none bg-transparent p-0 text-muted-foreground transition-colors hover:text-foreground" style={{ width: 20, height: 20 }} onClick={() => setShowCustomize((v) => !v)} aria-label="Customize sections" title="Customize sections">
                  <SlidersHorizontal size={14} />
                </button>
              </div>
              {showCustomize && <VisibilityPopover sections={allSectionGroups} isSectionVisible={isSectionVisible} onToggle={toggleVisibility} />}
            </div>

            {/* Sortable section groups */}
            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
              <SortableContext items={sectionIds} strategy={verticalListSortingStrategy}>
                {visibleSections.map((g) => (
                  <SortableSection key={g.type} group={g} sectionProps={sectionProps} />
                ))}
              </SortableContext>
            </DndContext>
          </nav>

          <CommitButton modifiedCount={modifiedCount} onClick={onCommitPush} />
          <ContextMenuOverlay pos={contextMenuPos} type={contextMenuType} innerRef={contextMenuRef} onOpenCustomize={(type) => { closeContextMenu(); setCustomizeTarget(type) }} />
          <CustomizeOverlay target={customizeTarget} typeEntryMap={typeEntryMap} innerRef={popoverRef} onCustomize={handleCustomize} onClose={closeCustomizeTarget} />
        </aside>
      )
    })