Merge branch 'Pouzor:main' into fix/zone-styling

This commit is contained in:
Brett Ferrante
2026-05-12 14:40:41 -04:00
committed by GitHub
67 changed files with 6400 additions and 748 deletions
@@ -0,0 +1,70 @@
import { useViewport } from '@xyflow/react'
import type { Guide } from '@/utils/alignment'
interface AlignmentGuidesProps {
guides: Guide[]
color?: string
}
/**
* SVG overlay that draws alignment guide lines on top of the React Flow canvas.
* Coordinates are in canvas (flow) space; we read the viewport transform to
* project them into screen space so lines stay locked to nodes when the user
* pans or zooms.
*/
export function AlignmentGuides({ guides, color = '#00d4ff' }: AlignmentGuidesProps) {
const { x: vx, y: vy, zoom } = useViewport()
if (guides.length === 0) return null
return (
<svg
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
pointerEvents: 'none',
zIndex: 5,
overflow: 'visible',
}}
>
{guides.map((g, i) => {
if (g.axis === 'x') {
const x = g.position * zoom + vx
const y1 = g.start * zoom + vy
const y2 = g.end * zoom + vy
return (
<line
key={`x-${i}-${g.position}`}
x1={x}
y1={y1}
x2={x}
y2={y2}
stroke={color}
strokeWidth={1}
strokeDasharray="4 3"
shapeRendering="crispEdges"
/>
)
}
const y = g.position * zoom + vy
const x1 = g.start * zoom + vx
const x2 = g.end * zoom + vx
return (
<line
key={`y-${i}-${g.position}`}
x1={x1}
y1={y}
x2={x2}
y2={y}
stroke={color}
strokeWidth={1}
strokeDasharray="4 3"
shapeRendering="crispEdges"
/>
)
})}
</svg>
)
}
@@ -20,6 +20,8 @@ import { THEMES } from '@/utils/themes'
import { nodeTypes } from './nodes/nodeTypes'
import { edgeTypes } from './edges/edgeTypes'
import { SearchBar } from './SearchBar'
import { AlignmentGuides } from './AlignmentGuides'
import { useAlignmentGuides } from '@/hooks/useAlignmentGuides'
import type { NodeData, EdgeData } from '@/types'
interface CanvasContainerProps {
@@ -83,6 +85,8 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
[]
)
const { guides, onNodeDrag, onNodeDragStop } = useAlignmentGuides()
return (
<div className="w-full h-full" style={{ background: theme.colors.canvasBackground }}>
<ReactFlow
@@ -96,6 +100,8 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
onEdgeDoubleClick={handleEdgeDoubleClick}
onNodeDoubleClick={handleNodeDoubleClick}
onNodeDragStart={onNodeDragStart}
onNodeDrag={onNodeDrag}
onNodeDragStop={onNodeDragStop}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
deleteKeyCode={['Backspace', 'Delete']}
@@ -121,6 +127,7 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
color={theme.colors.canvasDotColor}
/>
<SearchBar onOpenPending={onOpenPending} />
<AlignmentGuides guides={guides} />
<Controls>
<ControlButton
onClick={() => setLassoMode((m) => !m)}
+5 -3
View File
@@ -57,8 +57,10 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
const pendingResults = q
? pendingDevices.filter((d) =>
d.ip.toLowerCase().includes(q) ||
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)
@@ -196,10 +198,10 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
>
<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.hostname ?? d.ip}
{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}
{serviceName ?? d.ip ?? d.ieee_address ?? ''}
</span>
</button>
)
@@ -0,0 +1,47 @@
import { describe, it, expect, vi } from 'vitest'
import { render } from '@testing-library/react'
import { AlignmentGuides } from '../AlignmentGuides'
import type { Guide } from '@/utils/alignment'
vi.mock('@xyflow/react', () => ({
useViewport: () => ({ x: 50, y: 100, zoom: 2 }),
}))
describe('AlignmentGuides', () => {
it('renders nothing when no guides', () => {
const { container } = render(<AlignmentGuides guides={[]} />)
expect(container.querySelector('svg')).toBeNull()
})
it('projects an x-axis guide through the viewport transform', () => {
const guides: Guide[] = [{ axis: 'x', position: 100, start: 0, end: 200 }]
const { container } = render(<AlignmentGuides guides={guides} />)
const line = container.querySelector('line')!
// x = position * zoom + vx → 100*2 + 50 = 250
expect(line.getAttribute('x1')).toBe('250')
expect(line.getAttribute('x2')).toBe('250')
// y1 = start * zoom + vy → 0*2 + 100 = 100; y2 = 200*2 + 100 = 500
expect(line.getAttribute('y1')).toBe('100')
expect(line.getAttribute('y2')).toBe('500')
})
it('projects a y-axis guide horizontally', () => {
const guides: Guide[] = [{ axis: 'y', position: 50, start: 10, end: 60 }]
const { container } = render(<AlignmentGuides guides={guides} />)
const line = container.querySelector('line')!
// y = 50*2 + 100 = 200; x1 = 10*2 + 50 = 70; x2 = 60*2 + 50 = 170
expect(line.getAttribute('y1')).toBe('200')
expect(line.getAttribute('y2')).toBe('200')
expect(line.getAttribute('x1')).toBe('70')
expect(line.getAttribute('x2')).toBe('170')
})
it('renders one line per guide', () => {
const guides: Guide[] = [
{ axis: 'x', position: 100, start: 0, end: 200 },
{ axis: 'y', position: 50, start: 10, end: 60 },
]
const { container } = render(<AlignmentGuides guides={guides} />)
expect(container.querySelectorAll('line')).toHaveLength(2)
})
})
@@ -44,11 +44,13 @@ vi.mock('@/utils/nodeColors', () => ({
vi.mock('@/utils/nodeIcons', () => ({
resolveNodeIcon: (_typeIcon: unknown) => _typeIcon,
isBrandIconKey: (k: string | undefined) => !!k && k.startsWith('brand:'),
}))
vi.mock('@/utils/maskIp', () => ({
maskIp: (ip: string) => ip,
splitIps: (ip: string) => ip ? ip.split(',').map((s: string) => s.trim()).filter(Boolean) : [],
primaryIp: (ip: string) => ip ? ip.split(',')[0].trim() : '',
}))
vi.mock('@/utils/propertyIcons', () => ({
@@ -169,6 +171,49 @@ describe('BaseNode — properties rendering', () => {
})
})
describe('BaseNode — services visibility toggle', () => {
it('does not render service toggle button on the node', () => {
renderBaseNode({ services: [{ service_name: 'nginx', port: 80, protocol: 'tcp' }] })
expect(screen.queryByTitle('Show services')).toBeNull()
})
it('renders service rows when services are toggled on', () => {
renderBaseNode({
ip: '192.168.1.10',
custom_colors: { show_services: true },
services: [
{ service_name: 'nginx', port: 80, protocol: 'tcp' },
{ service_name: 'ssh', port: 22, protocol: 'tcp' },
],
})
expect(screen.getByText('nginx')).toBeDefined()
expect(screen.getByText('80')).toBeDefined()
expect(screen.getByText('ssh')).toBeDefined()
})
it('renders clickable service links for web services', () => {
renderBaseNode({
ip: '192.168.1.10',
custom_colors: { show_services: true },
services: [{ service_name: 'nginx', port: 80, protocol: 'tcp' }],
})
const link = screen.getByRole('link', { name: /nginx/i }) as HTMLAnchorElement
expect(link.getAttribute('href')).toBe('http://192.168.1.10:80')
})
it('keeps non-web services as non-clickable rows', () => {
renderBaseNode({
ip: '192.168.1.10',
custom_colors: { show_services: true },
services: [{ service_name: 'ssh', port: 22, protocol: 'tcp' }],
})
expect(screen.queryByRole('link', { name: /ssh/i })).toBeNull()
})
})
describe('BaseNode — legacy hardware fallback', () => {
it('renders legacy hardware when properties is undefined and show_hardware is true', () => {
renderBaseNode({
@@ -1,15 +1,17 @@
import { createElement, useEffect, useMemo } from 'react'
import { Handle, Position, NodeResizer, useUpdateNodeInternals, useViewport, type NodeProps, type Node } from '@xyflow/react'
import { Cpu, MemoryStick, HardDrive, type LucideIcon } from 'lucide-react'
import { Cpu, MemoryStick, HardDrive, ExternalLink, type LucideIcon } from 'lucide-react'
import type { NodeData } from '@/types'
import { resolveNodeColors } from '@/utils/nodeColors'
import { resolveNodeIcon } from '@/utils/nodeIcons'
import { resolveNodeIcon, isBrandIconKey } from '@/utils/nodeIcons'
import { NodeIcon } from '@/components/ui/NodeIcon'
import { resolvePropertyIcon } from '@/utils/propertyIcons'
import { useThemeStore } from '@/stores/themeStore'
import { THEMES } from '@/utils/themes'
import { useCanvasStore } from '@/stores/canvasStore'
import { maskIp, splitIps } from '@/utils/maskIp'
import { maskIp, primaryIp, splitIps } from '@/utils/maskIp'
import { bottomHandleId, bottomHandlePositions, clampBottomHandles } from '@/utils/handleUtils'
import { getServiceUrl } from '@/utils/serviceUrl'
interface BaseNodeProps extends NodeProps<Node<NodeData>> {
icon: LucideIcon
@@ -35,6 +37,9 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
const colors = resolveNodeColors(data, activeTheme)
const statusColor = theme.colors.statusColors[data.status]
const isOnline = data.status === 'online'
const services = data.services ?? []
const showServices = data.custom_colors?.show_services === true
const serviceHost = data.ip ? primaryIp(data.ip) : data.hostname
// Properties: prefer new system; fall back to legacy hardware fields for unmigrated nodes
const visibleProperties = data.properties?.filter((p) => p.visible) ?? null
@@ -94,7 +99,9 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
background: theme.colors.nodeIconBackground,
}}
>
{createElement(resolvedIcon, { size: 15 })}
{isBrandIconKey(data.custom_icon)
? <NodeIcon typeIcon={typeIcon} customIconKey={data.custom_icon} size={15} />
: createElement(resolvedIcon, { size: 15 })}
</div>
{/* Label + IP */}
@@ -138,6 +145,74 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
</>
)}
{showServices && services.length > 0 && (
<>
<div style={{ height: 1, background: `${colors.border}44`, margin: '0 8px' }} />
<div className="flex flex-col gap-1 px-2.5 py-1.5 overflow-hidden">
{services.map((svc, idx) => {
const url = getServiceUrl(svc, serviceHost)
const row = (
<div
className="nodrag flex items-center justify-between gap-2 px-1.5 py-1 rounded text-[10px] min-w-0 overflow-hidden"
style={{
background: theme.colors.nodeIconBackground,
color: theme.colors.nodeSubtextColor,
}}
>
<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 }}
title={svc.service_name}
>
{svc.service_name}
</span>
{/* RIGHT: path + port */}
<div className="flex items-center gap-2 shrink-0 min-w-0">
{svc.path && (
<span
className="truncate text-[#8b949e] text-right max-w-[80px]"
title={svc.path}
>
{svc.path}
</span>
)}
<span className="font-mono opacity-80 flex items-center gap-1">
<span>{svc.port}</span>
<ExternalLink
size={9}
className={`shrink-0 ${url ? '' : 'opacity-0'}`}
/>
</span>
</div>
</div>
</div>
)
if (!url) return <div key={`${svc.port}-${svc.protocol}-${svc.service_name}-${idx}`}>{row}</div>
return (
<a
key={`${svc.port}-${svc.protocol}-${svc.service_name}-${idx}`}
href={url}
target="_blank"
rel="noopener noreferrer"
className="block hover:opacity-85 transition-opacity"
title={url}
onClick={(e) => e.stopPropagation()}
>
{row}
</a>
)
})}
</div>
</>
)}
{/* Legacy hardware section — fallback for nodes not yet migrated */}
{showLegacyHardware && (
<>
@@ -3,7 +3,8 @@ import { Handle, Position, NodeResizer, type NodeProps, type Node } from '@xyflo
import { Layers } from 'lucide-react'
import type { NodeData } from '@/types'
import { resolveNodeColors } from '@/utils/nodeColors'
import { resolveNodeIcon } from '@/utils/nodeIcons'
import { resolveNodeIcon, isBrandIconKey } from '@/utils/nodeIcons'
import { NodeIcon } from '@/components/ui/NodeIcon'
import { resolvePropertyIcon } from '@/utils/propertyIcons'
import { useCanvasStore } from '@/stores/canvasStore'
import { maskIp, splitIps } from '@/utils/maskIp'
@@ -87,7 +88,9 @@ export function ProxmoxGroupNode(props: NodeProps<Node<NodeData>>) {
background: theme.colors.nodeIconBackground,
}}
>
{createElement(resolvedIcon, { size: 12 })}
{isBrandIconKey(data.custom_icon)
? <NodeIcon typeIcon={Layers} customIconKey={data.custom_icon} size={12} />
: createElement(resolvedIcon, { size: 12 })}
</div>
<div className="flex flex-col min-w-0 flex-1">
<span
@@ -0,0 +1,73 @@
import { NodeResizer, type NodeProps, type Node } from '@xyflow/react'
import { useCanvasStore } from '@/stores/canvasStore'
import type { NodeData } from '@/types'
const FONT_FAMILIES: Record<string, string> = {
inter: 'Inter, sans-serif',
mono: '"JetBrains Mono", monospace',
serif: 'Georgia, serif',
sans: 'system-ui, sans-serif',
}
export function TextNode({ id, data, selected }: NodeProps<Node<NodeData>>) {
const setEditingTextId = useCanvasStore((s) => s.setEditingTextId)
const rc = data.custom_colors ?? {}
const borderColor = rc.border ?? '#30363d'
const borderStyle = rc.border_style ?? 'none'
const borderWidth = rc.border_width ?? 1
const backgroundColor = rc.background ?? 'transparent'
const textColor = rc.text_color ?? '#e6edf3'
const textSize: number = rc.text_size ?? 14
const fontFamily = FONT_FAMILIES[rc.font ?? 'inter'] ?? FONT_FAMILIES.inter
const content = data.text_content ?? data.label ?? ''
return (
<>
<NodeResizer
isVisible={selected}
minWidth={40}
minHeight={20}
handleStyle={{
width: 8,
height: 8,
borderRadius: 2,
background: '#00d4ff',
border: '1px solid #0d1117',
}}
lineStyle={{ borderColor: 'transparent' }}
/>
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 8,
background: backgroundColor,
border: borderStyle === 'none' ? 'none' : `${borderWidth}px ${borderStyle} ${borderColor}`,
boxShadow: selected ? '0 0 0 1px #00d4ff, 0 0 8px #00d4ff44' : 'none',
borderRadius: 6,
boxSizing: 'border-box',
cursor: 'default',
color: textColor,
fontFamily,
fontSize: textSize,
fontWeight: 500,
userSelect: 'none',
whiteSpace: 'pre-wrap',
textAlign: 'center',
}}
onDoubleClick={(e) => {
e.stopPropagation()
setEditingTextId(id)
}}
>
{content}
</div>
</>
)
}
@@ -0,0 +1,67 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { render, fireEvent } from '@testing-library/react'
import { ReactFlowProvider } from '@xyflow/react'
import { TextNode } from '../TextNode'
import { useCanvasStore } from '@/stores/canvasStore'
import type { NodeData } from '@/types'
import type { NodeProps, Node } from '@xyflow/react'
function renderNode(data: Partial<NodeData> = {}) {
const fullData: NodeData = {
label: '',
type: 'text',
status: 'unknown',
services: [],
text_content: 'Hello',
...data,
}
const props = {
id: 't1',
data: fullData,
selected: false,
type: 'text',
zIndex: 0,
isConnectable: true,
xPos: 0,
yPos: 0,
dragging: false,
deletable: true,
draggable: true,
selectable: true,
positionAbsoluteX: 0,
positionAbsoluteY: 0,
width: 200,
height: 60,
dragHandle: undefined,
parentId: undefined,
sourcePosition: undefined,
targetPosition: undefined,
} as unknown as NodeProps<Node<NodeData>>
return render(
<ReactFlowProvider>
<TextNode {...props} />
</ReactFlowProvider>
)
}
describe('TextNode', () => {
beforeEach(() => {
useCanvasStore.setState({ editingTextId: null })
})
it('renders text_content', () => {
const { getByText } = renderNode({ text_content: 'My label' })
expect(getByText('My label')).toBeDefined()
})
it('falls back to label when text_content is missing', () => {
const { getByText } = renderNode({ text_content: undefined, label: 'Fallback' })
expect(getByText('Fallback')).toBeDefined()
})
it('double-click sets editingTextId in store', () => {
const { getByText } = renderNode({ text_content: 'Edit me' })
fireEvent.doubleClick(getByText('Edit me'))
expect(useCanvasStore.getState().editingTextId).toBe('t1')
})
})
@@ -1,7 +1,7 @@
import { type NodeProps, type Node } from '@xyflow/react'
import {
Globe, Router, Network, Server, Layers, Box, Container,
HardDrive, Cpu, Wifi, Circle, Cctv, Printer, Monitor, PlugZap, Anchor, Package, Flame,
HardDrive, Cpu, Wifi, Circle, Cctv, Printer, Monitor, PlugZap, Anchor, Package, Flame, Radio, Antenna,
} from 'lucide-react'
import { BaseNode } from './BaseNode'
import type { NodeData } from '@/types'
@@ -26,3 +26,7 @@ export const CplNode = (props: N) => <BaseNode {...props} icon={PlugZap} />
export const DockerHostNode = (props: N) => <BaseNode {...props} icon={Anchor} />
export const DockerContainerNode = (props: N) => <BaseNode {...props} icon={Package} />
export const GenericNode = (props: N) => <BaseNode {...props} icon={Circle} />
// Zigbee node types
export const ZigbeeCoordinatorNode = (props: N) => <BaseNode {...props} icon={Network} />
export const ZigbeeRouterNode = (props: N) => <BaseNode {...props} icon={Radio} />
export const ZigbeeEndDeviceNode = (props: N) => <BaseNode {...props} icon={Antenna} />
@@ -1,7 +1,8 @@
import { IspNode, RouterNode, FirewallNode, SwitchNode, ServerNode, VmNode, LxcNode, NasNode, IotNode, ApNode, CameraNode, PrinterNode, ComputerNode, CplNode, DockerHostNode, DockerContainerNode, GenericNode } from './index'
import { IspNode, RouterNode, FirewallNode, SwitchNode, ServerNode, VmNode, LxcNode, NasNode, IotNode, ApNode, CameraNode, PrinterNode, ComputerNode, CplNode, DockerHostNode, DockerContainerNode, GenericNode, ZigbeeCoordinatorNode, ZigbeeRouterNode, ZigbeeEndDeviceNode } from './index'
import { ProxmoxGroupNode } from './ProxmoxGroupNode'
import { GroupRectNode } from './GroupRectNode'
import { GroupNode } from './GroupNode'
import { TextNode } from './TextNode'
export const nodeTypes = {
isp: IspNode,
@@ -24,4 +25,8 @@ export const nodeTypes = {
generic: GenericNode,
groupRect: GroupRectNode,
group: GroupNode,
text: TextNode,
zigbee_coordinator: ZigbeeCoordinatorNode,
zigbee_router: ZigbeeRouterNode,
zigbee_enddevice: ZigbeeEndDeviceNode,
}
@@ -0,0 +1,85 @@
import { useMemo, useState } from 'react'
import { Input } from '@/components/ui/input'
import { brandIconUrl, BRAND_ICON_PREFIX } from '@/utils/nodeIcons'
import dashboardIcons from '@/data/dashboardIcons.json'
const SLUGS: string[] = dashboardIcons as string[]
const PAGE = 120
interface BrandIconPickerProps {
value?: string
onSelect: (key: string) => void
}
export function BrandIconPicker({ value, onSelect }: BrandIconPickerProps) {
const [query, setQuery] = useState('')
const [limit, setLimit] = useState(PAGE)
const filtered = useMemo(() => {
const q = query.trim().toLowerCase()
if (!q) return SLUGS
return SLUGS.filter((s) => s.includes(q))
}, [query])
const visible = filtered.slice(0, limit)
const selectedSlug = value?.startsWith(BRAND_ICON_PREFIX) ? value.slice(BRAND_ICON_PREFIX.length) : null
return (
<div className="flex flex-col gap-2">
<Input
type="text"
value={query}
onChange={(e) => { setQuery(e.target.value); setLimit(PAGE) }}
placeholder={`Search ${SLUGS.length} brand icons...`}
className="bg-[#0d1117] border-[#30363d] text-xs h-7"
aria-label="Brand icon search"
/>
<div className="text-[10px] text-muted-foreground/60">
{filtered.length} match{filtered.length === 1 ? '' : 'es'} · icons served via jsDelivr CDN
</div>
<div className="max-h-52 overflow-y-auto pr-1">
<div className="grid grid-cols-7 gap-1">
{visible.map((slug) => {
const selected = slug === selectedSlug
return (
<button
key={slug}
type="button"
onClick={() => onSelect(`${BRAND_ICON_PREFIX}${slug}`)}
title={slug}
aria-label={slug}
aria-pressed={selected}
className={`flex items-center justify-center aspect-square rounded-md border transition-colors cursor-pointer ${
selected
? 'border-[#00d4ff] bg-[#00d4ff]/10'
: 'border-[#30363d] hover:border-[#484f58] bg-[#0d1117]'
}`}
>
<img
src={brandIconUrl(slug)}
alt={slug}
loading="lazy"
width={20}
height={20}
style={{ width: 20, height: 20, objectFit: 'contain' }}
/>
</button>
)
})}
</div>
{filtered.length > limit && (
<button
type="button"
onClick={() => setLimit((l) => l + PAGE)}
className="mt-2 w-full text-[11px] text-muted-foreground hover:text-foreground py-1"
>
Load more ({filtered.length - limit} remaining)
</button>
)}
{filtered.length === 0 && (
<div className="text-center text-[11px] text-muted-foreground py-4">No icons match.</div>
)}
</div>
</div>
)
}
@@ -3,6 +3,7 @@ import { toast } from 'sonner'
import {
Globe, Router, Network, Server, Layers, Box, Container, HardDrive,
Cpu, Wifi, Camera, Printer, Monitor, PlugZap, Anchor, Package, Circle, Flame,
Radio, Zap, Lightbulb,
type LucideIcon,
} from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@@ -21,7 +22,8 @@ import { NODE_TYPE_LABELS, EDGE_TYPE_LABELS } from '@/types'
const EDITABLE_NODE_TYPES: NodeType[] = [
'isp', 'router', 'firewall', 'switch', 'server', 'proxmox', 'vm', 'lxc', 'nas',
'iot', 'ap', 'camera', 'printer', 'computer', 'cpl', 'docker_host',
'docker_container', 'generic',
'docker_container', 'zigbee_coordinator', 'zigbee_router', 'zigbee_enddevice',
'generic',
]
const EDITABLE_EDGE_TYPES: EdgeType[] = ['ethernet', 'wifi', 'iot', 'vlan', 'virtual', 'cluster']
@@ -30,7 +32,9 @@ const NODE_ICONS: Record<string, LucideIcon> = {
isp: Globe, router: Router, firewall: Flame, switch: Network, server: Server, proxmox: Layers,
vm: Box, lxc: Container, nas: HardDrive, iot: Cpu, ap: Wifi,
camera: Camera, printer: Printer, computer: Monitor, cpl: PlugZap,
docker_host: Anchor, docker_container: Package, generic: Circle,
docker_host: Anchor, docker_container: Package,
zigbee_coordinator: Radio, zigbee_router: Zap, zigbee_enddevice: Lightbulb,
generic: Circle,
}
// ── Default style for a node type (from default theme) ─────────────────────
+106 -16
View File
@@ -8,13 +8,15 @@ import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from '@/components/ui/select'
import { NODE_TYPE_LABELS, type NodeData, type NodeType, type CheckMethod } from '@/types'
import { resolveNodeColors } from '@/utils/nodeColors'
import { ICON_REGISTRY, ICON_CATEGORIES, NODE_TYPE_DEFAULT_ICONS } from '@/utils/nodeIcons'
import { ICON_REGISTRY, ICON_CATEGORIES, NODE_TYPE_DEFAULT_ICONS, isBrandIconKey, brandIconSlug, brandIconUrl } from '@/utils/nodeIcons'
import { BrandIconPicker } from './BrandIconPicker'
import { MIN_BOTTOM_HANDLES, MAX_BOTTOM_HANDLES, clampBottomHandles } from '@/utils/handleUtils'
const NODE_TYPE_GROUPS: { label: string; types: NodeType[] }[] = [
{ label: 'Hardware', types: ['isp', 'router', 'firewall', 'switch', 'server', 'nas', 'ap', 'printer'] },
{ label: 'Virtualization', types: ['proxmox', 'vm', 'lxc', 'docker_host', 'docker_container'] },
{ label: 'IoT', types: ['iot', 'camera', 'cpl'] },
{ label: 'Zigbee', types: ['zigbee_coordinator', 'zigbee_router', 'zigbee_enddevice'] },
{ label: 'Generic', types: ['computer', 'generic', 'groupRect'] },
]
@@ -60,7 +62,15 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
const [form, setForm] = useState<Partial<NodeData>>({ ...DEFAULT_DATA, ...initial })
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
const hasAppearanceOverrides = Boolean(
form.custom_colors?.border
|| form.custom_colors?.background
|| form.custom_colors?.icon
)
const set = (key: keyof NodeData, value: unknown) =>
setForm((f) => ({ ...f, [key]: value }))
@@ -87,7 +97,7 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="bg-[#161b22] border-[#30363d] text-foreground max-w-md">
<DialogContent className="bg-[#161b22] border-[#30363d] text-foreground max-w-md max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-sm font-semibold">{title}</DialogTitle>
</DialogHeader>
@@ -144,6 +154,10 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
>
<span className="flex items-center gap-2 min-w-0">
{(() => {
if (isBrandIconKey(form.custom_icon)) {
const slug = brandIconSlug(form.custom_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.custom_icon)
if (entry) {
return <>{createElement(entry.icon, { size: 13, className: 'text-[#00d4ff] shrink-0' })}<span className="text-foreground truncate">{entry.label}</span></>
@@ -159,6 +173,37 @@ 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)}
@@ -204,6 +249,8 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
)
})}
</div>
</>
)}
</div>
)}
@@ -298,21 +345,52 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
<div className="flex items-center justify-between col-span-2 py-1">
<div className="flex flex-col gap-0.5">
<Label className="text-xs text-muted-foreground">Container Mode</Label>
<span className="text-[10px] text-muted-foreground/60">Allow other nodes to nest inside this node</span>
<span className="text-[10px] text-muted-foreground/60">
Allow other nodes to nest inside this node
</span>
</div>
<button
type="button"
role="switch"
aria-label="Container Mode"
aria-checked={!!form.container_mode}
onClick={() => set('container_mode', !form.container_mode)}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full transition-colors focus:outline-none ${modalStyles['modal-interactive']}`}
style={{ background: form.container_mode ? '#ff6e00' : '#30363d' }}
>
<span
className="pointer-events-none absolute top-0.5 left-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-transform duration-200 ease-in-out"
style={{
transform: form.container_mode ? 'translateX(16px)' : 'translateX(0)'
}}
/>
</button>
</div>
)}
{/* Service visibility */}
{form.type !== 'groupRect' && form.type !== 'group' && (
<div className="flex items-start justify-between col-span-2 py-1">
<div className="flex flex-col gap-0.5">
<Label className="text-xs text-muted-foreground">Show Services</Label>
<span className="text-[10px] text-muted-foreground/60">Display discovered services on the node card</span>
</div>
<button
type="button"
role="switch"
aria-checked={!!form.container_mode}
onClick={() => set('container_mode', !form.container_mode)}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full transition-colors focus:outline-none ${modalStyles['modal-interactive']}`}
tabIndex={0}
aria-label="Toggle container mode"
style={{ background: form.container_mode ? '#ff6e00' : '#30363d' }}
aria-label="Show Services"
aria-checked={showServicesEnabled}
onClick={() => set('custom_colors', {
...form.custom_colors,
show_services: !showServicesEnabled,
})}
className="relative inline-flex h-5 w-9 mt-1 shrink-0 cursor-pointer rounded-full transition-colors focus:outline-none"
style={{ background: showServicesEnabled ? resolvedNodeColors.icon : '#30363d' }}
>
<span
className="pointer-events-none absolute top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-all"
style={{ left: form.container_mode ? 'calc(100% - 18px)' : '2px' }}
className="pointer-events-none absolute top-px left-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-transform duration-200 ease-in-out"
style={{ transform: showServicesEnabled ? 'translateX(16px)' : 'translateX(0)' }}
/>
</button>
</div>
@@ -322,10 +400,20 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
<div className="flex flex-col gap-2 col-span-2">
<div className="flex items-center justify-between">
<Label className="text-xs text-muted-foreground">Appearance</Label>
{form.custom_colors && (
{hasAppearanceOverrides && (
<button
type="button"
onClick={() => set('custom_colors', undefined)}
onClick={() => setForm((f) => {
if (!f.custom_colors) return f
const { border, background, icon, ...rest } = f.custom_colors
void border
void background
void icon
return {
...f,
custom_colors: Object.keys(rest).length > 0 ? rest : undefined,
}
})}
className="flex items-center gap-1 text-[10px] text-muted-foreground/60 hover:text-muted-foreground transition-colors"
>
<RotateCcw size={10} /> Reset to defaults
@@ -359,9 +447,11 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'
)
})}
</div>
{!form.custom_colors && (
<p className="text-[10px] text-muted-foreground/50">Using default colors for {NODE_TYPE_LABELS[form.type ?? 'generic']}. Click a swatch to customize.</p>
)}
<div className="min-h-3.5">
{!hasAppearanceOverrides && (
<p className="text-[10px] text-muted-foreground/50">Using default colors for {NODE_TYPE_LABELS[form.type ?? 'generic']}. Click a swatch to customize.</p>
)}
</div>
</div>
{/* Bottom connection points (not for group containers) */}
@@ -12,7 +12,7 @@ interface Service {
export interface PendingDevice {
id: string
ip: string
ip: string | null
mac: string | null
hostname: string | null
os: string | null
@@ -20,6 +20,12 @@ export interface PendingDevice {
suggested_type: string | null
status: string
discovery_source: string | null
ieee_address?: string | null
friendly_name?: string | null
device_subtype?: string | null
model?: string | null
vendor?: string | null
lqi?: number | null
discovered_at: string
}
@@ -77,6 +83,8 @@ export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnor
if (!device) return null
const TypeIcon = TYPE_ICONS[device.suggested_type ?? 'generic'] ?? Circle
const isZigbee = device.discovery_source === 'zigbee'
const titleLabel = device.friendly_name ?? device.hostname ?? device.ip ?? device.ieee_address ?? 'Pending device'
const handleApprove = () => { onApprove(device) }
const handleHide = () => { onHide(device); onClose() }
@@ -88,17 +96,30 @@ export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnor
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-sm font-semibold">
<TypeIcon size={15} className="text-[#00d4ff] shrink-0" />
{device.hostname ?? device.ip}
{titleLabel}
{isZigbee && (
<span className="ml-1 text-[9px] font-mono uppercase px-1 py-0.5 rounded bg-[#00d4ff]/15 text-[#00d4ff] border border-[#00d4ff]/30">
Zigbee
</span>
)}
</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 mt-1">
{/* Device info */}
<div className="flex flex-col gap-1.5 p-3 rounded-md bg-[#21262d] border border-[#30363d]">
<InfoRow label="IP" value={device.ip} />
{device.ip && <InfoRow label="IP" value={device.ip} />}
{device.hostname && <InfoRow label="Hostname" value={device.hostname} />}
{device.mac && <InfoRow label="MAC" value={device.mac} />}
{device.os && <InfoRow label="OS" value={device.os} />}
{device.ieee_address && <InfoRow label="IEEE" value={device.ieee_address} />}
{device.friendly_name && device.friendly_name !== device.hostname && (
<InfoRow label="Name" value={device.friendly_name} />
)}
{device.vendor && <InfoRow label="Vendor" value={device.vendor} />}
{device.model && <InfoRow label="Model" value={device.model} />}
{device.device_subtype && <InfoRow label="Role" value={device.device_subtype} />}
{device.lqi != null && <InfoRow label="LQI" value={String(device.lqi)} />}
{device.suggested_type && (
<InfoRow label="Type" value={device.suggested_type} />
)}
@@ -108,8 +129,8 @@ export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnor
<InfoRow label="Discovered" value={new Date(device.discovered_at.endsWith('Z') ? device.discovered_at : device.discovered_at + 'Z').toLocaleString()} />
</div>
{/* Services */}
<div>
{/* Services (skipped for Zigbee devices — they don't have IP services) */}
{!isZigbee && <div>
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1.5">
Services found ({device.services.length})
</p>
@@ -138,7 +159,7 @@ export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnor
))}
</div>
)}
</div>
</div>}
{/* Actions */}
<div className="flex gap-2 pt-1">
@@ -0,0 +1,677 @@
import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import {
Globe, Router, Server, Layers, Box, Container, HardDrive, Cpu, Wifi, Circle, Network,
Search, RefreshCw, X, CheckCircle2, EyeOff, Trash2, Loader2,
} from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { scanApi } from '@/api/client'
import { useCanvasStore } from '@/stores/canvasStore'
import { toast } from 'sonner'
import { PendingDeviceModal, type PendingDevice } from '@/components/modals/PendingDeviceModal'
import type { NodeType, ServiceInfo } from '@/types'
interface PendingDevicesModalProps {
open: boolean
onClose: () => void
highlightId?: string
initialStatus?: 'pending' | 'hidden'
}
const PORT_COLORS: Record<number, string> = {
22: '#a855f7', // SSH purple
80: '#00d4ff', // HTTP cyan
443: '#39d353', // HTTPS green
53: '#e3b341', // DNS amber
3306: '#a855f7', // MySQL
5432: '#a855f7', // Postgres
6379: '#f85149', // Redis
9090: '#e3b341', // Prometheus
3000: '#00d4ff', // Grafana/dev
8080: '#00d4ff',
8443: '#39d353',
}
const CATEGORY_COLORS: Record<string, string> = {
hypervisor: '#ff6e00',
nas: '#39d353',
automation: '#a855f7',
containers: '#00d4ff',
network: '#39d353',
security: '#f85149',
monitoring: '#e3b341',
database: '#a855f7',
web: '#00d4ff',
media: '#ff6e00',
iot: '#e3b341',
}
function serviceColor(port: number | null | undefined, category?: string | null): string {
if (port != null && PORT_COLORS[port]) return PORT_COLORS[port]
if (category && CATEGORY_COLORS[category.toLowerCase()]) return CATEGORY_COLORS[category.toLowerCase()]
return '#8b949e'
}
const TYPE_ICONS: Record<string, React.ElementType> = {
isp: Globe,
router: Router,
server: Server,
proxmox: Layers,
vm: Box,
lxc: Container,
nas: HardDrive,
iot: Cpu,
ap: Wifi,
switch: Network,
generic: Circle,
}
type SourceFilter = 'all' | 'ip' | 'zigbee'
type StatusFilter = 'pending' | 'hidden'
function inferSource(d: PendingDevice): 'zigbee' | 'ip' {
if (d.discovery_source === 'zigbee' || d.ieee_address) return 'zigbee'
return 'ip'
}
const COMMON_PORTS = new Set([22, 80, 443])
function specialServiceName(d: PendingDevice): string | undefined {
const candidates = (d.services ?? []).filter(
(s) => s.category != null && s.port != null && !COMMON_PORTS.has(s.port) && s.service_name,
)
// Deprioritize generic web category so apps like home assistant / jellyfin win
const nonWeb = candidates.find((s) => s.category?.toLowerCase() !== 'web')
return (nonWeb ?? candidates[0])?.service_name ?? undefined
}
function deviceLabel(d: PendingDevice): string {
return d.friendly_name ?? d.hostname ?? specialServiceName(d) ?? d.ip ?? d.ieee_address ?? 'device'
}
function injectAutoEdges(edges: { id: string; source: string; target: string }[] | undefined) {
if (!edges || edges.length === 0) return
useCanvasStore.setState((state) => ({
edges: [
...state.edges,
...edges.map((e) => ({
id: e.id,
source: e.source,
target: e.target,
sourceHandle: 'bottom',
targetHandle: 'top-t',
type: 'iot',
data: { type: 'iot' as const },
})),
],
hasUnsavedChanges: true,
}))
}
export function PendingDevicesModal({ open, onClose, highlightId, initialStatus = 'pending' }: PendingDevicesModalProps) {
const [devices, setDevices] = useState<PendingDevice[]>([])
const [loading, setLoading] = useState(false)
const [selected, setSelected] = useState<PendingDevice | null>(null)
const [selectMode, setSelectMode] = useState(false)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [search, setSearch] = useState('')
const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all')
const [typeFilter, setTypeFilter] = useState<string>('all')
const [statusFilter, setStatusFilter] = useState<StatusFilter>(initialStatus)
const { addNode, scanEventTs } = useCanvasStore()
const highlightRef = useRef<HTMLButtonElement>(null)
const load = useCallback(async () => {
setLoading(true)
try {
const res = statusFilter === 'pending' ? await scanApi.pending() : await scanApi.hidden()
setDevices(res.data)
} catch {
toast.error(`Failed to load ${statusFilter} devices`)
} finally {
setLoading(false)
}
}, [statusFilter])
useEffect(() => { if (open) load() }, [open, load])
useEffect(() => { if (open && scanEventTs > 0) load() }, [scanEventTs, open, load])
// Reset transient state when reopening
useEffect(() => {
if (!open) {
setSelectMode(false)
setSelectedIds(new Set())
setSearch('')
} else {
setStatusFilter(initialStatus)
}
}, [open, initialStatus])
const distinctTypes = useMemo(() => {
const set = new Set<string>()
devices.forEach((d) => { if (d.suggested_type) set.add(d.suggested_type) })
return [...set].sort()
}, [devices])
const filtered = useMemo(() => {
const q = search.trim().toLowerCase()
return devices.filter((d) => {
if (sourceFilter !== 'all' && inferSource(d) !== sourceFilter) return false
if (typeFilter !== 'all' && d.suggested_type !== typeFilter) return false
if (q) {
const hay = [
d.friendly_name, d.hostname, d.ip, d.mac, d.ieee_address, d.vendor, d.model,
...d.services.map((s) => s.service_name),
].filter(Boolean).join(' ').toLowerCase()
if (!hay.includes(q)) return false
}
return true
})
}, [devices, search, sourceFilter, typeFilter])
useEffect(() => {
if (!highlightId || loading || !open) return
highlightRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}, [highlightId, loading, open, filtered])
const toggleSelect = (id: string) => {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id); else next.add(id)
return next
})
}
const handleCardClick = (d: PendingDevice) => {
if (selectMode) { toggleSelect(d.id); return }
if (statusFilter === 'hidden') { handleRestore(d); return }
setSelected(d)
}
const handleRestore = async (device: PendingDevice) => {
try {
await scanApi.restore(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
toast.success(`Restored ${deviceLabel(device)}`)
} catch {
toast.error('Failed to restore device')
}
}
const handleBulkRestore = async () => {
const ids = [...selectedIds]
if (ids.length === 0) return
try {
const res = await scanApi.bulkRestore(ids)
setDevices((prev) => prev.filter((d) => !ids.includes(d.id)))
setSelectedIds(new Set())
toast.success(`Restored ${res.data.restored} device${res.data.restored !== 1 ? 's' : ''}`)
} catch {
toast.error('Failed to bulk restore devices')
}
}
const enterSelectMode = () => {
setSelectMode(true)
}
const exitSelectMode = () => {
setSelectMode(false)
setSelectedIds(new Set())
}
const selectAllVisible = () => {
setSelectedIds(new Set(filtered.map((d) => d.id)))
}
const handleClearAll = async () => {
const targets = filtered
if (targets.length === 0) return
const filtersActive = targets.length !== devices.length
try {
if (filtersActive) {
const results = await Promise.allSettled(targets.map((d) => scanApi.ignore(d.id)))
const failed = results.filter((r) => r.status === 'rejected').length
const removedIds = new Set(
targets.filter((_, i) => results[i].status === 'fulfilled').map((d) => d.id)
)
setDevices((prev) => prev.filter((d) => !removedIds.has(d.id)))
setSelectedIds(new Set())
if (failed > 0) toast.error(`Removed ${removedIds.size}, ${failed} failed`)
else toast.success(`Removed ${removedIds.size} device${removedIds.size !== 1 ? 's' : ''}`)
} else {
await scanApi.clearPending()
setDevices([])
setSelectedIds(new Set())
toast.success('Pending devices cleared')
}
} catch {
toast.error('Failed to clear pending devices')
}
}
const handleApprove = async (device: PendingDevice) => {
try {
const fallbackLabel = deviceLabel(device)
const nodeData = {
label: fallbackLabel,
type: (device.suggested_type ?? 'generic') as NodeType,
ip: device.ip ?? undefined,
hostname: device.hostname ?? undefined,
status: 'unknown',
services: (device.services ?? []) as ServiceInfo[],
}
const res = await scanApi.approve(device.id, nodeData)
const nodeId = res.data.node_id
addNode({
id: nodeId,
type: nodeData.type,
position: { x: 400, y: 300 },
data: { ...nodeData, status: 'unknown' as const },
})
injectAutoEdges(res.data.edges)
const extra = res.data.edges_created > 0 ? ` (+${res.data.edges_created} link${res.data.edges_created !== 1 ? 's' : ''})` : ''
toast.success(`Approved ${nodeData.label}${extra}`)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
setSelected(null)
} catch {
toast.error('Failed to approve device')
}
}
const handleHide = async (device: PendingDevice) => {
try {
await scanApi.hide(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
setSelected(null)
toast.success('Device hidden')
} catch {
toast.error('Failed to hide device')
}
}
const handleIgnore = async (device: PendingDevice) => {
try {
await scanApi.ignore(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
setSelected(null)
} catch {
toast.error('Failed to remove device')
}
}
const handleBulkApprove = async () => {
const ids = [...selectedIds]
if (ids.length === 0) return
try {
const res = await scanApi.bulkApprove(ids)
const deviceToNode: Record<string, string> = {}
res.data.device_ids.forEach((did, i) => { deviceToNode[did] = res.data.node_ids[i] })
const approvedDevices = devices.filter((d) => ids.includes(d.id))
approvedDevices.forEach((d, i) => {
const nodeId = deviceToNode[d.id]
if (!nodeId) return
addNode({
id: nodeId,
type: (d.suggested_type ?? 'generic') as NodeType,
position: { x: 400 + (i % 4) * 160, y: 300 + Math.floor(i / 4) * 100 },
data: {
label: deviceLabel(d),
type: (d.suggested_type ?? 'generic') as NodeType,
ip: d.ip ?? undefined,
hostname: d.hostname ?? undefined,
status: 'unknown' as const,
services: (d.services ?? []) as ServiceInfo[],
},
})
})
injectAutoEdges(res.data.edges)
setDevices((prev) => prev.filter((d) => !ids.includes(d.id)))
setSelectedIds(new Set())
const linkExtra = res.data.edges_created > 0 ? ` (+${res.data.edges_created} link${res.data.edges_created !== 1 ? 's' : ''})` : ''
toast.success(`Approved ${res.data.approved} device${res.data.approved !== 1 ? 's' : ''}${linkExtra}`)
} catch {
toast.error('Failed to bulk approve devices')
}
}
const handleBulkHide = async () => {
const ids = [...selectedIds]
if (ids.length === 0) return
try {
const res = await scanApi.bulkHide(ids)
setDevices((prev) => prev.filter((d) => !ids.includes(d.id)))
setSelectedIds(new Set())
toast.success(`Hidden ${res.data.hidden} device${res.data.hidden !== 1 ? 's' : ''}`)
} catch {
toast.error('Failed to bulk hide devices')
}
}
// Keyboard shortcuts: 's' select-mode, 'a' select-all-visible, Esc clears selection or closes, '/' focuses search
const searchRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (!open) return
const handler = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null
const inField = target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT')
if (e.key === 'Escape') {
if (selectMode && selectedIds.size > 0) { e.preventDefault(); setSelectedIds(new Set()) }
return
}
if (inField) return
if (e.key === '/') { e.preventDefault(); searchRef.current?.focus() }
else if (e.key.toLowerCase() === 's') { e.preventDefault(); if (selectMode) exitSelectMode(); else enterSelectMode() }
else if (e.key.toLowerCase() === 'a' && selectMode) { e.preventDefault(); selectAllVisible() }
else if (e.key === 'Enter' && selectMode && selectedIds.size > 0) { e.preventDefault(); handleBulkApprove() }
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, selectMode, selectedIds, filtered])
return (
<>
<Dialog open={open} onOpenChange={(v) => { if (!v) onClose() }}>
<DialogContent
showCloseButton={false}
className="!max-w-none w-[95vw] h-[90vh] p-0 flex flex-col gap-0 bg-[#0d1117] border-border"
>
<DialogHeader className="px-4 py-3 border-b border-border shrink-0">
<div className="flex items-center justify-between gap-3">
<DialogTitle className="text-base font-semibold flex items-center gap-2">
{statusFilter === 'pending' ? 'Pending Devices' : 'Hidden Devices'}
<span className="text-muted-foreground font-normal text-xs">
({filtered.length}{filtered.length !== devices.length && ` of ${devices.length}`})
</span>
</DialogTitle>
<div className="flex items-center gap-1">
<button onClick={load} className="text-muted-foreground hover:text-foreground p-1.5 rounded transition-colors" title="Refresh">
<RefreshCw size={14} />
</button>
{statusFilter === 'pending' && devices.length > 0 && (
<button
onClick={handleClearAll}
className="text-muted-foreground hover:text-[#f85149] p-1.5 rounded transition-colors"
title={filtered.length !== devices.length ? `Remove ${filtered.length} filtered` : 'Clear all pending'}
>
<Trash2 size={14} />
</button>
)}
<button onClick={onClose} className="text-muted-foreground hover:text-foreground p-1.5 rounded transition-colors" title="Close">
<X size={14} />
</button>
</div>
</div>
</DialogHeader>
{/* Toolbar */}
<div className="px-4 py-2 border-b border-border bg-[#161b22] shrink-0 flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-[200px] max-w-md">
<Search size={12} className="absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground" />
<input
ref={searchRef}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search name, IP, MAC, IEEE, service…"
className="w-full text-xs bg-[#0d1117] border border-border rounded px-7 py-1.5 outline-none focus:border-[#00d4ff]/50"
/>
</div>
<div className="flex rounded border border-border overflow-hidden text-xs" role="group" aria-label="Source filter">
<button
onClick={() => setSourceFilter('all')}
className={`px-2.5 py-1.5 transition-colors ${sourceFilter === 'all' ? 'bg-[#00d4ff]/20 text-[#00d4ff]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
>
All
</button>
<button
onClick={() => setSourceFilter('ip')}
className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'ip' ? 'bg-[#a855f7]/20 text-[#a855f7]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
>
IP scan
</button>
<button
onClick={() => setSourceFilter('zigbee')}
className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'zigbee' ? 'bg-[#00d4ff]/20 text-[#00d4ff]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
>
Zigbee
</button>
</div>
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="text-xs bg-[#0d1117] border border-border rounded px-2 py-1.5 outline-none focus:border-[#00d4ff]/50"
aria-label="Type filter"
>
<option value="all">All types</option>
{distinctTypes.map((t) => <option key={t} value={t}>{t}</option>)}
</select>
<div className="flex rounded border border-border overflow-hidden text-xs">
<button
onClick={() => setStatusFilter('pending')}
className={`px-2.5 py-1.5 transition-colors ${statusFilter === 'pending' ? 'bg-[#00d4ff]/20 text-[#00d4ff]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
>
Pending
</button>
<button
onClick={() => setStatusFilter('hidden')}
className={`px-2.5 py-1.5 transition-colors ${statusFilter === 'hidden' ? 'bg-[#8b949e]/20 text-foreground' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
>
Hidden
</button>
</div>
<button
onClick={() => selectMode ? exitSelectMode() : enterSelectMode()}
className={`text-xs px-2.5 py-1.5 rounded border transition-colors ${selectMode ? 'bg-[#00d4ff]/20 text-[#00d4ff] border-[#00d4ff]/50' : 'bg-[#0d1117] text-muted-foreground border-border hover:text-foreground'}`}
title="Toggle select mode (s)"
>
{selectMode ? 'Exit select' : 'Select mode'}
</button>
</div>
{/* Body */}
<div className="flex-1 min-h-0 overflow-y-auto p-4">
{loading && (
<div className="flex items-center justify-center py-10">
<Loader2 size={20} className="animate-spin text-muted-foreground" />
</div>
)}
{!loading && filtered.length === 0 && (
<p className="text-xs text-muted-foreground text-center py-10">
{devices.length === 0 ? `No ${statusFilter} devices` : 'No devices match filters'}
</p>
)}
{!loading && filtered.length > 0 && (
<div className="grid grid-cols-1 lg:grid-cols-2 2xl:grid-cols-3 gap-3">
{filtered.map((d) => (
<DeviceCard
key={d.id}
device={d}
selected={selectedIds.has(d.id)}
selectMode={selectMode}
highlighted={d.id === highlightId}
onClick={() => handleCardClick(d)}
cardRef={d.id === highlightId ? highlightRef : undefined}
/>
))}
</div>
)}
</div>
{/* Selection action bar */}
{selectMode && (
<div className="px-4 py-2.5 border-t border-border bg-[#161b22] shrink-0 flex items-center gap-2 flex-wrap">
<span className="text-xs text-muted-foreground mr-1">
{selectedIds.size} selected
</span>
<button
onClick={selectAllVisible}
className="text-xs px-2.5 py-1.5 rounded border border-border text-muted-foreground hover:text-foreground transition-colors"
>
Select all visible ({filtered.length})
</button>
<button
onClick={() => setSelectedIds(new Set())}
disabled={selectedIds.size === 0}
className="text-xs px-2.5 py-1.5 rounded border border-border text-muted-foreground hover:text-foreground disabled:opacity-40 transition-colors"
>
Clear
</button>
<div className="flex-1" />
{statusFilter === 'pending' && (
<>
<button
onClick={handleBulkApprove}
disabled={selectedIds.size === 0}
className="text-xs px-3 py-1.5 rounded bg-[#39d353]/20 text-[#39d353] hover:bg-[#39d353]/30 disabled:opacity-40 font-medium transition-colors"
>
Approve ({selectedIds.size})
</button>
<button
onClick={handleBulkHide}
disabled={selectedIds.size === 0}
className="text-xs px-3 py-1.5 rounded bg-[#8b949e]/20 text-[#8b949e] hover:bg-[#8b949e]/30 disabled:opacity-40 font-medium transition-colors"
>
Hide ({selectedIds.size})
</button>
</>
)}
{statusFilter === 'hidden' && (
<button
onClick={handleBulkRestore}
disabled={selectedIds.size === 0}
className="text-xs px-3 py-1.5 rounded bg-[#e3b341]/20 text-[#e3b341] hover:bg-[#e3b341]/30 disabled:opacity-40 font-medium transition-colors"
>
Restore ({selectedIds.size})
</button>
)}
</div>
)}
</DialogContent>
</Dialog>
<PendingDeviceModal
device={selected}
onClose={() => setSelected(null)}
onApprove={handleApprove}
onHide={handleHide}
onIgnore={handleIgnore}
/>
</>
)
}
interface DeviceCardProps {
device: PendingDevice
selected: boolean
selectMode: boolean
highlighted: boolean
onClick: () => void
cardRef?: React.Ref<HTMLButtonElement>
}
function DeviceCard({ device, selected, selectMode, highlighted, onClick, cardRef }: DeviceCardProps) {
const source = inferSource(device)
const Icon = TYPE_ICONS[device.suggested_type ?? 'generic'] ?? Circle
const label = deviceLabel(device)
const sourceColor = source === 'zigbee' ? '#00d4ff' : '#a855f7'
const sourceLabel = source === 'zigbee' ? 'ZIGBEE' : (device.discovery_source ?? 'IP').toUpperCase()
const services = device.services ?? []
const visibleServices = services.slice(0, 4)
const moreServices = services.length - visibleServices.length
const borderClass = highlighted
? 'border-[#e3b341] bg-[#2d3748]'
: selected
? 'border-[#00d4ff] bg-[#00d4ff]/5 shadow-[0_0_0_1px_rgba(0,212,255,0.4)] scale-[1.02]'
: 'border-border bg-[#161b22] hover:border-[#30363d] hover:bg-[#21262d]'
return (
<button
ref={cardRef}
onClick={onClick}
data-testid={`pending-card-${device.id}`}
className={`relative text-left rounded-lg border p-3 transition-all duration-150 ${borderClass}`}
>
{selectMode && selected && (
<CheckCircle2
size={18}
className="absolute top-2 right-2 text-[#00d4ff] fill-[#0d1117]"
/>
)}
{!selectMode && device.status === 'hidden' && (
<EyeOff size={14} className="absolute top-2 right-2 text-muted-foreground" />
)}
{/* Header */}
<div className="flex items-start gap-2 mb-2">
<div className="shrink-0 w-8 h-8 rounded bg-[#21262d] flex items-center justify-center text-foreground">
<Icon size={16} />
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-foreground break-all leading-snug">{label}</div>
<div className="flex items-center gap-1 mt-0.5 flex-wrap">
<span
className="text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider"
style={{ background: `${sourceColor}22`, color: sourceColor }}
>
{sourceLabel}
</span>
{device.suggested_type && (
<span className="text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider bg-[#21262d] text-muted-foreground">
{device.suggested_type}
</span>
)}
{device.lqi != null && (
<span className="text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider bg-[#21262d] text-muted-foreground">
LQI {device.lqi}
</span>
)}
</div>
</div>
</div>
{/* Tech grid */}
<div className="grid grid-cols-2 gap-x-2 gap-y-0.5 text-[11px] mb-2">
{device.ip && <InfoLine label="IP" value={device.ip} />}
{device.mac && <InfoLine label="MAC" value={device.mac} />}
{device.ieee_address && <InfoLine label="IEEE" value={device.ieee_address} />}
{device.hostname && <InfoLine label="Host" value={device.hostname} />}
{device.vendor && <InfoLine label="Vendor" value={device.vendor} />}
{device.model && <InfoLine label="Model" value={device.model} />}
</div>
{/* Services */}
{visibleServices.length > 0 && (
<div className="flex items-center gap-1 flex-wrap">
{visibleServices.map((s, i) => {
const color = serviceColor(s.port, s.category)
return (
<span
key={`${s.port}-${s.protocol}-${i}`}
className="text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider"
style={{ background: `${color}22`, color }}
title={`${s.service_name} (${s.protocol}/${s.port})`}
>
{s.service_name}
</span>
)
})}
{moreServices > 0 && (
<span className="text-[9px] font-mono px-1.5 py-0.5 rounded bg-[#21262d] text-muted-foreground">
+{moreServices}
</span>
)}
</div>
)}
</button>
)
}
function InfoLine({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-baseline gap-1.5 min-w-0">
<span className="text-muted-foreground shrink-0 w-12">{label}</span>
<span className="font-mono text-foreground truncate">{value}</span>
</div>
)
}
@@ -33,8 +33,10 @@ export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps)
).slice(0, 6)
const pendingResults = q.length === 0 ? [] : pendingDevices.filter((d) =>
d.ip.toLowerCase().includes(q) ||
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)
@@ -0,0 +1,272 @@
import { useState } from 'react'
import modalStyles from './modal-interactive.module.css'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { hexToRgba, rgbaToHex8 } from '@/utils/colorUtils'
export type TextBorderStyle = 'solid' | 'dashed' | 'dotted' | 'double' | 'none'
export interface TextFormData {
text: string
font: string
text_color: string
text_size: number
border_color: string
border_style: TextBorderStyle
border_width: number
background_color: string
}
const BORDER_STYLES: { value: TextBorderStyle; label: string; preview: string }[] = [
{ value: 'none', label: 'None', preview: ' ' },
{ value: 'solid', label: 'Solid', preview: '───' },
{ value: 'dashed', label: 'Dashed', preview: '╌╌╌' },
{ value: 'dotted', label: 'Dotted', preview: '···' },
{ value: 'double', label: 'Double', preview: '═══' },
]
const TEXT_SIZES: { value: number; label: string }[] = [
{ value: 10, label: '10' },
{ value: 12, label: '12' },
{ value: 14, label: '14' },
{ value: 18, label: '18' },
{ value: 24, label: '24' },
{ value: 32, label: '32' },
]
const BORDER_WIDTHS: { value: number; label: string }[] = [
{ value: 1, label: '1px' },
{ value: 2, label: '2px' },
{ value: 3, label: '3px' },
{ value: 4, label: '4px' },
{ value: 5, label: '5px' },
]
const FONTS = [
{ value: 'inter', label: 'Inter (sans-serif)' },
{ value: 'mono', label: 'JetBrains Mono' },
{ value: 'serif', label: 'Serif' },
{ value: 'sans', label: 'System Sans' },
]
const DEFAULT_FORM: TextFormData = {
text: '',
font: 'inter',
text_color: '#e6edf3',
text_size: 14,
border_color: '#30363d',
border_style: 'none',
border_width: 1,
background_color: '#00000000',
}
interface TextModalProps {
open: boolean
onClose: () => void
onSubmit: (data: TextFormData) => void
onDelete?: () => void
initial?: Partial<TextFormData>
title?: string
}
export function TextModal({ open, onClose, onSubmit, onDelete, initial, title = 'Add Text' }: TextModalProps) {
const [form, setForm] = useState<TextFormData>({ ...DEFAULT_FORM, ...initial })
const set = <K extends keyof TextFormData>(key: K, value: TextFormData[K]) =>
setForm((f) => ({ ...f, [key]: value }))
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
onSubmit(form)
onClose()
}
const colorFields = [
{ key: 'text_color' as const, label: 'Text' },
{ key: 'border_color' as const, label: 'Border' },
{ key: 'background_color' as const, label: 'Background' },
]
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">
{/* Text content */}
<div className="flex flex-col gap-1.5">
<Label className="text-xs text-muted-foreground">Text</Label>
<textarea
value={form.text}
onChange={(e) => set('text', e.target.value)}
placeholder="Type text…"
rows={3}
className={`bg-[#21262d] border border-[#30363d] text-sm p-2 resize-y min-h-[60px] focus:outline-none focus:border-[#00d4ff] ${modalStyles['modal-radius']}`}
/>
</div>
{/* Font (Police) */}
<div className="flex flex-col gap-1.5">
<Label className="text-xs text-muted-foreground">Police</Label>
<Select value={form.font} onValueChange={(v: string | null) => set('font', v ?? 'inter')}>
<SelectTrigger className={`bg-[#21262d] border-[#30363d] text-sm h-8 cursor-pointer ${modalStyles['modal-interactive']} ${modalStyles['modal-radius']}`}>
<SelectValue>
{FONTS.find((f) => f.value === form.font)?.label ?? form.font}
</SelectValue>
</SelectTrigger>
<SelectContent className="bg-[#21262d] border-[#30363d]">
{FONTS.map((f) => (
<SelectItem key={f.value} value={f.value} className="text-sm">
{f.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Colors */}
<div className="flex flex-col gap-1.5">
<Label className="text-xs text-muted-foreground">Colors</Label>
<div className="grid grid-cols-3 gap-2">
{colorFields.map(({ key, label }) => {
const { hex6, alpha } = hexToRgba(form[key])
return (
<div key={key} className="flex flex-col gap-1 items-center">
<label
className="relative w-full h-7 rounded-md border cursor-pointer overflow-hidden"
style={{ borderColor: '#30363d' }}
>
<input
type="color"
value={hex6}
onChange={(e) => set(key, rgbaToHex8(e.target.value, alpha))}
className="absolute inset-0 w-full h-full cursor-pointer opacity-0"
/>
<div className="w-full h-full rounded-sm" style={{ background: form[key] }} />
</label>
<input
type="range"
min={0}
max={100}
value={alpha}
onChange={(e) => set(key, rgbaToHex8(hex6, Number(e.target.value)))}
className="w-full h-1 accent-[#00d4ff] cursor-pointer"
title={`Opacity: ${alpha}%`}
/>
<span className="text-[9px] text-muted-foreground/60">{label} {alpha}%</span>
</div>
)
})}
</div>
</div>
{/* Text size */}
<div className="flex flex-col gap-1.5">
<Label className="text-xs text-muted-foreground">Size</Label>
<div className="grid grid-cols-6 gap-1">
{TEXT_SIZES.map(({ value, label }) => {
const isSelected = form.text_size === value
return (
<button
key={value}
type="button"
onClick={() => set('text_size', value)}
className={`flex items-center justify-center h-8 rounded transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
style={{
background: isSelected ? '#00d4ff22' : '#21262d',
border: `1px solid ${isSelected ? '#00d4ff88' : '#30363d'}`,
color: isSelected ? '#00d4ff' : '#8b949e',
fontSize: Math.min(value, 16),
}}
>
{label}
</button>
)
})}
</div>
</div>
{/* Border style */}
<div className="flex flex-col gap-1.5">
<Label className="text-xs text-muted-foreground">Border Style</Label>
<div className="grid grid-cols-5 gap-1">
{BORDER_STYLES.map(({ value, label, preview }) => {
const isSelected = form.border_style === value
return (
<button
key={value}
type="button"
title={label}
onClick={() => set('border_style', value)}
className={`flex flex-col items-center justify-center h-10 rounded text-xs gap-0.5 transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
style={{
background: isSelected ? '#00d4ff22' : '#21262d',
border: `1px solid ${isSelected ? '#00d4ff88' : '#30363d'}`,
color: isSelected ? '#00d4ff' : '#8b949e',
}}
>
<span className="font-mono text-[11px] leading-none">{preview}</span>
<span className="text-[9px]">{label}</span>
</button>
)
})}
</div>
</div>
{/* Border width (only when style != none) */}
{form.border_style !== 'none' && (
<div className="flex flex-col gap-1.5">
<Label className="text-xs text-muted-foreground">Border Width</Label>
<div className="grid grid-cols-5 gap-1">
{BORDER_WIDTHS.map(({ value, label }) => {
const isSelected = form.border_width === value
return (
<button
key={value}
type="button"
onClick={() => set('border_width', value)}
className={`flex items-center justify-center h-8 rounded text-xs transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
style={{
background: isSelected ? '#00d4ff22' : '#21262d',
border: `1px solid ${isSelected ? '#00d4ff88' : '#30363d'}`,
color: isSelected ? '#00d4ff' : '#8b949e',
}}
>
{label}
</button>
)
})}
</div>
</div>
)}
<div className="flex justify-between gap-2 pt-1">
{onDelete && (
<Button
type="button"
variant="ghost"
size="sm"
className="text-[#f85149] hover:text-[#f85149] hover:bg-[#f85149]/10 cursor-pointer"
onClick={() => { onDelete(); onClose() }}
>
Delete
</Button>
)}
<div className="flex gap-2 ml-auto">
<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">
{title === 'Add Text' ? 'Add' : 'Save'}
</Button>
</div>
</div>
</form>
</DialogContent>
</Dialog>
)
}
@@ -273,12 +273,45 @@ describe('NodeModal', () => {
it('toggles container_mode on click', () => {
const { onSubmit } = renderModal({ initial: { ...BASE, type: 'proxmox', container_mode: true } })
fireEvent.click(screen.getByRole('switch'))
fireEvent.click(screen.getByRole('switch', { name: 'Container Mode' }))
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
expect((onSubmit.mock.calls[0][0] as Partial<NodeData>).container_mode).toBe(false)
})
// ── Parent container ──────────────────────────────────────────────────
// ── Show services toggle (modal-only) ───────────────────────────────
it('shows Show Services toggle for regular nodes', () => {
renderModal({ initial: BASE })
expect(screen.getByText('Show Services')).toBeDefined()
expect(screen.getByRole('switch', { name: 'Show Services' })).toBeDefined()
})
it('hides Show Services toggle for groupRect', () => {
renderModal({ initial: { ...BASE, type: 'groupRect' } })
expect(screen.queryByText('Show Services')).toBeNull()
})
it('submits custom_colors.show_services=true when toggled on', () => {
const { onSubmit } = renderModal({ initial: BASE })
fireEvent.click(screen.getByRole('switch', { name: 'Show Services' }))
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
const data = onSubmit.mock.calls[0][0] as Partial<NodeData>
expect(data.custom_colors?.show_services).toBe(true)
})
it('keeps default colors hint visible when Show Services is toggled on', () => {
renderModal({ initial: BASE })
fireEvent.click(screen.getByRole('switch', { name: 'Show Services' }))
expect(screen.getByText(/Using default colors for/)).toBeDefined()
})
it('does not show Appearance reset when only Show Services is set', () => {
renderModal({ initial: BASE })
fireEvent.click(screen.getByRole('switch', { name: 'Show Services' }))
expect(screen.queryByText('Reset to defaults')).toBeNull()
})
// ── Parent Proxmox (vm / lxc only) ───────────────────────────────────
const parentContainerVisibleTypes = ['proxmox', 'vm', 'lxc', 'docker_host', 'isp', 'router', 'switch', 'server', 'nas', 'ap', 'printer', 'iot', 'camera', 'cpl', 'computer', 'generic'] as const
const parentContainerHiddenTypes = ['groupRect', 'group'] as const
@@ -0,0 +1,216 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { PendingDevicesModal } from '../PendingDevicesModal'
import { useCanvasStore } from '@/stores/canvasStore'
vi.mock('@/stores/canvasStore')
const mockBulkApprove = vi.fn()
const mockBulkHide = vi.fn()
const mockRestore = vi.fn()
const mockBulkRestore = vi.fn()
const mockApprove = vi.fn()
const mockHide = vi.fn()
const mockPending = vi.fn()
const mockHidden = vi.fn()
vi.mock('@/api/client', () => ({
scanApi: {
pending: (...a: unknown[]) => mockPending(...a),
hidden: (...a: unknown[]) => mockHidden(...a),
clearPending: vi.fn().mockResolvedValue({}),
approve: (...a: unknown[]) => mockApprove(...a),
hide: (...a: unknown[]) => mockHide(...a),
ignore: vi.fn().mockResolvedValue({}),
bulkApprove: (...a: unknown[]) => mockBulkApprove(...a),
bulkHide: (...a: unknown[]) => mockBulkHide(...a),
restore: (...a: unknown[]) => mockRestore(...a),
bulkRestore: (...a: unknown[]) => mockBulkRestore(...a),
},
}))
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
vi.mock('@/components/modals/PendingDeviceModal', () => ({
PendingDeviceModal: ({ device }: { device: unknown }) =>
device ? <div data-testid="approval-modal" /> : null,
}))
const DEVICE_IP = {
id: 'dev-a',
ip: '192.168.1.10',
hostname: 'host-a',
mac: 'aa:bb:cc:dd:ee:01',
os: null,
services: [{ port: 80, protocol: 'tcp', service_name: 'http' }],
suggested_type: 'server',
status: 'pending',
discovery_source: 'arp',
discovered_at: '2026-01-01T00:00:00Z',
}
const DEVICE_ZIGBEE = {
id: 'dev-b',
ip: null,
hostname: null,
mac: null,
os: null,
services: [],
suggested_type: 'iot',
status: 'pending',
discovery_source: 'zigbee',
ieee_address: '0x00124b001234abcd',
friendly_name: 'living-room-bulb',
vendor: 'Philips',
model: 'Hue White',
discovered_at: '2026-01-02T00:00:00Z',
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(useCanvasStore).mockReturnValue({
addNode: vi.fn(),
scanEventTs: 0,
} as unknown as ReturnType<typeof useCanvasStore>)
// setState is used by injectAutoEdges
;(useCanvasStore as unknown as { setState: (fn: unknown) => void }).setState = vi.fn()
mockPending.mockResolvedValue({ data: [DEVICE_IP, DEVICE_ZIGBEE] })
mockHidden.mockResolvedValue({ data: [] })
mockApprove.mockResolvedValue({ data: { node_id: 'n1', edges: [], edges_created: 0 } })
mockHide.mockResolvedValue({ data: {} })
mockBulkApprove.mockResolvedValue({
data: { approved: 2, node_ids: ['n1', 'n2'], device_ids: ['dev-a', 'dev-b'], edges: [], edges_created: 0 },
})
mockBulkHide.mockResolvedValue({ data: { hidden: 2, skipped: 0 } })
mockRestore.mockResolvedValue({ data: { restored: true, device_id: 'dev-a' } })
mockBulkRestore.mockResolvedValue({ data: { restored: 1, skipped: 0 } })
})
const baseProps = {
open: true,
onClose: vi.fn(),
}
describe('PendingDevicesModal', () => {
it('loads and renders pending devices on open', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByText('living-room-bulb')).toBeInTheDocument()
})
it('shows source chip ZIGBEE for zigbee device', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByText('ZIGBEE')).toBeInTheDocument()
})
it('filters by search query', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: 'living' } })
expect(screen.queryByTestId('pending-card-dev-a')).not.toBeInTheDocument()
expect(screen.getByTestId('pending-card-dev-b')).toBeInTheDocument()
})
it('filters by source (zigbee only)', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Zigbee' }))
expect(screen.queryByTestId('pending-card-dev-a')).not.toBeInTheDocument()
expect(screen.getByTestId('pending-card-dev-b')).toBeInTheDocument()
})
it('filters by suggested type', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.change(screen.getByLabelText('Type filter'), { target: { value: 'server' } })
expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
expect(screen.queryByTestId('pending-card-dev-b')).not.toBeInTheDocument()
})
it('switches to hidden status loads hidden devices', async () => {
mockHidden.mockResolvedValue({
data: [{ ...DEVICE_IP, id: 'h1', hostname: 'hidden-host', status: 'hidden' }],
})
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Hidden' }))
await waitFor(() => expect(screen.getByTestId('pending-card-h1')).toBeInTheDocument())
expect(mockHidden).toHaveBeenCalled()
})
it('opens approval modal when card is clicked outside select mode', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
expect(screen.getByTestId('approval-modal')).toBeInTheDocument()
})
it('toggles selection in select mode instead of opening approval', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument()
expect(screen.getByText('1 selected')).toBeInTheDocument()
})
it('select all visible selects only filtered devices', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: 'host-a' } })
fireEvent.click(screen.getByRole('button', { name: /Select all visible/ }))
expect(screen.getByText('1 selected')).toBeInTheDocument()
})
it('bulk approve calls API with selected ids', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
fireEvent.click(screen.getByTestId('pending-card-dev-b'))
fireEvent.click(screen.getByRole('button', { name: /Approve \(2\)/ }))
await waitFor(() => expect(mockBulkApprove).toHaveBeenCalledWith(['dev-a', 'dev-b']))
})
it('bulk hide calls API with selected ids', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
fireEvent.click(screen.getByRole('button', { name: /Hide \(1\)/ }))
await waitFor(() => expect(mockBulkHide).toHaveBeenCalledWith(['dev-a']))
})
it('does not load when closed', () => {
render(<PendingDevicesModal {...baseProps} open={false} />)
expect(mockPending).not.toHaveBeenCalled()
})
it('respects initialStatus=hidden', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, hostname: 'hidden-host', status: 'hidden' }] })
render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(mockHidden).toHaveBeenCalled())
expect(mockPending).not.toHaveBeenCalled()
})
it('clicking a hidden card restores it instead of opening approval', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, status: 'hidden' }] })
render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
await waitFor(() => expect(mockRestore).toHaveBeenCalledWith('dev-a'))
expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument()
})
it('bulk restore in hidden mode calls API with selected ids', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, status: 'hidden' }] })
render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
fireEvent.click(screen.getByRole('button', { name: /Restore \(1\)/ }))
await waitFor(() => expect(mockBulkRestore).toHaveBeenCalledWith(['dev-a']))
})
})
@@ -0,0 +1,75 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { TextModal, type TextFormData } from '../TextModal'
describe('TextModal', () => {
it('renders nothing when closed', () => {
const { container } = render(
<TextModal open={false} onClose={vi.fn()} onSubmit={vi.fn()} />
)
expect(container.querySelector('[role="dialog"]')).toBeNull()
})
it('renders form fields when open', () => {
render(<TextModal open onClose={vi.fn()} onSubmit={vi.fn()} />)
expect(screen.getByPlaceholderText('Type text…')).toBeDefined()
expect(screen.getByText('Add Text')).toBeDefined()
expect(screen.getByText('Police')).toBeDefined()
expect(screen.getByText('Border Style')).toBeDefined()
expect(screen.getByText('Size')).toBeDefined()
})
it('renders Edit Text title when provided', () => {
render(<TextModal open onClose={vi.fn()} onSubmit={vi.fn()} title="Edit Text" />)
expect(screen.getByText('Edit Text')).toBeDefined()
})
it('calls onSubmit with form data on submit', () => {
const onSubmit = vi.fn()
render(<TextModal open onClose={vi.fn()} onSubmit={onSubmit} />)
const ta = screen.getByPlaceholderText('Type text…')
fireEvent.change(ta, { target: { value: 'Hello' } })
fireEvent.click(screen.getByText('Add'))
expect(onSubmit).toHaveBeenCalledOnce()
const submitted = onSubmit.mock.calls[0][0] as TextFormData
expect(submitted.text).toBe('Hello')
expect(submitted.font).toBe('inter')
expect(submitted.border_style).toBe('none')
})
it('hides Border Width when style is none, shows when not', () => {
render(<TextModal open onClose={vi.fn()} onSubmit={vi.fn()} />)
expect(screen.queryByText('Border Width')).toBeNull()
fireEvent.click(screen.getByTitle('Solid'))
expect(screen.getByText('Border Width')).toBeDefined()
})
it('shows Delete button and calls handlers when provided', () => {
const onDelete = vi.fn()
const onClose = vi.fn()
render(<TextModal open onClose={onClose} onSubmit={vi.fn()} onDelete={onDelete} />)
fireEvent.click(screen.getByText('Delete'))
expect(onDelete).toHaveBeenCalledOnce()
expect(onClose).toHaveBeenCalledOnce()
})
it('pre-fills from initial prop', () => {
render(
<TextModal
open
onClose={vi.fn()}
onSubmit={vi.fn()}
initial={{ text: 'Pre-filled', text_size: 24, font: 'mono' }}
/>
)
const ta = screen.getByPlaceholderText('Type text…') as HTMLTextAreaElement
expect(ta.value).toBe('Pre-filled')
})
it('cancel calls onClose', () => {
const onClose = vi.fn()
render(<TextModal open onClose={onClose} onSubmit={vi.fn()} />)
fireEvent.click(screen.getByText('Cancel'))
expect(onClose).toHaveBeenCalledOnce()
})
})
+51 -53
View File
@@ -2,7 +2,7 @@ import { createElement, useState } from 'react'
import { X, Edit, Trash2, ExternalLink, Plus, Pencil, Layers, Ungroup, Eye, EyeOff } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from '@/components/ui/tooltip'
import { useCanvasStore } from '@/stores/canvasStore'
import { NODE_TYPE_LABELS, STATUS_COLORS, type ServiceInfo, type NodeData, type NodeProperty } from '@/types'
import { getServiceUrl } from '@/utils/serviceUrl'
@@ -234,7 +234,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
{data.mac && <DetailRow label="MAC" value={data.mac} mono />}
{data.os && <DetailRow label="OS" value={data.os} />}
{data.check_method && <DetailRow label="Check" value={data.check_method} mono />}
{data.last_seen && <DetailRow label="Last Seen" value={new Date(data.last_seen.endsWith('Z') ? data.last_seen : data.last_seen + 'Z').toLocaleString()} />}
{data.last_seen && <DetailRow label="Last Seen" value={new Date(/[Zz]|[+-]\d{2}:?\d{2}$/.test(data.last_seen) ? data.last_seen : data.last_seen + 'Z').toLocaleString()} />}
</div>
{/* Properties section */}
@@ -662,82 +662,80 @@ const CATEGORY_COLORS: Record<string, string> = {
function ServiceBadge({ svc, host, onEdit, onRemove }: { svc: ServiceInfo; host?: string; onEdit: () => void; onRemove: () => void }) {
const url = getServiceUrl(svc, host)
const color = CATEGORY_COLORS[svc.category ?? ''] ?? '#8b949e'
const hasPort = svc.port != null
const portLabel = hasPort ? String(svc.port) : ''
const pathLabel = svc.path?.trim() ? svc.path.trim() : ''
return (
<div
className="group flex items-center gap-1 border rounded-md text-xs transition-colors px-2 py-1.5 min-w-0"
className="group flex items-center justify-between gap-2 px-2 py-1.5 rounded-md border text-xs transition-colors min-w-0"
style={{ background: '#21262d', borderColor: '#30363d' }}
>
<span className="shrink-0 w-1.5 h-1.5 rounded-full" style={{ backgroundColor: color }} />
{url ? (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="font-medium truncate min-w-0 flex-1"
style={{ color }}
title={svc.service_name}
onClick={e => e.stopPropagation()}
>
{svc.service_name}
</a>
) : (
<span
className="font-medium truncate min-w-0 flex-1"
style={{ color }}
title={svc.service_name}
>
{svc.service_name}
</span>
)}
<div className="flex items-center gap-1 shrink-0">
{pathLabel && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span
className="truncate text-[#8b949e] max-w-[80px]"
tabIndex={0}
aria-label={pathLabel}
>
{pathLabel}
</span>
</TooltipTrigger>
<TooltipContent side="top">{pathLabel}</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{hasPort && (
<span className="font-mono text-[#8b949e] shrink-0">{portLabel}/{svc.protocol}</span>
)}
<div className="flex items-center gap-1.5 min-w-0 flex-1">
<span className="shrink-0 w-1.5 h-1.5 rounded-full" style={{ backgroundColor: color }} />
{url ? (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex w-2.5 h-2.5 items-center justify-center shrink-0"
aria-label="Open service link"
style={{ color: 'inherit' }}
className="font-medium truncate min-w-0 flex-1"
style={{ color }}
title={svc.service_name}
onClick={e => e.stopPropagation()}
>
{svc.service_name}
</a>
) : (
<span
className="font-medium truncate min-w-0 flex-1"
style={{ color }}
title={svc.service_name}
>
{svc.service_name}
</span>
)}
{pathLabel && (
<span
className="shrink-0 text-[#8b949e] text-right w-16 truncate"
title={pathLabel}
>
{pathLabel}
</span>
)}
</div>
<div className="flex items-center gap-1.5 shrink-0">
{svc.port != null && (
<span className="font-mono text-[#8b949e]">
{svc.port}/{svc.protocol}
</span>
)}
{url ? (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex w-2.5 h-2.5 items-center justify-center"
onClick={e => e.stopPropagation()}
>
<ExternalLink size={10} className="text-muted-foreground" />
</a>
) : (
<span className="w-2.5 shrink-0" />
<span className="w-2.5" />
)}
<button
onClick={(e) => { e.preventDefault(); e.stopPropagation(); onEdit() }}
className="opacity-100 transition-opacity text-[#8b949e] hover:text-[#00d4ff] ml-0.5"
className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#00d4ff] ml-0.5 cursor-pointer"
title="Edit service"
>
<Pencil size={10} />
</button>
<button
onClick={(e) => { e.preventDefault(); e.stopPropagation(); onRemove() }}
className="opacity-100 transition-opacity text-[#8b949e] hover:text-[#f85149] ml-0.5"
className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#f85149] ml-0.5 cursor-pointer"
title="Remove service"
>
<X size={10} />
+100 -391
View File
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect, useRef } from 'react'
import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, EyeOff, Trash2, RefreshCw, Loader2, Square, Eye, Settings, StopCircle, X, LogOut } from 'lucide-react'
import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, EyeOff, RefreshCw, Loader2, Square, Eye, Settings, StopCircle, LogOut, Network, Type } from 'lucide-react'
import { Logo } from '@/components/ui/Logo'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useCanvasStore } from '@/stores/canvasStore'
@@ -7,24 +7,26 @@ import { useAuthStore } from '@/stores/authStore'
import { scanApi, settingsApi } from '@/api/client'
import { toast } from 'sonner'
import { useLatestRelease } from '@/hooks/useLatestRelease'
import { PendingDeviceModal, type PendingDevice } from '@/components/modals/PendingDeviceModal'
import {
type AlignmentSettings,
readAlignmentSettings,
writeAlignmentSettings,
subscribeAlignmentSettings,
} from '@/utils/alignmentSettings'
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
type SidebarView = 'canvas' | 'pending' | 'hidden' | 'history' | 'settings'
type SidebarView = 'canvas' | 'history' | 'settings'
const ALL_VIEWS = [
{ id: 'canvas' as SidebarView, icon: LayoutDashboard, label: 'Canvas' },
{ id: 'pending' as SidebarView, icon: ScanLine, label: 'Pending Devices' },
{ id: 'hidden' as SidebarView, icon: EyeOff, label: 'Hidden Devices' },
{ id: 'history' as SidebarView, icon: Clock, label: 'Scan History' },
const PENDING_TRIGGERS: { kind: 'pending' | 'hidden'; icon: typeof ScanLine; label: string }[] = [
{ kind: 'pending', icon: ScanLine, label: 'Pending Devices' },
{ kind: 'hidden', icon: EyeOff, label: 'Hidden Devices' },
]
const VIEWS = STANDALONE ? ALL_VIEWS.slice(0, 1) : ALL_VIEWS
interface ScanRun {
id: string
status: string
kind?: string
ranges: string[]
devices_found: number
started_at: string
@@ -35,14 +37,15 @@ interface ScanRun {
interface SidebarProps {
onAddNode: () => void
onAddGroupRect: () => void
onAddText: () => void
onScan: () => void
onZigbeeImport: () => void
onSave: () => void
onNodeApproved: (nodeId: string) => void
forceView?: SidebarView
highlightPendingId?: string
onOpenPending: (deviceId?: string, status?: 'pending' | 'hidden') => void
}
export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeApproved, forceView, highlightPendingId }: SidebarProps) {
export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbeeImport, onSave, forceView, onOpenPending }: SidebarProps) {
const [collapsed, setCollapsed] = useState(false)
const [activeView, setActiveView] = useState<SidebarView>(forceView ?? 'canvas')
const [prevForceView, setPrevForceView] = useState(forceView)
@@ -59,7 +62,7 @@ export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeAppro
const { nodes, hasUnsavedChanges, hideIp, toggleHideIp } = useCanvasStore()
const networkNodes = nodes.filter((n) => n.data.type !== 'groupRect')
const networkNodes = nodes.filter((n) => n.data.type !== 'groupRect' && n.data.type !== 'text')
const onlineCount = networkNodes.filter((n) => n.data.status === 'online').length
const offlineCount = networkNodes.filter((n) => n.data.status === 'offline').length
@@ -87,23 +90,36 @@ export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeAppro
{/* Views */}
<nav className="flex flex-col gap-0.5 p-2">
{VIEWS.map(({ id, icon: Icon, label }) => (
<SidebarItem
icon={LayoutDashboard}
label="Canvas"
collapsed={collapsed}
active={activeView === 'canvas'}
onClick={() => setActiveView('canvas')}
/>
{!STANDALONE && PENDING_TRIGGERS.map((t) => (
<SidebarItem
key={id}
icon={Icon}
label={label}
key={t.kind}
icon={t.icon}
label={t.label}
collapsed={collapsed}
active={activeView === id}
onClick={() => setActiveView(id)}
onClick={() => onOpenPending(undefined, t.kind)}
/>
))}
{!STANDALONE && (
<SidebarItem
icon={Clock}
label="Scan History"
collapsed={collapsed}
active={activeView === 'history'}
onClick={() => setActiveView('history')}
/>
)}
</nav>
{/* View content (only when expanded) */}
{!collapsed && activeView !== 'canvas' && (
<div className="flex-1 min-h-0 overflow-y-auto border-t border-border">
{activeView === 'pending' && <PendingDevicesPanel onNodeApproved={onNodeApproved} highlightId={highlightPendingId} />}
{activeView === 'hidden' && <HiddenDevicesPanel />}
{activeView === 'history' && <ScanHistoryPanel />}
{activeView === 'settings' && <SettingsPanel />}
</div>
@@ -136,7 +152,9 @@ export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeAppro
<div className="flex flex-col gap-0.5 p-2 border-t border-border">
<SidebarItem icon={Plus} label="Add Node" collapsed={collapsed} onClick={onAddNode} />
<SidebarItem icon={Square} label="Add Zone" collapsed={collapsed} onClick={onAddGroupRect} />
<SidebarItem icon={Type} label="Add Text" collapsed={collapsed} onClick={onAddText} />
{!STANDALONE && <SidebarItem icon={ScanLine} label="Scan Network" collapsed={collapsed} onClick={handleScan} />}
{!STANDALONE && <SidebarItem icon={Network} label="Zigbee Import" collapsed={collapsed} onClick={onZigbeeImport} />}
<SidebarItem
icon={hideIp ? EyeOff : Eye}
label={hideIp ? 'Show IPs' : 'Hide IPs'}
@@ -176,325 +194,6 @@ export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeAppro
)
}
const COMMON_PORTS = new Set([22, 80, 443])
function PendingDevicesPanel({ onNodeApproved, highlightId }: { onNodeApproved: (nodeId: string) => void; highlightId?: string }) {
const [devices, setDevices] = useState<PendingDevice[]>([])
const [loading, setLoading] = useState(false)
const [selected, setSelected] = useState<PendingDevice | null>(null)
const [checkedIds, setCheckedIds] = useState<Set<string>>(new Set())
const { addNode, scanEventTs } = useCanvasStore()
const highlightRef = useRef<HTMLButtonElement>(null)
const allChecked = devices.length > 0 && checkedIds.size === devices.length
const someChecked = checkedIds.size > 0
const toggleCheck = (id: string, e: React.MouseEvent) => {
e.stopPropagation()
setCheckedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id); else next.add(id)
return next
})
}
const toggleAll = () => {
setCheckedIds(allChecked ? new Set() : new Set(devices.map((d) => d.id)))
}
const load = useCallback(async () => {
setLoading(true)
try {
const res = await scanApi.pending()
setDevices(res.data)
} catch {
toast.error('Failed to load pending devices')
} finally {
setLoading(false)
}
}, [])
const handleClearAll = async () => {
try {
await scanApi.clearPending()
setDevices([])
setCheckedIds(new Set())
toast.success('Pending devices cleared')
} catch {
toast.error('Failed to clear pending devices')
}
}
const handleBulkApprove = async () => {
const ids = [...checkedIds]
try {
const res = await scanApi.bulkApprove(ids)
const deviceToNode: Record<string, string> = {}
res.data.device_ids.forEach((did, i) => { deviceToNode[did] = res.data.node_ids[i] })
const approvedDevices = devices.filter((d) => ids.includes(d.id))
approvedDevices.forEach((d, i) => {
const nodeId = deviceToNode[d.id]
if (!nodeId) return
addNode({
id: nodeId,
type: (d.suggested_type ?? 'generic') as import('@/types').NodeType,
position: { x: 400 + (i % 4) * 160, y: 300 + Math.floor(i / 4) * 100 },
data: {
label: d.hostname ?? d.ip,
type: (d.suggested_type ?? 'generic') as import('@/types').NodeType,
ip: d.ip,
hostname: d.hostname ?? undefined,
status: 'unknown' as const,
services: (d.services ?? []) as import('@/types').ServiceInfo[],
},
})
onNodeApproved(nodeId)
})
setDevices((prev) => prev.filter((d) => !ids.includes(d.id)))
setCheckedIds(new Set())
toast.success(`Approved ${res.data.approved} device${res.data.approved !== 1 ? 's' : ''}`)
} catch {
toast.error('Failed to bulk approve devices')
}
}
const handleBulkHide = async () => {
const ids = [...checkedIds]
try {
const res = await scanApi.bulkHide(ids)
setDevices((prev) => prev.filter((d) => !ids.includes(d.id)))
setCheckedIds(new Set())
toast.success(`Hidden ${res.data.hidden} device${res.data.hidden !== 1 ? 's' : ''}`)
} catch {
toast.error('Failed to bulk hide devices')
}
}
useEffect(() => { load() }, [load])
useEffect(() => {
if (scanEventTs > 0) load()
}, [scanEventTs, load])
useEffect(() => {
if (!highlightId || loading) return
highlightRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}, [highlightId, loading])
const handleApprove = async (device: PendingDevice) => {
try {
const nodeData = {
label: device.hostname ?? device.ip,
type: (device.suggested_type ?? 'generic') as import('@/types').NodeType,
ip: device.ip,
hostname: device.hostname ?? undefined,
status: 'unknown',
services: (device.services ?? []) as import('@/types').ServiceInfo[],
}
const res = await scanApi.approve(device.id, nodeData)
const nodeId = res.data.node_id
addNode({
id: nodeId,
type: nodeData.type,
position: { x: 400, y: 300 },
data: { ...nodeData, status: 'unknown' as const },
})
toast.success(`Approved ${nodeData.label}`)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
setSelected(null)
onNodeApproved(nodeId)
} catch {
toast.error('Failed to approve device')
}
}
const handleHide = async (device: PendingDevice) => {
try {
await scanApi.hide(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
toast.success('Device hidden')
} catch {
toast.error('Failed to hide device')
}
}
const handleIgnore = async (device: PendingDevice) => {
try {
await scanApi.ignore(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
} catch {
toast.error('Failed to ignore device')
}
}
return (
<>
<div className="p-2">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-1.5">
{devices.length > 0 && (
<input
type="checkbox"
checked={allChecked}
ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked }}
onChange={toggleAll}
className="w-3 h-3 accent-[#00d4ff] cursor-pointer"
title="Select all"
/>
)}
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Pending</span>
</div>
<div className="flex items-center gap-1">
<button onClick={load} className="text-muted-foreground hover:text-foreground p-0.5" title="Refresh">
<RefreshCw size={12} />
</button>
{devices.length > 0 && (
<button onClick={handleClearAll} className="text-muted-foreground hover:text-[#f85149] p-0.5" title="Clear all pending">
<X size={12} />
</button>
)}
</div>
</div>
{someChecked && (
<div className="flex items-center gap-1 mb-2">
<button
onClick={handleBulkApprove}
className="flex-1 text-[10px] py-1 px-2 rounded bg-[#39d353]/20 text-[#39d353] hover:bg-[#39d353]/30 transition-colors font-medium"
>
Approve ({checkedIds.size})
</button>
<button
onClick={handleBulkHide}
className="flex-1 text-[10px] py-1 px-2 rounded bg-[#8b949e]/20 text-[#8b949e] hover:bg-[#8b949e]/30 transition-colors font-medium"
>
Hide ({checkedIds.size})
</button>
</div>
)}
{loading && <Loader2 size={14} className="animate-spin text-muted-foreground mx-auto my-4" />}
{!loading && devices.length === 0 && (
<p className="text-xs text-muted-foreground text-center py-4">No pending devices</p>
)}
{devices.map((d) => {
const namedService = d.services.find((s) => s.category != null && s.port != null && !COMMON_PORTS.has(s.port))
const titleService = namedService
?? d.services.find((s) => s.port === 80)
?? d.services.find((s) => s.port === 443)
?? d.services.find((s) => s.port === 22)
const title = titleService?.service_name ?? d.hostname ?? d.ip
const showIpBelow = title !== d.ip
const hasSsh = d.services.some((s) => s.port === 22)
const hasHttp = d.services.some((s) => s.port === 80)
const hasHttps = d.services.some((s) => s.port === 443)
const otherCount = d.services.filter((s) => s.port !== 22 && s.port !== 80 && s.port !== 443).length
const virtualBadge = detectVirtualBadge(d.mac)
const sourceColor = d.discovery_source === 'mdns' ? '#a855f7' : '#8b949e'
const sourceLabel = d.discovery_source === 'mdns' ? 'mDNS' : d.discovery_source === 'arp' ? 'ARP' : null
const isHighlighted = d.id === highlightId
return (
<button
key={d.id}
ref={isHighlighted ? highlightRef : null}
onClick={() => setSelected(d)}
className={`w-full mb-1.5 p-2 rounded-md text-xs text-left transition-colors border ${isHighlighted ? 'bg-[#2d3748] border-[#e3b341]' : checkedIds.has(d.id) ? 'bg-[#21262d] border-[#00d4ff]/40' : 'bg-[#21262d] border-transparent hover:bg-[#30363d] hover:border-[#30363d]'}`}
>
<div className="flex items-center gap-1.5">
<input
type="checkbox"
checked={checkedIds.has(d.id)}
onClick={(e) => e.stopPropagation()}
onChange={(e) => { e.stopPropagation(); toggleCheck(d.id, e as unknown as React.MouseEvent) }}
className="w-3 h-3 accent-[#00d4ff] cursor-pointer shrink-0"
/>
<span className="text-foreground truncate font-medium">{title}</span>
</div>
{showIpBelow && (
<div className="font-mono text-muted-foreground truncate pl-3 text-[10px] mt-0.5">{d.ip}</div>
)}
{(hasSsh || hasHttp || hasHttps || otherCount > 0 || virtualBadge || sourceLabel) && (
<div className="flex items-center gap-1 pl-3 mt-1.5 flex-wrap">
{sourceLabel && <ServiceBadge label={sourceLabel} color={sourceColor} />}
{virtualBadge && (
<Tooltip>
<TooltipTrigger>
<span><ServiceBadge label={virtualBadge.label} color="#ff6e00" /></span>
</TooltipTrigger>
<TooltipContent side="right">{virtualBadge.title}</TooltipContent>
</Tooltip>
)}
{hasSsh && <ServiceBadge label="SSH" color="#a855f7" />}
{hasHttp && <ServiceBadge label="HTTP" color="#00d4ff" />}
{hasHttps && <ServiceBadge label="HTTPS" color="#39d353" />}
{otherCount > 0 && <ServiceBadge label={`+${otherCount}`} color="#8b949e" />}
</div>
)}
</button>
)
})}
</div>
<PendingDeviceModal
device={selected}
onClose={() => setSelected(null)}
onApprove={handleApprove}
onHide={handleHide}
onIgnore={handleIgnore}
/>
</>
)
}
function HiddenDevicesPanel() {
const [devices, setDevices] = useState<PendingDevice[]>([])
const [loading, setLoading] = useState(false)
const load = useCallback(async () => {
setLoading(true)
try {
const res = await scanApi.hidden()
setDevices(res.data)
} catch {
toast.error('Failed to load hidden devices')
} finally {
setLoading(false)
}
}, [])
useEffect(() => { load() }, [load])
const handleIgnore = async (id: string) => {
try {
await scanApi.ignore(id)
setDevices((prev) => prev.filter((d) => d.id !== id))
} catch {
toast.error('Failed to remove device')
}
}
return (
<div className="p-2">
<div className="flex items-center justify-between mb-2">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Hidden</span>
<button onClick={load} className="text-muted-foreground hover:text-foreground p-0.5">
<RefreshCw size={12} />
</button>
</div>
{loading && <Loader2 size={14} className="animate-spin text-muted-foreground mx-auto my-4" />}
{!loading && devices.length === 0 && (
<p className="text-xs text-muted-foreground text-center py-4">No hidden devices</p>
)}
{devices.map((d) => (
<div key={d.id} className="mb-2 p-2 rounded-md bg-[#21262d] text-xs">
<div className="font-mono text-foreground">{d.ip}</div>
{d.hostname && <div className="text-muted-foreground truncate">{d.hostname}</div>}
<div className="flex gap-1 mt-1.5">
<ActionButton icon={Trash2} label="Remove" color="red" onClick={() => handleIgnore(d.id)} />
</div>
</div>
))}
</div>
)
}
function ScanHistoryPanel() {
const [runs, setRuns] = useState<ScanRun[]>([])
@@ -507,12 +206,19 @@ function ScanHistoryPanel() {
const res = await scanApi.runs()
const next: ScanRun[] = res.data
// Toast when a run transitions from running → error
// Surface transitions and refresh dependent UI
for (const run of next) {
const prev = prevRunsRef.current.find((r) => r.id === run.id)
if (prev?.status === 'running' && run.status === 'error') {
toast.error(`Scan failed: ${run.error ?? 'unknown error'}`)
}
if (prev?.status === 'running' && run.status === 'done') {
if (run.kind === 'zigbee') {
toast.success(`Zigbee import done — ${run.devices_found} device${run.devices_found !== 1 ? 's' : ''}`)
}
// Notify pending modal/canvas to refresh
useCanvasStore.getState().notifyScanDeviceFound()
}
}
prevRunsRef.current = next
setRuns(next)
@@ -573,6 +279,14 @@ function ScanHistoryPanel() {
<span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ backgroundColor: statusColor(r.status) }} />
<span className="font-mono text-foreground capitalize">{r.status}</span>
{r.status === 'running' && <Loader2 size={10} className="animate-spin text-[#e3b341]" />}
<span
className="text-[9px] font-mono px-1 py-0.5 rounded uppercase tracking-wider"
style={r.kind === 'zigbee'
? { background: '#00d4ff22', color: '#00d4ff' }
: { background: '#a855f722', color: '#a855f7' }}
>
{r.kind === 'zigbee' ? 'ZIG' : 'IP'}
</span>
<span className="ml-auto text-muted-foreground font-mono">{r.devices_found} found</span>
{r.status === 'running' && (
<Tooltip>
@@ -613,6 +327,7 @@ function ScanHistoryPanel() {
function SettingsPanel() {
const [interval, setIntervalValue] = useState(60)
const [saving, setSaving] = useState(false)
const [alignment, setAlignment] = useState<AlignmentSettings>(readAlignmentSettings)
useEffect(() => {
settingsApi.get()
@@ -620,6 +335,14 @@ function SettingsPanel() {
.catch(() => {/* use default */})
}, [])
useEffect(() => subscribeAlignmentSettings(setAlignment), [])
const updateAlignment = (patch: Partial<AlignmentSettings>) => {
const next = { ...alignment, ...patch }
setAlignment(next)
writeAlignmentSettings(next)
}
const handleSave = async () => {
setSaving(true)
try {
@@ -661,6 +384,41 @@ function SettingsPanel() {
>
{saving ? 'Saving…' : 'Save'}
</button>
<div className="pt-3 border-t border-border space-y-3">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Canvas</span>
<label className="flex items-center justify-between gap-2 cursor-pointer">
<span className="text-xs text-foreground">Snap to nodes</span>
<input
type="checkbox"
checked={alignment.enabled}
onChange={(e) => updateAlignment({ enabled: e.target.checked })}
className="cursor-pointer accent-[#00d4ff]"
aria-label="Toggle alignment guides"
/>
</label>
<div className={alignment.enabled ? 'space-y-1.5' : 'space-y-1.5 opacity-50 pointer-events-none'}>
<label className="text-xs text-muted-foreground">Snap distance</label>
<div className="flex items-center gap-2">
<input
type="range"
min={2}
max={16}
step={1}
value={alignment.threshold}
onChange={(e) => updateAlignment({ threshold: Number(e.target.value) })}
className="flex-1 cursor-pointer accent-[#00d4ff]"
aria-label="Alignment snap threshold"
/>
<span className="font-mono text-[11px] text-foreground w-8 text-right">{alignment.threshold}px</span>
</div>
<p className="text-[10px] text-muted-foreground leading-tight">
Distance at which dragged nodes snap to neighbours. Hold Alt while dragging to disable.
</p>
</div>
</div>
</div>
)
}
@@ -693,55 +451,6 @@ function VersionBadge() {
)
}
const MAC_OUI: Record<string, { label: string; title: string }> = {
'52:54:00': { label: 'QEMU', title: 'QEMU/KVM Virtual Machine' },
'bc:24:11': { label: 'PVE', title: 'Proxmox Virtual Machine or LXC' },
'00:50:56': { label: 'VMware', title: 'VMware Virtual Machine' },
'00:0c:29': { label: 'VMware', title: 'VMware Virtual Machine' },
'08:00:27': { label: 'VBox', title: 'VirtualBox Virtual Machine' },
'00:15:5d': { label: 'Hyper-V', title: 'Hyper-V Virtual Machine' },
}
function detectVirtualBadge(mac: string | null) {
if (!mac) return null
return MAC_OUI[mac.toLowerCase().slice(0, 8)] ?? null
}
function ServiceBadge({ label, color }: { label: string; color: string }) {
return (
<span
className="px-1 py-0.5 rounded text-[9px] font-mono font-medium leading-none border"
style={{ color, borderColor: `${color}40`, backgroundColor: `${color}15` }}
>
{label}
</span>
)
}
interface ActionButtonProps {
icon: React.ElementType
label: string
color?: 'green' | 'red'
onClick: () => void
}
function ActionButton({ icon: Icon, label, color, onClick }: ActionButtonProps) {
const colorClass =
color === 'green' ? 'text-[#39d353] hover:bg-[#39d353]/10' :
color === 'red' ? 'text-[#f85149] hover:bg-[#f85149]/10' :
'text-muted-foreground hover:text-foreground hover:bg-[#30363d]'
return (
<Tooltip>
<TooltipTrigger>
<button onClick={onClick} className={`p-1 rounded ${colorClass} transition-colors`}>
<Icon size={11} />
</button>
</TooltipTrigger>
<TooltipContent side="bottom">{label}</TooltipContent>
</Tooltip>
)
}
interface SidebarItemProps {
icon: React.ElementType
label: string
@@ -487,4 +487,27 @@ describe('DetailPanel', () => {
expect(screen.getByText('health').tagName).not.toBe('A')
})
})
describe('Last Seen formatting', () => {
it('renders a valid date when last_seen has +00:00 offset (no Z)', () => {
setupStore({ last_seen: '2026-05-10T17:54:38.221403+00:00' })
render(<DetailPanel onEdit={vi.fn()} />)
const row = screen.getByText('Last Seen').parentElement
expect(row?.textContent).not.toMatch(/Invalid Date/)
})
it('renders a valid date when last_seen ends with Z', () => {
setupStore({ last_seen: '2026-05-10T17:54:38.221403Z' })
render(<DetailPanel onEdit={vi.fn()} />)
const row = screen.getByText('Last Seen').parentElement
expect(row?.textContent).not.toMatch(/Invalid Date/)
})
it('treats naive ISO strings as UTC', () => {
setupStore({ last_seen: '2026-05-10T17:54:38' })
render(<DetailPanel onEdit={vi.fn()} />)
const row = screen.getByText('Last Seen').parentElement
expect(row?.textContent).not.toMatch(/Invalid Date/)
})
})
})
@@ -11,22 +11,11 @@ import type { NodeData } from '@/types'
vi.mock('@/stores/canvasStore')
vi.mock('@/stores/authStore')
const mockBulkApprove = vi.fn()
const mockBulkHide = vi.fn()
vi.mock('@/api/client', () => ({
scanApi: {
trigger: vi.fn().mockResolvedValue({}),
pending: vi.fn().mockResolvedValue({ data: [] }),
hidden: vi.fn().mockResolvedValue({ data: [] }),
runs: vi.fn().mockResolvedValue({ data: [] }),
stop: vi.fn().mockResolvedValue({}),
clearPending: vi.fn().mockResolvedValue({}),
approve: vi.fn().mockResolvedValue({ data: { approved: true, node_id: 'new-node-1' } }),
hide: vi.fn().mockResolvedValue({ data: { hidden: true } }),
ignore: vi.fn().mockResolvedValue({ data: { ignored: true } }),
bulkApprove: (...args: unknown[]) => mockBulkApprove(...args),
bulkHide: (...args: unknown[]) => mockBulkHide(...args),
},
settingsApi: {
get: vi.fn().mockResolvedValue({ data: { interval_seconds: 60 } }),
@@ -48,10 +37,6 @@ vi.mock('@/components/ui/tooltip', () => ({
TooltipContent: () => null,
}))
vi.mock('@/components/modals/PendingDeviceModal', () => ({
PendingDeviceModal: () => null,
}))
// ── Helpers ───────────────────────────────────────────────────────────────────
const makeNode = (id: string, status: NodeData['status'], type: NodeData['type'] = 'server'): Node<NodeData> => ({
@@ -86,8 +71,9 @@ const defaultProps = {
onAddNode: vi.fn(),
onAddGroupRect: vi.fn(),
onScan: vi.fn(),
onZigbeeImport: vi.fn(),
onSave: vi.fn(),
onNodeApproved: vi.fn(),
onOpenPending: vi.fn(),
}
// ── Tests ─────────────────────────────────────────────────────────────────────
@@ -129,26 +115,22 @@ describe('Sidebar', () => {
],
})
render(<Sidebar {...defaultProps} />)
// Total (excludes groupRect)
expect(screen.getByText('4')).toBeInTheDocument()
// Online
expect(screen.getByText('2')).toBeInTheDocument()
// Offline
expect(screen.getByText('1')).toBeInTheDocument()
})
it('excludes groupRect nodes from stats', () => {
mockStore({
nodes: [
makeNode('n1', 'unknown'), // 1 real node, not online/offline
makeNode('n1', 'unknown'),
makeNode('zone', 'unknown', 'groupRect'),
],
})
render(<Sidebar {...defaultProps} />)
// Total row shows 1 (groupRect excluded), online/offline both 0
const totalRow = screen.getByText('Total').closest('div')!
expect(totalRow).toHaveTextContent('1')
expect(screen.getAllByText('0')).toHaveLength(2) // online=0, offline=0
expect(screen.getAllByText('0')).toHaveLength(2)
})
// ── Collapse ───────────────────────────────────────────────────────────────
@@ -225,7 +207,6 @@ describe('Sidebar', () => {
it('shows unsaved badge dot on Save Canvas when hasUnsavedChanges', () => {
mockStore({ hasUnsavedChanges: true })
render(<Sidebar {...defaultProps} />)
// The badge is a span sibling of the Save Canvas button icon
const saveBtn = screen.getByText('Save Canvas').closest('button')!
const badge = saveBtn.querySelector('span.rounded-full')
expect(badge).toBeInTheDocument()
@@ -241,24 +222,24 @@ describe('Sidebar', () => {
// ── Scan action ────────────────────────────────────────────────────────────
it('calls onScan prop when Scan Network is clicked (scan trigger moved to ScanConfigModal)', () => {
it('calls onScan prop when Scan Network is clicked', () => {
render(<Sidebar {...defaultProps} />)
fireEvent.click(screen.getByText('Scan Network'))
expect(defaultProps.onScan).toHaveBeenCalledOnce()
})
// ── Navigation ─────────────────────────────────────────────────────────────
// ── Pending / Hidden open modal ────────────────────────────────────────────
it('shows Pending panel when Pending Devices nav item is clicked', async () => {
it('calls onOpenPending with pending status when Pending Devices is clicked', () => {
render(<Sidebar {...defaultProps} />)
fireEvent.click(screen.getByText('Pending Devices'))
await waitFor(() => expect(screen.getByText('No pending devices')).toBeInTheDocument())
expect(defaultProps.onOpenPending).toHaveBeenCalledWith(undefined, 'pending')
})
it('shows Hidden panel when Hidden Devices nav item is clicked', async () => {
it('calls onOpenPending with hidden status when Hidden Devices is clicked', () => {
render(<Sidebar {...defaultProps} />)
fireEvent.click(screen.getByText('Hidden Devices'))
await waitFor(() => expect(screen.getByText('No hidden devices')).toBeInTheDocument())
expect(defaultProps.onOpenPending).toHaveBeenCalledWith(undefined, 'hidden')
})
it('shows History panel when Scan History nav item is clicked', async () => {
@@ -267,16 +248,13 @@ describe('Sidebar', () => {
await waitFor(() => expect(screen.getByText('No scans yet')).toBeInTheDocument())
})
// Regression: forceView used to override local state on every render, freezing
// the sidebar on whichever view the parent forced (e.g. 'history' after a scan).
// Regression: forceView must not freeze local state across rerenders.
it('allows switching views after forceView is set by parent', async () => {
const { rerender } = render(<Sidebar {...defaultProps} forceView="history" />)
await waitFor(() => expect(screen.getByText('No scans yet')).toBeInTheDocument())
// Parent keeps forceView as 'history'; user clicks another nav item.
rerender(<Sidebar {...defaultProps} forceView="history" />)
fireEvent.click(screen.getByText('Pending Devices'))
await waitFor(() => expect(screen.getByText('No pending devices')).toBeInTheDocument())
expect(screen.queryByText('No scans yet')).not.toBeInTheDocument()
fireEvent.click(screen.getByText('Canvas'))
await waitFor(() => expect(screen.queryByText('No scans yet')).not.toBeInTheDocument())
})
it('toggles Settings panel on Settings click', async () => {
@@ -285,7 +263,6 @@ describe('Sidebar', () => {
await waitFor(() =>
expect(screen.getByText('Status check interval (s)')).toBeInTheDocument(),
)
// Click the nav button again to close (use role to avoid matching the panel heading)
fireEvent.click(screen.getByRole('button', { name: 'Settings' }))
expect(screen.queryByText('Status check interval (s)')).not.toBeInTheDocument()
})
@@ -303,101 +280,3 @@ describe('Sidebar', () => {
expect(mockLogout).toHaveBeenCalledOnce()
})
})
// ── PendingDevicesPanel — bulk select ─────────────────────────────────────────
const DEVICE_A = {
id: 'dev-a',
ip: '192.168.1.10',
hostname: 'host-a',
mac: null,
os: null,
services: [],
suggested_type: 'generic',
status: 'pending',
discovery_source: 'arp',
}
const DEVICE_B = {
id: 'dev-b',
ip: '192.168.1.11',
hostname: 'host-b',
mac: null,
os: null,
services: [],
suggested_type: 'generic',
status: 'pending',
discovery_source: 'arp',
}
describe('PendingDevicesPanel — bulk select', () => {
beforeEach(() => {
mockStore()
mockAuth()
vi.clearAllMocks()
mockBulkApprove.mockResolvedValue({
data: { approved: 2, node_ids: ['n1', 'n2'], device_ids: ['dev-a', 'dev-b'], skipped: 0 },
})
mockBulkHide.mockResolvedValue({ data: { hidden: 2, skipped: 0 } })
})
async function renderWithDevices() {
const { scanApi } = await import('@/api/client')
vi.mocked(scanApi.pending).mockResolvedValue({ data: [DEVICE_A, DEVICE_B] } as never)
render(<Sidebar {...defaultProps} forceView="pending" />)
await waitFor(() => expect(screen.getByText('host-a')).toBeInTheDocument())
}
it('renders checkboxes for each device', async () => {
await renderWithDevices()
const checkboxes = screen.getAllByRole('checkbox')
// select-all + 2 device checkboxes
expect(checkboxes.length).toBe(3)
})
it('shows bulk action bar when a device is checked', async () => {
await renderWithDevices()
const [, firstDeviceCheckbox] = screen.getAllByRole('checkbox')
fireEvent.click(firstDeviceCheckbox)
await waitFor(() => expect(screen.getByText(/Approve \(1\)/)).toBeInTheDocument())
expect(screen.getByText(/Hide \(1\)/)).toBeInTheDocument()
})
it('hides bulk action bar when no device is checked', async () => {
await renderWithDevices()
expect(screen.queryByText(/Approve \(/)).not.toBeInTheDocument()
})
it('select-all checks all devices', async () => {
await renderWithDevices()
const [selectAll] = screen.getAllByRole('checkbox')
fireEvent.click(selectAll)
await waitFor(() => expect(screen.getByText(/Approve \(2\)/)).toBeInTheDocument())
})
it('select-all unchecks all when all are selected', async () => {
await renderWithDevices()
const [selectAll] = screen.getAllByRole('checkbox')
fireEvent.click(selectAll) // select all
fireEvent.click(selectAll) // deselect all
await waitFor(() => expect(screen.queryByText(/Approve \(/)).not.toBeInTheDocument())
})
it('calls bulkApprove with checked ids and removes devices from list', async () => {
await renderWithDevices()
const [selectAll] = screen.getAllByRole('checkbox')
fireEvent.click(selectAll)
fireEvent.click(screen.getByText(/Approve \(2\)/))
await waitFor(() => expect(mockBulkApprove).toHaveBeenCalledWith(['dev-a', 'dev-b']))
await waitFor(() => expect(screen.queryByText('host-a')).not.toBeInTheDocument())
})
it('calls bulkHide with checked ids and removes devices from list', async () => {
await renderWithDevices()
const [selectAll] = screen.getAllByRole('checkbox')
fireEvent.click(selectAll)
fireEvent.click(screen.getByText(/Hide \(2\)/))
await waitFor(() => expect(mockBulkHide).toHaveBeenCalledWith(['dev-a', 'dev-b']))
await waitFor(() => expect(screen.queryByText('host-b')).not.toBeInTheDocument())
})
})
+35
View File
@@ -0,0 +1,35 @@
import { createElement } from 'react'
import type { LucideIcon } from 'lucide-react'
import { resolveCustomIcon, brandIconUrl, isBrandIconKey } from '@/utils/nodeIcons'
interface NodeIconProps {
/** Default icon for the node type (lucide). Used when no customIconKey or unknown key. */
typeIcon: LucideIcon
/** Optional override key. Legacy lucide keys or `brand:<slug>` for dashboard-icons. */
customIconKey?: string
size?: number
className?: string
/** Optional inline color (lucide only — ignored for brand icons). */
color?: string
}
export function NodeIcon({ typeIcon, customIconKey, size = 16, className, color }: NodeIconProps) {
const resolved = resolveCustomIcon(customIconKey)
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' }}
/>
)
}
const Icon = resolved?.kind === 'lucide' ? resolved.icon : typeIcon
return createElement(Icon, { size, className, color })
}
export { brandIconUrl, isBrandIconKey }
@@ -0,0 +1,450 @@
import { useState } from 'react'
import { Network, Router, Cpu, CheckCircle2, XCircle, Loader2, Plus } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { zigbeeApi } from '@/api/client'
import { toast } from 'sonner'
import type { ZigbeeNode, ZigbeeEdge } from './types'
interface ZigbeeImportModalProps {
open: boolean
onClose: () => void
onAddToCanvas: (nodes: ZigbeeNode[], edges: ZigbeeEdge[]) => void
onPendingImported?: (
coordinator?: { id: string; label: string; ieee_address: string } | null,
) => void
}
type ImportMode = 'pending' | 'canvas'
interface ConnectionForm {
mqtt_host: string
mqtt_port: string
mqtt_username: string
mqtt_password: string
base_topic: string
mqtt_tls: boolean
mqtt_tls_insecure: boolean
port_user_edited: boolean
}
const DEFAULT_FORM: ConnectionForm = {
mqtt_host: '',
mqtt_port: '1883',
mqtt_username: '',
mqtt_password: '',
base_topic: 'zigbee2mqtt',
mqtt_tls: false,
mqtt_tls_insecure: false,
port_user_edited: false,
}
const DEVICE_TYPE_ICON = {
zigbee_coordinator: Network,
zigbee_router: Router,
zigbee_enddevice: Cpu,
} as const
const DEVICE_TYPE_LABEL = {
zigbee_coordinator: 'Coordinator',
zigbee_router: 'Router',
zigbee_enddevice: 'End Device',
} as const
const DEVICE_TYPE_COLOR = {
zigbee_coordinator: '#00d4ff',
zigbee_router: '#39d353',
zigbee_enddevice: '#e3b341',
} as const
export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onPendingImported }: ZigbeeImportModalProps) {
const [form, setForm] = useState<ConnectionForm>(DEFAULT_FORM)
const [connectionStatus, setConnectionStatus] = useState<'idle' | 'testing' | 'ok' | 'fail'>('idle')
const [connectionMsg, setConnectionMsg] = useState('')
const [loading, setLoading] = useState(false)
const [devices, setDevices] = useState<ZigbeeNode[]>([])
const [edges, setEdges] = useState<ZigbeeEdge[]>([])
const [checked, setChecked] = useState<Set<string>>(new Set())
const [importMode, setImportMode] = useState<ImportMode>('pending')
const updateField = (field: keyof ConnectionForm, value: string) =>
setForm((f) => ({
...f,
[field]: value,
...(field === 'mqtt_port' ? { port_user_edited: true } : {}),
}))
const toggleTls = (next: boolean) =>
setForm((f) => {
const port = f.port_user_edited
? f.mqtt_port
: next
? '8883'
: '1883'
return {
...f,
mqtt_tls: next,
mqtt_tls_insecure: next ? f.mqtt_tls_insecure : false,
mqtt_port: port,
}
})
const buildPayload = () => ({
mqtt_host: form.mqtt_host.trim(),
mqtt_port: Number(form.mqtt_port) || (form.mqtt_tls ? 8883 : 1883),
mqtt_username: form.mqtt_username.trim() || undefined,
mqtt_password: form.mqtt_password || undefined,
base_topic: form.base_topic.trim() || 'zigbee2mqtt',
mqtt_tls: form.mqtt_tls,
mqtt_tls_insecure: form.mqtt_tls_insecure,
})
const handleTestConnection = async () => {
if (!form.mqtt_host.trim()) { toast.error('Enter a broker hostname'); return }
setConnectionStatus('testing')
try {
const res = await zigbeeApi.testConnection({
mqtt_host: form.mqtt_host.trim(),
mqtt_port: Number(form.mqtt_port) || (form.mqtt_tls ? 8883 : 1883),
mqtt_username: form.mqtt_username.trim() || undefined,
mqtt_password: form.mqtt_password || undefined,
mqtt_tls: form.mqtt_tls,
mqtt_tls_insecure: form.mqtt_tls_insecure,
})
if (res.data.connected) {
setConnectionStatus('ok')
setConnectionMsg(res.data.message)
} else {
setConnectionStatus('fail')
setConnectionMsg(res.data.message)
}
} catch {
setConnectionStatus('fail')
setConnectionMsg('Request failed — check broker address')
}
}
const extractError = (err: unknown): string | undefined => {
if (err && typeof err === 'object' && 'response' in err) {
return (err as { response?: { data?: { detail?: string } } }).response?.data?.detail
}
return undefined
}
const handleFetchDevices = async () => {
if (!form.mqtt_host.trim()) { toast.error('Enter a broker hostname'); return }
setLoading(true)
try {
if (importMode === 'pending') {
await zigbeeApi.importToPending(buildPayload())
toast.success('Zigbee import started — track progress in Scan History')
onPendingImported?.(null)
handleClose()
} else {
const res = await zigbeeApi.importNetwork(buildPayload())
setDevices(res.data.nodes)
setEdges(res.data.edges)
setChecked(new Set(res.data.nodes.map((n) => n.id)))
if (res.data.device_count === 0) {
toast.info('No Zigbee devices found in the network map')
} else {
toast.success(`Found ${res.data.device_count} device${res.data.device_count !== 1 ? 's' : ''}`)
}
}
} catch (err: unknown) {
toast.error(extractError(err) ?? 'Failed to fetch Zigbee devices')
} finally {
setLoading(false)
}
}
const toggleCheck = (id: string) =>
setChecked((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id); else next.add(id)
return next
})
const toggleAll = () => {
setChecked(checked.size === devices.length ? new Set() : new Set(devices.map((d) => d.id)))
}
const handleAddToCanvas = () => {
const selectedDevices = devices.filter((d) => checked.has(d.id))
const selectedIds = new Set(selectedDevices.map((d) => d.id))
const selectedEdges = edges.filter((e) => selectedIds.has(e.source) && selectedIds.has(e.target))
onAddToCanvas(selectedDevices, selectedEdges)
toast.success(`Added ${selectedDevices.length} device${selectedDevices.length !== 1 ? 's' : ''} to canvas`)
onClose()
}
const handleClose = () => {
setDevices([])
setEdges([])
setChecked(new Set())
setConnectionStatus('idle')
setConnectionMsg('')
setImportMode('pending')
onClose()
}
const groupedDevices = {
zigbee_coordinator: devices.filter((d) => d.type === 'zigbee_coordinator'),
zigbee_router: devices.filter((d) => d.type === 'zigbee_router'),
zigbee_enddevice: devices.filter((d) => d.type === 'zigbee_enddevice'),
} as const
return (
<Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
<DialogContent className="bg-[#161b22] border-border max-w-xl max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<Network size={16} className="text-[#00d4ff]" />
Zigbee2MQTT Import
</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-y-auto space-y-4 py-2 min-h-0">
{/* Connection Form */}
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div className="col-span-2 space-y-1">
<Label className="text-xs text-muted-foreground">Broker Host</Label>
<Input
value={form.mqtt_host}
onChange={(e) => updateField('mqtt_host', e.target.value)}
placeholder="192.168.1.x or mqtt.local"
className="font-mono text-sm bg-[#0d1117] border-border"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Port</Label>
<Input
value={form.mqtt_port}
onChange={(e) => updateField('mqtt_port', e.target.value)}
placeholder="1883"
type="number"
className="font-mono text-sm bg-[#0d1117] border-border"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Base Topic</Label>
<Input
value={form.base_topic}
onChange={(e) => updateField('base_topic', e.target.value)}
placeholder="zigbee2mqtt"
className="font-mono text-sm bg-[#0d1117] border-border"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Username (optional)</Label>
<Input
value={form.mqtt_username}
onChange={(e) => updateField('mqtt_username', e.target.value)}
placeholder="mqtt_user"
className="text-sm bg-[#0d1117] border-border"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Password (optional)</Label>
<Input
value={form.mqtt_password}
onChange={(e) => updateField('mqtt_password', e.target.value)}
placeholder="••••••••"
type="password"
autoComplete="new-password"
className="text-sm bg-[#0d1117] border-border"
/>
</div>
<div className="col-span-2 flex items-center gap-4 pt-1">
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
checked={form.mqtt_tls}
onChange={(e) => toggleTls(e.target.checked)}
className="w-3 h-3 accent-[#00d4ff] cursor-pointer"
/>
Use TLS (port 8883)
</label>
<label
className={`flex items-center gap-1.5 text-xs cursor-pointer ${
form.mqtt_tls ? 'text-[#f85149]' : 'text-muted-foreground/40 cursor-not-allowed'
}`}
>
<input
type="checkbox"
checked={form.mqtt_tls_insecure}
disabled={!form.mqtt_tls}
onChange={(e) =>
setForm((f) => ({ ...f, mqtt_tls_insecure: e.target.checked }))
}
className="w-3 h-3 accent-[#f85149] cursor-pointer disabled:cursor-not-allowed"
/>
Skip cert verify (self-signed only)
</label>
</div>
</div>
{/* Connection status indicator */}
{connectionStatus !== 'idle' && (
<div className={`flex items-center gap-1.5 text-xs px-2 py-1.5 rounded-md border ${
connectionStatus === 'ok'
? 'bg-[#39d353]/10 border-[#39d353]/30 text-[#39d353]'
: connectionStatus === 'fail'
? 'bg-[#f85149]/10 border-[#f85149]/30 text-[#f85149]'
: 'bg-[#e3b341]/10 border-[#e3b341]/30 text-[#e3b341]'
}`}>
{connectionStatus === 'testing' && <Loader2 size={12} className="animate-spin" />}
{connectionStatus === 'ok' && <CheckCircle2 size={12} />}
{connectionStatus === 'fail' && <XCircle size={12} />}
<span>{connectionStatus === 'testing' ? 'Testing…' : connectionMsg}</span>
</div>
)}
<div className="flex items-center gap-3 text-xs">
<span className="text-muted-foreground">Send devices to:</span>
<label className="flex items-center gap-1.5 cursor-pointer text-foreground">
<input
type="radio"
name="zigbee-import-mode"
checked={importMode === 'pending'}
onChange={() => setImportMode('pending')}
className="accent-[#00d4ff] cursor-pointer"
/>
Pending section
</label>
<label className="flex items-center gap-1.5 cursor-pointer text-foreground">
<input
type="radio"
name="zigbee-import-mode"
checked={importMode === 'canvas'}
onChange={() => setImportMode('canvas')}
className="accent-[#00d4ff] cursor-pointer"
/>
Canvas directly
</label>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant="ghost"
className="gap-1.5 text-muted-foreground hover:text-foreground border border-border hover:bg-[#21262d]"
onClick={handleTestConnection}
disabled={connectionStatus === 'testing' || loading}
>
{connectionStatus === 'testing'
? <Loader2 size={13} className="animate-spin" />
: <CheckCircle2 size={13} />}
Test Connection
</Button>
<Button
size="sm"
style={{ background: '#00d4ff', color: '#0d1117' }}
className="gap-1.5"
onClick={handleFetchDevices}
disabled={loading || connectionStatus === 'testing'}
>
{loading ? <Loader2 size={13} className="animate-spin" /> : <Network size={13} />}
{importMode === 'pending' ? 'Import to Pending' : 'Fetch Devices'}
</Button>
</div>
<p className="text-[11px] text-muted-foreground italic">
Fetching the network map can take several minutes on large meshes.
</p>
</div>
{/* Device List */}
{devices.length > 0 && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<input
type="checkbox"
checked={checked.size === devices.length}
ref={(el) => { if (el) el.indeterminate = checked.size > 0 && checked.size < devices.length }}
onChange={toggleAll}
className="w-3 h-3 accent-[#00d4ff] cursor-pointer"
title="Select all"
/>
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
Devices ({checked.size}/{devices.length} selected)
</span>
</div>
</div>
{(Object.entries(groupedDevices) as [keyof typeof groupedDevices, ZigbeeNode[]][])
.filter(([, group]) => group.length > 0)
.map(([type, group]) => {
const Icon = DEVICE_TYPE_ICON[type]
const color = DEVICE_TYPE_COLOR[type]
return (
<div key={type}>
<div className="flex items-center gap-1.5 mb-1">
<Icon size={11} style={{ color }} />
<span className="text-[10px] font-medium uppercase tracking-wider" style={{ color }}>
{DEVICE_TYPE_LABEL[type]} ({group.length})
</span>
</div>
{group.map((device) => (
<div
key={device.id}
className={`flex items-start gap-2 p-2 mb-1 rounded-md text-xs cursor-pointer transition-colors border ${
checked.has(device.id)
? 'bg-[#21262d] border-[#00d4ff]/40'
: 'bg-[#21262d] border-transparent hover:bg-[#30363d]'
}`}
onClick={() => toggleCheck(device.id)}
>
<input
type="checkbox"
checked={checked.has(device.id)}
onChange={() => toggleCheck(device.id)}
onClick={(e) => e.stopPropagation()}
className="w-3 h-3 mt-0.5 accent-[#00d4ff] cursor-pointer shrink-0"
/>
<div className="flex-1 min-w-0">
<div className="text-foreground font-medium truncate">{device.friendly_name}</div>
<div className="font-mono text-[10px] text-muted-foreground truncate">{device.ieee_address}</div>
{(device.model || device.vendor) && (
<div className="text-[10px] text-muted-foreground truncate">
{[device.vendor, device.model].filter(Boolean).join(' · ')}
</div>
)}
</div>
{device.lqi != null && (
<span
className="text-[9px] font-mono px-1 py-0.5 rounded border shrink-0"
style={{ color: '#8b949e', borderColor: '#8b949e40' }}
>
LQI {device.lqi}
</span>
)}
</div>
))}
</div>
)
})}
</div>
)}
</div>
<DialogFooter className="gap-2 shrink-0 pt-2 border-t border-border">
<Button variant="ghost" onClick={handleClose}>Cancel</Button>
{devices.length > 0 && (
<Button
onClick={handleAddToCanvas}
disabled={checked.size === 0}
style={{ background: '#00d4ff', color: '#0d1117' }}
className="gap-1.5"
>
<Plus size={13} />
Add {checked.size} to Canvas
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,223 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { ZigbeeImportModal } from '../ZigbeeImportModal'
vi.mock('@/api/client', () => ({
zigbeeApi: {
testConnection: vi.fn(),
importNetwork: vi.fn(),
importToPending: vi.fn(),
},
}))
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }))
import { zigbeeApi } from '@/api/client'
import { toast } from 'sonner'
const defaultProps = {
open: true,
onClose: vi.fn(),
onAddToCanvas: vi.fn(),
}
const sampleNodes = [
{
id: '0x0000',
label: 'Coordinator',
type: 'zigbee_coordinator' as const,
ieee_address: '0x0000',
friendly_name: 'Coordinator',
device_type: 'Coordinator',
model: null,
vendor: null,
lqi: null,
parent_id: null,
},
{
id: '0x0001',
label: 'router_1',
type: 'zigbee_router' as const,
ieee_address: '0x0001',
friendly_name: 'router_1',
device_type: 'Router',
model: 'CC2530',
vendor: 'TI',
lqi: 200,
parent_id: '0x0000',
},
]
describe('ZigbeeImportModal', () => {
beforeEach(() => {
vi.mocked(zigbeeApi.testConnection).mockReset()
vi.mocked(zigbeeApi.importNetwork).mockReset()
vi.mocked(zigbeeApi.importToPending).mockReset()
vi.mocked(toast.success).mockReset()
vi.mocked(toast.error).mockReset()
vi.mocked(toast.info).mockReset()
defaultProps.onClose.mockReset()
defaultProps.onAddToCanvas.mockReset()
})
it('renders nothing when closed', () => {
const { container } = render(<ZigbeeImportModal {...defaultProps} open={false} />)
expect(container.querySelector('[role="dialog"]')).toBeNull()
})
it('renders the modal with form fields when open', () => {
render(<ZigbeeImportModal {...defaultProps} />)
expect(screen.getByText('Zigbee2MQTT Import')).toBeDefined()
expect(screen.getByPlaceholderText('192.168.1.x or mqtt.local')).toBeDefined()
expect(screen.getByPlaceholderText('1883')).toBeDefined()
expect(screen.getByPlaceholderText('zigbee2mqtt')).toBeDefined()
})
it('shows error toast when testing connection without a host', async () => {
render(<ZigbeeImportModal {...defaultProps} />)
fireEvent.click(screen.getByRole('button', { name: /test connection/i }))
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith('Enter a broker hostname')
})
expect(zigbeeApi.testConnection).not.toHaveBeenCalled()
})
it('shows success status when connection test passes', async () => {
vi.mocked(zigbeeApi.testConnection).mockResolvedValue({
data: { connected: true, message: 'Connection successful' },
} as never)
render(<ZigbeeImportModal {...defaultProps} />)
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /test connection/i }))
await waitFor(() => {
expect(screen.getByText('Connection successful')).toBeDefined()
})
})
it('shows failure status when connection test fails', async () => {
vi.mocked(zigbeeApi.testConnection).mockResolvedValue({
data: { connected: false, message: 'Connection refused' },
} as never)
render(<ZigbeeImportModal {...defaultProps} />)
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '10.0.0.1' } })
fireEvent.click(screen.getByRole('button', { name: /test connection/i }))
await waitFor(() => {
expect(screen.getByText('Connection refused')).toBeDefined()
})
})
const selectCanvasMode = () => {
fireEvent.click(screen.getByRole('radio', { name: /canvas directly/i }))
}
it('fetches devices and renders them grouped by type', async () => {
vi.mocked(zigbeeApi.importNetwork).mockResolvedValue({
data: { nodes: sampleNodes, edges: [], device_count: 2 },
} as never)
render(<ZigbeeImportModal {...defaultProps} />)
selectCanvasMode()
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))
await waitFor(() => {
expect(screen.getByText('Coordinator')).toBeDefined()
expect(screen.getByText('router_1')).toBeDefined()
})
expect(toast.success).toHaveBeenCalledWith('Found 2 devices')
})
it('shows info toast when no devices found', async () => {
vi.mocked(zigbeeApi.importNetwork).mockResolvedValue({
data: { nodes: [], edges: [], device_count: 0 },
} as never)
render(<ZigbeeImportModal {...defaultProps} />)
selectCanvasMode()
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))
await waitFor(() => {
expect(toast.info).toHaveBeenCalledWith('No Zigbee devices found in the network map')
})
})
it('calls onAddToCanvas with selected devices and closes modal', async () => {
vi.mocked(zigbeeApi.importNetwork).mockResolvedValue({
data: { nodes: sampleNodes, edges: [{ source: '0x0000', target: '0x0001' }], device_count: 2 },
} as never)
render(<ZigbeeImportModal {...defaultProps} />)
selectCanvasMode()
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))
await waitFor(() => screen.getByText('Coordinator'))
// Click "Add N to Canvas" button
const addBtn = screen.getByRole('button', { name: /add.*canvas/i })
fireEvent.click(addBtn)
await waitFor(() => {
expect(defaultProps.onAddToCanvas).toHaveBeenCalledOnce()
expect(defaultProps.onClose).toHaveBeenCalledOnce()
})
})
it('calls onClose when Cancel is clicked', () => {
render(<ZigbeeImportModal {...defaultProps} />)
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(defaultProps.onClose).toHaveBeenCalledOnce()
})
it('imports to pending by default and notifies parent', async () => {
vi.mocked(zigbeeApi.importToPending).mockResolvedValue({
data: {
id: 'run-1',
status: 'running',
kind: 'zigbee',
ranges: ['192.168.1.100:1883'],
devices_found: 0,
started_at: '2026-01-01T00:00:00Z',
finished_at: null,
error: null,
},
} as never)
const onPendingImported = vi.fn()
render(<ZigbeeImportModal {...defaultProps} onPendingImported={onPendingImported} />)
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /import to pending/i }))
await waitFor(() => {
expect(zigbeeApi.importToPending).toHaveBeenCalled()
expect(onPendingImported).toHaveBeenCalled()
expect(defaultProps.onClose).toHaveBeenCalled()
})
expect(zigbeeApi.importNetwork).not.toHaveBeenCalled()
})
it('switching to canvas mode calls importNetwork and not importToPending', async () => {
vi.mocked(zigbeeApi.importNetwork).mockResolvedValue({
data: { nodes: sampleNodes, edges: [], device_count: 2 },
} as never)
render(<ZigbeeImportModal {...defaultProps} />)
fireEvent.click(screen.getByRole('radio', { name: /canvas directly/i }))
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))
await waitFor(() => expect(zigbeeApi.importNetwork).toHaveBeenCalled())
expect(zigbeeApi.importToPending).not.toHaveBeenCalled()
})
})
+37
View File
@@ -0,0 +1,37 @@
/** Shared Zigbee type definitions for the frontend. */
export interface ZigbeeNode {
id: string
label: string
type: 'zigbee_coordinator' | 'zigbee_router' | 'zigbee_enddevice'
ieee_address: string
friendly_name: string
device_type: string
model?: string | null
vendor?: string | null
lqi?: number | null
parent_id?: string | null
}
export interface ZigbeeEdge {
source: string
target: string
}
export interface ZigbeeImportResponse {
nodes: ZigbeeNode[]
edges: ZigbeeEdge[]
device_count: number
}
export interface ZigbeeTestConnectionRequest {
mqtt_host: string
mqtt_port: number
mqtt_username?: string
mqtt_password?: string
}
export interface ZigbeeTestConnectionResponse {
connected: boolean
message: string
}