Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

9.2 KB
Raw Blame
import { useState, useEffect, useRef } from 'react'
import { useReactFlow } from '@xyflow/react'
import { Search, X } from 'lucide-react'
import { useCanvasStore } from '@/stores/canvasStore'
import { scanApi } from '@/api/client'
import { NODE_TYPE_LABELS } from '@/types'
import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'

interface SearchBarProps {
  onOpenInventory?: (deviceId: string) => void
}

export function SearchBar({ onOpenInventory }: SearchBarProps) {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const [inventoryDevices, setInventoryEntrys] = useState<InventoryEntry[]>([])
  const inputRef = useRef<HTMLInputElement>(null)
  const { nodes, setSelectedNode } = useCanvasStore()
  const { setCenter } = useReactFlow()

  useEffect(() => {
    if (!open) return
    scanApi.pending().then((res) => setInventoryEntrys(res.data)).catch(() => {})
  }, [open])

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault()
        setOpen(true)
      }
      if (e.key === 'Escape') {
        setOpen(false)
        setQuery('')
      }
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [])

  useEffect(() => {
    if (open) inputRef.current?.focus()
  }, [open])

  const q = query.toLowerCase().trim()

  const nodeResults = q
    ? nodes.flatMap((n) => {
        if (n.data.type === 'groupRect') return []

        const contains = (v?: string | null) => v?.toLowerCase().includes(q)

        const matches: Array<{ key: string; display_value: string }> = []

        // Label matches make the node a result, but it is already shown in the
        // header — don't repeat it in the matched-values column.
        const labelMatch = contains(n.data.label)

        for (const [key, value] of [
          ['notes', n.data.notes],
          ['ip', n.data.ip],
          ['hostname', n.data.hostname],
        ] as const) {
          if (contains(value)) {
            matches.push({ key, display_value: value ?? '' })
          }
        }

        for (const s of n.data.services ?? []) {
          if (contains(s.service_name)) {
            matches.push({ key: 'services', display_value: s.service_name ?? '' })
          }
        }

        for (const p of (n.data.properties ?? []).filter((p) => p.visible)) {
          if (contains(p.key) || contains(p.value)) {
            matches.push({
              key: 'properties',
              display_value: `${p.key ?? ''} = ${p.value ?? ''}`,
            })
          }
        }

        return labelMatch || matches.length > 0 ? [{ node: n, matches }] : []
      })
    : []

  const pendingResults = q
    ? inventoryDevices.filter((d) =>
        d.ip?.toLowerCase().includes(q) ||
        d.hostname?.toLowerCase().includes(q) ||
        d.friendly_name?.toLowerCase().includes(q) ||
        d.ieee_address?.toLowerCase().includes(q) ||
        d.services.some((s) =>
          s.service_name?.toLowerCase().includes(q) ||
          s.category?.toLowerCase().includes(q)
        )
      ).slice(0, 4)
    : []

  const totalResults = nodeResults.length + pendingResults.length

  const goToNode = (id: string) => {
    const node = nodes.find((n) => n.id === id)
    if (!node) return
    setSelectedNode(id)
    // For grouped nodes, add parent's absolute position
    let absX = node.position.x
    let absY = node.position.y
    if (node.parentId) {
      const parent = nodes.find((n) => n.id === node.parentId)
      if (parent) { absX += parent.position.x; absY += parent.position.y }
    }
    const w = node.measured?.width ?? node.width ?? 200
    const h = node.measured?.height ?? node.height ?? 80
    setCenter(absX + w / 2, absY + h / 2, { zoom: 1.5, duration: 500 })
    setOpen(false)
    setQuery('')
  }

  if (!open) return null

  return (
    <div
      className="nodrag nowheel"
      style={{
        position: 'absolute',
        top: 16,
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 1000,
        width: 360,
        pointerEvents: 'all',
      }}
    >
      <div style={{
        background: '#161b22',
        border: '1px solid #30363d',
        borderRadius: 8,
        boxShadow: '0 8px 24px rgba(0,0,0,0.6)',
        overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px' }}>
          <Search size={14} style={{ color: '#8b949e', flexShrink: 0 }} />
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search by name, IP, hostname or service…"
            style={{
              flex: 1,
              background: 'transparent',
              border: 'none',
              outline: 'none',
              color: '#e6edf3',
              fontSize: 13,
            }}
          />
          {query && (
            <span style={{ fontSize: 11, color: '#6e7681', flexShrink: 0 }}>
              {totalResults} result{totalResults !== 1 ? 's' : ''}
            </span>
          )}
          <button
            onClick={() => { setOpen(false); setQuery('') }}
            aria-label="Close search"
            style={{ color: '#8b949e', background: 'none', border: 'none', cursor: 'pointer', padding: 2 }}
          >
            <X size={14} />
          </button>
        </div>

        {totalResults > 0 && (
          <div style={{ borderTop: '1px solid #30363d', maxHeight: 260, overflowY: 'auto' }}>
            {nodeResults.map((n, idx) => (
              <button
                key={`${n.node.id}-${idx}`}
                onClick={() => goToNode(n.node.id)}
                style={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 10,
                  padding: '7px 12px',
                  background: 'none',
                  border: 'none',
                  cursor: 'pointer',
                  textAlign: 'left',
                }}
                onMouseEnter={(e) => (e.currentTarget.style.background = '#21262d')}
                onMouseLeave={(e) => (e.currentTarget.style.background = 'none')}
              >
                <span style={{ fontSize: 12, fontWeight: 600, color: '#e6edf3', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {n.node.data.label}
                </span>
                {n.matches.length > 0 && (
                  <span style={{ maxWidth: "50%", display: 'flex', flexDirection: 'column', gap: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {n.matches.map((m, mIdx) => (
                      <span key={`${m.key}-${mIdx}`} style={{ fontSize: 11, color: '#8b949e', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0, display: 'inline-block' }}>
                        {m.display_value}
                      </span>
                    ))}
                  </span>
                )}
                <span style={{ fontSize: 10, color: '#6e7681', flexShrink: 0 }}>
                  {NODE_TYPE_LABELS[n.node.data.type] ?? n.node.data.type}
                </span>
              </button>
            ))}
            {pendingResults.length > 0 && nodeResults.length > 0 && (
              <div style={{ height: 1, background: '#30363d', margin: '2px 0' }} />
            )}
            {pendingResults.map((d) => {
              const serviceName = d.services.find((s) => s.service_name)?.service_name
              return (
                <button
                  key={d.id}
                  onClick={() => { onOpenInventory?.(d.id); setOpen(false); setQuery('') }}
                  style={{
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 10,
                    padding: '7px 12px',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    textAlign: 'left',
                  }}
                  onMouseEnter={(e) => (e.currentTarget.style.background = '#21262d')}
                  onMouseLeave={(e) => (e.currentTarget.style.background = 'none')}
                >
                  <span style={{ fontSize: 10, color: '#e3b341', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>pending</span>
                  <span style={{ fontSize: 12, fontWeight: 600, color: '#e6edf3', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {d.friendly_name ?? d.hostname ?? d.ip ?? d.ieee_address ?? 'device'}
                  </span>
                  <span style={{ fontSize: 11, color: '#8b949e', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>
                    {serviceName ?? d.ip ?? d.ieee_address ?? ''}
                  </span>
                </button>
              )
            })}
          </div>
        )}

        {q && totalResults === 0 && (
          <div style={{ borderTop: '1px solid #30363d', padding: '10px 12px', fontSize: 12, color: '#6e7681', textAlign: 'center' }}>
            No results for &ldquo;{query}&rdquo;
          </div>
        )}
      </div>
    </div>
  )
}