Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat: per edge type animation speed and color in the custom style editor (#555)
Pouzor - Rémy Jardientc9b61921036d
diff --git a/frontend/src/components/canvas/edges/__tests__/HomelableEdge.animStyle.test.tsx b/frontend/src/components/canvas/edges/__tests__/HomelableEdge.animStyle.test.tsxnew file mode 100644index 0000000..0337ac5--- /dev/null+++ b/frontend/src/components/canvas/edges/__tests__/HomelableEdge.animStyle.test.tsx@@ -0,0 +1,94 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { render } from '@testing-library/react'+import { ReactFlowProvider } from '@xyflow/react'+import type { EdgeProps, Edge } from '@xyflow/react'+import { HomelableEdge } from '../index'+import { useThemeStore } from '@/stores/themeStore'+import type { EdgeData, EdgeTypeStyle } from '@/types'++/**+ * Animation speed and highlight colour (#396) live on the edge *type*'s custom+ * style and are read live by the renderer — never copied onto the edge.+ */+function renderEdge(data: Partial<EdgeData>) {+ const props = {+ id: 'e1',+ source: 'a',+ target: 'b',+ sourceX: 0,+ sourceY: 0,+ targetX: 100,+ targetY: 100,+ sourcePosition: 'bottom',+ targetPosition: 'top',+ data: { type: 'wifi', ...data } as EdgeData,+ selected: false,+ } as unknown as EdgeProps<Edge<EdgeData>>++ return render(+ <ReactFlowProvider>+ <svg>+ <HomelableEdge {...props} />+ </svg>+ </ReactFlowProvider>,+ )+}++function animatedPath(container: HTMLElement, keyframes: string) {+ return Array.from(container.querySelectorAll('path')).find((p) =>+ (p.getAttribute('style') ?? '').includes(keyframes),+ )+}++function setWifiStyle(partial: Partial<EdgeTypeStyle>) {+ useThemeStore.setState({+ customStyle: { nodes: {}, edges: { wifi: partial as EdgeTypeStyle } },+ })+}++describe('HomelableEdge type-level animation speed / colour', () => {+ beforeEach(() => {+ useThemeStore.setState({ customStyle: { nodes: {}, edges: {} } })+ })++ it('keeps the default durations without a custom style', () => {+ expect(animatedPath(renderEdge({ animated: 'snake' }).container, 'homelable-snake')!+ .getAttribute('style')).toContain('10s')+ })++ it('scales snake / flow / basic durations by the type speed', () => {+ setWifiStyle({ animSpeed: 2 })+ expect(animatedPath(renderEdge({ animated: 'snake' }).container, 'homelable-snake')!+ .getAttribute('style')).toContain('homelable-snake 5s')+ expect(animatedPath(renderEdge({ animated: 'flow' }).container, 'homelable-flow')!+ .getAttribute('style')).toContain('homelable-flow 0.6s')+ expect(animatedPath(renderEdge({ animated: 'basic' }).container, 'homelable-basic-dash')!+ .getAttribute('style')).toContain('homelable-basic-dash 0.25s')+ })++ it('ignores another type\'s speed', () => {+ useThemeStore.setState({+ customStyle: { nodes: {}, edges: { ethernet: { animSpeed: 4 } as EdgeTypeStyle } },+ })+ expect(animatedPath(renderEdge({ animated: 'flow' }).container, 'homelable-flow')!+ .getAttribute('style')).toContain('homelable-flow 1.2s')+ })++ it('draws the snake highlight in the type animColor, over the edge custom_color', () => {+ setWifiStyle({ animColor: '#ff0000' })+ const { container } = renderEdge({ animated: 'snake', custom_color: '#00ff00' })+ expect(animatedPath(container, 'homelable-snake')!.getAttribute('stroke')).toBe('#ff0000')+ })++ it('falls back to the line colour when animColor is unset or not a hex', () => {+ setWifiStyle({ animColor: 'javascript:alert(1)' })+ const { container } = renderEdge({ animated: 'flow', custom_color: '#00ff00' })+ expect(animatedPath(container, 'homelable-flow')!.getAttribute('stroke')).toBe('#00ff00')+ })++ it('basic mode keeps the line colour', () => {+ setWifiStyle({ animColor: '#ff0000' })+ const { container } = renderEdge({ animated: 'basic', custom_color: '#00ff00' })+ expect(animatedPath(container, 'homelable-basic-dash')!.getAttribute('stroke')).toBe('#00ff00')+ })+})diff --git a/frontend/src/components/canvas/edges/index.tsx b/frontend/src/components/canvas/edges/index.tsxindex f1b4335..aa5a0a4 100644--- a/frontend/src/components/canvas/edges/index.tsx+++ b/frontend/src/components/canvas/edges/index.tsx@@ -15,6 +15,7 @@ import { useCanvasStore } from '@/stores/canvasStore'import { THEMES } from '@/utils/themes'import { MARKER_GEOMETRY, normalizeMarker, type NonNoneMarkerShape } from '@/utils/edgeMarkers'import { clampWidthMult, dashArrayFor } from '@/utils/edgeLineStyle'+import { animDuration, resolveAnimColor } from '@/utils/edgeAnimation'import { buildWaypointPath, getAddWaypointHandlePosition, getWaypointLabelPosition, snap45, snap45both } from './waypointUtils'const VLAN_COLORS = ['#00d4ff', '#a855f7', '#39d353', '#ff6e00', '#e3b341', '#f85149']@@ -386,7 +387,11 @@ export function HomelableEdge({ id, source, target, sourceHandleId, targetHandledata?.animated === 'flow' ? 'flow' :data?.animated === 'basic' ? 'basic' : 'none'- const animColor = customColor ?? (edgeType === 'vlan' ? getVlanColor(data?.vlan_id as number | undefined) : edgeColors[edgeType as keyof typeof edgeColors] as string)+ // Speed and highlight colour come from the edge type's custom style, read+ // live like showLqi — they are never copied onto the edge.+ const typeStyle = customEdgeStyles[edgeType]+ const animSpeed = typeStyle?.animSpeed+ const animColor = resolveAnimColor(typeStyle?.animColor) ?? customColor ?? (edgeType === 'vlan' ? getVlanColor(data?.vlan_id as number | undefined) : edgeColors[edgeType as keyof typeof edgeColors] as string)const midpoints = selected? segmentMidpoints(sourceX, sourceY, waypoints, targetX, targetY, pathStyle, sourcePosition)@@ -454,7 +459,7 @@ export function HomelableEdge({ id, source, target, sourceHandleId, targetHandle// from the endpoints' screen positions: an edge drawn bottom-to-top// marches the same way as one drawn top-to-bottom, like the snake// and flow modes.- animation: 'homelable-basic-dash 0.5s linear infinite',+ animation: `homelable-basic-dash ${animDuration('basic', animSpeed)} linear infinite`,}}/>)}@@ -470,9 +475,9 @@ export function HomelableEdge({ id, source, target, sourceHandleId, targetHandlestyle={{pointerEvents: 'none',// CSS (not SMIL) so it pauses when the tab is hidden — see index.css.- // Bidirectional yo-yos via `alternate` (10s each way = 20s round trip,- // matching the old SMIL keyTimes); unidirectional loops in one direction.- animation: `homelable-snake 10s linear infinite${isBidirectional ? ' alternate' : ''}`,+ // Bidirectional yo-yos via `alternate` (10s each way at 1× = 20s round+ // trip, matching the old SMIL keyTimes); unidirectional loops in one direction.+ animation: `homelable-snake ${animDuration('snake', animSpeed)} linear infinite${isBidirectional ? ' alternate' : ''}`,}}/>)}@@ -487,7 +492,7 @@ export function HomelableEdge({ id, source, target, sourceHandleId, targetHandlestrokeOpacity={0.85}style={{pointerEvents: 'none',- animation: 'homelable-flow 1.2s linear infinite',+ animation: `homelable-flow ${animDuration('flow', animSpeed)} linear infinite`,}}/>)}diff --git a/frontend/src/components/modals/CustomStyleModal.tsx b/frontend/src/components/modals/CustomStyleModal.tsxindex 3997173..2a7be32 100644--- a/frontend/src/components/modals/CustomStyleModal.tsx+++ b/frontend/src/components/modals/CustomStyleModal.tsx@@ -21,6 +21,7 @@ import {EDGE_LINE_STYLES, EDGE_LINE_STYLE_LABELS, EDGE_TYPE_BASE_WIDTH, EDGE_TYPE_DEFAULT_LINE,clampWidthMult, dashArrayFor,} from '@/utils/edgeLineStyle'+import { MIN_ANIM_SPEED, MAX_ANIM_SPEED, clampAnimSpeed, resolveAnimColor } from '@/utils/edgeAnimation'import { MarkerShapePicker } from './MarkerShapePicker'// ── Node types exposed for custom style, grouped by category (skip groupRect/group) ──@@ -272,6 +273,9 @@ function EdgeEditor({ edgeType, style, onChange, onApplyToExisting }: EdgeEditoronChange({ ...style, [k]: v })}, [style, onChange])+ const animSpeed = clampAnimSpeed(style.animSpeed)+ const animColor = resolveAnimColor(style.animColor)+return (<div className="flex flex-col gap-4"><div className="text-sm font-semibold text-[#e6edf3]">{EDGE_TYPE_LABELS[edgeType]}</div>@@ -367,6 +371,51 @@ function EdgeEditor({ edgeType, style, onChange, onApplyToExisting }: EdgeEditor</select></div>+ {/* Speed and highlight colour apply live to every edge of this type,+ whatever its own animation mode — no "Apply to existing" needed. */}+ <div>+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs text-[#8b949e]">Animation speed</span>+ <span className="text-xs text-[#8b949e]">{animSpeed}×</span>+ </div>+ <input+ type="range"+ min={MIN_ANIM_SPEED}+ max={MAX_ANIM_SPEED}+ step={0.25}+ value={animSpeed}+ onChange={(e) => set('animSpeed', clampAnimSpeed(parseFloat(e.target.value)))}+ aria-label="Animation speed multiplier"+ className="w-full h-1 accent-[#00d4ff]"+ />+ </div>++ <div>+ <div className="text-xs text-[#8b949e] mb-1">Animation color</div>+ <div className="text-xs text-[#8b949e]/60 mb-2">Snake and Flow highlight. Basic keeps the line color.</div>+ <div className="flex items-center gap-3">+ <input+ type="color"+ value={animColor ?? style.color}+ onChange={(e) => set('animColor', e.target.value)}+ aria-label="Animation color"+ className="w-7 h-7 rounded cursor-pointer border border-[#30363d] bg-transparent p-0.5"+ />+ <span className="text-xs text-[#8b949e] flex-1">+ {animColor ? animColor : 'Same as line'}+ </span>+ {animColor && (+ <button+ type="button"+ onClick={() => set('animColor', undefined)}+ className="px-2 py-0.5 text-xs rounded border border-[#30363d] text-[#8b949e] hover:text-[#e6edf3]"+ >+ Reset+ </button>+ )}+ </div>+ </div>+<div><div className="text-xs text-[#8b949e] mb-2">Endpoints</div><div className="flex flex-col gap-1.5">diff --git a/frontend/src/components/modals/__tests__/CustomStyleModal.test.tsx b/frontend/src/components/modals/__tests__/CustomStyleModal.test.tsxindex 393e597..bedfb2d 100644--- a/frontend/src/components/modals/__tests__/CustomStyleModal.test.tsx+++ b/frontend/src/components/modals/__tests__/CustomStyleModal.test.tsx@@ -3,6 +3,7 @@ import { render, screen, fireEvent } from '@testing-library/react'import { CustomStyleModal } from '../CustomStyleModal'import { useThemeStore } from '@/stores/themeStore'import { useCanvasStore } from '@/stores/canvasStore'+import type { EdgeTypeStyle } from '@/types'vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())import { toast } from 'sonner'@@ -246,3 +247,56 @@ describe('CustomStyleModal', () => {expect((reopenedWidth as HTMLInputElement).value).toBe('0')})})++describe('CustomStyleModal — animation speed / colour (#396)', () => {+ beforeEach(() => {+ useThemeStore.setState({ customStyle: { nodes: {}, edges: {} } })+ useCanvasStore.setState({ markUnsaved: vi.fn() })+ })++ const openWifi = () => {+ render(<CustomStyleModal open onClose={vi.fn()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edges' }))+ fireEvent.click(screen.getByRole('button', { name: /Wi-Fi/ }))+ }++ it('defaults to 1× and "Same as line"', () => {+ openWifi()+ const slider = screen.getByRole('slider', { name: 'Animation speed multiplier' }) as HTMLInputElement+ expect(slider.value).toBe('1')+ expect(screen.getByText('Same as line')).toBeDefined()+ expect(screen.queryByRole('button', { name: 'Reset' })).toBeNull()+ })++ it('Save Custom Style persists animSpeed and animColor on the type', () => {+ openWifi()+ fireEvent.change(screen.getByRole('slider', { name: 'Animation speed multiplier' }), { target: { value: '2.5' } })+ fireEvent.input(screen.getByLabelText('Animation color'), { target: { value: '#ff8800' } })+ expect(screen.getByText('#ff8800')).toBeDefined()+ fireEvent.click(screen.getByRole('button', { name: 'Save Custom Style' }))+ const wifi = useThemeStore.getState().customStyle.edges.wifi!+ expect(wifi.animSpeed).toBe(2.5)+ expect(wifi.animColor).toBe('#ff8800')+ })++ it('Reset clears animColor back to the line colour', () => {+ openWifi()+ fireEvent.input(screen.getByLabelText('Animation color'), { target: { value: '#ff8800' } })+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }))+ expect(screen.getByText('Same as line')).toBeDefined()+ fireEvent.click(screen.getByRole('button', { name: 'Save Custom Style' }))+ expect(useThemeStore.getState().customStyle.edges.wifi!.animColor).toBeUndefined()+ })++ it('shows the saved values when reopened', () => {+ useThemeStore.setState({+ customStyle: { nodes: {}, edges: { wifi: {+ color: '#58a6ff', opacity: 1, pathStyle: 'bezier', lineStyle: 'dashed', widthMult: 1,+ animated: 'flow', arrowStart: 'none', arrowEnd: 'none', animSpeed: 0.5, animColor: '#123456',+ } satisfies EdgeTypeStyle } },+ })+ openWifi()+ expect((screen.getByRole('slider', { name: 'Animation speed multiplier' }) as HTMLInputElement).value).toBe('0.5')+ expect(screen.getByText('#123456')).toBeDefined()+ })+})diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 8273e4f..03e5dc6 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -409,6 +409,17 @@ export interface EdgeTypeStyle {* it is offered for the types the Zigbee import writes (`iot`, `zigbee_mesh`).*/showLqi?: boolean+ /**+ * Animation speed multiplier (0.25×–4×) for every edge of this type. Read+ * live like `showLqi`, never copied onto edges. Unset = 1×.+ */+ animSpeed?: number+ /**+ * Colour of the snake / flow highlight (`#rrggbb`), independent from the+ * line colour. Read live. Unset = follow the line colour. Basic mode+ * replaces the line itself, so it keeps the line colour.+ */+ animColor?: string}export interface CustomStyleDef {diff --git a/frontend/src/utils/__tests__/edgeAnimation.test.ts b/frontend/src/utils/__tests__/edgeAnimation.test.tsnew file mode 100644index 0000000..ef2c95f--- /dev/null+++ b/frontend/src/utils/__tests__/edgeAnimation.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest'+import { animDuration, clampAnimSpeed, resolveAnimColor } from '../edgeAnimation'++describe('clampAnimSpeed', () => {+ it('defaults unset / invalid values to 1×', () => {+ expect(clampAnimSpeed(undefined)).toBe(1)+ expect(clampAnimSpeed(NaN)).toBe(1)+ expect(clampAnimSpeed(Infinity)).toBe(1)+ expect(clampAnimSpeed(0)).toBe(1)+ expect(clampAnimSpeed(-2)).toBe(1)+ })++ it('clamps to 0.25×–4×', () => {+ expect(clampAnimSpeed(0.1)).toBe(0.25)+ expect(clampAnimSpeed(10)).toBe(4)+ expect(clampAnimSpeed(1.5)).toBe(1.5)+ })+})++describe('animDuration', () => {+ it('keeps the historical durations at 1× / unset', () => {+ expect(animDuration('basic', undefined)).toBe('0.5s')+ expect(animDuration('snake', undefined)).toBe('10s')+ expect(animDuration('flow', 1)).toBe('1.2s')+ })++ it('divides the base duration by the speed', () => {+ expect(animDuration('snake', 2)).toBe('5s')+ expect(animDuration('flow', 0.5)).toBe('2.4s')+ expect(animDuration('basic', 4)).toBe('0.125s')+ })++ it('clamps an out-of-range speed before dividing', () => {+ expect(animDuration('snake', 100)).toBe('2.5s')+ })+})++describe('resolveAnimColor', () => {+ it('accepts a #rrggbb hex', () => {+ expect(resolveAnimColor('#ff00AA')).toBe('#ff00AA')+ })++ it('rejects anything else so the line colour is used', () => {+ expect(resolveAnimColor(undefined)).toBeUndefined()+ expect(resolveAnimColor('')).toBeUndefined()+ expect(resolveAnimColor('red')).toBeUndefined()+ expect(resolveAnimColor('#fff')).toBeUndefined()+ expect(resolveAnimColor('url(#x)')).toBeUndefined()+ })+})diff --git a/frontend/src/utils/edgeAnimation.ts b/frontend/src/utils/edgeAnimation.tsnew file mode 100644index 0000000..7e9c7da--- /dev/null+++ b/frontend/src/utils/edgeAnimation.ts@@ -0,0 +1,37 @@+export type EdgeAnimMode = 'basic' | 'snake' | 'flow'++/** Seconds per cycle at 1× speed — the durations the renderer always used. */+export const EDGE_ANIM_BASE_DURATION: Record<EdgeAnimMode, number> = {+ basic: 0.5,+ snake: 10,+ flow: 1.2,+}++export const MIN_ANIM_SPEED = 0.25+export const MAX_ANIM_SPEED = 4++/**+ * Speed multiplier, limited to 0.25×–4×. A multiplier rather than seconds+ * because the base durations differ 20× between modes, so one value means+ * the same thing whichever mode an edge runs. Unset or invalid → 1×.+ */+export function clampAnimSpeed(v: number | undefined): number {+ if (v == null || !Number.isFinite(v) || v <= 0) return 1+ return Math.min(MAX_ANIM_SPEED, Math.max(MIN_ANIM_SPEED, v))+}++/** CSS duration for a mode at a given speed (2× speed = half the cycle). */+export function animDuration(mode: EdgeAnimMode, speed: number | undefined): string {+ return `${+(EDGE_ANIM_BASE_DURATION[mode] / clampAnimSpeed(speed)).toFixed(3)}s`+}++const HEX_COLOR = /^#[0-9a-f]{6}$/i++/**+ * The animation highlight colour, or undefined to follow the line colour.+ * Only a `#rrggbb` hex is accepted: custom_style comes back from the server+ * as free JSON and lands straight in an SVG `stroke`.+ */+export function resolveAnimColor(v: string | undefined): string | undefined {+ return v && HEX_COLOR.test(v) ? v : undefined+}