All files / src/components NoteList.tsx

85.71% Statements 210/245
76.49% Branches 192/251
85.52% Functions 65/76
87.5% Lines 182/208

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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702                            2x                       118x 118x                                     118x 116x 116x 116x       116x 116x 116x 116x 112x 112x       266x       43x 43x 43x 12x 12x 12x         5x     5x 5x 5x 25x 25x 20x 20x 20x     5x       78x         2x             2x               66x   58x   4x   13x   2x 5x 5x 5x 1x         2x     33x 33x 33x   33x         3x 3x         6x 6x 6x   6x 28x 22x 22x 1x 1x   1x 1x                       29x 29x 12x 13x                 6x 6x 6x     6x               6x 6x         6x 28x   6x     6x     28x         6x     6x 6x         6x 6x 5x   6x 5x 5x 5x         6x 28x   6x     6x 1x   6x   6x       67x   61x   81x       7x   40x       22x       2x 11x                           67x 67x   67x 46x       4x 4x     67x             4x         73x                 16x               3x 3x 3x                                   55x 55x 55x 55x   55x 55x 55x   55x 3x 3x 3x 3x       55x 2x 2x 2x 1x 2x         55x 47x 47x 141x   47x       55x 47x 3x 15x     55x 47x       55x 47x       55x   55x 49x       55x   55x 50x       55x 48x                       55x 50x 5x 8x     55x 109x 109x 109x 109x 109x 109x                                                                                                                         55x 9x 9x 9x 9x 9x                                                                 17x 17x 17x 17x               2x                                               18x                 55x                                                 2x                                         1x                   9x 9x                                                                                                         91x                 2x  
import { useState, useMemo, useCallback, useEffect, useRef, memo } from 'react'
// Virtuoso removed — flat list rendering used instead
import type { VaultEntry, SidebarSelection, ModifiedFile } from '../types'
import { cn } from '@/lib/utils'
import { Input } from '@/components/ui/input'
import {
  MagnifyingGlass, Plus, Wrench, Flask, Target, ArrowsClockwise,
  Users, CalendarBlank, Tag, FileText, CaretDown, CaretRight, StackSimple,
  ArrowsDownUp, Check, Warning,
} from '@phosphor-icons/react'
import type { ComponentType, SVGAttributes } from 'react'
import { getTypeColor, getTypeLightColor } from '../utils/typeColors'
import { resolveIcon } from './TypeCustomizePopover'
 
const TYPE_ICON_MAP: Record<string, ComponentType<SVGAttributes<SVGSVGElement>>> = {
  Project: Wrench,
  Experiment: Flask,
  Responsibility: Target,
  Procedure: ArrowsClockwise,
  Person: Users,
  Event: CalendarBlank,
  Topic: Tag,
  Type: StackSimple,
}
 
function getTypeIcon(isA: string | null, customIcon?: string | null): ComponentType<SVGAttributes<SVGSVGElement>> {
  Iif (customIcon) return resolveIcon(customIcon)
  return (isA && TYPE_ICON_MAP[isA]) || FileText
}
 
interface NoteListProps {
  entries: VaultEntry[]
  selection: SidebarSelection
  selectedNote: VaultEntry | null
  allContent: Record<string, string>
  modifiedFiles?: ModifiedFile[]
  onSelectNote: (entry: VaultEntry) => void
  onCreateNote: () => void
}
 
interface RelationshipGroup {
  label: string
  entries: VaultEntry[]
}
 
