Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(canvas): open a node's document from its detail panel
Pouzor7c116571e3d9
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 2fb7f39..ef740b1 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -493,6 +493,18 @@ export default function App() {setDocsViewInUrl(appView === 'documentation', openDocId)}, [appView, openDocId])+ // The canvas' way into Documentation: it knows a device id, and the section+ // resolves that to a document — writing one from the device's facts when+ // there is none, exactly as picking the device in its tree would.+ const openDocumentationFor = useCallback(+ async (deviceId: string, label: string) => {+ setAppView('documentation')+ const ok = await useDocsStore.getState().openForDevice(deviceId, label)+ if (!ok) toast.error('Could not open the documentation for that device')+ },+ [setAppView],+ )+// Reopen the section, and the document, the URL asks for. Once, on boot.const docsUrlApplied = useRef(false)useEffect(() => {@@ -1190,6 +1202,11 @@ export default function App() {// Standalone has no Device Inventory to open (ADR-001 style// gate: the whole scan surface is backend-only).onOpenInventory={STANDALONE ? undefined : (deviceId) => openInventoryModal(deviceId)}+ onOpenDocumentation={+ STANDALONE+ ? undefined+ : (deviceId, label) => void openDocumentationFor(deviceId, label)+ }/>)}</div>diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsxindex 478de63..67ec011 100644--- a/frontend/src/components/modals/DeviceInventoryModal.tsx+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx@@ -236,10 +236,29 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus})}, [devices, search, sourceFilter, typeFilter, statusFilter, showOnCanvas, withServicesOnly, rackableOnly])+ // The device a caller asked for, opened once. Scrolling the card into view+ // was never the whole request — "open in inventory" means show me that+ // device, so its detail modal comes up with it. Remembering which id was+ // already honoured keeps a later filter change from reopening a modal the+ // user closed, and picker mode is left alone: it wants a device back, not a+ // second dialog on top.+ const openedHighlight = useRef<string | undefined>(undefined)useEffect(() => {- if (!highlightId || loading || !open) return- highlightRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })- }, [highlightId, loading, open, filtered])+ if (!open) {+ openedHighlight.current = undefined+ return+ }+ if (!highlightId || loading) return+ if (!onPick && openedHighlight.current !== highlightId) {+ const device = devices.find((d) => d.id === highlightId)+ if (device) {+ openedHighlight.current = highlightId+ setSelected(device)+ }+ }+ // Last, so a browser without it cannot cost the caller the detail modal.+ highlightRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'nearest' })+ }, [devices, highlightId, loading, onPick, open, filtered])const toggleSelect = (id: string) => {setSelectedIds((prev) => {diff --git a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsxindex e777265..80f1a7e 100644--- a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx+++ b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx@@ -36,10 +36,19 @@ vi.mock('@/api/client', () => ({vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())vi.mock('@/components/modals/InventoryDeviceModal', () => ({- InventoryDeviceModal: ({ device, onApprove }: { device: unknown; onApprove: (d: unknown) => void }) =>+ InventoryDeviceModal: ({+ device,+ onApprove,+ onClose,+ }: {+ device: unknown+ onApprove: (d: unknown) => void+ onClose: () => void+ }) =>device ? (<div data-testid="approval-modal"><button data-testid="do-approve" onClick={() => onApprove(device)}>approve</button>+ <button data-testid="close-detail" onClick={onClose}>close</button></div>) : null,}))@@ -164,6 +173,9 @@ const baseProps = {onClose: vi.fn(),}+// jsdom lays nothing out and has no scrollIntoView; the highlighted card calls it.+Element.prototype.scrollIntoView = vi.fn()+describe('DeviceInventoryModal', () => {it('loads and renders pending devices on open', async () => {render(<DeviceInventoryModal {...baseProps} />)@@ -272,6 +284,36 @@ describe('DeviceInventoryModal', () => {expect(screen.getByTestId('approval-modal')).toBeInTheDocument()})+ // ── highlightId — the caller asking for one device ─────────────────────────++ it('opens the detail of the device a caller pointed at', async () => {+ render(<DeviceInventoryModal {...baseProps} highlightId="dev-a" />)+ await waitFor(() => expect(screen.getByTestId('approval-modal')).toBeInTheDocument())+ })++ it('leaves the detail closed when nothing was pointed at', async () => {+ render(<DeviceInventoryModal {...baseProps} />)+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())+ expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument()+ })++ it('does not reopen a detail the user closed', async () => {+ render(<DeviceInventoryModal {...baseProps} highlightId="dev-a" />)+ await waitFor(() => expect(screen.getByTestId('approval-modal')).toBeInTheDocument())+ fireEvent.click(screen.getByTestId('close-detail'))+ // A filter change re-runs the effect; the device is still highlighted.+ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: 'host' } })+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())+ expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument()+ })++ it('hands the device back instead of stacking a dialog in picker mode', async () => {+ const onPick = vi.fn()+ render(<DeviceInventoryModal {...baseProps} highlightId="dev-a" onPick={onPick} />)+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())+ expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument()+ })+const DUP_409 = {response: {status: 409,diff --git a/frontend/src/components/panels/DetailPanel.tsx b/frontend/src/components/panels/DetailPanel.tsxindex 73546ae..3c730af 100644--- a/frontend/src/components/panels/DetailPanel.tsx+++ b/frontend/src/components/panels/DetailPanel.tsx@@ -1,5 +1,5 @@import { createElement, useRef, useState } from 'react'-import { X, Edit, Trash2, ExternalLink, Plus, Pencil, Layers, Ungroup, Eye, EyeOff, GripVertical, Boxes } from 'lucide-react'+import { X, Edit, Trash2, ExternalLink, Plus, Pencil, Layers, Ungroup, Eye, EyeOff, GripVertical, Boxes, BookOpen } from 'lucide-react'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -19,12 +19,15 @@ interface DetailPanelProps {/** Opens the Device Inventory on this node's row. Absent in contexts with no* inventory (standalone, the tour), where the link is simply not offered. */onOpenInventory?: (deviceId: string) => void+ /** Opens the Documentation section on this node's device, writing the+ * document first if it has none. Absent wherever there is no backend. */+ onOpenDocumentation?: (deviceId: string, label: string) => void}/** Open service editor: `index === null` means "add a new service". */type SvcModalState = { nodeId: string; index: number | null; form?: ServiceFormData }-export function DetailPanel({ onEdit, onOpenInventory }: DetailPanelProps) {+export function DetailPanel({ onEdit, onOpenInventory, onOpenDocumentation }: DetailPanelProps) {const { nodes, selectedNodeId, selectedNodeIds, setSelectedNode, deleteNode, updateNode, snapshotHistory, createGroup, ungroup, removeFromGroup, setNodeSize } = useCanvasStore()const serviceStatuses = useCanvasStore((s) => s.serviceStatuses)@@ -224,13 +227,25 @@ export function DetailPanel({ onEdit, onOpenInventory }: DetailPanelProps) {{data.updated_at && <DetailRow label="Last Modified" value={formatTimestamp(data.updated_at)} />}{/* The row behind this node — where the same facts live for every othercanvas showing it. */}- {data.device_id && onOpenInventory && (- <button- onClick={() => onOpenInventory(data.device_id as string)}- className="mt-1 flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"- >- <Boxes size={10} /> Open in inventory- </button>+ {data.device_id && (onOpenInventory || onOpenDocumentation) && (+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1">+ {onOpenInventory && (+ <button+ onClick={() => onOpenInventory(data.device_id as string)}+ className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"+ >+ <Boxes size={10} /> Open in inventory+ </button>+ )}+ {onOpenDocumentation && (+ <button+ onClick={() => onOpenDocumentation(data.device_id as string, data.label)}+ className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"+ >+ <BookOpen size={10} /> Open in documentation+ </button>+ )}+ </div>)}</div>diff --git a/frontend/src/components/panels/__tests__/DetailPanelInventoryLink.test.tsx b/frontend/src/components/panels/__tests__/DetailPanelInventoryLink.test.tsxindex ee96a4f..e317e11 100644--- a/frontend/src/components/panels/__tests__/DetailPanelInventoryLink.test.tsx+++ b/frontend/src/components/panels/__tests__/DetailPanelInventoryLink.test.tsx@@ -1,6 +1,7 @@/**- * The panel offers a way through to the Device Inventory row behind the node —- * the place the same facts live for every other canvas showing this device.+ * The panel offers a way through to the two places the device also lives: its+ * Device Inventory row — the same facts, for every other canvas showing it —+ * and its document.*/import { describe, it, expect, vi, beforeEach } from 'vitest'import { render, screen, fireEvent } from '@testing-library/react'@@ -45,7 +46,7 @@ function setupStore(nodeData: Partial<NodeData> = {}) {beforeEach(() => vi.clearAllMocks())-describe('DetailPanel — inventory link', () => {+describe('DetailPanel — links out to the device', () => {it('opens the inventory on the linked device', () => {setupStore({ device_id: 'dev-1' })const onOpenInventory = vi.fn()@@ -66,4 +67,32 @@ describe('DetailPanel — inventory link', () => {render(<DetailPanel onEdit={vi.fn()} />)expect(screen.queryByRole('button', { name: /Open in inventory/i })).toBeNull()})++ it('opens the documentation on the linked device, naming it after the node', () => {+ setupStore({ device_id: 'dev-1', label: 'bazarr' })+ const onOpenDocumentation = vi.fn()+ render(<DetailPanel onEdit={vi.fn()} onOpenDocumentation={onOpenDocumentation} />)++ fireEvent.click(screen.getByRole('button', { name: /Open in documentation/i }))+ expect(onOpenDocumentation).toHaveBeenCalledWith('dev-1', 'bazarr')+ })++ it('offers the documentation link for a device row, and nothing without one', () => {+ setupStore({})+ render(<DetailPanel onEdit={vi.fn()} onOpenDocumentation={vi.fn()} />)+ expect(screen.queryByRole('button', { name: /Open in documentation/i })).toBeNull()+ })++ it('offers nothing where there is no backend to document against (standalone)', () => {+ setupStore({ device_id: 'dev-1' })+ render(<DetailPanel onEdit={vi.fn()} onOpenInventory={vi.fn()} />)+ expect(screen.queryByRole('button', { name: /Open in documentation/i })).toBeNull()+ })++ it('shows both ways out side by side', () => {+ setupStore({ device_id: 'dev-1' })+ render(<DetailPanel onEdit={vi.fn()} onOpenInventory={vi.fn()} onOpenDocumentation={vi.fn()} />)+ expect(screen.getByRole('button', { name: /Open in inventory/i })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Open in documentation/i })).toBeInTheDocument()+ })})diff --git a/frontend/src/documentation/__tests__/store.test.ts b/frontend/src/documentation/__tests__/store.test.tsindex 18a409c..7a197b5 100644--- a/frontend/src/documentation/__tests__/store.test.ts+++ b/frontend/src/documentation/__tests__/store.test.ts@@ -419,3 +419,58 @@ describe('overdueIds', () => {expect([...overdueIds(docs, now)]).toEqual(['due'])})})++// ── the way in from the canvas ──────────────────────────────────────────────++describe('openForDevice', () => {+ const deviceDoc = summary({ id: 'doc-dev', kind: 'device', device_id: 'dev-1', title: 'bazarr' })++ it('opens the document a device already has', async () => {+ useDocsStore.setState({ docs: [deviceDoc], loaded: true })+ api.get.mockResolvedValue({ data: doc({ id: 'doc-dev', device_id: 'dev-1' }) } as never)++ expect(await useDocsStore.getState().openForDevice('dev-1', 'bazarr')).toBe(true)+ expect(api.create).not.toHaveBeenCalled()+ expect(api.get).toHaveBeenCalledWith('doc-dev')+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-dev')+ })++ it('fetches the listing first when the section was never opened', async () => {+ useDocsStore.setState({ docs: [], loaded: false })+ api.list.mockResolvedValue({ data: [deviceDoc] } as never)+ api.get.mockResolvedValue({ data: doc({ id: 'doc-dev', device_id: 'dev-1' }) } as never)++ expect(await useDocsStore.getState().openForDevice('dev-1', 'bazarr')).toBe(true)+ expect(api.list).toHaveBeenCalled()+ expect(api.create).not.toHaveBeenCalled()+ })++ it('writes one from the device facts when there is none', async () => {+ useDocsStore.setState({ docs: [], loaded: true })+ api.create.mockResolvedValue({ data: doc({ id: 'doc-new', device_id: 'dev-1' }) } as never)+ api.get.mockResolvedValue({ data: doc({ id: 'doc-new', device_id: 'dev-1' }) } as never)++ expect(await useDocsStore.getState().openForDevice('dev-1', 'bazarr')).toBe(true)+ expect(api.create).toHaveBeenCalledWith(+ expect.objectContaining({ title: 'bazarr', kind: 'device', device_id: 'dev-1' }),+ )+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-new')+ })++ it('falls back to a title rather than creating an unnamed document', async () => {+ useDocsStore.setState({ docs: [], loaded: true })+ api.create.mockResolvedValue({ data: doc({ id: 'doc-new' }) } as never)+ api.get.mockResolvedValue({ data: doc({ id: 'doc-new' }) } as never)++ await useDocsStore.getState().openForDevice('dev-1', ' ')+ expect(api.create).toHaveBeenCalledWith(expect.objectContaining({ title: 'Untitled device' }))+ })++ it('reports a failure rather than switching to an empty section', async () => {+ useDocsStore.setState({ docs: [], loaded: true })+ api.create.mockRejectedValue(new Error('nope'))++ expect(await useDocsStore.getState().openForDevice('dev-1', 'bazarr')).toBe(false)+ expect(useDocsStore.getState().openDoc).toBeNull()+ })+})diff --git a/frontend/src/documentation/store.ts b/frontend/src/documentation/store.tsindex 7b3bba7..55eb379 100644--- a/frontend/src/documentation/store.ts+++ b/frontend/src/documentation/store.ts@@ -120,6 +120,8 @@ export interface DocsState {loadDocs: () => Promise<void>open: (id: string) => Promise<void>+ /** Open the document describing a device, writing one first if it has none. */+ openForDevice: (deviceId: string, fallbackTitle?: string) => Promise<boolean>close: () => voidstartEdit: () => void@@ -227,6 +229,29 @@ export const useDocsStore = create<DocsState>()((set, get) => ({}},+ // The entry point from outside the section: the canvas knows a device id and+ // nothing about documents. The list may never have been fetched — this is+ // reachable without ever opening Documentation — so load it first, and treat+ // a device with no document the way the tree does, by writing one from its+ // facts rather than showing an empty section.+ openForDevice: async (deviceId, fallbackTitle) => {+ if (STANDALONE) return false+ if (!get().loaded) await get().loadDocs()+ const existing = get().docs.find((doc) => doc.device_id === deviceId)+ if (existing) {+ await get().open(existing.id)+ return true+ }+ const created = await get().create({+ title: fallbackTitle?.trim() || 'Untitled device',+ kind: 'device',+ deviceId,+ })+ if (!created) return false+ await get().open(created.id)+ return true+ },+close: () => set({ openDoc: null, draft: null, dirty: false, pendingDraft: null, revisions: [] }),startEdit: () => {