Skip to content

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

feat(services): brand icon picker and dedicated add/edit modal

Pouzorc4017c763431
diff --git a/frontend/src/components/canvas/__tests__/BaseNode.test.tsx b/frontend/src/components/canvas/__tests__/BaseNode.test.tsx
index 3c948dd..4f71303 100644
--- a/frontend/src/components/canvas/__tests__/BaseNode.test.tsx
+++ b/frontend/src/components/canvas/__tests__/BaseNode.test.tsx
@@ -44,9 +44,11 @@ vi.mock('@/utils/nodeColors', () => ({
resolveNodeColors: () => ({ background: '#161b22', border: '#30363d', icon: '#00d4ff' }),
}))
-vi.mock('@/utils/nodeIcons', () => ({
+// Partial mock: node-type icon resolution is stubbed, but the brand/lucide
+// resolver stays real so service icons render as they do in the app.
+vi.mock('@/utils/nodeIcons', async (importActual) => ({
+ ...(await importActual<typeof import('@/utils/nodeIcons')>()),
resolveNodeIcon: (_typeIcon: unknown) => _typeIcon,
- isBrandIconKey: (k: string | undefined) => !!k && k.startsWith('brand:'),
}))
vi.mock('@/utils/maskIp', () => ({
@@ -252,6 +254,27 @@ describe('BaseNode — services visibility toggle', () => {
expect(screen.queryByRole('link', { name: /ssh/i })).toBeNull()
})
+
+ it('renders the brand icon of a service that has one', () => {
+ renderBaseNode({
+ ip: '192.168.1.10',
+ custom_colors: { show_services: true },
+ services: [{ service_name: 'plex', port: 32400, protocol: 'tcp', icon: 'brand:plex' }],
+ })
+
+ const img = screen.getByAltText('plex') as HTMLImageElement
+ expect(img.src).toContain('dashboard-icons/svg/plex.svg')
+ })
+
+ it('renders no service icon when the service has none', () => {
+ renderBaseNode({
+ ip: '192.168.1.10',
+ custom_colors: { show_services: true },
+ services: [{ service_name: 'ssh', port: 22, protocol: 'tcp' }],
+ })
+
+ expect(screen.queryByRole('img')).toBeNull()
+ })
})
describe('BaseNode — legacy hardware fallback', () => {
diff --git a/frontend/src/components/canvas/nodes/BaseNode.tsx b/frontend/src/components/canvas/nodes/BaseNode.tsx
index fbfda1b..c24de87 100644
--- a/frontend/src/components/canvas/nodes/BaseNode.tsx
+++ b/frontend/src/components/canvas/nodes/BaseNode.tsx
@@ -5,6 +5,7 @@ import type { NodeData } from '@/types'
import { resolveNodeColors } from '@/utils/nodeColors'
import { resolveNodeIcon, isBrandIconKey } from '@/utils/nodeIcons'
import { NodeIcon } from '@/components/ui/NodeIcon'
+import { ServiceIcon } from '@/components/ui/ServiceIcon'
import { resolvePropertyIcon } from '@/utils/propertyIcons'
import { useThemeStore } from '@/stores/themeStore'
import { THEMES } from '@/utils/themes'
@@ -172,13 +173,16 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
>
<div className="flex items-center justify-between gap-2 w-full min-w-0">
- {/* LEFT: service name */}
- <span
- className="font-medium truncate"
- style={{ minWidth: 0, color: svcOffline ? '#f85149' : undefined }}
- title={svc.service_name}
- >
- {svc.service_name}
+ {/* LEFT: icon + service name */}
+ <span className="flex items-center gap-1 min-w-0">
+ <ServiceIcon iconKey={svc.icon} size={11} />
+ <span
+ className="font-medium truncate"
+ style={{ minWidth: 0, color: svcOffline ? '#f85149' : undefined }}
+ title={svc.service_name}
+ >
+ {svc.service_name}
+ </span>
</span>
{/* RIGHT: path + port */}
diff --git a/frontend/src/components/modals/IconPickerPanel.tsx b/frontend/src/components/modals/IconPickerPanel.tsx
new file mode 100644
index 0000000..27e5c44
--- /dev/null
+++ b/frontend/src/components/modals/IconPickerPanel.tsx
@@ -0,0 +1,93 @@
+import { createElement, useState } from 'react'
+import modalStyles from './modal-interactive.module.css'
+import { Input } from '@/components/ui/input'
+import { ICON_REGISTRY, ICON_CATEGORIES, isBrandIconKey } from '@/utils/nodeIcons'
+import { BrandIconPicker } from './BrandIconPicker'
+
+interface IconPickerPanelProps {
+ /** Current icon key — a lucide registry key or `brand:<slug>`. */
+ value?: string
+ /** Called with the new key, or `undefined` when the current generic icon is toggled off. */
+ onSelect: (key: string | undefined) => void
+ /** Focus the generic-icon search field on mount. */
+ autoFocus?: boolean
+}
+
+/**
+ * Shared Generic/Brand icon picker body. Used by NodeModal and ServiceModal so
+ * both surfaces offer the same lucide registry + dashboard-icons brand catalog.
+ */
+export function IconPickerPanel({ value, onSelect, autoFocus }: IconPickerPanelProps) {
+ const [search, setSearch] = useState('')
+ const [tab, setTab] = useState<'generic' | 'brand'>(isBrandIconKey(value) ? 'brand' : 'generic')
+
+ const tabClass = (active: boolean) =>
+ `text-[11px] px-2 py-1 rounded transition-colors cursor-pointer ${
+ active ? 'bg-[#21262d] text-foreground border border-[#30363d]' : 'text-muted-foreground hover:text-foreground'
+ }`
+
+ return (
+ <div className="flex flex-col gap-2 p-2.5 rounded-md bg-[#0d1117] border border-[#30363d]">
+ <div className="flex gap-1 mb-1" role="tablist" aria-label="Icon source">
+ <button type="button" role="tab" aria-selected={tab === 'generic'} onClick={() => setTab('generic')} className={tabClass(tab === 'generic')}>
+ Generic
+ </button>
+ <button type="button" role="tab" aria-selected={tab === 'brand'} onClick={() => setTab('brand')} className={tabClass(tab === 'brand')}>
+ Brand
+ </button>
+ </div>
+
+ {tab === 'brand' ? (
+ <BrandIconPicker value={value} onSelect={onSelect} />
+ ) : (
+ <>
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search icons…"
+ className={`bg-[#21262d] border-[#30363d] text-xs h-7 ${modalStyles['modal-radius']}`}
+ autoFocus={autoFocus}
+ />
+ <div className="flex flex-col gap-2 max-h-52 overflow-y-auto">
+ {ICON_CATEGORIES.map((cat) => {
+ const q = search.toLowerCase()
+ const entries = ICON_REGISTRY.filter(
+ (e) => e.category === cat && (search === '' || e.label.toLowerCase().includes(q) || e.key.includes(q))
+ )
+ if (entries.length === 0) return null
+ return (
+ <div key={cat}>
+ <p className="text-[9px] font-semibold text-muted-foreground/50 uppercase tracking-wider mb-1">{cat}</p>
+ <div className="grid grid-cols-7 gap-1">
+ {entries.map((entry) => {
+ const isSelected = value === entry.key
+ return (
+ <button
+ key={entry.key}
+ type="button"
+ title={entry.label}
+ onClick={() => onSelect(isSelected ? undefined : entry.key)}
+ className={`flex items-center justify-center w-7 h-7 rounded transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
+ aria-label={`Select icon ${entry.label}`}
+ style={{
+ background: isSelected ? '#00d4ff22' : 'transparent',
+ border: isSelected ? '1px solid #00d4ff88' : '1px solid transparent',
+ color: isSelected ? '#00d4ff' : '#8b949e',
+ }}
+ onMouseEnter={(e) => { if (!isSelected) (e.currentTarget as HTMLButtonElement).style.background = '#21262d' }}
+ onMouseLeave={(e) => { if (!isSelected) (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
+ >
+ {createElement(entry.icon, { size: 13 })}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/components/modals/NodeModal.tsx b/frontend/src/components/modals/NodeModal.tsx
index 4d622bf..1b11e1e 100644
--- a/frontend/src/components/modals/NodeModal.tsx
+++ b/frontend/src/components/modals/NodeModal.tsx
@@ -10,8 +10,8 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSepa
import { NODE_TYPE_LABELS, type NodeData, type NodeType, type CheckMethod, type NodeTypeStyle } from '@/types'
import { useThemeStore } from '@/stores/themeStore'
import { resolveNodeColors } from '@/utils/nodeColors'
-import { ICON_REGISTRY, ICON_CATEGORIES, NODE_TYPE_DEFAULT_ICONS, isBrandIconKey, brandIconSlug, brandIconUrl } from '@/utils/nodeIcons'
-import { BrandIconPicker } from './BrandIconPicker'
+import { ICON_REGISTRY, NODE_TYPE_DEFAULT_ICONS, isBrandIconKey, brandIconSlug, brandIconUrl } from '@/utils/nodeIcons'
+import { IconPickerPanel } from './IconPickerPanel'
import { MAX_HANDLES, clampHandles, sideDefault, handleCountField, type Side } from '@/utils/handleUtils'
import { getValidParentTypes } from '@/utils/virtualEdgeParent'
@@ -142,9 +142,7 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
const merged = { ...DEFAULT_DATA, ...initial }
if (MESH_TYPES.includes((merged.type ?? '') as NodeType)) merged.check_method = 'none'
const [form, setForm] = useState<Partial<NodeData>>(merged)
- const [iconSearch, setIconSearch] = useState('')
const [iconPickerOpen, setIconPickerOpen] = useState(false)
- const [iconTab, setIconTab] = useState<'generic' | 'brand'>(isBrandIconKey(initial?.custom_icon) ? 'brand' : 'generic')
const [labelError, setLabelError] = useState(false)
const resolvedNodeColors = resolveNodeColors({ type: form.type ?? 'generic', custom_colors: form.custom_colors })
const showServicesEnabled = form.custom_colors?.show_services === true
@@ -298,85 +296,12 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
{/* Inline icon picker - full width, shown below the type+icon row */}
{iconPickerOpen && (
- <div className="flex flex-col gap-2 p-2.5 rounded-md bg-[#0d1117] border border-[#30363d] col-span-2">
- <div className="flex gap-1 mb-1" role="tablist" aria-label="Icon source">
- <button
- type="button"
- role="tab"
- aria-selected={iconTab === 'generic'}
- onClick={() => setIconTab('generic')}
- className={`text-[11px] px-2 py-1 rounded transition-colors cursor-pointer ${
- iconTab === 'generic' ? 'bg-[#21262d] text-foreground border border-[#30363d]' : 'text-muted-foreground hover:text-foreground'
- }`}
- >
- Generic
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={iconTab === 'brand'}
- onClick={() => setIconTab('brand')}
- className={`text-[11px] px-2 py-1 rounded transition-colors cursor-pointer ${
- iconTab === 'brand' ? 'bg-[#21262d] text-foreground border border-[#30363d]' : 'text-muted-foreground hover:text-foreground'
- }`}
- >
- Brand
- </button>
- </div>
- {iconTab === 'brand' ? (
- <BrandIconPicker
- value={form.custom_icon}
- onSelect={(key) => { set('custom_icon', key); setIconPickerOpen(false) }}
- />
- ) : (
- <>
- <Input
- value={iconSearch}
- onChange={(e) => setIconSearch(e.target.value)}
- placeholder="Search icons…"
- className={`bg-[#21262d] border-[#30363d] text-xs h-7 ${modalStyles['modal-radius']}`}
+ <div className="col-span-2">
+ <IconPickerPanel
+ value={form.custom_icon}
+ onSelect={(key) => { set('custom_icon', key); setIconPickerOpen(false) }}
autoFocus
/>
- <div className="flex flex-col gap-2 max-h-52 overflow-y-auto">
- {ICON_CATEGORIES.map((cat) => {
- const entries = ICON_REGISTRY.filter(
- (e) => e.category === cat &&
- (iconSearch === '' || e.label.toLowerCase().includes(iconSearch.toLowerCase()) || e.key.includes(iconSearch.toLowerCase()))
- )
- if (entries.length === 0) return null
- return (
- <div key={cat}>
- <p className="text-[9px] font-semibold text-muted-foreground/50 uppercase tracking-wider mb-1">{cat}</p>
- <div className="grid grid-cols-7 gap-1">
- {entries.map((entry) => {
- const isSelected = form.custom_icon === entry.key
- return (
- <button
- key={entry.key}
- type="button"
- title={entry.label}
- onClick={() => { set('custom_icon', isSelected ? undefined : entry.key); setIconPickerOpen(false) }}
- className={`flex items-center justify-center w-7 h-7 rounded transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
- aria-label={`Select icon ${entry.label}`}
- style={{
- background: isSelected ? '#00d4ff22' : 'transparent',
- border: isSelected ? '1px solid #00d4ff88' : '1px solid transparent',
- color: isSelected ? '#00d4ff' : '#8b949e',
- }}
- onMouseEnter={(e) => { if (!isSelected) (e.currentTarget as HTMLButtonElement).style.background = '#21262d' }}
- onMouseLeave={(e) => { if (!isSelected) (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
- >
- {createElement(entry.icon, { size: 13 })}
- </button>
- )
- })}
- </div>
- </div>
- )
- })}
- </div>
- </>
- )}
</div>
)}
diff --git a/frontend/src/components/modals/ServiceModal.tsx b/frontend/src/components/modals/ServiceModal.tsx
new file mode 100644
index 0000000..bbbc7f0
--- /dev/null
+++ b/frontend/src/components/modals/ServiceModal.tsx
@@ -0,0 +1,191 @@
+import { createElement, useState } from 'react'
+import { ChevronDown, RotateCcw, Circle } from 'lucide-react'
+import modalStyles from './modal-interactive.module.css'
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { ICON_REGISTRY, isBrandIconKey, brandIconSlug, brandIconUrl } from '@/utils/nodeIcons'
+import { IconPickerPanel } from './IconPickerPanel'
+import { EMPTY_SERVICE_FORM, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'
+
+interface ServiceModalProps {
+ open: boolean
+ onClose: () => void
+ onSubmit: (data: ServiceSubmitData) => void
+ initial?: ServiceFormData
+ title?: string
+ confirmLabel?: string
+}
+
+export function ServiceModal({ open, onClose, onSubmit, initial, title = 'Add Service', confirmLabel = 'Add' }: ServiceModalProps) {
+ const [form, setForm] = useState<ServiceFormData>(initial ?? EMPTY_SERVICE_FORM)
+ const [iconPickerOpen, setIconPickerOpen] = useState(false)
+ const [nameError, setNameError] = useState(false)
+
+ const set = <K extends keyof ServiceFormData>(key: K, value: ServiceFormData[K]) =>
+ setForm((f) => ({ ...f, [key]: value }))
+
+ const setPort = (value: string) => set('port', value.replace(/\D/g, '').slice(0, 5))
+
+ const clampPort = () => {
+ if (!form.port) return
+ const parsed = Number.parseInt(form.port, 10)
+ set('port', Number.isFinite(parsed) ? String(Math.max(1, Math.min(65535, parsed))) : '')
+ }
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault()
+ const name = form.service_name.trim()
+ if (!name) {
+ setNameError(true)
+ return
+ }
+ const trimmedPort = form.port.trim()
+ const port = trimmedPort === '' ? undefined : Number.parseInt(trimmedPort, 10)
+ if (port != null && (Number.isNaN(port) || port < 1 || port > 65535)) return
+ const path = form.path.trim()
+ onSubmit({
+ service_name: name,
+ protocol: form.protocol,
+ port,
+ path: path || undefined,
+ icon: form.icon,
+ })
+ onClose()
+ }
+
+ const iconPreview = () => {
+ if (isBrandIconKey(form.icon)) {
+ const slug = brandIconSlug(form.icon!)
+ return (
+ <>
+ <img src={brandIconUrl(slug)} alt={slug} width={13} height={13} className="shrink-0" style={{ width: 13, height: 13, objectFit: 'contain' }} />
+ <span className="text-foreground truncate">{slug}</span>
+ </>
+ )
+ }
+ const entry = ICON_REGISTRY.find((e) => e.key === form.icon)
+ if (entry) {
+ return (
+ <>
+ {createElement(entry.icon, { size: 13, className: 'text-[#00d4ff] shrink-0' })}
+ <span className="text-foreground truncate">{entry.label}</span>
+ </>
+ )
+ }
+ // A key we can't resolve (e.g. a legacy scanner signature name) is still
+ // shown verbatim so saving doesn't look like it silently dropped it.
+ return (
+ <>
+ {createElement(Circle, { size: 13, className: 'text-muted-foreground shrink-0' })}
+ <span className="text-muted-foreground truncate">{form.icon ?? 'None'}</span>
+ </>
+ )
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
+ <DialogContent className="bg-[#161b22] border-[#30363d] text-foreground max-w-sm">
+ <DialogHeader>
+ <DialogTitle className="text-sm font-semibold">{title}</DialogTitle>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit} className="flex flex-col gap-4 mt-2">
+ {/* Name */}
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs text-muted-foreground">Name *</Label>
+ <Input
+ value={form.service_name}
+ onChange={(e) => { set('service_name', e.target.value); if (nameError) setNameError(false) }}
+ placeholder="Service name"
+ autoFocus
+ className={`bg-[#21262d] text-sm h-8 ${nameError ? 'border-[#f85149]' : 'border-[#30363d]'}`}
+ />
+ {nameError && <span className="text-[10px] text-[#f85149]">Name is required</span>}
+ </div>
+
+ {/* Port + protocol */}
+ <div className="grid grid-cols-2 gap-3">
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs text-muted-foreground">Port</Label>
+ <Input
+ type="text"
+ inputMode="numeric"
+ pattern="[0-9]*"
+ value={form.port}
+ onChange={(e) => setPort(e.target.value)}
+ onBlur={clampPort}
+ placeholder="Port"
+ className="bg-[#21262d] border-[#30363d] font-mono text-sm h-8"
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs text-muted-foreground">Protocol</Label>
+ <select
+ value={form.protocol}
+ aria-label="Protocol"
+ onChange={(e) => set('protocol', e.target.value as 'tcp' | 'udp')}
+ className={`bg-[#21262d] border border-[#30363d] text-sm h-8 px-2 text-foreground ${modalStyles['modal-radius']}`}
+ >
+ <option value="tcp">tcp</option>
+ <option value="udp">udp</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Path */}
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs text-muted-foreground">Path</Label>
+ <Input
+ value={form.path}
+ onChange={(e) => set('path', e.target.value)}
+ placeholder="Path (/admin)"
+ className="bg-[#21262d] border-[#30363d] font-mono text-sm h-8"
+ />
+ </div>
+
+ {/* Icon */}
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <Label className="text-xs text-muted-foreground">Icon</Label>
+ {form.icon && (
+ <button
+ type="button"
+ onClick={() => { set('icon', undefined); setIconPickerOpen(false) }}
+ className="flex items-center gap-1 text-[10px] text-muted-foreground/60 hover:text-muted-foreground transition-colors"
+ >
+ <RotateCcw size={10} /> Reset
+ </button>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={() => setIconPickerOpen((o) => !o)}
+ className={`flex items-center justify-between gap-2 h-8 px-3 bg-[#21262d] border border-[#30363d] text-sm transition-colors w-full cursor-pointer ${modalStyles['modal-interactive']} ${modalStyles['modal-radius']}`}
+ aria-label="Icon picker trigger"
+ >
+ <span className="flex items-center gap-2 min-w-0">{iconPreview()}</span>
+ <ChevronDown size={12} className="text-muted-foreground shrink-0" style={{ transform: iconPickerOpen ? 'rotate(180deg)' : undefined, transition: 'transform 0.15s' }} />
+ </button>
+ {iconPickerOpen && (
+ <IconPickerPanel
+ value={form.icon}
+ onSelect={(key) => { set('icon', key); setIconPickerOpen(false) }}
+ />
+ )}
+ </div>
+
+ <div className="flex justify-end gap-2 pt-1">
+ <Button type="button" variant="ghost" size="sm" className={`cursor-pointer ${modalStyles['modal-cancel-hover']}`} onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" className="bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 cursor-pointer">
+ {confirmLabel}
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/components/modals/__tests__/IconPickerPanel.test.tsx b/frontend/src/components/modals/__tests__/IconPickerPanel.test.tsx
new file mode 100644
index 0000000..7c8cd9c
--- /dev/null
+++ b/frontend/src/components/modals/__tests__/IconPickerPanel.test.tsx
@@ -0,0 +1,51 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { IconPickerPanel } from '../IconPickerPanel'
+
+describe('IconPickerPanel', () => {
+ it('opens on the Generic tab by default', () => {
+ render(<IconPickerPanel onSelect={vi.fn()} />)
+ expect(screen.getByRole('tab', { name: 'Generic' }).getAttribute('aria-selected')).toBe('true')
+ })
+
+ it('opens on the Brand tab when the current value is a brand key', () => {
+ render(<IconPickerPanel value="brand:plex" onSelect={vi.fn()} />)
+ expect(screen.getByRole('tab', { name: 'Brand' }).getAttribute('aria-selected')).toBe('true')
+ })
+
+ it('emits the lucide key when a generic icon is picked', () => {
+ const onSelect = vi.fn()
+ render(<IconPickerPanel onSelect={onSelect} />)
+ fireEvent.click(screen.getByLabelText('Select icon Database (SQL/NoSQL)'))
+ expect(onSelect).toHaveBeenCalledWith('database')
+ })
+
+ it('emits undefined when the already-selected generic icon is clicked again', () => {
+ const onSelect = vi.fn()
+ render(<IconPickerPanel value="database" onSelect={onSelect} />)
+ fireEvent.click(screen.getByLabelText('Select icon Database (SQL/NoSQL)'))
+ expect(onSelect).toHaveBeenCalledWith(undefined)
+ })
+
+ it('filters the generic grid by search text', () => {
+ render(<IconPickerPanel onSelect={vi.fn()} />)
+ fireEvent.change(screen.getByPlaceholderText('Search icons…'), { target: { value: 'grafana' } })
+ expect(screen.getByLabelText('Select icon Grafana / Kibana')).toBeDefined()
+ expect(screen.queryByLabelText('Select icon Database (SQL/NoSQL)')).toBeNull()
+ })
+
+ it('emits a prefixed key when a brand icon is picked', () => {
+ const onSelect = vi.fn()
+ render(<IconPickerPanel onSelect={onSelect} />)
+ fireEvent.click(screen.getByRole('tab', { name: 'Brand' }))
+ fireEvent.change(screen.getByLabelText('Brand icon search'), { target: { value: 'plex' } })
+ fireEvent.click(screen.getByRole('button', { name: 'plex' }))
+ expect(onSelect).toHaveBeenCalledWith('brand:plex')
+ })
+
+ it('keeps the generic search box out of the Brand tab', () => {
+ render(<IconPickerPanel onSelect={vi.fn()} />)
+ fireEvent.click(screen.getByRole('tab', { name: 'Brand' }))
+ expect(screen.queryByPlaceholderText('Search icons…')).toBeNull()
+ })
+})
diff --git a/frontend/src/components/modals/__tests__/ServiceModal.test.tsx b/frontend/src/components/modals/__tests__/ServiceModal.test.tsx
new file mode 100644
index 0000000..a5d1c1c
--- /dev/null
+++ b/frontend/src/components/modals/__tests__/ServiceModal.test.tsx
@@ -0,0 +1,182 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { ServiceModal } from '../ServiceModal'
+import { serviceToForm } from '@/utils/serviceForm'
+
+function setup(props: Partial<React.ComponentProps<typeof ServiceModal>> = {}) {
+ const onSubmit = vi.fn()
+ const onClose = vi.fn()
+ render(<ServiceModal open onClose={onClose} onSubmit={onSubmit} {...props} />)
+ return { onSubmit, onClose }
+}
+
+const submit = (label = 'Add') =>
+ fireEvent.click(screen.getByRole('button', { name: label }))
+
+describe('ServiceModal', () => {
+ describe('form submission', () => {
+ it('submits name, port, protocol and path', () => {
+ const { onSubmit, onClose } = setup()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'nginx' } })
+ fireEvent.change(screen.getByPlaceholderText('Port'), { target: { value: '80' } })
+ fireEvent.change(screen.getByLabelText('Protocol'), { target: { value: 'udp' } })
+ fireEvent.change(screen.getByPlaceholderText('Path (/admin)'), { target: { value: '/admin' } })
+ submit()
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ service_name: 'nginx',
+ protocol: 'udp',
+ port: 80,
+ path: '/admin',
+ icon: undefined,
+ })
+ expect(onClose).toHaveBeenCalledOnce()
+ })
+
+ it('submits without a port', () => {
+ const { onSubmit } = setup()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'health' } })
+ submit()
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ service_name: 'health', port: undefined, path: undefined }))
+ })
+
+ it('trims whitespace off the name and path', () => {
+ const { onSubmit } = setup()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: ' nginx ' } })
+ fireEvent.change(screen.getByPlaceholderText('Path (/admin)'), { target: { value: ' /admin ' } })
+ submit()
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ service_name: 'nginx', path: '/admin' }))
+ })
+
+ it('blocks submission and flags the field when the name is blank', () => {
+ const { onSubmit, onClose } = setup()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: ' ' } })
+ submit()
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(onClose).not.toHaveBeenCalled()
+ expect(screen.getByText('Name is required')).toBeDefined()
+ })
+
+ it('clears the name error once the user types', () => {
+ setup()
+ submit()
+ expect(screen.getByText('Name is required')).toBeDefined()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'n' } })
+ expect(screen.queryByText('Name is required')).toBeNull()
+ })
+
+ it('strips non-digits from the port field', () => {
+ setup()
+ fireEvent.change(screen.getByPlaceholderText('Port'), { target: { value: '8a0b80' } })
+ expect((screen.getByPlaceholderText('Port') as HTMLInputElement).value).toBe('8080')
+ })
+
+ it('clamps an out-of-range port on blur', () => {
+ setup()
+ const port = screen.getByPlaceholderText('Port')
+ fireEvent.change(port, { target: { value: '99999' } })
+ fireEvent.blur(port)
+ expect((port as HTMLInputElement).value).toBe('65535')
+ })
+
+ it('calls onClose without submitting on Cancel', () => {
+ const { onSubmit, onClose } = setup()
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(onClose).toHaveBeenCalledOnce()
+ })
+ })
+
+ describe('edit mode', () => {
+ const initial = serviceToForm({ port: 80, protocol: 'tcp', service_name: 'nginx', path: '/admin', icon: 'brand:nginx' })
+
+ it('prefills the form from an existing service', () => {
+ setup({ initial, title: 'Edit Service', confirmLabel: 'Save' })
+ expect((screen.getByPlaceholderText('Service name') as HTMLInputElement).value).toBe('nginx')
+ expect((screen.getByPlaceholderText('Port') as HTMLInputElement).value).toBe('80')
+ expect((screen.getByPlaceholderText('Path (/admin)') as HTMLInputElement).value).toBe('/admin')
+ expect(screen.getByText('Edit Service')).toBeDefined()
+ })
+
+ it('keeps the existing icon when nothing else changes', () => {
+ const { onSubmit } = setup({ initial, confirmLabel: 'Save' })
+ submit('Save')
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ icon: 'brand:nginx' }))
+ })
+
+ it('clears a port that the user emptied', () => {
+ const { onSubmit } = setup({ initial, confirmLabel: 'Save' })
+ fireEvent.change(screen.getByPlaceholderText('Port'), { target: { value: '' } })
+ submit('Save')
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ port: undefined }))
+ })
+
+ it('clears a path that the user emptied', () => {
+ const { onSubmit } = setup({ initial, confirmLabel: 'Save' })
+ fireEvent.change(screen.getByPlaceholderText('Path (/admin)'), { target: { value: '' } })
+ submit('Save')
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ path: undefined }))
+ })
+ })
+
+ describe('icon picker', () => {
+ it('shows "None" until an icon is picked', () => {
+ setup()
+ expect(screen.getByLabelText('Icon picker trigger').textContent).toContain('None')
+ })
+
+ it('shows an unresolvable legacy key verbatim rather than "None"', () => {
+ setup({ initial: serviceToForm({ protocol: 'tcp', service_name: 'grafana', icon: 'bar-chart-2' }) })
+ expect(screen.getByLabelText('Icon picker trigger').textContent).toContain('bar-chart-2')
+ })
+
+ it('keeps an unresolvable legacy key on save instead of dropping it', () => {
+ const { onSubmit } = setup({ initial: serviceToForm({ protocol: 'tcp', service_name: 'grafana', icon: 'bar-chart-2' }), confirmLabel: 'Save' })
+ submit('Save')
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ icon: 'bar-chart-2' }))
+ })
+
+ it('selects a generic lucide icon', () => {
+ const { onSubmit } = setup()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'db' } })
+ fireEvent.click(screen.getByLabelText('Icon picker trigger'))
+ fireEvent.click(screen.getByLabelText('Select icon Database (SQL/NoSQL)'))
+ submit()
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ icon: 'database' }))
+ })
+
+ it('selects a brand icon from the Brand tab', () => {
+ const { onSubmit } = setup()
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'plex' } })
+ fireEvent.click(screen.getByLabelText('Icon picker trigger'))
+ fireEvent.click(screen.getByRole('tab', { name: 'Brand' }))
+ fireEvent.change(screen.getByLabelText('Brand icon search'), { target: { value: 'plex' } })
+ fireEvent.click(screen.getByRole('button', { name: 'plex' }))
+ submit()
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ icon: 'brand:plex' }))
+ })
+
+ it('opens on the Brand tab when the service already carries a brand icon', () => {
+ setup({ initial: serviceToForm({ protocol: 'tcp', service_name: 'plex', icon: 'brand:plex' }) })
+ fireEvent.click(screen.getByLabelText('Icon picker trigger'))
+ expect(screen.getByRole('tab', { name: 'Brand' }).getAttribute('aria-selected')).toBe('true')
+ })
+
+ it('previews the selected brand icon on the trigger', () => {
+ setup({ initial: serviceToForm({ protocol: 'tcp', service_name: 'plex', icon: 'brand:plex' }) })
+ expect(screen.getByLabelText('Icon picker trigger').textContent).toContain('plex')
+ })
+
+ it('resets the icon back to none', () => {
+ const { onSubmit } = setup({ initial: serviceToForm({ protocol: 'tcp', service_name: 'plex', icon: 'brand:plex' }) })
+ fireEvent.click(screen.getByRole('button', { name: /Reset/ }))
+ submit()
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ icon: undefined }))
+ })
+
+ it('hides the Reset button when no icon is set', () => {
+ setup()
+ expect(screen.queryByRole('button', { name: /Reset/ })).toBeNull()
+ })
+ })
+})
diff --git a/frontend/src/components/panels/DetailPanel.tsx b/frontend/src/components/panels/DetailPanel.tsx
index 637bddb..fc78bee 100644
--- a/frontend/src/components/panels/DetailPanel.tsx
+++ b/frontend/src/components/panels/DetailPanel.tsx
@@ -9,14 +9,17 @@ import { getServiceUrl } from '@/utils/serviceUrl'
import { splitIps } from '@/utils/maskIp'
import { PROPERTY_ICONS, PROPERTY_ICON_NAMES, resolvePropertyIcon } from '@/utils/propertyIcons'
import { formatTimestamp } from '@/utils/timeFormat'
+import { ServiceModal } from '@/components/modals/ServiceModal'
+import { serviceToForm, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'
+import { ServiceIcon } from '@/components/ui/ServiceIcon'
import type { Node } from '@xyflow/react'
interface DetailPanelProps {
onEdit: (id: string) => void
}
-type SvcForm = { port: string; protocol: 'tcp' | 'udp'; service_name: string; path: string }
-const EMPTY_FORM: SvcForm = { port: '', protocol: 'tcp', service_name: '', path: '' }
+/** Open service editor: `index === null` means "add a new service". */
+type SvcModalState = { nodeId: string; index: number | null; form?: ServiceFormData }
type PropForm = { key: string; value: string; icon: string | null; visible: boolean }
const EMPTY_PROP: PropForm = { key: '', value: '', icon: null, visible: true }
@@ -25,10 +28,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
const { nodes, selectedNodeId, selectedNodeIds, setSelectedNode, deleteNode, updateNode, snapshotHistory, createGroup, ungroup, removeFromGroup, setNodeSize } = useCanvasStore()
const serviceStatuses = useCanvasStore((s) => s.serviceStatuses)
- const [addingForNode, setAddingForNode] = useState<string | null>(null)
- const [newSvc, setNewSvc] = useState<SvcForm>(EMPTY_FORM)
- const [editingFor, setEditingFor] = useState<{ nodeId: string; index: number } | null>(null)
- const [editSvc, setEditSvc] = useState<SvcForm>(EMPTY_FORM)
+ const [svcModal, setSvcModal] = useState<SvcModalState | null>(null)
const [groupName, setGroupName] = useState('')
const [creatingGroup, setCreatingGroup] = useState(false)
@@ -89,8 +89,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
}
// Normal single-node panel
- const addingService = addingForNode === node.id
- const editingIndex = editingFor?.nodeId === node.id ? editingFor.index : null
+ const openSvcModal = svcModal?.nodeId === node.id ? svcModal : null
const { data } = node
const services = data.services ?? []
const statusColor = STATUS_COLORS[data.status]
@@ -104,60 +103,46 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
}
}
- const handleAddService = () => {
- const trimmedPort = newSvc.port.trim()
- const port = trimmedPort === '' ? undefined : parseInt(trimmedPort, 10)
- if (!newSvc.service_name.trim()) return
- if (trimmedPort !== '' && (port == null || Number.isNaN(port) || port < 1 || port > 65535)) return
+ const handleSubmitService = (data: ServiceSubmitData) => {
+ if (!openSvcModal) return
snapshotHistory()
- const path = newSvc.path.trim()
- const svc: ServiceInfo = {
- ...(port != null ? { port } : {}),
- protocol: newSvc.protocol,
- service_name: newSvc.service_name.trim(),
- ...(path ? { path } : {}),
+ if (openSvcModal.index === null) {
+ const svc: ServiceInfo = {
+ ...(data.port != null ? { port: data.port } : {}),
+ protocol: data.protocol,
+ service_name: data.service_name,
+ ...(data.path ? { path: data.path } : {}),
+ ...(data.icon ? { icon: data.icon } : {}),
+ }
+ updateNode(node.id, { services: [...services, svc] })
+ return
}
- updateNode(node.id, { services: [...services, svc] })
- setNewSvc(EMPTY_FORM)
- setAddingForNode(null)
+ const updated = services.map((svc, i) =>
+ i === openSvcModal.index
+ ? {
+ ...svc,
+ protocol: data.protocol,
+ service_name: data.service_name,
+ port: data.port,
+ path: data.path,
+ icon: data.icon,
+ }
+ : svc
+ )
+ updateNode(node.id, { services: updated })
}
const handleRemoveService = (index: number) => {
snapshotHistory()
const updated = services.filter((_, i) => i !== index)
updateNode(node.id, { services: updated })
- if (editingIndex === index) setEditingFor(null)
+ if (openSvcModal?.index === index) setSvcModal(null)
}
const handleStartEdit = (index: number) => {
const svc = services[index]
if (!svc) return
- setEditSvc({ port: svc.port != null ? String(svc.port) : '', protocol: svc.protocol, service_name: svc.service_name, path: svc.path ?? '' })
- setEditingFor({ nodeId: node.id, index })
- setAddingForNode(null)
- }
-
- const handleSaveEdit = () => {
- if (editingIndex === null) return
- const trimmedPort = editSvc.port.trim()
- const port = trimmedPort === '' ? undefined : parseInt(trimmedPort, 10)
- if (!editSvc.service_name.trim()) return
- if (trimmedPort !== '' && (port == null || Number.isNaN(port) || port < 1 || port > 65535)) return
- snapshotHistory()
- const path = editSvc.path.trim()
- const updated = services.map((svc, i) =>
- i === editingIndex
- ? {
- ...svc,
- protocol: editSvc.protocol,
- service_name: editSvc.service_name.trim(),
- ...(port != null ? { port } : { port: undefined }),
- ...(path ? { path } : { path: undefined }),
- }
- : svc
- )
- updateNode(node.id, { services: updated })
- setEditingFor(null)
+ setSvcModal({ nodeId: node.id, index, form: serviceToForm(svc) })
}
const handleReorderService = (from: number, to: number) => {
@@ -351,17 +336,13 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
<div className="px-4 py-3 border-t border-border">
<div className="flex items-center justify-between mb-2">
<span className="text-xs text-muted-foreground">Services{services.length > 0 ? ` (${services.length})` : ''}</span>
- <button onClick={() => { setAddingForNode((v) => v === node.id ? null : node.id); setEditingFor(null) }} className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer">
+ <button onClick={() => setSvcModal({ nodeId: node.id, index: null })} className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer">
<Plus size={10} /> Add
</button>
</div>
- {addingService && <ServiceForm form={newSvc} onChange={setNewSvc} onConfirm={handleAddService} onCancel={() => setAddingForNode(null)} confirmLabel="Add" autoFocus />}
{services.length > 0 && (
<div className="flex flex-col gap-1.5">
- {services.map((svc, i) =>
- editingIndex === i ? (
- <ServiceForm key={`edit-${i}`} form={editSvc} onChange={setEditSvc} onConfirm={handleSaveEdit} onCancel={() => setEditingFor(null)} confirmLabel="Save" autoFocus />
- ) : (
+ {services.map((svc, i) => (
<ServiceBadge
key={`${svc.port ?? 'host'}-${svc.protocol}-${svc.path ?? ''}-${i}`}
svc={svc}
@@ -381,13 +362,24 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
onEdit={() => handleStartEdit(i)}
onRemove={() => handleRemoveService(i)}
/>
- )
- )}
+ ))}
</div>
)}
- {services.length === 0 && !addingService && <p className="text-[10px] text-muted-foreground/50">No services — click Add to register one.</p>}
+ {services.length === 0 && <p className="text-[10px] text-muted-foreground/50">No services — click Add to register one.</p>}
</div>
+ {openSvcModal && (
+ <ServiceModal
+ key={`svc-${openSvcModal.index ?? 'new'}`}
+ open
+ onClose={() => setSvcModal(null)}
+ onSubmit={handleSubmitService}
+ initial={openSvcModal.form}
+ title={openSvcModal.index === null ? 'Add Service' : 'Edit Service'}
+ confirmLabel={openSvcModal.index === null ? 'Add' : 'Save'}
+ />
+ )}
+
{data.notes && (
<div className="px-4 py-3 border-t border-border">
<div className="text-xs text-muted-foreground mb-1">Notes</div>
@@ -697,55 +689,6 @@ function DetailRow({ label, value, mono }: { label: string; value: string; mono?
)
}
-function ServiceForm({ form, onChange, onConfirm, onCancel, confirmLabel, autoFocus }: {
- form: { port: string; protocol: 'tcp' | 'udp'; service_name: string; path: string }
- onChange: (f: { port: string; protocol: 'tcp' | 'udp'; service_name: string; path: string }) => void
- onConfirm: () => void
- onCancel: () => void
- confirmLabel: string
- autoFocus?: boolean
-}) {
- const setPort = (value: string) => {
- const digitsOnly = value.replace(/\D/g, '').slice(0, 5)
- onChange({ ...form, port: digitsOnly })
- }
-
- const clampPort = (value: string) => {
- if (!value) return ''
- const parsed = Number.parseInt(value, 10)
- if (!Number.isFinite(parsed)) return ''
- return String(Math.max(1, Math.min(65535, parsed)))
- }
-
- return (
- <div className="flex flex-col gap-1.5 mb-1 p-2 rounded-md bg-[#0d1117] border border-[#30363d]">
- <Input value={form.service_name} onChange={(e) => onChange({ ...form, service_name: e.target.value })} placeholder="Service name" className="bg-[#21262d] border-[#30363d] text-xs h-7" autoFocus={autoFocus} onKeyDown={(e) => e.key === 'Enter' && onConfirm()} />
- <div className="flex gap-1.5">
- <Input
- type="text"
- inputMode="numeric"
- pattern="[0-9]*"
- value={form.port}
- onChange={(e) => setPort(e.target.value)}
- onBlur={() => onChange({ ...form, port: clampPort(form.port) })}
- placeholder="Port"
- className="bg-[#21262d] border-[#30363d] font-mono text-xs h-7 w-28 shrink-0"
- onKeyDown={(e) => e.key === 'Enter' && onConfirm()}
- />
- <select value={form.protocol} onChange={(e) => onChange({ ...form, protocol: e.target.value as 'tcp' | 'udp' })} className="flex-1 bg-[#21262d] border border-[#30363d] rounded-md text-xs h-7 px-1.5 text-foreground">
- <option value="tcp">tcp</option>
- <option value="udp">udp</option>
- </select>
- </div>
- <Input value={form.path} onChange={(e) => onChange({ ...form, path: e.target.value })} placeholder="Path (/admin)" className="bg-[#21262d] border-[#30363d] font-mono text-xs h-7" onKeyDown={(e) => e.key === 'Enter' && onConfirm()} />
- <div className="flex gap-1.5">
- <Button size="sm" className="flex-1 h-6 text-[10px] bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90" onClick={onConfirm}>{confirmLabel}</Button>
- <Button size="sm" variant="ghost" className="h-6 text-[10px]" onClick={onCancel}>Cancel</Button>
- </div>
- </div>
- )
-}
-
// --- Property components ---
function PropertyForm({ form, onChange, onConfirm, onCancel, confirmLabel }: {
@@ -926,6 +869,7 @@ function ServiceBadge({ svc, host, status, draggable, isDragging, isDragOver, on
</span>
)}
<span className="shrink-0 w-1.5 h-1.5 rounded-full" style={{ backgroundColor: color }} />
+ <ServiceIcon iconKey={svc.icon} size={12} className="shrink-0" color={color} />
{url ? (
<a
diff --git a/frontend/src/components/panels/__tests__/DetailPanel.test.tsx b/frontend/src/components/panels/__tests__/DetailPanel.test.tsx
index b40ba35..b3241e2 100644
--- a/frontend/src/components/panels/__tests__/DetailPanel.test.tsx
+++ b/frontend/src/components/panels/__tests__/DetailPanel.test.tsx
@@ -343,15 +343,58 @@ describe('DetailPanel', () => {
})
describe('Services — add/remove', () => {
- it('shows add form when Add is clicked', () => {
+ it('opens the Add Service modal when Add is clicked', () => {
setupStore({})
render(<DetailPanel onEdit={vi.fn()} />)
// Two "Add" buttons: first = properties, second = services
const addButtons = screen.getAllByText('Add')
fireEvent.click(addButtons[addButtons.length - 1])
+ expect(screen.getByText('Add Service')).toBeDefined()
expect(screen.getByPlaceholderText('Service name')).toBeDefined()
})
+ it('renders no service form until the modal is opened', () => {
+ setupStore({})
+ render(<DetailPanel onEdit={vi.fn()} />)
+ expect(screen.queryByPlaceholderText('Service name')).toBeNull()
+ })
+
+ it('persists the icon chosen in the modal', () => {
+ const updateNode = vi.fn()
+ vi.mocked(canvasStore.useCanvasStore).mockReturnValue({
+ nodes: [makeNode({})],
+ selectedNodeId: 'n1',
+ selectedNodeIds: [],
+ setSelectedNode: vi.fn(),
+ deleteNode: vi.fn(),
+ updateNode,
+ snapshotHistory: vi.fn(),
+ createGroup: vi.fn(),
+ ungroup: vi.fn(),
+ } as unknown as ReturnType<typeof canvasStore.useCanvasStore>)
+ render(<DetailPanel onEdit={vi.fn()} />)
+ const addHeaders = screen.getAllByText('Add')
+ fireEvent.click(addHeaders[addHeaders.length - 1])
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'plex' } })
+ fireEvent.click(screen.getByLabelText('Icon picker trigger'))
+ fireEvent.click(screen.getByRole('tab', { name: 'Brand' }))
+ fireEvent.change(screen.getByLabelText('Brand icon search'), { target: { value: 'plex' } })
+ fireEvent.click(screen.getByRole('button', { name: 'plex' }))
+ fireEvent.click(screen.getAllByRole('button', { name: 'Add' }).at(-1) as HTMLButtonElement)
+
+ expect(updateNode.mock.calls[0][1].services[0]).toMatchObject({ service_name: 'plex', icon: 'brand:plex' })
+ })
+
+ it('closes the modal after adding', () => {
+ setupStore({})
+ render(<DetailPanel onEdit={vi.fn()} />)
+ const addHeaders = screen.getAllByText('Add')
+ fireEvent.click(addHeaders[addHeaders.length - 1])
+ fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'nginx' } })
+ fireEvent.click(screen.getAllByRole('button', { name: 'Add' }).at(-1) as HTMLButtonElement)
+ expect(screen.queryByPlaceholderText('Service name')).toBeNull()
+ })
+
it('calls updateNode with new service on Add confirm', () => {
const updateNode = vi.fn()
vi.mocked(canvasStore.useCanvasStore).mockReturnValue({
@@ -372,7 +415,7 @@ describe('DetailPanel', () => {
fireEvent.change(screen.getByPlaceholderText('Service name'), { target: { value: 'nginx' } })
fireEvent.change(screen.getByPlaceholderText('Port'), { target: { value: '80' } })
fireEvent.change(screen.getByPlaceholderText('Path (/admin)'), { target: { value: '/admin' } })
- fireEvent.keyDown(screen.getByPlaceholderText('Port'), { key: 'Enter' })
+ fireEvent.click(screen.getAllByRole('button', { name: 'Add' }).at(-1) as HTMLButtonElement)
expect(updateNode).toHaveBeenCalledOnce()
expect(updateNode.mock.calls[0][1].services[0]).toMatchObject({ service_name: 'nginx', port: 80, protocol: 'tcp', path: '/admin' })
})
@@ -473,12 +516,13 @@ describe('DetailPanel', () => {
describe('Services — edit', () => {
const svc = { port: 80, protocol: 'tcp' as const, service_name: 'nginx' }
- it('shows edit form pre-filled when pencil is clicked', () => {
+ it('opens the Edit Service modal pre-filled when pencil is clicked', () => {
setupStore({ services: [{ ...svc, path: '/admin' }] })
render(<DetailPanel onEdit={vi.fn()} />)
// Hover to reveal edit button (fireEvent.mouseOver isn't needed — opacity is CSS only)
const editBtn = screen.getByTitle('Edit service')
fireEvent.click(editBtn)
+ expect(screen.getByText('Edit Service')).toBeDefined()
const nameInput = screen.getByPlaceholderText('Service name') as HTMLInputElement
expect(nameInput.value).toBe('nginx')
const portInput = screen.getByPlaceholderText('Port') as HTMLInputElement
@@ -512,6 +556,46 @@ describe('DetailPanel', () => {
expect(updateNode.mock.calls[0][1].services[0].path).toBe('/admin')
})
+ it('keeps fields the modal does not own, like category', () => {
+ const updateNode = vi.fn()
+ vi.mocked(canvasStore.useCanvasStore).mockReturnValue({
+ nodes: [makeNode({ services: [{ ...svc, category: 'web' }] })],
+ selectedNodeId: 'n1',
+ setSelectedNode: vi.fn(),
+ deleteNode: vi.fn(),
+ updateNode,
+ snapshotHistory: vi.fn(),
+ } as unknown as ReturnType<typeof canvasStore.useCanvasStore>)
+
+ render(<DetailPanel onEdit={vi.fn()} />)
+ fireEvent.click(screen.getByTitle('Edit service'))
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+
+ expect(updateNode.mock.calls[0][1].services[0].category).toBe('web')
+ })
+
+ it('saves a brand icon picked while editing', () => {
+ const updateNode = vi.fn()
+ vi.mocked(canvasStore.useCanvasStore).mockReturnValue({
+ nodes: [makeNode({ services: [svc] })],
+ selectedNodeId: 'n1',
+ setSelectedNode: vi.fn(),
+ deleteNode: vi.fn(),
+ updateNode,
+ snapshotHistory: vi.fn(),
+ } as unknown as ReturnType<typeof canvasStore.useCanvasStore>)
+
+ render(<DetailPanel onEdit={vi.fn()} />)
+ fireEvent.click(screen.getByTitle('Edit service'))
+ fireEvent.click(screen.getByLabelText('Icon picker trigger'))
+ fireEvent.click(screen.getByRole('tab', { name: 'Brand' }))
+ fireEvent.change(screen.getByLabelText('Brand icon search'), { target: { value: 'nginx' } })
+ fireEvent.click(screen.getByRole('button', { name: 'nginx' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+
+ expect(updateNode.mock.calls[0][1].services[0].icon).toBe('brand:nginx')
+ })
+
it('cancels edit without updating', () => {
const updateNode = vi.fn()
vi.mocked(canvasStore.useCanvasStore).mockReturnValue({
@@ -586,6 +670,25 @@ describe('DetailPanel', () => {
expect(screen.getByText('8080/tcp')).toBeDefined()
})
+ it('renders a brand icon image when the service carries one', () => {
+ setupStore({ services: [{ port: 32400, protocol: 'tcp', service_name: 'plex', icon: 'brand:plex' }] })
+ render(<DetailPanel onEdit={vi.fn()} />)
+ const img = screen.getByAltText('plex') as HTMLImageElement
+ expect(img.src).toContain('dashboard-icons/svg/plex.svg')
+ })
+
+ it('renders no icon image when the service has no icon', () => {
+ setupStore({ services: [{ port: 80, protocol: 'tcp', service_name: 'nginx' }] })
+ render(<DetailPanel onEdit={vi.fn()} />)
+ expect(screen.queryByRole('img')).toBeNull()
+ })
+
+ it('renders no icon image for an unresolvable legacy icon key', () => {
+ setupStore({ services: [{ port: 80, protocol: 'tcp', service_name: 'nginx', icon: 'bar-chart-2' }] })
+ render(<DetailPanel onEdit={vi.fn()} />)
+ expect(screen.queryByRole('img')).toBeNull()
+ })
+
it('renders path label when path is set', () => {
setupStore({ services: [{ port: 80, protocol: 'tcp', service_name: 'web', path: '/admin' }] })
render(<DetailPanel onEdit={vi.fn()} />)
diff --git a/frontend/src/components/ui/ServiceIcon.tsx b/frontend/src/components/ui/ServiceIcon.tsx
new file mode 100644
index 0000000..42eab88
--- /dev/null
+++ b/frontend/src/components/ui/ServiceIcon.tsx
@@ -0,0 +1,33 @@
+import { createElement } from 'react'
+import { resolveCustomIcon } from '@/utils/nodeIcons'
+
+interface ServiceIconProps {
+ /** Icon key on the service — a lucide registry key or `brand:<slug>`. */
+ iconKey?: string
+ size?: number
+ className?: string
+ color?: string
+}
+
+/**
+ * Renders a service's icon, or nothing when the service has no icon (or carries
+ * a key we can't resolve — e.g. a legacy scanner signature name).
+ */
+export function ServiceIcon({ iconKey, size = 12, className, color }: ServiceIconProps) {
+ const resolved = resolveCustomIcon(iconKey)
+ if (!resolved) return null
+ if (resolved.kind === 'brand') {
+ return (
+ <img
+ src={resolved.url}
+ alt={resolved.slug}
+ width={size}
+ height={size}
+ loading="lazy"
+ className={className}
+ style={{ width: size, height: size, objectFit: 'contain', flexShrink: 0 }}
+ />
+ )
+ }
+ return createElement(resolved.icon, { size, className, color })
+}
diff --git a/frontend/src/utils/__tests__/serviceForm.test.ts b/frontend/src/utils/__tests__/serviceForm.test.ts
new file mode 100644
index 0000000..3889d9a
--- /dev/null
+++ b/frontend/src/utils/__tests__/serviceForm.test.ts
@@ -0,0 +1,32 @@
+import { describe, it, expect } from 'vitest'
+import { serviceToForm, EMPTY_SERVICE_FORM } from '../serviceForm'
+
+describe('serviceToForm', () => {
+ it('maps a service onto string form fields', () => {
+ expect(serviceToForm({ port: 443, protocol: 'udp', service_name: 'svc', path: '/x', icon: 'database' })).toEqual({
+ service_name: 'svc',
+ port: '443',
+ protocol: 'udp',
+ path: '/x',
+ icon: 'database',
+ })
+ })
+
+ it('blanks out absent port and path', () => {
+ expect(serviceToForm({ protocol: 'tcp', service_name: 'svc' })).toEqual({
+ service_name: 'svc',
+ port: '',
+ protocol: 'tcp',
+ path: '',
+ icon: undefined,
+ })
+ })
+
+ it('keeps a brand icon key intact', () => {
+ expect(serviceToForm({ protocol: 'tcp', service_name: 'plex', icon: 'brand:plex' }).icon).toBe('brand:plex')
+ })
+
+ it('starts from a blank tcp form', () => {
+ expect(EMPTY_SERVICE_FORM).toEqual({ service_name: '', port: '', protocol: 'tcp', path: '' })
+ })
+})
diff --git a/frontend/src/utils/serviceForm.ts b/frontend/src/utils/serviceForm.ts
new file mode 100644
index 0000000..782eb6b
--- /dev/null
+++ b/frontend/src/utils/serviceForm.ts
@@ -0,0 +1,37 @@
+import type { ServiceInfo } from '@/types'
+
+/** String-based shape the service editor works with. */
+export interface ServiceFormData {
+ service_name: string
+ port: string
+ protocol: 'tcp' | 'udp'
+ path: string
+ icon?: string
+}
+
+/** Fields a submitted service form contributes. `undefined` clears the field. */
+export interface ServiceSubmitData {
+ service_name: string
+ protocol: 'tcp' | 'udp'
+ port: number | undefined
+ path: string | undefined
+ icon: string | undefined
+}
+
+export const EMPTY_SERVICE_FORM: ServiceFormData = {
+ service_name: '',
+ port: '',
+ protocol: 'tcp',
+ path: '',
+}
+
+/** Turn a stored service into the string-based form shape. */
+export function serviceToForm(svc: ServiceInfo): ServiceFormData {
+ return {
+ service_name: svc.service_name,
+ port: svc.port != null ? String(svc.port) : '',
+ protocol: svc.protocol,
+ path: svc.path ?? '',
+ icon: svc.icon,
+ }
+}