function relativeDate(ts: number | null): string {
  if (!ts) return ''
  const now = Math.floor(Date.now() / 1000)
  const diff = now - ts
  Iif (diff < 0) {
    const date = new Date(ts * 1000)
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
  }
  Iif (diff < 60) return 'just now'
  Iif (diff < 3600) return `${Math.floor(diff / 60)}m ago`
  Iif (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
  if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`
  const date = new Date(ts * 1000)
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}
 
function getDisplayDate(entry: VaultEntry): number | null {
  return entry.modifiedAt ?? entry.createdAt
}
 
function refsMatch(refs: string[], entry: VaultEntry): boolean {
  const stem = entry.path.replace(/^.*\/Laputa\//, '').replace(/\.md$/, '')
  const fileStem = entry.filename.replace(/\.md$/, '')
  return refs.some((ref) => {
    const raw = ref.replace(/^\[\[/, '').replace(/\]\]$/, '')
    const inner = raw.split('|')[0]
    return inner === stem || inner.split('/').pop() === fileStem
  })
}
 
function resolveRefs(refs: string[], entries: VaultEntry[]): VaultEntry[] {
  return refs
    .map((ref) => {
      // Strip [[ ]] and remove alias (|display text) if present
      const raw = ref.replace(/^\[\[/, '').replace(/\]\]$/, '')
      const inner = raw.split('|')[0]
      return entries.find((e) => {
        const stem = e.path.replace(/^.*\/Laputa\//, '').replace(/\.md$/, '')
        if (stem === inner) return true
        const fileStem = e.filename.replace(/\.md$/, '')
        Iif (fileStem === inner.split('/').pop()) return true
        return false
      })
    })
    .filter((e): e is VaultEntry => e !== undefined)
}
 
export function sortByModified(a: VaultEntry, b: VaultEntry): number {
  return (getDisplayDate(b) ?? 0) - (getDisplayDate(a) ?? 0)
}
 
export type SortOption = 'modified' | 'created' | 'title' | 'status'
 
export const SORT_OPTIONS: { value: SortOption; label: string }[] = [
  { value: 'modified', label: 'Modified' },
  { value: 'created', label: 'Created' },
  { value: 'title', label: 'Title' },
  { value: 'status', label: 'Status' },
]
 
const STATUS_ORDER: Record<string, number> = {
  Active: 0,
  Paused: 1,
  Done: 2,
  Finished: 3,
}
 
export function getSortComparator(option: SortOption): (a: VaultEntry, b: VaultEntry) => number {
  switch (option) {
    case 'modified':
      return sortByModified
    case 'created':
      return (a, b) => (b.createdAt ?? b.modifiedAt ?? 0) - (a.createdAt ?? a.modifiedAt ?? 0)
    case 'title':
      return (a, b) => a.title.localeCompare(b.title)
    case 'status':
      return (a, b) => {
        const sa = STATUS_ORDER[a.status ?? ''] ?? 999
        const sb = STATUS_ORDER[b.status ?? ''] ?? 999
        if (sa !== sb) return sa - sb
        return sortByModified(a, b)
      }
  }
}
 
const SORT_STORAGE_KEY = 'laputa-sort-preferences'
 
function loadSortPreferences(): Record<string, SortOption> {
  try {
    const raw = localStorage.getItem(SORT_STORAGE_KEY)
    return raw ? JSON.parse(raw) : {}
  } catch {
    return {}
  }
}
 
function saveSortPreferences(prefs: Record<string, SortOption>) {
  try {
    localStorage.setItem(SORT_STORAGE_KEY, JSON.stringify(prefs))
  } catch { /* ignore */ }
}
 
function findBacklinks(entity: VaultEntry, allEntries: VaultEntry[], allContent: Record<string, string>): VaultEntry[] {
  const stem = entity.filename.replace(/\.md$/, '')
  const pathStem = entity.path.replace(/^.*\/Laputa\//, '').replace(/\.md$/, '')
  const targets = [entity.title, ...entity.aliases]
 
  return allEntries.filter((e) => {
    if (e.path === entity.path) return false
    const content = allContent[e.path]
    if (!content) return false
    for (const t of targets) {
      Iif (content.includes(`[[${t}]]`)) return true
    }
    Iif (content.includes(`[[${stem}]]`)) return true
    Eif (content.includes(`[[${pathStem}]]`)) return true
    if (content.includes(`[[${pathStem}|`)) return true
    return false
  })
}
 
function addGroup(
  groups: RelationshipGroup[],
  label: string,
  entries: VaultEntry[],
  seen: Set<string>,
) {
  const unseen = entries.filter((e) => !seen.has(e.path))
  if (unseen.length > 0) {
    groups.push({ label, entries: unseen })
    unseen.forEach((e) => seen.add(e.path))
  }
}
 
export function buildRelationshipGroups(
  entity: VaultEntry,
  allEntries: VaultEntry[],
  allContent: Record<string, string>,
): RelationshipGroup[] {
  const groups: RelationshipGroup[] = []
  const seen = new Set<string>([entity.path])
  const rels = entity.relationships ?? {}
 
  // 0. "Instances" — for type documents, show all entries of this type
  Iif (entity.isA === 'Type') {
    const instances = allEntries
      .filter((e) => e.isA === entity.title && !seen.has(e.path))
      .sort(sortByModified)
    addGroup(groups, 'Instances', instances, seen)
  }
 
  // 1. "Has" — from the entity's own relationships map
  const hasRefs = rels['Has'] ?? []
  Iif (hasRefs.length > 0) {
    addGroup(groups, 'Has', resolveRefs(hasRefs, allEntries).sort(sortByModified), seen)
  }
 
  // 2. Children — entries whose belongsTo points to this entity (reverse lookup, excluding events)
  const children = allEntries
    .filter((e) => !seen.has(e.path) && e.isA !== 'Event' && refsMatch(e.belongsTo, entity))
    .sort(sortByModified)
  addGroup(groups, 'Children', children, seen)
 
  // 3. Events — entities of type Event that reference this entity via belongsTo/relatedTo
  const events = allEntries
    .filter(
      (e) =>
        !seen.has(e.path) &&
        e.isA === 'Event' &&
        (refsMatch(e.belongsTo, entity) || refsMatch(e.relatedTo, entity))
    )
    .sort(sortByModified)
  addGroup(groups, 'Events', events, seen)
 
  // 4. "Topics" — from the entity's own relationships map
  const topicRefs = rels['Topics'] ?? []
  Iif (topicRefs.length > 0) {
    addGroup(groups, 'Topics', resolveRefs(topicRefs, allEntries).sort(sortByModified), seen)
  }
 
  // 5. All other generic relationship fields (alphabetically)
  const handledKeys = new Set(['Has', 'Topics'])
  const otherKeys = Object.keys(rels)
    .filter((k) => !handledKeys.has(k) && k.toLowerCase() !== 'type')
    .sort((a, b) => a.localeCompare(b))
  for (const key of otherKeys) {
    const refs = rels[key]
    Eif (refs && refs.length > 0) {
      addGroup(groups, key, resolveRefs(refs, allEntries).sort(sortByModified), seen)
    }
  }
 
  // 6. Referenced By — entries that reference this entity via relatedTo (reverse lookup)
  const referencedBy = allEntries
    .filter((e) => !seen.has(e.path) && e.isA !== 'Event' && refsMatch(e.relatedTo, entity))
    .sort(sortByModified)
  addGroup(groups, 'Referenced By', referencedBy, seen)
 
  // 7. Backlinks — always last
  const backlinks = findBacklinks(entity, allEntries, allContent)
    .filter((e) => !seen.has(e.path))
    .sort(sortByModified)
  addGroup(groups, 'Backlinks', backlinks, seen)
 
  return groups
}
 
export function filterEntries(entries: VaultEntry[], selection: SidebarSelection, _modifiedFiles?: ModifiedFile[]): VaultEntry[] {
  switch (selection.kind) {
    case 'filter':
      switch (selection.filter) {
        case 'all':
          return entries.filter((e) => !e.archived && !e.trashed)
        case 'favorites':
          return []
        case 'archived':
          return entries.filter((e) => e.archived && !e.trashed)
        case 'trash':
          return entries.filter((e) => e.trashed)
      }
      break
    case 'sectionGroup':
      return entries.filter((e) => e.isA === selection.type && !e.archived && !e.trashed)
    case 'entity':
      return []
    case 'topic': {
      const topic = selection.entry
      return entries.filter((e) => refsMatch(e.relatedTo, topic) && !e.archived && !e.trashed)
    }
  }
}
 
function SortDropdown({
  groupLabel,
  current,
  onChange,
}: {
  groupLabel: string
  current: SortOption
  onChange: (groupLabel: string, option: SortOption) => void
}) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)
 
  useEffect(() => {
    if (!open) return
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [open])
 
  return (
    <div ref={ref} className="relative" style={{ zIndex: open ? 10 : 0 }}>
      <button
        className={cn(
          "flex items-center gap-0.5 rounded px-1 py-0.5 text-muted-foreground transition-colors hover:text-foreground hover:bg-accent",
          open && "bg-accent text-foreground"
        )}
        onClick={(e) => { e.stopPropagation(); setOpen(!open) }}
        title={`Sort by ${current}`}
        data-testid={`sort-button-${groupLabel}`}
      >
        <ArrowsDownUp size={12} />
        <span className="text-[10px] font-medium">{SORT_OPTIONS.find((o) => o.value === current)?.label}</span>
      </button>
      {open && (
        <div
          className="absolute right-0 top-full mt-1 rounded-md border border-border bg-popover shadow-md"
          style={{ width: 130, padding: 4 }}
          data-testid={`sort-menu-${groupLabel}`}
        >
          {SORT_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              className={cn(
                "flex w-full items-center gap-1.5 rounded px-2 text-[12px] text-popover-foreground hover:bg-accent",
                opt.value === current && "bg-accent font-medium"
              )}
              style={{ height: 28, border: 'none', cursor: 'pointer', background: opt.value === current ? 'var(--accent)' : 'transparent' }}
              onClick={(e) => {
                e.stopPropagation()
                onChange(groupLabel, opt.value)
                setOpen(false)
              }}
              data-testid={`sort-option-${opt.value}`}
            >
              {opt.value === current
                ? <Check size={12} />
                : <span style={{ width: 12, height: 12, display: 'inline-block' }} />
              }
              {opt.label}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
 
function NoteListInner({ entries, selection, selectedNote, allContent, modifiedFiles, onSelectNote, onCreateNote }: NoteListProps) {
  const [search, setSearch] = useState('')
  const [searchVisible, setSearchVisible] = useState(false)
  const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set())
  const [sortPrefs, setSortPrefs] = useState<Record<string, SortOption>>(loadSortPreferences)
 
  const isEntityView = selection.kind === 'entity'
  const isSectionGroup = selection.kind === 'sectionGroup'
  const isTrashView = selection.kind === 'filter' && selection.filter === 'trash'
 
  const handleSortChange = useCallback((groupLabel: string, option: SortOption) => {
    setSortPrefs((prev) => {
      const next = { ...prev, [groupLabel]: option }
      saveSortPreferences(next)
      return next
    })
  }, [])
 
  const toggleGroup = useCallback((label: string) => {
    setCollapsedGroups((prev) => {
      const next = new Set(prev)
      if (next.has(label)) next.delete(label)
      else next.add(label)
      return next
    })
  }, [])
 
  // Build type entry map for custom icon/color lookup
  const typeEntryMap = useMemo(() => {
    const map: Record<string, VaultEntry> = {}
    for (const e of entries) {
      Iif (e.isA === 'Type') map[e.title] = e
    }
    return map
  }, [entries])
 
  // Find the type document for this section group (e.g., type/project.md for "Project")
  const typeDocument = useMemo(() => {
    if (!isSectionGroup) return null
    const typeName = (selection as { kind: 'sectionGroup'; type: string }).type
    return entries.find((e) => e.isA === 'Type' && e.title === typeName) ?? null
  }, [isSectionGroup, selection, entries])
 
  const entityGroups = useMemo(
    () => isEntityView ? buildRelationshipGroups(selection.entry, entries, allContent) : [],
    [isEntityView, selection, entries, allContent]
  )
 
  const filtered = useMemo(
    () => isEntityView ? [] : filterEntries(entries, selection, modifiedFiles),
    [entries, selection, modifiedFiles, isEntityView]
  )
 
  const listSort = sortPrefs['__list__'] ?? 'modified'
 
  const sorted = useMemo(
    () => isEntityView ? [] : [...filtered].sort(getSortComparator(listSort)),
    [filtered, isEntityView, listSort]
  )
 
  const query = search.trim().toLowerCase()
 
  const searched = useMemo(
    () => query ? sorted.filter((e) => e.title.toLowerCase().includes(query)) : sorted,
    [sorted, query]
  )
 
  const searchedGroups = useMemo(
    () => query
      ? entityGroups
          .map((g) => ({
            ...g,
            entries: g.entries.filter((e) => e.title.toLowerCase().includes(query)),
          }))
          .filter((g) => g.entries.length > 0)
      : entityGroups,
    [entityGroups, query]
  )
 
 
  const expiredTrashCount = useMemo(() => {
    if (!isTrashView) return 0
    const now = Date.now() / 1000
    return searched.filter((e) => e.trashedAt && (now - e.trashedAt) >= 86400 * 30).length
  }, [isTrashView, searched])
 
  const renderItem = useCallback((entry: VaultEntry, isPinned = false) => {
    const isSelected = selectedNote?.path === entry.path && !isPinned
    const te = typeEntryMap[entry.isA ?? '']
    const typeColor = getTypeColor(entry.isA ?? 'Note', te?.color)
    const typeLightColor = getTypeLightColor(entry.isA ?? 'Note', te?.color)
    const TypeIcon = getTypeIcon(entry.isA, te?.icon)
    return (
      <div
        key={entry.path}
        className={cn(
          "relative cursor-pointer border-b border-[var(--border)] transition-colors",
          isPinned && "border-l-[3px] border-l-[var(--accent-green)] bg-muted",
          isSelected && "border-l-[3px]",
          !isPinned && !isSelected && "hover:bg-muted"
        )}
        style={{
          padding: isPinned || isSelected ? '14px 16px 14px 13px' : '14px 16px',
          ...(isSelected && {
            borderLeftColor: typeColor,
            backgroundColor: typeLightColor,
          }),
        }}
        onClick={() => onSelectNote(entry)}
      >
        <TypeIcon
          width={14}
          height={14}
          className="absolute right-3 top-2.5"
          style={{ color: typeColor }}
          data-testid="type-icon"
        />
        <div className="pr-5">
          <div className={cn(
            "truncate text-[13px] text-foreground",
            isSelected ? "font-semibold" : "font-medium"
          )}>
            {entry.title}
            {entry.archived && (
              <span
                className="ml-1.5 inline-block align-middle text-muted-foreground"
                style={{ fontSize: 9, fontWeight: 500, background: 'var(--muted)', borderRadius: 4, padding: '1px 4px', verticalAlign: 'middle' }}
              >
                ARCHIVED
              </span>
            )}
            {entry.trashed && (
              <span
                className="ml-1.5 inline-block align-middle"
                style={{ fontSize: 9, fontWeight: 500, background: 'var(--destructive-light, #ef44441a)', color: 'var(--destructive)', borderRadius: 4, padding: '1px 4px', verticalAlign: 'middle' }}
              >
                TRASHED
              </span>
            )}
          </div>
        </div>
        <div className="mt-0.5 text-[12px] leading-[1.5] text-muted-foreground" style={{ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {entry.snippet}
        </div>
        <div className="mt-0.5 text-[10px] text-muted-foreground" style={entry.trashed && entry.trashedAt && (Date.now() / 1000 - entry.trashedAt) >= 86400 * 30 ? { color: 'var(--destructive)', fontWeight: 500 } : undefined}>
          {entry.trashed && entry.trashedAt
            ? `Trashed ${relativeDate(entry.trashedAt)}${(Date.now() / 1000 - entry.trashedAt) >= 86400 * 30 ? ' — will be permanently deleted' : ''}`
            : relativeDate(getDisplayDate(entry))}
        </div>
      </div>
    )
  }, [selectedNote?.path, onSelectNote, typeEntryMap])
 
  const renderPinnedView = useCallback((entity: VaultEntry, groups: RelationshipGroup[]) => {
    const ete = typeEntryMap[entity.isA ?? '']
    const entityTypeColor = getTypeColor(entity.isA ?? '', ete?.color)
    const entityLightColor = getTypeLightColor(entity.isA ?? '', ete?.color)
    const EntityIcon = getTypeIcon(entity.isA, ete?.icon)
    return (
      <div className="h-full overflow-y-auto">
        {/* Prominent card */}
        <div
          className="relative cursor-pointer border-b border-[var(--border)]"
          style={{ backgroundColor: entityLightColor, padding: '14px 16px' }}
          onClick={() => onSelectNote(entity)}
        >
          <EntityIcon
            width={16}
            height={16}
            className="absolute right-3 top-3.5"
            style={{ color: entityTypeColor }}
            data-testid="type-icon"
          />
          <div className="pr-6 text-[14px] font-bold" style={{ color: entityTypeColor }}>
            {entity.title}
          </div>
          <div className="mt-1 text-[12px] leading-[1.5] opacity-80" style={{ color: entityTypeColor, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
            {entity.snippet}
          </div>
          <div className="mt-1 text-[11px] opacity-60" style={{ color: entityTypeColor }}>
            {relativeDate(getDisplayDate(entity))}
          </div>
        </div>
 
        {/* Relationship groups */}
        {groups.length === 0 ? (
          <div className="px-4 py-8 text-center text-[13px] text-muted-foreground">
            {query ? 'No matching items' : 'No related items'}
          </div>
        ) : (
          groups.map((group) => {
            const isGroupCollapsed = collapsedGroups.has(group.label)
            const groupSort = sortPrefs[group.label] ?? 'modified'
            const sortedEntries = [...group.entries].sort(getSortComparator(groupSort))
            return (
              <div key={group.label}>
                <div
                  className="flex w-full items-center justify-between bg-muted"
                  style={{ height: 32, padding: '0 16px' }}
                >
                  <button
                    className="flex flex-1 items-center gap-1.5 border-none bg-transparent cursor-pointer p-0"
                    onClick={() => toggleGroup(group.label)}
                  >
                    <span className="font-mono-label text-muted-foreground">
                      {group.label}
                    </span>
                    <span className="font-mono-label text-muted-foreground" style={{ fontWeight: 400 }}>{group.entries.length}</span>
                  </button>
                  <span className="flex items-center gap-1.5">
                    <SortDropdown
                      groupLabel={group.label}
                      current={groupSort}
                      onChange={handleSortChange}
                    />
                    <button
                      className="flex items-center border-none bg-transparent cursor-pointer p-0 text-muted-foreground"
                      onClick={() => toggleGroup(group.label)}
                    >
                      {isGroupCollapsed
                        ? <CaretRight size={12} />
                        : <CaretDown size={12} />
                      }
                    </button>
                  </span>
                </div>
                {!isGroupCollapsed && sortedEntries.map((groupEntry) => renderItem(groupEntry))}
              </div>
            )
          })
        )}
      </div>
    )
  }, [onSelectNote, query, collapsedGroups, toggleGroup, renderItem, typeEntryMap, sortPrefs, handleSortChange])
 
  return (
    <div className="flex flex-col overflow-hidden border-r border-border bg-card text-foreground" style={{ height: '100%' }}>
      {/* Header */}
      <div className="flex h-[45px] shrink-0 items-center justify-between border-b border-border px-4" data-tauri-drag-region style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}>
        <h3 className="m-0 min-w-0 flex-1 truncate text-[14px] font-semibold">
          {isEntityView
            ? selection.entry.title
            : typeDocument
              ? typeDocument.title
              : selection.kind === 'filter' && (selection as { filter: string }).filter === 'archived'
                ? 'Archive'
                : selection.kind === 'filter' && (selection as { filter: string }).filter === 'trash'
                  ? 'Trash'
                  : 'Notes'}
        </h3>
        <div className="flex items-center gap-3" style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}>
          {!isEntityView && (
            <SortDropdown
              groupLabel="__list__"
              current={listSort}
              onChange={handleSortChange}
            />
          )}
          <button
            className="flex items-center text-muted-foreground transition-colors hover:text-foreground"
            onClick={() => { setSearchVisible(!searchVisible); Iif (searchVisible) setSearch('') }}
            title="Search notes"
          >
            <MagnifyingGlass size={16} />
          </button>
          <button
            className="flex items-center text-muted-foreground transition-colors hover:text-foreground"
            onClick={onCreateNote}
            title="Create new note"
          >
            <Plus size={16} />
          </button>
        </div>
      </div>
 
      {/* Search (toggle on icon click) */}
      {searchVisible && (
        <div className="border-b border-border px-3 py-2">
          <Input
            placeholder="Search notes..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-8 text-[13px]"
            autoFocus
          />
        </div>
      )}
 
      {/* Items */}
      <div className="flex-1 overflow-hidden" style={{ minHeight: 0 }}>
        {isEntityView ? (() => {
          const entity = selection.entry
          return renderPinnedView(entity, searchedGroups)
        })() : (
          <div className="h-full overflow-y-auto">
            {/* Type document pinned card (for sectionGroup view) */}
            {typeDocument && (() => {
              const tde = typeEntryMap[typeDocument.title] ?? typeDocument
              const tdColor = getTypeColor(typeDocument.isA ?? 'Type', tde?.color)
              const tdLightColor = getTypeLightColor(typeDocument.isA ?? 'Type', tde?.color)
              const TDIcon = getTypeIcon(typeDocument.isA, tde?.icon)
              return (
                <div
                  className="relative cursor-pointer border-b border-[var(--border)]"
                  style={{ backgroundColor: tdLightColor, padding: '14px 16px' }}
                  onClick={() => onSelectNote(typeDocument)}
                >
                  <TDIcon
                    width={16}
                    height={16}
                    className="absolute right-3 top-3.5"
                    style={{ color: tdColor }}
                    data-testid="type-icon"
                  />
                  <div className="pr-6 text-[14px] font-bold" style={{ color: tdColor }}>
                    {typeDocument.title}
                  </div>
                  <div className="mt-1 text-[12px] leading-[1.5] opacity-80" style={{ color: tdColor, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                    {typeDocument.snippet}
                  </div>
                </div>
              )
            })()}
            {/* 30-day warning banner for trash view */}
            {isTrashView && expiredTrashCount > 0 && (
              <div
                className="flex items-start gap-2 border-b border-[var(--border)]"
                style={{ padding: '10px 12px', background: 'color-mix(in srgb, var(--destructive) 6%, transparent)' }}
              >
                <Warning size={16} className="shrink-0" style={{ color: 'var(--destructive)', marginTop: 1 }} />
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--destructive)' }}>
                    Notes in trash for 30+ days will be permanently deleted
                  </div>
                  <div className="text-muted-foreground" style={{ fontSize: 11 }}>
                    {expiredTrashCount} {expiredTrashCount === 1 ? 'note is' : 'notes are'} past the 30-day retention period
                  </div>
                </div>
              </div>
            )}
            {searched.length === 0 ? (
              <div className="px-4 py-8 text-center text-[13px] text-muted-foreground">
                {isTrashView ? 'Trash is empty' : 'No notes found'}
              </div>
            ) : (
              searched.map((entry) => renderItem(entry))
            )}
          </div>
        )}
      </div>
    </div>
  )
}
 
export const NoteList = memo(NoteListInner)