Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(docs): find documents from the canvas search
Pouzor5aa6dedce0ce
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex b31f1c7..1b888ce 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1429,6 +1429,14 @@ export default function App() {open={searchOpen}onClose={() => setSearchOpen(false)}onOpenInventory={(deviceId) => openInventoryModal(deviceId)}+ onOpenDocument={+ STANDALONE+ ? undefined+ : (docId) => {+ setAppView('documentation')+ void useDocsStore.getState().open(docId)+ }+ }/><ShortcutsModal open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />diff --git a/frontend/src/components/modals/SearchModal.tsx b/frontend/src/components/modals/SearchModal.tsxindex 60f1b77..d04e968 100644--- a/frontend/src/components/modals/SearchModal.tsx+++ b/frontend/src/components/modals/SearchModal.tsx@@ -2,18 +2,29 @@ import { useState, useCallback, useEffect } from 'react'import { useReactFlow } from '@xyflow/react'import { Search } from 'lucide-react'import { useCanvasStore } from '@/stores/canvasStore'-import { scanApi } from '@/api/client'+import { documentsApi, scanApi } from '@/api/client'+import type { DocSearchHit } from '@/documentation/types'import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'++/** Long enough that a stray keystroke does not hit the server. */+const DOC_SEARCH_DEBOUNCE = 250+interface SearchModalProps {open: booleanonClose: () => voidonOpenInventory: (deviceId: string) => void+ /** Omitted in standalone, where there are no documents to open. */+ onOpenDocument?: (docId: string) => void}-export function SearchModal({ open, onClose, onOpenInventory }: SearchModalProps) {+export function SearchModal({ open, onClose, onOpenInventory, onOpenDocument }: SearchModalProps) {const [query, setQuery] = useState('')const [inventoryDevices, setInventoryEntrys] = useState<InventoryEntry[]>([])+ // Kept with the query it answered, so a stale answer is never shown against a+ // newer query and no effect has to clear it.+ const [docHits, setDocHits] = useState<{ query: string; hits: DocSearchHit[] }>({ query: '', hits: [] })const nodes = useCanvasStore((s) => s.nodes)const setSelectedNode = useCanvasStore((s) => s.setSelectedNode)const { fitView } = useReactFlow()@@ -23,9 +34,33 @@ export function SearchModal({ open, onClose, onOpenInventory }: SearchModalPropsscanApi.pending().then((res) => setInventoryEntrys(res.data)).catch(() => {})}, [open])- const searchable = nodes.filter((n) => n.data.type !== 'groupRect')const q = query.toLowerCase()+ // Documents are not in memory — the tree only ever holds their metadata, and+ // the body is what makes a search worth running — so this one goes to the+ // server's index rather than filtering a local list.+ useEffect(() => {+ if (!open || STANDALONE || !onOpenDocument) return+ const needle = query.trim()+ if (needle.length < 2) return+ let live = true+ const timer = setTimeout(async () => {+ try {+ const { data } = await documentsApi.search(needle, 5)+ if (live) setDocHits({ query: needle, hits: data.hits })+ } catch {+ // The rest of the modal still works without the index.+ if (live) setDocHits({ query: needle, hits: [] })+ }+ }, DOC_SEARCH_DEBOUNCE)+ return () => {+ live = false+ clearTimeout(timer)+ }+ }, [open, query, onOpenDocument])++ const searchable = nodes.filter((n) => n.data.type !== 'groupRect')+const nodeResults = q.length === 0 ? [] : searchable.filter((n) =>n.data.label?.toLowerCase().includes(q) ||n.data.ip?.toLowerCase().includes(q) ||@@ -43,7 +78,9 @@ export function SearchModal({ open, onClose, onOpenInventory }: SearchModalProps)).slice(0, 4)- const totalResults = nodeResults.length + pendingResults.length+ const documentResults = docHits.query && docHits.query === query.trim() ? docHits.hits : []++ const totalResults = nodeResults.length + pendingResults.length + documentResults.lengthconst handleSelectNode = useCallback((nodeId: string) => {setSelectedNode(nodeId)@@ -58,6 +95,12 @@ export function SearchModal({ open, onClose, onOpenInventory }: SearchModalPropssetQuery('')}, [onOpenInventory, onClose])+ const handleSelectDocument = useCallback((docId: string) => {+ onOpenDocument?.(docId)+ onClose()+ setQuery('')+ }, [onOpenDocument, onClose])+if (!open) return nullreturn (@@ -72,12 +115,14 @@ export function SearchModal({ open, onClose, onOpenInventory }: SearchModalPropsautoFocusvalue={query}onChange={(e) => setQuery(e.target.value)}- placeholder="Search nodes, pending devices by IP or service…"+ placeholder="Search nodes, devices and documents…"className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none"onKeyDown={(e) => {if (e.key === 'Escape') { onClose(); setQuery('') }+ // Enter takes the first result in the order they are listed.if (e.key === 'Enter' && nodeResults.length > 0) handleSelectNode(nodeResults[0].id)- if (e.key === 'Enter' && nodeResults.length === 0 && pendingResults.length > 0) handleSelectInventoryDevice(pendingResults[0].id)+ else if (e.key === 'Enter' && pendingResults.length > 0) handleSelectInventoryDevice(pendingResults[0].id)+ else if (e.key === 'Enter' && documentResults.length > 0) handleSelectDocument(documentResults[0].doc_id)}}/><kbd className="text-[10px] text-muted-foreground border border-border rounded px-1">ESC</kbd>@@ -117,6 +162,30 @@ export function SearchModal({ open, onClose, onOpenInventory }: SearchModalProps</li>)})}+ {documentResults.length > 0 && nodeResults.length + pendingResults.length > 0 && (+ <li className="px-4 py-1">+ <div className="h-px bg-border" />+ </li>+ )}+ {documentResults.map((hit) => (+ <li+ key={hit.doc_id}+ className="flex items-center gap-3 px-4 py-2 hover:bg-[#21262d] cursor-pointer"+ onClick={() => handleSelectDocument(hit.doc_id)}+ >+ <span className="text-xs font-mono text-[#a855f7] w-16 shrink-0">+ {hit.kind === 'device' ? 'doc·dev' : 'doc'}+ </span>+ <span className="text-sm text-foreground font-medium flex-1 truncate">{hit.title}</span>+ {/* The snippet is the line the match sits on; it is the only+ reason a body search beats scanning the tree by eye. */}+ {hit.snippet && (+ <span className="text-xs text-muted-foreground shrink-0 max-w-[45%] truncate">+ {hit.snippet}+ </span>+ )}+ </li>+ ))}</ul>)}@@ -125,7 +194,9 @@ export function SearchModal({ open, onClose, onOpenInventory }: SearchModalProps)}{q.length === 0 && (- <p className="px-4 py-3 text-xs text-muted-foreground">Type to search nodes and pending devices…</p>+ <p className="px-4 py-3 text-xs text-muted-foreground">+ Type to search nodes, pending devices{onOpenDocument && !STANDALONE ? ' and documents' : ''}…+ </p>)}</div></div>diff --git a/frontend/src/components/modals/__tests__/SearchModalDocuments.test.tsx b/frontend/src/components/modals/__tests__/SearchModalDocuments.test.tsxnew file mode 100644index 0000000..c3bf0d0--- /dev/null+++ b/frontend/src/components/modals/__tests__/SearchModalDocuments.test.tsx@@ -0,0 +1,160 @@+/**+ * Documents in the global search.+ *+ * Nodes and pending devices filter a list already in memory; documents cannot —+ * the tree holds their metadata and never their bodies — so this half goes to+ * the server's index, debounced, and has to behave when it is slow, when it+ * fails, and when the query has moved on.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'++import { SearchModal } from '../SearchModal'+import { documentsApi } from '@/api/client'+import { useCanvasStore } from '@/stores/canvasStore'++vi.mock('@xyflow/react', () => ({+ useReactFlow: () => ({ fitView: vi.fn() }),+}))++vi.mock('@/api/client', () => ({+ scanApi: { pending: vi.fn().mockResolvedValue({ data: [] }) },+ documentsApi: { search: vi.fn() },+}))++const api = vi.mocked(documentsApi)++function hit(overrides: Partial<{ doc_id: string; title: string; kind: string; snippet: string }> = {}) {+ return {+ doc_id: 'doc-1',+ title: 'VLAN plan',+ kind: 'page',+ snippet: 'the VLAN plan for the lab',+ device_id: null,+ ...overrides,+ }+}++function open(onOpenDocument = vi.fn()) {+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={vi.fn()} onOpenDocument={onOpenDocument} />)+ return { onOpenDocument, input: screen.getByPlaceholderText(/search nodes/i) }+}++/** Type, then let the debounce fire and the promise settle. */+async function search(input: HTMLElement, text: string) {+ fireEvent.change(input, { target: { value: text } })+ await act(async () => {+ vi.advanceTimersByTime(300)+ })+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ vi.clearAllMocks()+ useCanvasStore.setState({ nodes: [], edges: [], selectedNodeId: null })+ api.search.mockResolvedValue({ data: { engine: 'fts5', hits: [hit()] } } as never)+})++afterEach(() => vi.useRealTimers())++describe('SearchModal — documents', () => {+ it('lists a matching document with its snippet', async () => {+ const { input } = open()++ await search(input, 'vlan')++ expect(api.search).toHaveBeenCalledWith('vlan', 5)+ await waitFor(() => expect(screen.getByText('VLAN plan')).toBeTruthy())+ expect(screen.getByText('the VLAN plan for the lab')).toBeTruthy()+ })++ it('opens the document that was picked', async () => {+ const { input, onOpenDocument } = open()++ await search(input, 'vlan')+ await waitFor(() => screen.getByText('VLAN plan'))+ fireEvent.click(screen.getByText('VLAN plan'))++ expect(onOpenDocument).toHaveBeenCalledWith('doc-1')+ })++ it('marks a device document apart from a page', async () => {+ api.search.mockResolvedValue({+ data: { engine: 'fts5', hits: [hit({ kind: 'device', title: 'nas-01' })] },+ } as never)+ const { input } = open()++ await search(input, 'nas')++ await waitFor(() => expect(screen.getByText('doc·dev')).toBeTruthy())+ })++ it('does not ask the server for a one-character query', async () => {+ const { input } = open()++ await search(input, 'v')++ expect(api.search).not.toHaveBeenCalled()+ })++ it('asks once for a query typed in one go, not once per keystroke', async () => {+ const { input } = open()++ fireEvent.change(input, { target: { value: 'vl' } })+ fireEvent.change(input, { target: { value: 'vla' } })+ await search(input, 'vlan')++ expect(api.search).toHaveBeenCalledTimes(1)+ expect(api.search).toHaveBeenCalledWith('vlan', 5)+ })++ it('drops an answer once the query has moved on', async () => {+ const { input } = open()+ await search(input, 'vlan')+ await waitFor(() => screen.getByText('VLAN plan'))++ // Answers are kept with the query they answered, so this one stops applying.+ fireEvent.change(input, { target: { value: 'vlan switch' } })++ expect(screen.queryByText('VLAN plan')).toBeNull()+ })++ it('keeps working when the index is unavailable', async () => {+ api.search.mockRejectedValue(new Error('no fts'))+ useCanvasStore.setState({+ nodes: [+ {+ id: 'n1',+ type: 'server',+ position: { x: 0, y: 0 },+ data: { label: 'vlan-router', type: 'server', status: 'unknown', services: [] },+ },+ ],+ } as never)+ const { input } = open()++ await search(input, 'vlan')++ expect(screen.getByText('vlan-router')).toBeTruthy()+ expect(screen.queryByText('VLAN plan')).toBeNull()+ })++ it('asks for nothing at all when the host offers no way to open a document', async () => {+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={vi.fn()} />)++ await search(screen.getByPlaceholderText(/search nodes/i), 'vlan')++ expect(api.search).not.toHaveBeenCalled()+ expect(screen.getByText(/no results match/i)).toBeTruthy()+ })++ it('opens the first document on Enter when nothing else matched', async () => {+ const { input, onOpenDocument } = open()++ await search(input, 'vlan')+ await waitFor(() => screen.getByText('VLAN plan'))+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onOpenDocument).toHaveBeenCalledWith('doc-1')+ })+})