Skip to content

A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.

feat(app): export features (json+png)

dextmorgn05f577a2a009
diff --git a/flowsint-app/src/api/sketch-service.ts b/flowsint-app/src/api/sketch-service.ts
index 7ab2ffe1..bc44a516 100644
--- a/flowsint-app/src/api/sketch-service.ts
+++ b/flowsint-app/src/api/sketch-service.ts
@@ -114,5 +114,25 @@ export const sketchService = {
method: 'PUT',
body: JSON.stringify({ positions })
})
+ },
+ exportSketch: async (sketchId: string, format: 'json' = 'json'): Promise<any> => {
+ const response = await fetchWithAuth(`/api/sketches/${sketchId}/export?format=${format}`, {
+ method: 'GET'
+ })
+
+ if (format === 'json') {
+ const data = await response
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
+ const url = window.URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `sketch-${sketchId}.json`
+ document.body.appendChild(a)
+ a.click()
+ window.URL.revokeObjectURL(url)
+ document.body.removeChild(a)
+ }
+
+ return response
}
}
diff --git a/flowsint-app/src/components/sketches/graph/index.tsx b/flowsint-app/src/components/sketches/graph/index.tsx
index 237c4b2f..730b0177 100644
--- a/flowsint-app/src/components/sketches/graph/index.tsx
+++ b/flowsint-app/src/components/sketches/graph/index.tsx
@@ -56,12 +56,25 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
const nodeColors = useNodesDisplaySettings((s) => s.colors)
const setActions = useGraphControls((s) => s.setActions)
const setCurrentLayoutType = useGraphControls((s) => s.setCurrentLayoutType)
- const autoZoomOnCurrentNode = useGraphSettingsStore((s) => s.getSettingValue('general', 'autoZoomOnCurrentNode'))
- const showMinimapSetting = useGraphSettingsStore((s) => s.getSettingValue('general', 'showMinimap'))
+ const autoZoomOnCurrentNode = useGraphSettingsStore((s) =>
+ s.getSettingValue('general', 'autoZoomOnCurrentNode')
+ )
+ const showMinimapSetting = useGraphSettingsStore((s) =>
+ s.getSettingValue('general', 'showMinimap')
+ )
const forceSettings = useGraphSettingsStore((s) => s.forceSettings)
const setImportModalOpen = useGraphSettingsStore((s) => s.setImportModalOpen)
- const { currentNode, currentEdge, selectedNodes, selectedEdges, toggleEdgeSelection, setCurrentEdge, clearSelectedEdges, setOpenMainDialog } = useGraphStore(
+ const {
+ currentNode,
+ currentEdge,
+ selectedNodes,
+ selectedEdges,
+ toggleEdgeSelection,
+ setCurrentEdge,
+ clearSelectedEdges,
+ setOpenMainDialog
+ } = useGraphStore(
useShallow((s) => ({
currentNode: s.currentNode,
currentEdge: s.currentEdge,
@@ -76,10 +89,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
const { theme } = useTheme()
- const selectedNodeIds = useMemo(
- () => new Set(selectedNodes.map(n => n.id)),
- [selectedNodes]
- )
+ const selectedNodeIds = useMemo(() => new Set(selectedNodes.map((n) => n.id)), [selectedNodes])
const currentNodeId = currentNode?.id
const selectedNodeIdsRef = useRef(selectedNodeIds)
@@ -87,28 +97,16 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
selectedNodeIdsRef.current = selectedNodeIds
}, [selectedNodeIds])
- const edgeMap = useMemo(
- () => new Map(edges.map(e => [e.id, e])),
- [edges]
- )
+ const edgeMap = useMemo(() => new Map(edges.map((e) => [e.id, e])), [edges])
- const isCurrent = useCallback(
- (nodeId: string) => nodeId === currentNodeId,
- [currentNodeId]
- )
+ const isCurrent = useCallback((nodeId: string) => nodeId === currentNodeId, [currentNodeId])
- const isSelected = useCallback(
- (nodeId: string) => selectedNodeIds.has(nodeId),
- [selectedNodeIds]
- )
+ const isSelected = useCallback((nodeId: string) => selectedNodeIds.has(nodeId), [selectedNodeIds])
- const graph2ScreenCoords = useCallback(
- (node: any) => {
- if (!graphRef.current) return { x: 0, y: 0 }
- return graphRef.current.graph2ScreenCoords(node.x, node.y)
- },
- []
- )
+ const graph2ScreenCoords = useCallback((node: any) => {
+ if (!graphRef.current) return { x: 0, y: 0 }
+ return graphRef.current.graph2ScreenCoords(node.x, node.y)
+ }, [])
// Preload icons
useEffect(() => {
@@ -168,12 +166,22 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
graphData
})
- const wrappedRegenerateLayout = useCallback((layoutType: 'force' | 'hierarchy') => {
- setCurrentLayoutType(layoutType)
- regenerateLayout(layoutType)
- }, [regenerateLayout, setCurrentLayoutType])
+ const wrappedRegenerateLayout = useCallback(
+ (layoutType: 'force' | 'hierarchy') => {
+ setCurrentLayoutType(layoutType)
+ regenerateLayout(layoutType)
+ },
+ [regenerateLayout, setCurrentLayoutType]
+ )
- const { highlightNodes, highlightLinks, hoverNode, handleNodeHover, handleLinkHover, clearHighlights } = useHighlightState()
+ const {
+ highlightNodes,
+ highlightLinks,
+ hoverNode,
+ handleNodeHover,
+ handleLinkHover,
+ clearHighlights
+ } = useHighlightState()
const { tooltip, showTooltip, hideTooltip } = useTooltip(graphRef)
@@ -213,9 +221,12 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
saveAllNodePositions
})
- const wrappedHandleNodeDragEnd = useCallback((node: any) => {
- handleNodeDragEnd(node, graphData)
- }, [handleNodeDragEnd, graphData])
+ const wrappedHandleNodeDragEnd = useCallback(
+ (node: any) => {
+ handleNodeDragEnd(node, graphData)
+ },
+ [handleNodeDragEnd, graphData]
+ )
const hasPerformedInitialZoom = useRef(false)
@@ -229,6 +240,36 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
}
}, [])
+ const exportToPNG = useCallback(async () => {
+ if (!graphRef.current) {
+ throw new Error('Graph ref not available')
+ }
+ // Get the canvas element from the ForceGraph2D component
+ const canvas = containerRef.current?.querySelector('canvas')
+ if (!canvas) {
+ throw new Error('Canvas element not found')
+ }
+ return new Promise<void>((resolve, reject) => {
+ canvas.toBlob((blob) => {
+ if (!blob) {
+ reject(new Error('Failed to create image blob'))
+ return
+ }
+ // Create download link
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `sketch-${sketchId || 'export'}-${Date.now()}.png`
+ document.body.appendChild(a)
+ a.click()
+ // Cleanup
+ URL.revokeObjectURL(url)
+ document.body.removeChild(a)
+ resolve()
+ }, 'image/png')
+ })
+ }, [sketchId])
+
useGraphInitialization({
graphRef,
instanceId,
@@ -238,6 +279,14 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
regenerateLayout: wrappedRegenerateLayout
})
+ // Expose export function to global store
+ useEffect(() => {
+ setActions({ exportToPNG })
+ return () => {
+ setActions({ exportToPNG: async () => {} })
+ }
+ }, [exportToPNG, setActions])
+
// Clear highlights when graph data changes
useEffect(() => {
clearHighlights()
@@ -268,7 +317,17 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
hoverNode
})
},
- [forceSettings, showLabels, showIcons, isCurrent, isSelected, theme, highlightNodes, highlightLinks, hoverNode]
+ [
+ forceSettings,
+ showLabels,
+ showIcons,
+ isCurrent,
+ isSelected,
+ theme,
+ highlightNodes,
+ highlightLinks,
+ hoverNode
+ ]
)
const renderLinkCallback = useCallback(
@@ -290,7 +349,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
if (!nodes.length) {
return (
- <div ref={containerRef} className={"h-full"} style={style}>
+ <div ref={containerRef} className={'h-full'} style={style}>
<GraphEmptyState
onOpenAddDialog={handleOpenNewAddItemDialog}
onOpenImportDialog={handleOpenImportDialog}
diff --git a/flowsint-app/src/components/sketches/toolbar.tsx b/flowsint-app/src/components/sketches/toolbar.tsx
index d5d6360d..1b97228c 100644
--- a/flowsint-app/src/components/sketches/toolbar.tsx
+++ b/flowsint-app/src/components/sketches/toolbar.tsx
@@ -17,7 +17,8 @@ import {
ZoomIn,
ChevronDown,
SquareDashed,
- Focus
+ Focus,
+ Download
} from 'lucide-react'
import { memo, useCallback } from 'react'
import { toast } from 'sonner'
@@ -31,8 +32,10 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuTrigger,
+ DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
+import { sketchService } from '@/api/sketch-service'
+import { useParams } from '@tanstack/react-router'
// Tooltip wrapper component to avoid repetition
export const ToolbarButton = memo(function ToolbarButton({
@@ -60,15 +63,15 @@ export const ToolbarButton = memo(function ToolbarButton({
onClick={onClick}
disabled={disabled}
variant="ghost"
- size={showLabel ? "sm" : "icon"}
+ size={showLabel ? 'sm' : 'icon'}
className={cn(
'h-7 relative items-center shadow-none',
- !showLabel && "w-7",
+ !showLabel && 'w-7',
toggled &&
- 'bg-primary/30 border-primary/40 text-primary hover:bg-primary/40 hover:text-primary'
+ 'bg-primary/30 border-primary/40 text-primary hover:bg-primary/40 hover:text-primary'
)}
>
- {icon} {showLabel && <span className='hidden md:block'>{tooltip}</span>}
+ {icon} {showLabel && <span className="hidden md:block">{tooltip}</span>}
{badge && (
<span className="absolute -top-1 -right-2 !z-[500] bg-primary text-white text-[10px] rounded-full w-auto min-w-4.5 h-4.5 p-1 flex items-center justify-center">
{badge}
@@ -83,6 +86,7 @@ export const ToolbarButton = memo(function ToolbarButton({
})
export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean }) {
const { confirm } = useConfirm()
+ const { id: sketchId } = useParams({ strict: false })
const view = useGraphControls((s) => s.view)
const setView = useGraphControls((s) => s.setView)
const zoomToFit = useGraphControls((s) => s.zoomToFit)
@@ -91,6 +95,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
const zoomOut = useGraphControls((s) => s.zoomOut)
const regenerateLayout = useGraphControls((s) => s.regenerateLayout)
const refetchGraph = useGraphControls((s) => s.refetchGraph)
+ const exportToPNG = useGraphControls((s) => s.exportToPNG)
const isSelectorModeActive = useGraphControls((s) => s.isSelectorModeActive)
const setIsSelectorModeActive = useGraphControls((s) => s.setIsSelectorModeActive)
const selectionMode = useGraphControls((s) => s.selectionMode)
@@ -102,10 +107,10 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
const saveStatus = useGraphSaveStatus((s) => s.saveStatus)
useKeyboard(
- "s",
+ 's',
() => setIsSelectorModeActive(true),
- () => setIsSelectorModeActive(false),
- );
+ () => setIsSelectorModeActive(false)
+ )
const handleRefresh = useCallback(() => {
try {
@@ -116,10 +121,10 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
}, [refetchGraph])
const handleApplyForceLayout = useCallback(async () => {
-
const confirmed = await confirm({
title: 'Apply force layout?',
- message: 'This will reset all node positions and regenerate them using the force-directed layout algorithm. Current positions will be lost.'
+ message:
+ 'This will reset all node positions and regenerate them using the force-directed layout algorithm. Current positions will be lost.'
})
if (!confirmed) {
@@ -129,14 +134,17 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
regenerateLayout('force')
toast.success('Force layout applied successfully')
} catch (error) {
- toast.error(`Failed to apply layout: ${error instanceof Error ? error.message : 'Unknown error'}`)
+ toast.error(
+ `Failed to apply layout: ${error instanceof Error ? error.message : 'Unknown error'}`
+ )
}
}, [confirm, regenerateLayout])
const handleApplyHierarchyLayout = useCallback(async () => {
const confirmed = await confirm({
title: 'Apply hierarchy layout?',
- message: 'This will reset all node positions and regenerate them using the hierarchical layout algorithm. Current positions will be lost.'
+ message:
+ 'This will reset all node positions and regenerate them using the hierarchical layout algorithm. Current positions will be lost.'
})
if (!confirmed) {
@@ -146,7 +154,9 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
regenerateLayout('hierarchy')
toast.success('Hierarchy layout applied successfully')
} catch (error) {
- toast.error(`Failed to apply layout: ${error instanceof Error ? error.message : 'Unknown error'}`)
+ toast.error(
+ `Failed to apply layout: ${error instanceof Error ? error.message : 'Unknown error'}`
+ )
}
}, [confirm, regenerateLayout])
@@ -162,12 +172,34 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
setIsSelectorModeActive(!isSelectorModeActive)
}, [setIsSelectorModeActive, isSelectorModeActive])
- const handleSelectMode = useCallback((mode: 'lasso' | 'rectangle') => {
- setSelectionMode(mode)
- if (!isSelectorModeActive) {
- setIsSelectorModeActive(true)
- }
- }, [setSelectionMode, isSelectorModeActive, setIsSelectorModeActive])
+ const handleSelectMode = useCallback(
+ (mode: 'lasso' | 'rectangle') => {
+ setSelectionMode(mode)
+ if (!isSelectorModeActive) {
+ setIsSelectorModeActive(true)
+ }
+ },
+ [setSelectionMode, isSelectorModeActive, setIsSelectorModeActive]
+ )
+
+ const handleExport = useCallback(
+ async (format: 'json' | 'png') => {
+ if (!sketchId) return
+ try {
+ if (format === 'png') {
+ await exportToPNG()
+ } else {
+ await sketchService.exportSketch(sketchId, format)
+ }
+ toast.success(`Sketch exported as ${format.toUpperCase()}`)
+ } catch (error) {
+ toast.error(
+ `Failed to export sketch: ${error instanceof Error ? error.message : 'Unknown error'}`
+ )
+ }
+ },
+ [sketchId, exportToPNG]
+ )
const areExactlyTwoSelected = selectedNodes.length === 2
const areMergeable =
@@ -178,9 +210,9 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
)
return (
- <div className='flex justify-between h-10 z-50 items-center gap-6 overflow-x-auto overflow-y-hidden hide-scrollbar w-full border-b bg-card p-1 px-2'>
- <div className='flex h-full items-center gap-2'>
- <div className='flex gap-1'>
+ <div className="flex justify-between h-10 z-50 items-center gap-6 overflow-x-auto overflow-y-hidden hide-scrollbar w-full border-b bg-card p-1 px-2">
+ <div className="flex h-full items-center gap-2">
+ <div className="flex gap-1">
<ToolbarButton
icon={<GitPullRequestArrow className="h-4 w-4 opacity-70" />}
tooltip="Connect"
@@ -197,7 +229,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
/>
</div>
<Separator decorative orientation="vertical" />
- <div className='flex gap-1'>
+ <div className="flex gap-1">
<ToolbarButton
icon={<ZoomIn className="h-4 w-4 opacity-70" />}
tooltip="Zoom In"
@@ -224,7 +256,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
/>
</div>
<Separator decorative orientation="vertical" />
- <div className='flex gap-0.5'>
+ <div className="flex gap-0.5">
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -235,7 +267,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
className={cn(
'h-7 w-7 rounded relative items-center shadow-none',
isSelectorModeActive &&
- 'bg-primary/30 border-primary/40 text-primary hover:bg-primary/40 hover:text-primary'
+ 'bg-primary/30 border-primary/40 text-primary hover:bg-primary/40 hover:text-primary'
)}
>
{selectionMode === 'lasso' ? (
@@ -260,7 +292,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
className={cn(
'h-7 w-5 px-0 rounded relative items-center shadow-none',
isSelectorModeActive &&
- 'bg-primary/30 border-primary/40 text-primary hover:bg-primary/40 hover:text-primary'
+ 'bg-primary/30 border-primary/40 text-primary hover:bg-primary/40 hover:text-primary'
)}
>
<ChevronDown className="h-3 w-3 opacity-50" />
@@ -302,7 +334,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
</Filters>
</div>
<Separator orientation="vertical" />
- <div className="flex items-center gap-1" >
+ <div className="flex items-center gap-1">
<>
<ToolbarButton
icon={<NetworkIcon className="h-4 w-4 opacity-70" />}
@@ -322,7 +354,30 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
{/* Center: View Toggle Group */}
<ViewToggle view={view} setView={setView} />
</div>
- <div className='flex item-center gap-2'>
+ <div className="flex item-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ disabled={isLoading}
+ className="h-7 w-7 relative items-center shadow-none"
+ >
+ <Download className="h-4 w-4 opacity-70" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Export</TooltipContent>
+ </Tooltip>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-[140px]">
+ <DropdownMenuItem onClick={() => handleExport('json')}>Export as JSON</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => handleExport('png')}>Export as PNG</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
<ToolbarButton
onClick={handleRefresh}
disabled={isLoading}
@@ -331,6 +386,6 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
/>
<SaveStatusIndicator status={saveStatus} />
</div>
- </div >
+ </div>
)
-})
\ No newline at end of file
+})
diff --git a/flowsint-app/src/components/sketches/webgl/components/lod-indicator.tsx b/flowsint-app/src/components/sketches/webgl/components/lod-indicator.tsx
deleted file mode 100644
index 04407da2..00000000
--- a/flowsint-app/src/components/sketches/webgl/components/lod-indicator.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import React from 'react'
-import { getLODLevel } from '../utils/visibility-calculator'
-
-interface LODIndicatorProps {
- zoomLevel: number
- visible?: boolean
-}
-
-/**
- * LOD Indicator - Debug component to show current Level of Detail
- * Useful for development to understand when features are visible
- *
- * @example
- * ```tsx
- * <LODIndicator zoomLevel={currentZoom} visible={isDevelopment} />
- * ```
- */
-export const LODIndicator: React.FC<LODIndicatorProps> = ({ zoomLevel, visible = true }) => {
- if (!visible) return null
-
- const lodLevel = getLODLevel(zoomLevel)
-
- const getLODColor = (level: string) => {
- switch (level) {
- case 'minimal':
- return 'bg-red-500/80'
- case 'low':
- return 'bg-orange-500/80'
- case 'medium':
- return 'bg-yellow-500/80'
- case 'high':
- return 'bg-green-500/80'
- default:
- return 'bg-gray-500/80'
- }
- }
-
- const getLODDescription = (level: string) => {
- switch (level) {
- case 'minimal':
- return 'Nodes + Edges only'
- case 'low':
- return 'Basic labels visible'
- case 'medium':
- return 'Icons visible'
- case 'high':
- return 'All features visible'
- default:
- return 'Unknown'
- }
- }
-
- return (
- <div className="pointer-events-none absolute top-4 right-4 z-50 select-none">
- <div className="flex flex-col gap-1 rounded-lg border border-white/20 bg-black/60 p-3 text-xs backdrop-blur-sm">
- <div className="flex items-center gap-2">
- <div className={`h-2 w-2 rounded-full ${getLODColor(lodLevel)}`} />
- <span className="font-semibold text-white">
- LOD: {lodLevel.toUpperCase()}
- </span>
- </div>
- <div className="text-gray-300">{getLODDescription(lodLevel)}</div>
- <div className="text-gray-400">Zoom: {zoomLevel.toFixed(2)}x</div>
- </div>
- </div>
- )
-}
-
-export default LODIndicator
diff --git a/flowsint-app/src/components/sketches/webgl/constants.ts b/flowsint-app/src/components/sketches/webgl/constants.ts
deleted file mode 100644
index fe3faa0a..00000000
--- a/flowsint-app/src/components/sketches/webgl/constants.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * WebGL Graph Viewer Constants
- * Centralized configuration for graph rendering
- */
-
-export const GRAPH_CONSTANTS = {
- // Node rendering
- NODE_DEFAULT_SIZE: 10,
- NODE_FONT_SIZE: 3.5,
- NODE_LABEL_FONT_SIZE: 3.5,
- MIN_FONT_SIZE: 0.5,
-
- // Edge rendering
- LINK_WIDTH: 1,
-
- // Colors (hexadecimal)
- NODE_DEFAULT_COLOR: 0x0074D9,
- HOVER_COLOR: 0xff7300,
- NODE_HIGHLIGHT_HOVER: 0xff0000,
- NODE_HIGHLIGHT_DEFAULT: 0xffa500,
- BACKGROUND_COLOR: 0x1a1a1a,
- LABEL_COLOR: 0xe0e0e0,
- LABEL_BG_COLOR: 0x1a1a1a,
- LABEL_BG_BORDER_COLOR: 0x404040,
- LINK_DEFAULT_COLOR: 0x808080,
- LINK_DIMMED_COLOR: 0x858585,
- EDGE_LABEL_BG_COLOR: 0x202020,
-
- // Zoom/Pan
- MIN_ZOOM: 0.25,
- MAX_ZOOM: 4,
- ZOOM_IN_FACTOR: 1.5,
- ZOOM_OUT_FACTOR: 0.75,
- ZOOM_TRANSITION_DURATION: 300,
- ZOOM_FIT_DURATION: 500,
- ZOOM_FIT_PADDING: 50,
-
- // Label visibility
- MIN_VISIBLE_LABELS: 5,
- MAX_VISIBLE_LABELS_PER_ZOOM: 15,
- EDGE_LABEL_MIN_ZOOM: 1.2,
-
- // Level of Details (LOD) thresholds
- LOD_ICON_MIN_ZOOM: 0.6, // Show icons when zoom >= 0.6
- LOD_NODE_LABEL_MIN_ZOOM: 0.5, // Show node labels when zoom >= 0.5
- LOD_EDGE_LABEL_MIN_ZOOM: 1.2, // Enable edge labels when zoom >= 1.2 (only shown when nodes are active)
- LOD_HIGH_DETAIL_ZOOM: 1.5, // High detail mode (all features) when zoom >= 1.5
-
- // Performance
- MAX_LABEL_LENGTH: 58,
- RESIZE_DEBOUNCE_MS: 150,
- DEVICE_PIXEL_RATIO_MIN: 2,
-
- // Force simulation
- FORCE_LINK_DISTANCE: 100,
- FORCE_CHARGE_STRENGTH: -300,
- FORCE_ALPHA_TARGET_DRAG: 0.3,
-
- // Interaction
- CLICK_DISTANCE_THRESHOLD: 10,
-
- // Rendering
- EDGE_LABEL_PADDING: 3,
- EDGE_LABEL_BORDER_RADIUS: 2,
- NODE_LABEL_PADDING_X: 6,
- NODE_LABEL_PADDING_Y: 3,
- NODE_LABEL_BORDER_RADIUS: 4,
- NODE_LABEL_BORDER_WIDTH: 1,
- NODE_HIGHLIGHT_SCALE: 1.2,
- NODE_BORDER_WIDTH: 2,
- ICON_SIZE_MULTIPLIER: 1.6,
-
- // Opacity
- DIMMED_ALPHA: 0.2,
- HIGHLIGHTED_ALPHA: 1,
- LINK_DEFAULT_ALPHA: 0.6,
- LINK_HIGHLIGHTED_ALPHA: 0.68,
- LINK_DIMMED_ALPHA: 0.23,
- EDGE_LABEL_BG_ALPHA: 0.9,
- NODE_HIGHLIGHT_RING_ALPHA: 0.3,
- NODE_LABEL_BG_ALPHA: 0.92,
- NODE_LABEL_BG_BORDER_ALPHA: 0.3,
-} as const
-
-export type GraphConstants = typeof GRAPH_CONSTANTS
diff --git a/flowsint-app/src/components/sketches/webgl/exports.ts b/flowsint-app/src/components/sketches/webgl/exports.ts
deleted file mode 100644
index 466dfc5d..00000000
--- a/flowsint-app/src/components/sketches/webgl/exports.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Public exports for WebGL Graph Viewer
- * Use this file to export types, utilities, and constants that external consumers might need
- */
-
-// Main component
-export { default as WebGLGraphViewer } from './index'
-
-// Types
-export type {
- WebGLGraphViewerProps,
- SimulationNode,
- SimulationLink,
- GraphControlActions,
- HighlightState,
- EnricherState,
- VisibilitySettings,
- ForceSettings,
- NodeLabelObjects,
- EdgeLabelObjects,
- LayoutMode,
-} from './types/graph.types'
-export type { LabelBoundingBox } from './utils/label-decluttering'
-
-// Constants (if external consumers need them)
-export { GRAPH_CONSTANTS } from './constants'
-
-// Utilities (if external consumers need them)
-export { textureCache } from './utils/texture-cache'
-export {
- calculateVisibleLabels, // @deprecated - Use selectLabelsWithDecluttering instead
- shouldShowEdgeLabels,
- shouldShowNodeIcons,
- shouldShowNodeLabels,
- isHighDetailMode,
- getLODLevel,
- calculateNodeLabelFontSize,
-} from './utils/visibility-calculator'
-export {
- calculateLabelBoundingBox,
- boundingBoxesOverlap,
- selectLabelsWithDecluttering,
- selectLabelsWithDeclutteringFast,
-} from './utils/label-decluttering'
-export {
- cssToPixiColor,
- pixiToCssColor,
- getNodeColor,
- getEdgeStyle,
-} from './utils/color-utils'
-
-// Hooks (if external consumers want to build custom viewers)
-export { usePixiApp } from './hooks/use-pixi-app'
-export { useForceSimulation } from './hooks/use-force-simulation'
-export { useGraphInteractions } from './hooks/use-graph-interactions'
-export { useZoomPan } from './hooks/use-zoom-pan'
-export { useGraphRenderer } from './hooks/use-graph-renderer'
-
-// Renderers (if external consumers want to customize rendering)
-export {
- renderNode,
- updateIconSprite,
- calculateNodeSize,
-} from './renderers/node-renderer'
-export { renderEdges, createLinkKey } from './renderers/edge-renderer'
-export {
- updateNodeLabel,
- updateEdgeLabel,
- createNodeLabel,
- createEdgeLabel,
-} from './renderers/label-renderer'
-
-// Debug components
-export { LODIndicator } from './components/lod-indicator'
diff --git a/flowsint-app/src/components/sketches/webgl/hooks/use-force-simulation.ts b/flowsint-app/src/components/sketches/webgl/hooks/use-force-simulation.ts
deleted file mode 100644
index e9d69a44..00000000
--- a/flowsint-app/src/components/sketches/webgl/hooks/use-force-simulation.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { useEffect, useRef, useState } from 'react'
-import { forceSimulation, forceLink, forceManyBody, forceCenter, Simulation } from 'd3-force'
-import { GRAPH_CONSTANTS } from '../constants'
-import type { GraphNode, GraphEdge } from '@/types'
-import type { SimulationNode, SimulationLink, LayoutMode } from '../types/graph.types'
-import type { ItemType } from '@/stores/node-display-settings'
-import { getDagreLayoutedElements } from '@/lib/utils'
-
-interface UseForceSimulationProps {
- nodes: GraphNode[]
- edges: GraphEdge[]
- width: number
- height: number
- nodeColors: Record<ItemType, string>
- layoutMode: LayoutMode
- dagLevelDistance?: number
- forceLinkDistance?: number
- forceLinkStrength?: number
- forceChargeStrength?: number
-}
-
-/**
- * Hook to manage D3 force simulation or static layouts
- *
- * Supports three layout modes:
- * - 'none': Static grid layout, no physics
- * - 'force': D3 force-directed layout with physics
- * - 'dagre': Hierarchical layout using Dagre algorithm
- *
- * @param props - Simulation configuration
- * @returns Simulation nodes, links, and simulation control
- */
-export function useForceSimulation({
- nodes,
- edges,
- width,
- height,
- nodeColors,
- layoutMode,
- dagLevelDistance = 50,
- forceLinkDistance = GRAPH_CONSTANTS.FORCE_LINK_DISTANCE,
- forceLinkStrength,
- forceChargeStrength = GRAPH_CONSTANTS.FORCE_CHARGE_STRENGTH,
-}: UseForceSimulationProps) {
- const [simulationNodes, setSimulationNodes] = useState<SimulationNode[]>([])
- const [simulationLinks, setSimulationLinks] = useState<SimulationLink[]>([])
- const simulationRef = useRef<Simulation<SimulationNode, SimulationLink> | null>(null)
-
- useEffect(() => {
- // Common node preparation
- const prepareNode = (node: GraphNode, x: number, y: number): SimulationNode => {
- const type = node.data?.type as ItemType
- const nodeColor =
- nodeColors[type] ||
- `#${GRAPH_CONSTANTS.NODE_DEFAULT_COLOR.toString(16).padStart(6, '0')}`
-
- return {
- ...node,
- x,
- y,
- nodeColor,
- nodeSize: GRAPH_CONSTANTS.NODE_DEFAULT_SIZE,
- neighbors: [] as SimulationNode[],
- links: [] as SimulationLink[],
- }
- }
-
- let simNodes: SimulationNode[]
-
- // Layout-specific node positioning
- if (layoutMode === 'dagre') {
- // Use Dagre hierarchical layout
- const { nodes: layoutedNodes } = getDagreLayoutedElements(nodes, edges, {
- direction: 'TB',
- dagLevelDistance: dagLevelDistance,
- })
- simNodes = layoutedNodes.map((node) => prepareNode(node, node.x || 0, node.y || 0))
- } else if (layoutMode === 'none') {
- // Static grid layout
- const cols = Math.ceil(Math.sqrt(nodes.length))
- const cellWidth = width / (cols + 1)
- const cellHeight = height / (Math.ceil(nodes.length / cols) + 1)
-
- simNodes = nodes.map((node, i) => {
- const row = Math.floor(i / cols)
- const col = i % cols
- const x = cellWidth * (col + 1)
- const y = cellHeight * (row + 1)
- return prepareNode(node, x, y)
- })
- } else {
- // Force layout - random initial positions
- simNodes = nodes.map((node) =>
- prepareNode(node, Math.random() * width, Math.random() * height)
- )
- }
-
- const simLinks: SimulationLink[] = edges.map((edge) => ({
- source: edge.source,
- target: edge.target,
- }))
-
- // Build node relationships
- const nodeMap = new Map(simNodes.map((node) => [node.id, node]))
- simLinks.forEach((link) => {
- const sourceId = typeof link.source === 'string' ? link.source : link.source.id
- const targetId = typeof link.target === 'string' ? link.target : link.target.id
- const sourceNode = nodeMap.get(sourceId)
- const targetNode = nodeMap.get(targetId)
-
- if (sourceNode && targetNode) {
- if (!sourceNode.neighbors.includes(targetNode)) {
- sourceNode.neighbors.push(targetNode)
- }
- if (!targetNode.neighbors.includes(sourceNode)) {
- targetNode.neighbors.push(sourceNode)
- }
- sourceNode.links.push(link)
- targetNode.links.push(link)
- }
- })
-
- setSimulationNodes(simNodes)
- setSimulationLinks(simLinks)
-
- // Create D3 force simulation only for force layout
- if (layoutMode === 'force') {
- const linkForce = forceLink(simLinks)
- .id((d: any) => d.id)
- .distance(forceLinkDistance)
-
- // Apply link strength if provided (for fixed distance links)
- if (forceLinkStrength !== undefined) {
- linkForce.strength(forceLinkStrength)
- }
-
- const simulation = forceSimulation(simNodes)
- .force('link', linkForce)
- .force('charge', forceManyBody().strength(forceChargeStrength))
- .force('center', forceCenter(width / 2, height / 2))
-
- simulationRef.current = simulation
-
- return () => {
- simulation.stop()
- simulationRef.current = null
- }
- } else {
- // For static layouts, clean up any existing simulation
- if (simulationRef.current) {
- simulationRef.current.stop()
- simulationRef.current = null
- }
- }
- }, [
- nodes,
- edges,
- width,
- height,
- nodeColors,
- layoutMode,
- dagLevelDistance,
- forceLinkDistance,
- forceLinkStrength,
- forceChargeStrength,
- ])
-
- return {
- simulationNodes,
- simulationLinks,
- simulation: simulationRef.current,
- }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/hooks/use-graph-interactions.ts b/flowsint-app/src/components/sketches/webgl/hooks/use-graph-interactions.ts
deleted file mode 100644
index 9ed0d6b2..00000000
--- a/flowsint-app/src/components/sketches/webgl/hooks/use-graph-interactions.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-import { useCallback, useRef, useState } from 'react'
-import { Graphics, FederatedPointerEvent } from 'pixi.js'
-import { GRAPH_CONSTANTS } from '../constants'
-import type { SimulationNode, HighlightState, EnricherState } from '../types/graph.types'
-import type { Simulation } from 'd3-force'
-import type { GraphNode } from '@/types'
-
-interface UseGraphInteractionsProps {
- simulation: Simulation<SimulationNode, any> | null
- onNodeClick?: (node: GraphNode, event: MouseEvent) => void
- onNodeRightClick?: (node: GraphNode, event: MouseEvent) => void
- onBackgroundClick?: () => void
-}
-
-/**
- * Hook to manage graph interactions (hover, click, drag)
- *
- * @param props - Interaction configuration
- * @returns Interaction state and handlers
- */
-export function useGraphInteractions({
- simulation,
- onNodeClick,
- onNodeRightClick,
- onBackgroundClick,
-}: UseGraphInteractionsProps) {
- const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null)
- const [highlightState, setHighlightState] = useState<HighlightState>({
- nodes: new Set(),
- links: new Set(),
- })
- const [isDragging, setIsDragging] = useState(false)
-
- const transformRef = useRef<EnricherState>({ k: 1, x: 0, y: 0 })
- const nodeWasClickedRef = useRef(false)
-
- /**
- * Handle node hover
- */
- const handleNodeHover = useCallback((node: SimulationNode) => {
- setHoveredNodeId(node.id)
-
- const nodes = new Set<string>([node.id])
- const links = new Set<string>()
-
- // Add neighbors
- node.neighbors.forEach((neighbor) => {
- nodes.add(neighbor.id)
- })
-
- // Add connected links
- node.links.forEach((link: any) => {
- const sourceId = typeof link.source === 'object' ? link.source.id : link.source
- const targetId = typeof link.target === 'object' ? link.target.id : link.target
- links.add(`${sourceId}-${targetId}`)
- })
-
- setHighlightState({ nodes, links })
- }, [])
-
- /**
- * Handle node hover leave
- */
- const handleNodeLeave = useCallback(() => {
- setHoveredNodeId(null)
- setHighlightState({ nodes: new Set(), links: new Set() })
- }, [])
-
- /**
- * Create pointer down handler for a node
- */
- const createNodePointerDownHandler = useCallback(
- (node: SimulationNode, nodeGfx: Graphics, stage: any) => {
- return (event: FederatedPointerEvent) => {
- event.stopPropagation()
- setIsDragging(true)
-
- const dragStartPos = event.global.clone()
- node.fx = node.x
- node.fy = node.y
- simulation?.alphaTarget(GRAPH_CONSTANTS.FORCE_ALPHA_TARGET_DRAG).restart()
- nodeGfx.cursor = 'grabbing'
-
- let lastPos = event.global.clone()
-
- const onMove = (e: FederatedPointerEvent) => {
- const newPos = e.global
- const dx = (newPos.x - lastPos.x) / transformRef.current.k
- const dy = (newPos.y - lastPos.y) / transformRef.current.k
- node.fx = (node.fx || node.x!) + dx
- node.fy = (node.fy || node.y!) + dy
- lastPos = newPos.clone()
- }
-
- const onUp = (e: FederatedPointerEvent) => {
- const distance = Math.hypot(
- e.global.x - dragStartPos.x,
- e.global.y - dragStartPos.y
- )
-
- setIsDragging(false)
- node.fx = null
- node.fy = null
- simulation?.alphaTarget(0)
- nodeGfx.cursor = 'pointer'
-
- stage.off('pointermove', onMove)
- stage.off('pointerup', onUp)
- stage.off('pointerupoutside', onUp)
-
- // Trigger click if drag distance is small
- if (distance < GRAPH_CONSTANTS.CLICK_DISTANCE_THRESHOLD) {
- nodeWasClickedRef.current = true
- const mouseEvent = new MouseEvent('click', {
- ctrlKey: e.ctrlKey,
- shiftKey: e.shiftKey,
- metaKey: e.metaKey,
- })
- onNodeClick?.(node, mouseEvent)
- }
-
- handleNodeLeave()
- }
-
- stage.on('pointermove', onMove)
- stage.on('pointerup', onUp)
- stage.on('pointerupoutside', onUp)
- }
- },
- [simulation, onNodeClick, handleNodeLeave]
- )
-
- /**
- * Create right click handler for a node
- */
- const createNodeRightClickHandler = useCallback(
- (node: SimulationNode) => {
- return (event: FederatedPointerEvent) => {
- if (onNodeRightClick) {
- event.stopPropagation()
- const mouseEvent = new MouseEvent('contextmenu', {
- clientX: event.global.x,
- clientY: event.global.y,
- ctrlKey: event.ctrlKey,
- shiftKey: event.shiftKey,
- metaKey: event.metaKey,
- })
- onNodeRightClick(node, mouseEvent)
- }
- }
- },
- [onNodeRightClick]
- )
-
- /**
- * Handle background click
- */
- const handleBackgroundClick = useCallback(() => {
- if (!nodeWasClickedRef.current && onBackgroundClick) {
- onBackgroundClick()
- }
- nodeWasClickedRef.current = false
- }, [onBackgroundClick])
-
- /**
- * Update transform reference (for drag calculations)
- */
- const updateEnricher = useCallback((transform: EnricherState) => {
- transformRef.current = transform
- }, [])
-
- return {
- hoveredNodeId,
- highlightState,
- isDragging,
- handleNodeHover,
- handleNodeLeave,
- createNodePointerDownHandler,
- createNodeRightClickHandler,
- handleBackgroundClick,
- updateEnricher,
- }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/hooks/use-graph-renderer.ts b/flowsint-app/src/components/sketches/webgl/hooks/use-graph-renderer.ts
deleted file mode 100644
index 2f19a3ee..00000000
--- a/flowsint-app/src/components/sketches/webgl/hooks/use-graph-renderer.ts
+++ /dev/null
@@ -1,440 +0,0 @@
-import { useEffect, useRef, useState, useCallback } from 'react'
-import { Graphics, Sprite } from 'pixi.js'
-import type { Application, Container } from 'pixi.js'
-import type { GraphEdge } from '@/types'
-import type {
- SimulationNode,
- SimulationLink,
- EdgeLabelObjects,
- NodeLabelObjects,
- HighlightState,
- ForceSettings,
-} from '../types/graph.types'
-import type { ItemType } from '@/stores/node-display-settings'
-import { textureCache } from '../utils/texture-cache'
-import {
- shouldShowEdgeLabels,
- shouldShowNodeIcons,
- shouldShowNodeLabels,
-} from '../utils/visibility-calculator'
-import { selectLabelsWithDeclutteringFast } from '../utils/label-decluttering'
-import { renderNode, updateIconSprite, calculateNodeSize } from '../renderers/node-renderer'
-import { renderEdges } from '../renderers/edge-renderer'
-import {
- updateNodeLabel,
- updateEdgeLabel,
- createNodeLabel,
- createEdgeLabel,
-} from '../renderers/label-renderer'
-
-interface UseGraphRendererProps {
- app: Application | null
- containers: {
- linkContainer: Container
- edgeLabelContainer: Container
- nodeContainer: Container
- labelContainer: Container
- } | null
- simulationNodes: SimulationNode[]
- simulationLinks: SimulationLink[]
- edges: GraphEdge[]
- selectedNodeIds: Set<string>
- hoveredNodeId: string | null
- highlightState: HighlightState
- forceSettings: ForceSettings
- showIcons: boolean
- showLabels: boolean
- onNodeHover: (node: SimulationNode) => void
- onNodeLeave: () => void
- createNodePointerDownHandler: (node: SimulationNode, nodeGfx: Graphics, stage: any) => any
- createNodeRightClickHandler: (node: SimulationNode) => any
-}
-
-/**
- * Main rendering hook that orchestrates all rendering logic
- *
- * @param props - Renderer configuration
- * @returns Zoom change callback
- */
-export function useGraphRenderer({
- app,
- containers,
- simulationNodes,
- simulationLinks,
- edges,
- selectedNodeIds,
- hoveredNodeId,
- highlightState,
- forceSettings,
- showIcons,
- showLabels,
- onNodeHover,
- onNodeLeave,
- createNodePointerDownHandler,
- createNodeRightClickHandler,
-}: UseGraphRendererProps) {
- const nodeGraphicsMapRef = useRef(new Map<string, Graphics>())
- const nodeLabelMapRef = useRef(new Map<string, NodeLabelObjects>())
- const nodeIconMapRef = useRef(new Map<string, Sprite>())
- const edgeLabelMapRef = useRef(new Map<string, EdgeLabelObjects>())
- const linkGraphicsRef = useRef<Graphics | null>(null)
-
- const [visibleLabels, setVisibleLabels] = useState<Set<string>>(new Set())
- const [currentZoom, setCurrentZoom] = useState(1)
- const animationFrameRef = useRef<number | null>(null)
- const stopAnimationRef = useRef(false)
- const lastLabelUpdateRef = useRef<number>(0)
- const isZoomingRef = useRef(false)
- const zoomTimeoutRef = useRef<NodeJS.Timeout | null>(null)
-
- // LOD state (derived from zoom)
- const showIconsLOD = shouldShowNodeIcons(currentZoom)
- const showLabelsLOD = shouldShowNodeLabels(currentZoom)
- const showEdgeLabelsLOD = shouldShowEdgeLabels(currentZoom)
-
- /**
- * Handle zoom change with throttling
- * PERFORMANCE: Throttle label recalculation and detect zooming state
- */
- const handleZoomChange = useCallback((zoomLevel: number) => {
- setCurrentZoom(zoomLevel)
-
- // Mark as zooming
- isZoomingRef.current = true
-
- // Clear previous timeout
- if (zoomTimeoutRef.current) {
- clearTimeout(zoomTimeoutRef.current)
- }
-
- // Mark zoom as finished after 300ms of no zoom changes
- zoomTimeoutRef.current = setTimeout(() => {
- isZoomingRef.current = false
- }, 300)
-
- // Throttle label recalculation (max once every 200ms)
- const now = Date.now()
- if (now - lastLabelUpdateRef.current > 200) {
- lastLabelUpdateRef.current = now
-
- // Recalculate visible labels with decluttering
- if (app && app.renderer && app.stage) {
- const viewport = app.renderer
- const stage = app.stage
-
- const visibleLabels = selectLabelsWithDeclutteringFast(
- simulationNodes,
- forceSettings.nodeSize.value,
- zoomLevel,
- forceSettings.nodeLabelFontSize?.value ?? 50,
- viewport.width,
- viewport.height,
- -stage.position.x / stage.scale.x,
- -stage.position.y / stage.scale.y,
- selectedNodeIds,
- highlightState.nodes
- )
- setVisibleLabels(visibleLabels)
- }
- }
- }, [simulationNodes, app, forceSettings, selectedNodeIds, highlightState.nodes])
-
- /**
- * Initialize rendering objects (nodes, labels, icons, etc.)
- */
- useEffect(() => {
- if (!containers || !app) return
-
- const { linkContainer, edgeLabelContainer, nodeContainer, labelContainer } = containers
-
- // Clear existing objects
- nodeGraphicsMapRef.current.clear()
- nodeLabelMapRef.current.clear()
- nodeIconMapRef.current.clear()
- edgeLabelMapRef.current.clear()
- linkContainer.removeChildren()
- edgeLabelContainer.removeChildren()
- nodeContainer.removeChildren()
- labelContainer.removeChildren()
-
- // Create link graphics
- const linkGraphics = new Graphics()
- linkContainer.addChild(linkGraphics)
- linkGraphicsRef.current = linkGraphics
-
- // Preload icons
- const loadIcons = async () => {
- if (showIcons) {
- const iconTypes = new Set<ItemType>()
- simulationNodes.forEach((node) => {
- if (node.data?.type) {
- iconTypes.add(node.data.type as ItemType)
- }
- })
- await textureCache.preloadBatch(Array.from(iconTypes))
- }
-
- // Create node graphics, labels, and icons
- simulationNodes.forEach((node) => {
- // Create node graphics
- const nodeGfx: Graphics = new Graphics({
- interactive: true,
- eventMode: 'static',
- cursor: 'pointer',
- })
-
- // Attach event handlers
- nodeGfx
- .on('pointerover', () => onNodeHover(node))
- .on('pointerleave', () => onNodeLeave())
- .on('pointerdown', createNodePointerDownHandler(node, nodeGfx, app.stage))
- .on('rightclick', createNodeRightClickHandler(node))
-
- nodeContainer.addChild(nodeGfx)
- nodeGraphicsMapRef.current.set(node.id, nodeGfx)
-
- // Create icon sprite if needed (only if showIcons is enabled globally)
- // Note: Icons will be hidden/shown based on zoom level in the render loop
- if (showIcons && node.data?.type) {
- const nodeType = node.data.type as ItemType
- const cachedTexture = textureCache.get(nodeType)
- if (cachedTexture) {
- const iconSprite = new Sprite(cachedTexture)
- iconSprite.anchor.set(0.5)
- iconSprite.eventMode = 'none'
- iconSprite.roundPixels = false
- iconSprite.visible = false // Start hidden, will be shown based on LOD
- if (cachedTexture.source) {
- cachedTexture.source.scaleMode = 'linear'
- }
- nodeContainer.addChild(iconSprite)
- nodeIconMapRef.current.set(node.id, iconSprite)
- }
- }
-
- // Create node label with background
- const labelText = node.data?.label || node.id
- const labelObjects = createNodeLabel(labelText)
- // Add background first (so it renders behind the text)
- labelContainer.addChild(labelObjects.background)
- labelContainer.addChild(labelObjects.text)
- nodeLabelMapRef.current.set(node.id, labelObjects)
- })
-
- // Create edge labels
- if (showLabels) {
- edges.forEach((edge) => {
- if (edge.label) {
- const edgeKey = `${edge.source}-${edge.target}`
- const edgeLabel = createEdgeLabel(edge.label)
- edgeLabelContainer.addChild(edgeLabel.background)
- edgeLabelContainer.addChild(edgeLabel.text)
- edgeLabelMapRef.current.set(edgeKey, edgeLabel)
- }
- })
- }
-
- // Initialize visible labels with decluttering
- if (app && app.renderer && app.stage) {
- const viewport = app.renderer
- const stage = app.stage
-
- const initialVisibleLabels = selectLabelsWithDeclutteringFast(
- simulationNodes,
- forceSettings.nodeSize.value,
- 1, // Initial zoom level
- forceSettings.nodeLabelFontSize?.value ?? 50,
- viewport.width,
- viewport.height,
- -stage.position.x / stage.scale.x,
- -stage.position.y / stage.scale.y,
- new Set(), // No selected nodes initially
- new Set() // No highlighted nodes initially
- )
- setVisibleLabels(initialVisibleLabels)
- }
- }
-
- loadIcons()
- }, [
- app,
- containers,
- simulationNodes,
- edges,
- showIcons,
- showLabels,
- forceSettings,
- onNodeHover,
- onNodeLeave,
- createNodePointerDownHandler,
- createNodeRightClickHandler,
- ])
-
- /**
- * Animation loop
- */
- useEffect(() => {
- if (!app || !containers) return
-
- stopAnimationRef.current = false
-
- const animate = () => {
- if (stopAnimationRef.current || !app || !app.stage || app.stage.destroyed) return
-
- const linkGraphics = linkGraphicsRef.current
- if (!linkGraphics) return
-
- const hasAnyHighlight = highlightState.nodes.size > 0 || highlightState.links.size > 0
-
- // Render edges
- const linkWidth = forceSettings?.linkWidth?.value ?? 2
- renderEdges(linkGraphics, simulationLinks, highlightState.links, linkWidth)
-
- // Render edge labels (only if LOD allows AND nodes are active)
- // PERFORMANCE: Skip edge labels during zoom
- if (isZoomingRef.current || !showLabels || !showEdgeLabelsLOD) {
- // Hide all edge labels during zoom or if LOD doesn't allow
- edgeLabelMapRef.current.forEach((edgeLabel) => {
- edgeLabel.text.visible = false
- edgeLabel.background.visible = false
- })
- } else {
- simulationLinks.forEach((link) => {
- const source = link.source as SimulationNode
- const target = link.target as SimulationNode
- const linkKey = `${source.id}-${target.id}`
- const edgeLabel = edgeLabelMapRef.current.get(linkKey)
-
- if (edgeLabel) {
- // Show edge label only if at least one of its nodes is active
- const sourceActive =
- highlightState.nodes.has(source.id) || selectedNodeIds.has(source.id)
- const targetActive =
- highlightState.nodes.has(target.id) || selectedNodeIds.has(target.id)
- const shouldShowEdgeLabel = sourceActive || targetActive
-
- if (shouldShowEdgeLabel) {
- const isHighlighted = highlightState.links.has(linkKey)
- updateEdgeLabel(edgeLabel, link, currentZoom, isHighlighted, hasAnyHighlight)
- } else {
- // Hide edge label if nodes are not active
- edgeLabel.text.visible = false
- edgeLabel.background.visible = false
- }
- }
- })
- }
-
- // Render nodes
- // PERFORMANCE: Limit labels per frame to prevent lag
- let renderedLabelCount = 0
- const MAX_LABELS_PER_FRAME = 100
-
- simulationNodes.forEach((node) => {
- const nodeGfx = nodeGraphicsMapRef.current.get(node.id)
- if (!nodeGfx) return
-
- const nodeSize = calculateNodeSize(node, forceSettings.nodeSize.value)
- const isHovered = hoveredNodeId === node.id
- const isHighlighted = highlightState.nodes.has(node.id)
- const isSelected = selectedNodeIds.has(node.id)
-
- // Render node
- renderNode(
- nodeGfx,
- node,
- nodeSize,
- isHovered,
- isHighlighted,
- isSelected,
- hasAnyHighlight
- )
-
- // Update icon (only if LOD allows)
- if (showIcons && showIconsLOD) {
- const iconSprite = nodeIconMapRef.current.get(node.id)
- if (iconSprite) {
- iconSprite.visible = true
- updateIconSprite(iconSprite, node, nodeSize, isHighlighted, hasAnyHighlight)
- }
- } else if (showIcons) {
- // Hide icons if LOD doesn't allow them
- const iconSprite = nodeIconMapRef.current.get(node.id)
- if (iconSprite) {
- iconSprite.visible = false
- }
- }
-
- // Update label (only if LOD allows)
- const labelObjects = nodeLabelMapRef.current.get(node.id)
- if (labelObjects) {
- // PERFORMANCE: Skip label rendering during active zoom
- if (isZoomingRef.current) {
- labelObjects.text.visible = false
- labelObjects.background.visible = false
- return
- }
-
- // PERFORMANCE: Limit total labels rendered per frame
- const shouldShowBySelection = visibleLabels.has(node.id) || isHighlighted || isSelected
- const shouldShow = showLabelsLOD && shouldShowBySelection && renderedLabelCount < MAX_LABELS_PER_FRAME
-
- if (shouldShow) {
- renderedLabelCount++
- }
-
- const fontSizeSetting = forceSettings?.nodeLabelFontSize?.value ?? 50
- updateNodeLabel(
- labelObjects,
- node,
- nodeSize,
- shouldShow,
- currentZoom,
- fontSizeSetting,
- isHighlighted,
- hasAnyHighlight
- )
- }
- })
-
- // Render
- try {
- app.renderer.render(app.stage)
- } catch (error) {
- console.error('Render error:', error)
- stopAnimationRef.current = true
- return
- }
-
- // Continue animation
- if (!stopAnimationRef.current) {
- animationFrameRef.current = requestAnimationFrame(animate)
- }
- }
-
- animationFrameRef.current = requestAnimationFrame(animate)
-
- return () => {
- stopAnimationRef.current = true
- if (animationFrameRef.current !== null) {
- cancelAnimationFrame(animationFrameRef.current)
- animationFrameRef.current = null
- }
- }
- }, [
- app,
- containers,
- simulationNodes,
- simulationLinks,
- selectedNodeIds,
- hoveredNodeId,
- highlightState,
- forceSettings,
- showIcons,
- showLabels,
- currentZoom,
- visibleLabels,
- ])
-
- return { handleZoomChange }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/hooks/use-pixi-app.ts b/flowsint-app/src/components/sketches/webgl/hooks/use-pixi-app.ts
deleted file mode 100644
index 7796e054..00000000
--- a/flowsint-app/src/components/sketches/webgl/hooks/use-pixi-app.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { useEffect, useRef, useState } from 'react'
-import { Application, Container } from 'pixi.js'
-import { GRAPH_CONSTANTS } from '../constants'
-
-/**
- * Hook to manage Pixi.js Application lifecycle
- *
- * @param container - HTML div container element
- * @returns Pixi app, stage, and containers
- */
-export function usePixiApp(container: HTMLDivElement | null) {
- const [app, setApp] = useState<Application | null>(null)
- const [containers, setContainers] = useState<{
- linkContainer: Container
- edgeLabelContainer: Container
- nodeContainer: Container
- labelContainer: Container
- } | null>(null)
- const cleanupRef = useRef<(() => void) | null>(null)
-
- useEffect(() => {
- if (!container) return
-
- let mounted = true
-
- const initApp = async () => {
- const rect = container.getBoundingClientRect()
- const width = rect.width
- const height = rect.height
-
- // Create Pixi application
- const pixiApp = new Application()
- await pixiApp.init({
- width,
- height,
- backgroundColor: GRAPH_CONSTANTS.BACKGROUND_COLOR,
- antialias: true,
- autoStart: false, // Manual rendering for performance
- autoDensity: true,
- resolution: Math.max(
- window.devicePixelRatio || 1,
- GRAPH_CONSTANTS.DEVICE_PIXEL_RATIO_MIN
- ),
- })
-
- if (!mounted) {
- pixiApp.destroy(true)
- return
- }
-
- container.appendChild(pixiApp.canvas)
-
- const stage = pixiApp.stage
- stage.interactive = true
- stage.eventMode = 'static'
-
- // Create layer containers
- const linkContainer = new Container()
- const edgeLabelContainer = new Container()
- const nodeContainer = new Container()
- const labelContainer = new Container()
-
- stage.addChild(linkContainer, edgeLabelContainer, nodeContainer, labelContainer)
-
- setApp(pixiApp)
- setContainers({ linkContainer, edgeLabelContainer, nodeContainer, labelContainer })
-
- // Cleanup function
- cleanupRef.current = () => {
- if (pixiApp) {
- pixiApp.destroy(true, {
- children: true,
- texture: false, // Keep textures cached
- textureSource: false,
- })
- }
- }
- }
-
- initApp()
-
- return () => {
- mounted = false
- if (cleanupRef.current) {
- cleanupRef.current()
- cleanupRef.current = null
- }
- }
- }, [container])
-
- return { app, containers }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/hooks/use-zoom-pan.ts b/flowsint-app/src/components/sketches/webgl/hooks/use-zoom-pan.ts
deleted file mode 100644
index c864a29f..00000000
--- a/flowsint-app/src/components/sketches/webgl/hooks/use-zoom-pan.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { useEffect, useCallback, useRef } from 'react'
-// @ts-ignore - d3 types may not be available
-import { select, zoom, zoomIdentity, ZoomBehavior } from 'd3'
-import { GRAPH_CONSTANTS } from '../constants'
-import type { Application, Container } from 'pixi.js'
-import type { SimulationNode, TransformState } from '../types/graph.types'
-
-interface UseZoomPanProps {
- app: Application | null
- stage: Container | null
- width: number
- height: number
- isDragging: boolean
- simulationNodes: SimulationNode[]
- onEnricherChange: (transform: TransformState) => void
- onZoomChange: (zoomLevel: number) => void
-}
-
-/**
- * Hook to manage zoom and pan behavior
- *
- * @param props - Zoom/pan configuration
- * @returns Zoom control functions
- */
-export function useZoomPan({
- app,
- stage,
- width,
- height,
- isDragging,
- simulationNodes,
- onEnricherChange,
- onZoomChange,
-}: UseZoomPanProps) {
- const zoomBehaviorRef = useRef<ZoomBehavior<HTMLCanvasElement, unknown> | null>(null)
- const canvasSelectionRef = useRef<any>(null)
- const currentEnricherRef = useRef<TransformState>({ k: 1, x: 0, y: 0 })
-
- useEffect(() => {
- if (!app || !stage) return
-
- const zoomBehavior = zoom<HTMLCanvasElement, unknown>()
- .extent([
- [0, 0],
- [width, height],
- ])
- .scaleExtent([GRAPH_CONSTANTS.MIN_ZOOM, GRAPH_CONSTANTS.MAX_ZOOM])
- .filter(() => !isDragging) // Don't zoom/pan while dragging nodes
- .on('zoom', (event: any) => {
- const { transform } = event
- currentEnricherRef.current = transform
- stage.scale.set(transform.k, transform.k)
- stage.position.set(transform.x, transform.y)
- onEnricherChange(transform)
- onZoomChange(transform.k)
- })
-
- const canvasSelection = select<HTMLCanvasElement, unknown>(app.canvas)
- canvasSelection.call(zoomBehavior)
-
- zoomBehaviorRef.current = zoomBehavior
- canvasSelectionRef.current = canvasSelection
-
- return () => {
- canvasSelection.on('.zoom', null)
- zoomBehaviorRef.current = null
- canvasSelectionRef.current = null
- }
- }, [app, stage, width, height, isDragging, onEnricherChange, onZoomChange])
-
- /**
- * Zoom in
- */
- const zoomIn = useCallback(() => {
- if (!canvasSelectionRef.current || !zoomBehaviorRef.current) return
-
- const currentZoom = currentEnricherRef.current.k
- const newZoom = Math.min(
- currentZoom * GRAPH_CONSTANTS.ZOOM_IN_FACTOR,
- GRAPH_CONSTANTS.MAX_ZOOM
- )
-
- canvasSelectionRef.current
- .transition()
- .duration(GRAPH_CONSTANTS.ZOOM_TRANSITION_DURATION)
- .call(zoomBehaviorRef.current.scaleTo, newZoom)
- }, [])
-
- /**
- * Zoom out
- */
- const zoomOut = useCallback(() => {
- if (!canvasSelectionRef.current || !zoomBehaviorRef.current) return
-
- const currentZoom = currentEnricherRef.current.k
- const newZoom = Math.max(
- currentZoom * GRAPH_CONSTANTS.ZOOM_OUT_FACTOR,
- GRAPH_CONSTANTS.MIN_ZOOM
- )
-
- canvasSelectionRef.current
- .transition()
- .duration(GRAPH_CONSTANTS.ZOOM_TRANSITION_DURATION)
- .call(zoomBehaviorRef.current.scaleTo, newZoom)
- }, [])
-
- /**
- * Zoom to fit all nodes
- */
- const zoomToFit = useCallback(() => {
- if (!canvasSelectionRef.current || !zoomBehaviorRef.current) return
-
- // Calculate bounding box
- let minX = Infinity,
- minY = Infinity,
- maxX = -Infinity,
- maxY = -Infinity
-
- simulationNodes.forEach((node) => {
- if (node.x && node.y) {
- minX = Math.min(minX, node.x)
- minY = Math.min(minY, node.y)
- maxX = Math.max(maxX, node.x)
- maxY = Math.max(maxY, node.y)
- }
- })
-
- if (minX === Infinity) return // No nodes
-
- // Add padding
- const padding = GRAPH_CONSTANTS.ZOOM_FIT_PADDING
- const graphWidth = maxX - minX + padding * 2
- const graphHeight = maxY - minY + padding * 2
-
- // Calculate scale to fit
- const scaleX = width / graphWidth
- const scaleY = height / graphHeight
- const scale = Math.min(scaleX, scaleY, GRAPH_CONSTANTS.MAX_ZOOM)
-
- // Calculate center
- const centerX = (minX + maxX) / 2
- const centerY = (minY + maxY) / 2
-
- // Calculate translation to center
- const translateX = width / 2 - centerX * scale
- const translateY = height / 2 - centerY * scale
-
- // Apply transformation
- canvasSelectionRef.current
- .transition()
- .duration(GRAPH_CONSTANTS.ZOOM_FIT_DURATION)
- .call(
- zoomBehaviorRef.current.transform,
- zoomIdentity.translate(translateX, translateY).scale(scale)
- )
- }, [width, height, simulationNodes])
-
- return {
- zoomIn,
- zoomOut,
- zoomToFit,
- }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/index.tsx b/flowsint-app/src/components/sketches/webgl/index.tsx
deleted file mode 100644
index c26b3682..00000000
--- a/flowsint-app/src/components/sketches/webgl/index.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { useNodesDisplaySettings } from '@/stores/node-display-settings'
-import { useGraphSettingsStore } from '@/stores/graph-settings-store'
-import { useGraphStore } from '@/stores/graph-store'
-import { useGraphControls } from '@/stores/graph-controls-store'
-import type { WebGLGraphViewerProps } from './types/graph.types'
-import { usePixiApp } from './hooks/use-pixi-app'
-import { useForceSimulation } from './hooks/use-force-simulation'
-import { useGraphInteractions } from './hooks/use-graph-interactions'
-import { useZoomPan } from './hooks/use-zoom-pan'
-import { useGraphRenderer } from './hooks/use-graph-renderer'
-import { GRAPH_CONSTANTS } from './constants'
-// Uncomment to enable LOD debug indicator:
-// import { LODIndicator } from './components/lod-indicator'
-
-/**
- * WebGL Graph Viewer - High-performance graph visualization
- *
- * A clean, reusable, and performant graph viewer built with:
- * - Pixi.js (WebGL) for rendering
- * - D3-force for physics simulation
- * - Modular architecture with separation of concerns
- *
- * @example
- * ```tsx
- * <WebGLGraphViewer
- * nodes={nodes}
- * edges={edges}
- * onNodeClick={(node) => console.log('Clicked:', node)}
- * showIcons={true}
- * showLabels={true}
- * />
- * ```
- */
-const WebGLGraphViewer: React.FC<WebGLGraphViewerProps> = ({
- nodes,
- edges,
- className = '',
- style,
- onNodeClick,
- onNodeRightClick,
- onBackgroundClick,
- showIcons = true,
- showLabels = true,
- layoutMode = 'none',
-}) => {
- const containerRef = useRef<HTMLDivElement | null>(null)
- const [containerElement, setContainerElement] = useState<HTMLDivElement | null>(null)
- const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
- const resizeObserverRef = useRef<ResizeObserver | null>(null)
- // Track zoom for LOD indicator (uncomment if using LODIndicator)
- // const [currentZoom, setCurrentZoom] = useState(1)
-
- // Store selectors
- const selectedNodes = useGraphStore((s) => s.selectedNodes)
- const selectedNodeIds = useMemo(
- () => new Set(selectedNodes.map((n) => n.id)),
- [selectedNodes]
- )
-
- const nodeColors = useNodesDisplaySettings((s) => s.colors)
- const forceSettings = useGraphSettingsStore((s) => s.forceSettings)
- const { setActions } = useGraphControls()
-
- // Initialize Pixi.js app
- const { app, containers } = usePixiApp(containerElement)
-
- // Initialize force simulation
- const { simulationNodes, simulationLinks, simulation } = useForceSimulation({
- nodes,
- edges,
- width: dimensions.width,
- height: dimensions.height,
- nodeColors,
- layoutMode,
- dagLevelDistance: forceSettings.dagLevelDistance?.value,
- forceLinkDistance: forceSettings.d3ForceLinkDistance?.value,
- forceLinkStrength: forceSettings.d3ForceLinkStrength?.value,
- forceChargeStrength: forceSettings.d3ForceChargeStrength?.value,
- })
-
- // Graph interactions (hover, click, drag)
- const {
- hoveredNodeId,
- highlightState,
- isDragging,
- handleNodeHover,
- handleNodeLeave,
- createNodePointerDownHandler,
- createNodeRightClickHandler,
- handleBackgroundClick,
- updateEnricher,
- } = useGraphInteractions({
- simulation,
- onNodeClick,
- onNodeRightClick,
- onBackgroundClick,
- })
-
- // Handle background click on stage
- useEffect(() => {
- if (!app) return
- const stage = app.stage
- stage.on('click', handleBackgroundClick)
- return () => {
- stage.off('click', handleBackgroundClick)
- }
- }, [app, handleBackgroundClick])
-
- // Graph renderer
- const { handleZoomChange } = useGraphRenderer({
- app,
- containers,
- simulationNodes,
- simulationLinks,
- edges,
- selectedNodeIds,
- hoveredNodeId,
- highlightState,
- forceSettings,
- showIcons,
- showLabels,
- onNodeHover: handleNodeHover,
- onNodeLeave: handleNodeLeave,
- createNodePointerDownHandler,
- createNodeRightClickHandler,
- })
-
- // Zoom and pan controls
- const { zoomIn, zoomOut, zoomToFit } = useZoomPan({
- app,
- stage: app?.stage ?? null,
- width: dimensions.width,
- height: dimensions.height,
- isDragging,
- simulationNodes,
- onEnricherChange: updateEnricher,
- onZoomChange: (zoom) => {
- handleZoomChange(zoom)
- // Uncomment if using LODIndicator:
- // setCurrentZoom(zoom)
- },
- })
-
- // Expose zoom controls to global store
- useEffect(() => {
- setActions({ zoomIn, zoomOut, zoomToFit })
- return () => {
- setActions({
- zoomIn: () => {},
- zoomOut: () => {},
- zoomToFit: () => {},
- })
- }
- }, [zoomIn, zoomOut, zoomToFit, setActions])
-
- // Container ref callback with resize observer
- const containerCallback = useCallback((element: HTMLDivElement | null) => {
- containerRef.current = element
- setContainerElement(element)
-
- // Cleanup previous observer
- if (resizeObserverRef.current) {
- resizeObserverRef.current.disconnect()
- resizeObserverRef.current = null
- }
-
- if (!element) return
-
- // Update initial dimensions
- const rect = element.getBoundingClientRect()
- setDimensions({ width: rect.width, height: rect.height })
-
- // Setup resize observer with debounce
- let resizeTimeout: NodeJS.Timeout | null = null
- const handleResize = (entries: ResizeObserverEntry[]) => {
- if (resizeTimeout) clearTimeout(resizeTimeout)
- resizeTimeout = setTimeout(() => {
- const entry = entries[0]
- if (entry) {
- const { width, height } = entry.contentRect
- setDimensions({ width, height })
- }
- }, GRAPH_CONSTANTS.RESIZE_DEBOUNCE_MS)
- }
-
- resizeObserverRef.current = new ResizeObserver(handleResize)
- resizeObserverRef.current.observe(element)
- }, [])
-
- // Cleanup resize observer on unmount
- useEffect(() => {
- return () => {
- if (resizeObserverRef.current) {
- resizeObserverRef.current.disconnect()
- resizeObserverRef.current = null
- }
- }
- }, [])
-
- // Empty state
- if (!nodes.length) {
- return (
- <div
- className={`flex h-full w-full items-center justify-center ${className}`}
- style={style}
- >
- <div className="text-center text-muted-foreground">
- <p>No data to visualize</p>
- </div>
- </div>
- )
- }
-
- return (
- <div
- ref={containerCallback}
- className={className}
- style={{
- width: '100%',
- height: '100%',
- position: 'relative',
- ...style,
- }}
- >
- {/* Uncomment to show LOD indicator for debugging:
- <LODIndicator zoomLevel={currentZoom} visible={process.env.NODE_ENV === 'development'} />
- */}
- </div>
- )
-}
-
-export default WebGLGraphViewer
diff --git a/flowsint-app/src/components/sketches/webgl/renderers/edge-renderer.ts b/flowsint-app/src/components/sketches/webgl/renderers/edge-renderer.ts
deleted file mode 100644
index 65215dde..00000000
--- a/flowsint-app/src/components/sketches/webgl/renderers/edge-renderer.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { Graphics } from 'pixi.js'
-import { GRAPH_CONSTANTS } from '../constants'
-import { getEdgeStyle } from '../utils/color-utils'
-import type { SimulationLink, SimulationNode } from '../types/graph.types'
-
-/**
- * Batch of edges with the same rendering style
- */
-interface EdgeBatch {
- highlighted: SimulationLink[]
- dimmed: SimulationLink[]
- default: SimulationLink[]
-}
-
-/**
- * Render all edges to a Graphics object
- * Groups edges by style for optimal performance
- *
- * @param graphics - Pixi.js Graphics object to draw on
- * @param links - Array of simulation links
- * @param highlightedLinks - Set of highlighted link keys
- * @param linkWidth - Width setting for links
- */
-export function renderEdges(
- graphics: Graphics,
- links: SimulationLink[],
- highlightedLinks: Set<string>,
- linkWidth: number
-): void {
- graphics.clear()
-
- const hasAnyHighlight = highlightedLinks.size > 0
-
- // Batch edges by rendering style
- const batches: EdgeBatch = {
- highlighted: [],
- dimmed: [],
- default: [],
- }
-
- // Categorize edges
- links.forEach((link) => {
- const source = link.source as SimulationNode
- const target = link.target as SimulationNode
-
- if (!source.x || !source.y || !target.x || !target.y) return
-
- const linkKey = `${source.id}-${target.id}`
- const isHighlighted = highlightedLinks.has(linkKey)
-
- if (isHighlighted) {
- batches.highlighted.push(link)
- } else if (hasAnyHighlight) {
- batches.dimmed.push(link)
- } else {
- batches.default.push(link)
- }
- })
-
- // Render highlighted edges
- if (batches.highlighted.length > 0) {
- const style = getEdgeStyle(true, hasAnyHighlight)
- batches.highlighted.forEach((link) => {
- const source = link.source as SimulationNode
- const target = link.target as SimulationNode
- graphics.moveTo(source.x!, source.y!)
- graphics.lineTo(target.x!, target.y!)
- })
- graphics.stroke({
- width: GRAPH_CONSTANTS.LINK_WIDTH * linkWidth * style.widthMultiplier,
- color: style.color,
- alpha: style.alpha,
- })
- }
-
- // Render dimmed edges
- if (batches.dimmed.length > 0) {
- const style = getEdgeStyle(false, true)
- batches.dimmed.forEach((link) => {
- const source = link.source as SimulationNode
- const target = link.target as SimulationNode
- graphics.moveTo(source.x!, source.y!)
- graphics.lineTo(target.x!, target.y!)
- })
- graphics.stroke({
- width: GRAPH_CONSTANTS.LINK_WIDTH * linkWidth * style.widthMultiplier,
- color: style.color,
- alpha: style.alpha,
- })
- }
-
- // Render default edges
- if (batches.default.length > 0) {
- const style = getEdgeStyle(false, false)
- batches.default.forEach((link) => {
- const source = link.source as SimulationNode
- const target = link.target as SimulationNode
- graphics.moveTo(source.x!, source.y!)
- graphics.lineTo(target.x!, target.y!)
- })
- graphics.stroke({
- width: GRAPH_CONSTANTS.LINK_WIDTH * linkWidth * style.widthMultiplier,
- color: style.color,
- alpha: style.alpha,
- })
- }
-}
-
-/**
- * Create a link key for highlighting
- *
- * @param sourceId - Source node ID
- * @param targetId - Target node ID
- * @returns Link key string
- */
-export function createLinkKey(sourceId: string, targetId: string): string {
- return `${sourceId}-${targetId}`
-}
diff --git a/flowsint-app/src/components/sketches/webgl/renderers/label-renderer.ts b/flowsint-app/src/components/sketches/webgl/renderers/label-renderer.ts
deleted file mode 100644
index ab92c633..00000000
--- a/flowsint-app/src/components/sketches/webgl/renderers/label-renderer.ts
+++ /dev/null
@@ -1,282 +0,0 @@
-import { Text, Graphics } from 'pixi.js'
-import { GRAPH_CONSTANTS } from '../constants'
-import { calculateNodeLabelFontSize } from '../utils/visibility-calculator'
-import type {
- SimulationNode,
- SimulationLink,
- EdgeLabelObjects,
- NodeLabelObjects,
-} from '../types/graph.types'
-
-/**
- * Update node label visibility and position
- * PERFORMANCE OPTIMIZED: Minimal recalculation, cached dimensions
- *
- * @param labelObjects - Node label objects (text and background)
- * @param node - Associated node
- * @param nodeSize - Size of the node
- * @param shouldShow - Whether the label (and background) should be visible
- * @param zoomLevel - Current zoom level
- * @param fontSizeSetting - Font size setting (percentage)
- * @param isHighlighted - Whether the node is highlighted
- * @param hasAnyHighlight - Whether any node is highlighted
- */
-export function updateNodeLabel(
- labelObjects: NodeLabelObjects,
- node: SimulationNode,
- nodeSize: number,
- shouldShow: boolean,
- zoomLevel: number,
- fontSizeSetting: number,
- isHighlighted: boolean,
- hasAnyHighlight: boolean
-): void {
- const { text: label, background } = labelObjects
-
- if (!node.x || !node.y) {
- label.visible = false
- background.visible = false
- return
- }
-
- if (!shouldShow) {
- label.visible = false
- background.visible = false
- return
- }
-
- // Calculate font size
- const fontSize = calculateNodeLabelFontSize(
- nodeSize,
- zoomLevel,
- fontSizeSetting
- )
-
- // Update label style
- label.style.fontSize = fontSize
- label.visible = true
-
- const labelY = node.y + nodeSize + fontSize * 0.6
- label.position.set(node.x, labelY)
-
- // Update alpha based on highlight state
- const alpha =
- hasAnyHighlight && !isHighlighted
- ? GRAPH_CONSTANTS.DIMMED_ALPHA
- : GRAPH_CONSTANTS.HIGHLIGHTED_ALPHA
-
- label.alpha = alpha
-
- // PERFORMANCE: Redraw background only when fontSize changes
- // @ts-ignore - cache last fontSize
- const lastFontSize = background._lastFontSize || 0
- const fontSizeChanged = Math.abs(fontSize - lastFontSize) > 0.5
-
- if (fontSizeChanged) {
- // Estimate text dimensions
- const textLength = label.text.length
- const estimatedCharWidth = fontSize * 0.6
- const textWidth = textLength * estimatedCharWidth
- const textHeight = fontSize
-
- const bgWidth = textWidth + GRAPH_CONSTANTS.NODE_LABEL_PADDING_X * 2
- const bgHeight = textHeight + GRAPH_CONSTANTS.NODE_LABEL_PADDING_Y * 2
-
- const bgX = -bgWidth / 2
- const bgY = -GRAPH_CONSTANTS.NODE_LABEL_PADDING_Y
-
- // Redraw background with new size
- background.clear()
- background.roundRect(
- bgX,
- bgY,
- bgWidth,
- bgHeight,
- GRAPH_CONSTANTS.NODE_LABEL_BORDER_RADIUS
- )
- background.fill({
- color: GRAPH_CONSTANTS.LABEL_BG_COLOR,
- alpha: GRAPH_CONSTANTS.NODE_LABEL_BG_ALPHA,
- })
- background.stroke({
- width: GRAPH_CONSTANTS.NODE_LABEL_BORDER_WIDTH,
- color: GRAPH_CONSTANTS.LABEL_BG_BORDER_COLOR,
- alpha: GRAPH_CONSTANTS.NODE_LABEL_BG_BORDER_ALPHA,
- })
-
- // @ts-ignore - cache fontSize
- background._lastFontSize = fontSize
- }
-
- // Update position and alpha
- background.position.set(node.x, labelY)
- background.alpha = alpha
- background.visible = true
-}
-
-/**
- * Create a node label with background
- * PERFORMANCE: Background is pre-rendered once with estimated max size
- *
- * @param labelText - Text to display
- * @returns Node label objects (text and background)
- */
-export function createNodeLabel(labelText: string): NodeLabelObjects {
- const truncated =
- labelText.length > GRAPH_CONSTANTS.MAX_LABEL_LENGTH
- ? labelText.substring(0, GRAPH_CONSTANTS.MAX_LABEL_LENGTH) + '...'
- : labelText
-
- const text = new Text({
- text: truncated,
- style: {
- fontSize: 12,
- fill: GRAPH_CONSTANTS.LABEL_COLOR,
- fontFamily: 'sans-serif',
- fontWeight: '500',
- },
- anchor: { x: 0.5, y: 0 },
- resolution: 2,
- })
-
- // Pre-create background with estimated dimensions
- // We use the text length to estimate size (avoids expensive getBounds)
- const estimatedCharWidth = 12 * 0.6 // fontSize * 0.6
- const estimatedWidth = truncated.length * estimatedCharWidth
- const estimatedHeight = 12 // fontSize
-
- const bgWidth = estimatedWidth + GRAPH_CONSTANTS.NODE_LABEL_PADDING_X * 2
- const bgHeight = estimatedHeight + GRAPH_CONSTANTS.NODE_LABEL_PADDING_Y * 2
-
- const bgX = -bgWidth / 2
- const bgY = -GRAPH_CONSTANTS.NODE_LABEL_PADDING_Y
-
- const background = new Graphics()
-
- // Draw background ONCE, never clear and redraw
- background.roundRect(
- bgX,
- bgY,
- bgWidth,
- bgHeight,
- GRAPH_CONSTANTS.NODE_LABEL_BORDER_RADIUS
- )
- background.fill({
- color: GRAPH_CONSTANTS.LABEL_BG_COLOR,
- alpha: GRAPH_CONSTANTS.NODE_LABEL_BG_ALPHA,
- })
- background.stroke({
- width: GRAPH_CONSTANTS.NODE_LABEL_BORDER_WIDTH,
- color: GRAPH_CONSTANTS.LABEL_BG_BORDER_COLOR,
- alpha: GRAPH_CONSTANTS.NODE_LABEL_BG_BORDER_ALPHA,
- })
-
- return { text, background }
-}
-
-/**
- * Update edge label position and visibility
- *
- * @param edgeLabel - Edge label objects (text and background)
- * @param link - Associated link
- * @param zoomLevel - Current zoom level
- * @param isHighlighted - Whether the edge is highlighted
- * @param hasAnyHighlight - Whether any edge is highlighted
- */
-export function updateEdgeLabel(
- edgeLabel: EdgeLabelObjects,
- link: SimulationLink,
- zoomLevel: number,
- isHighlighted: boolean,
- hasAnyHighlight: boolean
-): void {
- const source = link.source as SimulationNode
- const target = link.target as SimulationNode
-
- if (!source.x || !source.y || !target.x || !target.y) {
- edgeLabel.text.visible = false
- edgeLabel.background.visible = false
- return
- }
-
- // Calculate midpoint
- const midX = (source.x + target.x) / 2
- const midY = (source.y + target.y) / 2
-
- // Calculate rotation angle
- const dx = target.x - source.x
- const dy = target.y - source.y
- let angle = Math.atan2(dy, dx)
-
- // Keep text readable (flip if upside down)
- if (angle > Math.PI / 2 || angle < -Math.PI / 2) {
- angle += angle > 0 ? -Math.PI : Math.PI
- }
-
- // Scale to compensate for zoom
- const scale = 1 / zoomLevel
-
- // Update text
- edgeLabel.text.position.set(midX, midY)
- edgeLabel.text.rotation = angle
- edgeLabel.text.scale.set(scale, scale)
-
- // Update background
- const padding = GRAPH_CONSTANTS.EDGE_LABEL_PADDING
- const textMetrics = 10 // Fixed font size
- const estimatedTextWidth = edgeLabel.text.text.length * textMetrics * 0.5
- const bgWidth = estimatedTextWidth + padding * 2
- const bgHeight = textMetrics + padding
-
- edgeLabel.background.clear()
- edgeLabel.background.position.set(midX, midY)
- edgeLabel.background.rotation = angle
- edgeLabel.background.scale.set(scale, scale)
-
- edgeLabel.background.roundRect(
- -bgWidth / 2,
- -bgHeight / 2,
- bgWidth,
- bgHeight,
- GRAPH_CONSTANTS.EDGE_LABEL_BORDER_RADIUS
- )
- edgeLabel.background.fill({
- color: GRAPH_CONSTANTS.EDGE_LABEL_BG_COLOR,
- alpha: GRAPH_CONSTANTS.EDGE_LABEL_BG_ALPHA,
- })
-
- // Update alpha based on highlight state
- const alpha =
- hasAnyHighlight && !isHighlighted
- ? GRAPH_CONSTANTS.DIMMED_ALPHA
- : GRAPH_CONSTANTS.HIGHLIGHTED_ALPHA
-
- edgeLabel.text.alpha = alpha
- edgeLabel.background.alpha = alpha * GRAPH_CONSTANTS.EDGE_LABEL_BG_ALPHA
-
- edgeLabel.text.visible = true
- edgeLabel.background.visible = true
-}
-
-/**
- * Create edge label objects (text and background)
- *
- * @param labelText - Text to display
- * @returns Edge label objects
- */
-export function createEdgeLabel(labelText: string): EdgeLabelObjects {
- const background = new Graphics()
- const text = new Text({
- text: labelText,
- style: {
- fontSize: 10,
- fill: GRAPH_CONSTANTS.LABEL_COLOR,
- fontFamily: 'sans-serif',
- fontWeight: '400',
- },
- anchor: { x: 0.5, y: 0.5 },
- resolution: 2,
- })
-
- return { text, background }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/renderers/node-renderer.ts b/flowsint-app/src/components/sketches/webgl/renderers/node-renderer.ts
deleted file mode 100644
index 75fc24ee..00000000
--- a/flowsint-app/src/components/sketches/webgl/renderers/node-renderer.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { Graphics, Sprite } from 'pixi.js'
-import { GRAPH_CONSTANTS } from '../constants'
-import { getNodeColor } from '../utils/color-utils'
-import type { SimulationNode } from '../types/graph.types'
-
-/**
- * Render a node with its visual states (hover, highlight, selection)
- *
- * @param graphics - Pixi.js Graphics object to draw on
- * @param node - Node to render
- * @param nodeSize - Size of the node
- * @param isHovered - Whether the node is hovered
- * @param isHighlighted - Whether the node is highlighted
- * @param isSelected - Whether the node is selected
- * @param hasAnyHighlight - Whether any node is highlighted
- */
-export function renderNode(
- graphics: Graphics,
- node: SimulationNode,
- nodeSize: number,
- isHovered: boolean,
- isHighlighted: boolean,
- isSelected: boolean,
- hasAnyHighlight: boolean
-): void {
- if (!node.x || !node.y) return
-
- graphics.clear()
-
- // Draw highlight ring for selected or highlighted nodes
- if (isSelected || isHighlighted) {
- const highlightColor = isHovered
- ? GRAPH_CONSTANTS.NODE_HIGHLIGHT_HOVER
- : GRAPH_CONSTANTS.NODE_HIGHLIGHT_DEFAULT
- graphics.circle(0, 0, nodeSize * GRAPH_CONSTANTS.NODE_HIGHLIGHT_SCALE)
- graphics.fill({
- color: highlightColor,
- alpha: GRAPH_CONSTANTS.NODE_HIGHLIGHT_RING_ALPHA,
- })
- }
-
- // Get node color based on state
- const baseColorHex = parseInt(node.nodeColor.replace('#', ''), 16)
- const { color, alpha } = getNodeColor(
- baseColorHex,
- isHovered,
- isHighlighted,
- hasAnyHighlight
- )
-
- // Draw node circle
- graphics.circle(0, 0, nodeSize)
- graphics.fill({ color, alpha })
-
- // Draw selection border
- if (isSelected) {
- graphics.circle(0, 0, nodeSize)
- graphics.stroke({
- width: GRAPH_CONSTANTS.NODE_BORDER_WIDTH,
- color: 0xffffff,
- alpha: 1,
- })
- }
-
- // Update position
- graphics.position.set(node.x, node.y)
-}
-
-/**
- * Update icon sprite position and visibility
- *
- * @param sprite - Pixi.js Sprite object
- * @param node - Node associated with the sprite
- * @param nodeSize - Size of the node
- * @param isHighlighted - Whether the node is highlighted
- * @param hasAnyHighlight - Whether any node is highlighted
- */
-export function updateIconSprite(
- sprite: Sprite,
- node: SimulationNode,
- nodeSize: number,
- isHighlighted: boolean,
- hasAnyHighlight: boolean
-): void {
- if (!node.x || !node.y) return
-
- sprite.position.set(node.x, node.y)
-
- // Update icon size
- const iconSize = nodeSize * GRAPH_CONSTANTS.ICON_SIZE_MULTIPLIER
- sprite.width = iconSize
- sprite.height = iconSize
-
- // Update alpha based on highlight state
- sprite.alpha =
- hasAnyHighlight && !isHighlighted
- ? GRAPH_CONSTANTS.DIMMED_ALPHA
- : GRAPH_CONSTANTS.HIGHLIGHTED_ALPHA
-}
-
-/**
- * Calculate node size based on connection count and settings
- *
- * @param node - Node to calculate size for
- * @param nodeSizeSetting - Node size setting value (0-200)
- * @returns Calculated node size
- */
-export function calculateNodeSize(
- node: SimulationNode,
- nodeSizeSetting: number
-): number {
- return (
- Math.min(node.nodeSize + node.neighbors.length / 5, 20) *
- (nodeSizeSetting / 100 + 0.4)
- )
-}
diff --git a/flowsint-app/src/components/sketches/webgl/types/graph.types.ts b/flowsint-app/src/components/sketches/webgl/types/graph.types.ts
deleted file mode 100644
index 12b3ff3e..00000000
--- a/flowsint-app/src/components/sketches/webgl/types/graph.types.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import type { GraphNode, GraphEdge } from '@/types'
-import type { Graphics, Text, Sprite } from 'pixi.js'
-
-/**
- * Simulation node with D3-force properties
- */
-export interface SimulationNode extends GraphNode {
- x?: number
- y?: number
- vx?: number
- vy?: number
- fx?: number | null
- fy?: number | null
- neighbors: SimulationNode[]
- links: SimulationLink[]
- nodeColor: string
- nodeSize: number
-}
-
-/**
- * Simulation link for D3-force
- */
-export interface SimulationLink {
- source: string | SimulationNode
- target: string | SimulationNode
-}
-
-/**
- * Edge label rendering objects
- */
-export interface EdgeLabelObjects {
- text: Text
- background: Graphics
-}
-
-/**
- * Node rendering objects
- */
-export interface NodeRenderObjects {
- graphics: Graphics
- label?: Text
- labelBackground?: Graphics
- icon?: Sprite
-}
-
-/**
- * Node label rendering objects
- */
-export interface NodeLabelObjects {
- text: Text
- background: Graphics
-}
-
-/**
- * Highlight state for nodes and links
- */
-export interface HighlightState {
- nodes: Set<string>
- links: Set<string>
-}
-
-/**
- * Enricher state for zoom/pan
- */
-export interface TransformState {
- k: number // scale
- x: number // translateX
- y: number // translateY
-}
-
-/**
- * Visibility settings
- */
-export interface VisibilitySettings {
- showIcons: boolean
- showLabels: boolean
- visibleNodeLabels: Set<string>
-}
-
-/**
- * Force settings from store
- */
-export interface ForceSettings {
- nodeSize: { value: number }
- linkWidth: { value: number }
- nodeLabelFontSize: { value: number }
-}
-
-/**
- * Graph renderer state
- */
-export interface GraphRendererState {
- hoveredNodeId: string | null
- isDragging: boolean
- highlightState: HighlightState
- transform: TransformState
- visibilitySettings: VisibilitySettings
-}
-
-/**
- * Layout mode for graph
- */
-export type LayoutMode = 'none' | 'force' | 'dagre'
-
-/**
- * Props for WebGL Graph Viewer
- */
-export interface WebGLGraphViewerProps {
- nodes: GraphNode[]
- edges: GraphEdge[]
- className?: string
- style?: React.CSSProperties
- onNodeClick?: (node: GraphNode, event: MouseEvent) => void
- onNodeRightClick?: (node: GraphNode, event: MouseEvent) => void
- onBackgroundClick?: () => void
- showIcons?: boolean
- showLabels?: boolean
- layoutMode?: LayoutMode
-}
-
-/**
- * Graph controls actions
- */
-export interface GraphControlActions {
- zoomIn: () => void
- zoomOut: () => void
- zoomToFit: () => void
-}
diff --git a/flowsint-app/src/components/sketches/webgl/utils/color-utils.ts b/flowsint-app/src/components/sketches/webgl/utils/color-utils.ts
deleted file mode 100644
index 77b542e7..00000000
--- a/flowsint-app/src/components/sketches/webgl/utils/color-utils.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { GRAPH_CONSTANTS } from '../constants'
-
-/**
- * Convert CSS color string to Pixi.js hexadecimal color
- *
- * @param cssColor - CSS color string (e.g., "#FF5733")
- * @returns Hexadecimal color number
- */
-export function cssToPixiColor(cssColor: string): number {
- return parseInt(cssColor.replace('#', ''), 16)
-}
-
-/**
- * Convert hexadecimal color to CSS color string
- *
- * @param hexColor - Hexadecimal color number
- * @returns CSS color string
- */
-export function pixiToCssColor(hexColor: number): string {
- return `#${hexColor.toString(16).padStart(6, '0')}`
-}
-
-/**
- * Get node color based on state (hover, highlight, default)
- *
- * @param baseColor - Base color of the node (hex number)
- * @param isHovered - Whether the node is hovered
- * @param isHighlighted - Whether the node is highlighted
- * @param hasAnyHighlight - Whether any node is highlighted
- * @returns Color object with color and alpha
- */
-export function getNodeColor(
- baseColor: number,
- isHovered: boolean,
- isHighlighted: boolean,
- hasAnyHighlight: boolean
-): { color: number; alpha: number } {
- if (isHovered) {
- return {
- color: GRAPH_CONSTANTS.HOVER_COLOR,
- alpha: GRAPH_CONSTANTS.HIGHLIGHTED_ALPHA,
- }
- }
-
- if (hasAnyHighlight) {
- if (isHighlighted) {
- return {
- color: baseColor,
- alpha: GRAPH_CONSTANTS.HIGHLIGHTED_ALPHA,
- }
- } else {
- return {
- color: baseColor,
- alpha: GRAPH_CONSTANTS.DIMMED_ALPHA,
- }
- }
- }
-
- return {
- color: baseColor,
- alpha: GRAPH_CONSTANTS.HIGHLIGHTED_ALPHA,
- }
-}
-
-/**
- * Get edge color and alpha based on highlight state
- *
- * @param isHighlighted - Whether the edge is highlighted
- * @param hasAnyHighlight - Whether any edge/node is highlighted
- * @returns Style object with color, alpha, and width multiplier
- */
-export function getEdgeStyle(
- isHighlighted: boolean,
- hasAnyHighlight: boolean
-): { color: number; alpha: number; widthMultiplier: number } {
- if (isHighlighted) {
- return {
- color: GRAPH_CONSTANTS.HOVER_COLOR,
- alpha: GRAPH_CONSTANTS.LINK_HIGHLIGHTED_ALPHA,
- widthMultiplier: 1 / 3,
- }
- }
-
- if (hasAnyHighlight) {
- return {
- color: GRAPH_CONSTANTS.LINK_DIMMED_COLOR,
- alpha: GRAPH_CONSTANTS.LINK_DIMMED_ALPHA,
- widthMultiplier: 1 / 5,
- }
- }
-
- return {
- color: GRAPH_CONSTANTS.LINK_DEFAULT_COLOR,
- alpha: GRAPH_CONSTANTS.LINK_DEFAULT_ALPHA,
- widthMultiplier: 1 / 5,
- }
-}
diff --git a/flowsint-app/src/components/sketches/webgl/utils/label-decluttering.ts b/flowsint-app/src/components/sketches/webgl/utils/label-decluttering.ts
deleted file mode 100644
index ce4833c0..00000000
--- a/flowsint-app/src/components/sketches/webgl/utils/label-decluttering.ts
+++ /dev/null
@@ -1,358 +0,0 @@
-import { GRAPH_CONSTANTS } from '../constants'
-import { calculateNodeLabelFontSize } from './visibility-calculator'
-import type { SimulationNode } from '../types/graph.types'
-
-/**
- * Bounding box for a label in screen space
- */
-export interface LabelBoundingBox {
- nodeId: string
- x: number // Center X
- y: number // Center Y (top of label)
- width: number
- height: number
- priority: number // Higher = more important
-}
-
-/**
- * Calculate the bounding box for a node label
- *
- * @param node - Simulation node
- * @param nodeSize - Visual size of the node
- * @param zoomLevel - Current zoom level
- * @param fontSizeSetting - Font size setting percentage
- * @param viewportWidth - Viewport width for spatial priority
- * @param viewportHeight - Viewport height for spatial priority
- * @param cameraX - Camera X position (for viewport centering)
- * @param cameraY - Camera Y position (for viewport centering)
- * @returns Bounding box or null if node has no position
- */
-export function calculateLabelBoundingBox(
- node: SimulationNode,
- nodeSize: number,
- zoomLevel: number,
- fontSizeSetting: number,
- viewportWidth: number,
- viewportHeight: number,
- cameraX: number = 0,
- cameraY: number = 0
-): LabelBoundingBox | null {
- if (!node.x || !node.y) return null
-
- const fontSize = calculateNodeLabelFontSize(nodeSize, zoomLevel, fontSizeSetting)
- const labelText = node.data?.label || node.id
- const truncated =
- labelText.length > GRAPH_CONSTANTS.MAX_LABEL_LENGTH
- ? labelText.substring(0, GRAPH_CONSTANTS.MAX_LABEL_LENGTH) + '...'
- : labelText
-
- // Estimate text dimensions (same as label-renderer.ts)
- const textLength = truncated.length
- const estimatedCharWidth = fontSize * 0.6
- const textWidth = textLength * estimatedCharWidth
- const textHeight = fontSize
-
- const bgWidth = textWidth + GRAPH_CONSTANTS.NODE_LABEL_PADDING_X * 2
- const bgHeight = textHeight + GRAPH_CONSTANTS.NODE_LABEL_PADDING_Y * 2
-
- // Label position (below the node)
- const labelY = node.y + nodeSize + fontSize * 0.6
-
- // Calculate priority based on multiple factors
- const priority = calculateNodePriority(
- node,
- node.x,
- node.y,
- viewportWidth,
- viewportHeight,
- cameraX,
- cameraY
- )
-
- return {
- nodeId: node.id,
- x: node.x,
- y: labelY,
- width: bgWidth,
- height: bgHeight,
- priority,
- }
-}
-
-/**
- * Calculate node priority for label selection
- * Combines multiple factors:
- * - Connection count (importance)
- * - Distance from viewport center (spatial relevance)
- * - Node degree centrality
- *
- * @returns Priority score (higher = more important)
- */
-function calculateNodePriority(
- node: SimulationNode,
- nodeX: number,
- nodeY: number,
- viewportWidth: number,
- viewportHeight: number,
- cameraX: number,
- cameraY: number
-): number {
- // Factor 1: Connection count (normalized 0-1)
- const connectionScore = Math.min(node.neighbors.length / 20, 1)
-
- // Factor 2: Distance from viewport center (0-1, closer = higher)
- const viewportCenterX = cameraX + viewportWidth / 2
- const viewportCenterY = cameraY + viewportHeight / 2
- const dx = nodeX - viewportCenterX
- const dy = nodeY - viewportCenterY
- const distanceFromCenter = Math.sqrt(dx * dx + dy * dy)
- const maxDistance = Math.sqrt(
- (viewportWidth / 2) ** 2 + (viewportHeight / 2) ** 2
- )
- const centerScore = Math.max(0, 1 - distanceFromCenter / maxDistance)
-
- // Weighted combination (connections more important than position)
- return connectionScore * 0.7 + centerScore * 0.3
-}
-
-/**
- * Check if two bounding boxes overlap
- *
- * @param a - First bounding box
- * @param b - Second bounding box
- * @returns True if boxes overlap
- */
-export function boundingBoxesOverlap(
- a: LabelBoundingBox,
- b: LabelBoundingBox
-): boolean {
- // Add small margin to prevent labels from being too close
- const margin = 4
-
- const aLeft = a.x - a.width / 2 - margin
- const aRight = a.x + a.width / 2 + margin
- const aTop = a.y - margin
- const aBottom = a.y + a.height + margin
-
- const bLeft = b.x - b.width / 2 - margin
- const bRight = b.x + b.width / 2 + margin
- const bTop = b.y - margin
- const bBottom = b.y + b.height + margin
-
- // Check for overlap
- return !(aRight < bLeft || aLeft > bRight || aBottom < bTop || aTop > bBottom)
-}
-
-/**
- * Greedy label selection algorithm with collision detection
- * Selects labels in priority order, skipping those that collide
- *
- * @param nodes - All simulation nodes
- * @param nodeSize - Base node size
- * @param zoomLevel - Current zoom level
- * @param fontSizeSetting - Font size setting percentage
- * @param viewportWidth - Viewport width
- * @param viewportHeight - Viewport height
- * @param cameraX - Camera X position
- * @param cameraY - Camera Y position
- * @param selectedNodeIds - Set of selected node IDs (always show)
- * @param highlightedNodeIds - Set of highlighted node IDs (always show)
- * @returns Set of node IDs whose labels should be visible
- */
-export function selectLabelsWithDecluttering(
- nodes: SimulationNode[],
- nodeSize: number,
- zoomLevel: number,
- fontSizeSetting: number,
- viewportWidth: number,
- viewportHeight: number,
- cameraX: number,
- cameraY: number,
- selectedNodeIds: Set<string>,
- highlightedNodeIds: Set<string>
-): Set<string> {
- const visibleSet = new Set<string>()
-
- // Step 1: Calculate bounding boxes for all nodes
- const boundingBoxes: LabelBoundingBox[] = []
- for (const node of nodes) {
- const bbox = calculateLabelBoundingBox(
- node,
- nodeSize,
- zoomLevel,
- fontSizeSetting,
- viewportWidth,
- viewportHeight,
- cameraX,
- cameraY
- )
- if (bbox) {
- boundingBoxes.push(bbox)
- }
- }
-
- // Step 2: Sort by priority (highest first)
- boundingBoxes.sort((a, b) => b.priority - a.priority)
-
- // Step 3: Always include selected and highlighted nodes first
- const selectedBboxes: LabelBoundingBox[] = []
- const highlightedBboxes: LabelBoundingBox[] = []
- const regularBboxes: LabelBoundingBox[] = []
-
- for (const bbox of boundingBoxes) {
- if (selectedNodeIds.has(bbox.nodeId)) {
- selectedBboxes.push(bbox)
- visibleSet.add(bbox.nodeId)
- } else if (highlightedNodeIds.has(bbox.nodeId)) {
- highlightedBboxes.push(bbox)
- visibleSet.add(bbox.nodeId)
- } else {
- regularBboxes.push(bbox)
- }
- }
-
- // Step 4: Greedy selection - add labels that don't collide
- const placedBboxes = [...selectedBboxes, ...highlightedBboxes]
-
- for (const candidate of regularBboxes) {
- // Check if this label collides with any already placed label
- let hasCollision = false
- for (const placed of placedBboxes) {
- if (boundingBoxesOverlap(candidate, placed)) {
- hasCollision = true
- break
- }
- }
-
- if (!hasCollision) {
- placedBboxes.push(candidate)
- visibleSet.add(candidate.nodeId)
- }
- }
-
- return visibleSet
-}
-
-/**
- * Fast label selection with spatial hashing for large graphs
- * Uses a simplified collision detection for better performance
- *
- * @param nodes - All simulation nodes
- * @param nodeSize - Base node size
- * @param zoomLevel - Current zoom level
- * @param fontSizeSetting - Font size setting percentage
- * @param viewportWidth - Viewport width
- * @param viewportHeight - Viewport height
- * @param cameraX - Camera X position
- * @param cameraY - Camera Y position
- * @param selectedNodeIds - Set of selected node IDs (always show)
- * @param highlightedNodeIds - Set of highlighted node IDs (always show)
- * @param maxLabels - Maximum number of labels to show (performance limit)
- * @returns Set of node IDs whose labels should be visible
- */
-export function selectLabelsWithDeclutteringFast(
- nodes: SimulationNode[],
- nodeSize: number,
- zoomLevel: number,
- fontSizeSetting: number,
- viewportWidth: number,
- viewportHeight: number,
- cameraX: number,
- cameraY: number,
- selectedNodeIds: Set<string>,
- highlightedNodeIds: Set<string>,
- maxLabels: number = 200
-): Set<string> {
- // For small graphs, use the accurate algorithm
- if (nodes.length < 500) {
- return selectLabelsWithDecluttering(
- nodes,
- nodeSize,
- zoomLevel,
- fontSizeSetting,
- viewportWidth,
- viewportHeight,
- cameraX,
- cameraY,
- selectedNodeIds,
- highlightedNodeIds
- )
- }
-
- // For large graphs, use spatial grid for faster collision detection
- const visibleSet = new Set<string>()
- const gridSize = 100 // Grid cell size in pixels
- const occupiedCells = new Set<string>()
-
- const getCellKey = (x: number, y: number): string => {
- const cellX = Math.floor(x / gridSize)
- const cellY = Math.floor(y / gridSize)
- return `${cellX},${cellY}`
- }
-
- // Calculate bounding boxes
- const boundingBoxes: LabelBoundingBox[] = []
- for (const node of nodes) {
- const bbox = calculateLabelBoundingBox(
- node,
- nodeSize,
- zoomLevel,
- fontSizeSetting,
- viewportWidth,
- viewportHeight,
- cameraX,
- cameraY
- )
- if (bbox) {
- boundingBoxes.push(bbox)
- }
- }
-
- // Sort by priority
- boundingBoxes.sort((a, b) => b.priority - a.priority)
-
- // Always add selected and highlighted first
- for (const bbox of boundingBoxes) {
- if (selectedNodeIds.has(bbox.nodeId) || highlightedNodeIds.has(bbox.nodeId)) {
- visibleSet.add(bbox.nodeId)
- const cellKey = getCellKey(bbox.x, bbox.y)
- occupiedCells.add(cellKey)
-
- // Also mark adjacent cells as occupied
- const cellX = Math.floor(bbox.x / gridSize)
- const cellY = Math.floor(bbox.y / gridSize)
- for (let dx = -1; dx <= 1; dx++) {
- for (let dy = -1; dy <= 1; dy++) {
- occupiedCells.add(`${cellX + dx},${cellY + dy}`)
- }
- }
-
- if (visibleSet.size >= maxLabels) break
- }
- }
-
- // Add regular labels
- for (const bbox of boundingBoxes) {
- if (visibleSet.size >= maxLabels) break
- if (selectedNodeIds.has(bbox.nodeId) || highlightedNodeIds.has(bbox.nodeId)) {
- continue // Already added
- }
-
- const cellKey = getCellKey(bbox.x, bbox.y)
- if (!occupiedCells.has(cellKey)) {
- visibleSet.add(bbox.nodeId)
- occupiedCells.add(cellKey)
-
- // Mark adjacent cells as occupied
- const cellX = Math.floor(bbox.x / gridSize)
- const cellY = Math.floor(bbox.y / gridSize)
- for (let dx = -1; dx <= 1; dx++) {
- for (let dy = -1; dy <= 1; dy++) {
- occupiedCells.add(`${cellX + dx},${cellY + dy}`)
- }
- }
- }
- }
-
- return visibleSet
-}
diff --git a/flowsint-app/src/components/sketches/webgl/utils/texture-cache.ts b/flowsint-app/src/components/sketches/webgl/utils/texture-cache.ts
deleted file mode 100644
index 57ba5528..00000000
--- a/flowsint-app/src/components/sketches/webgl/utils/texture-cache.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { Texture, Assets } from 'pixi.js'
-import type { ItemType } from '@/stores/node-display-settings'
-
-/**
- * Texture cache for icons
- * Manages loading and caching of SVG icon textures for optimal performance
- */
-class TextureCache {
- private cache = new Map<string, Texture>()
- private loadingPromises = new Map<string, Promise<Texture>>()
-
- /**
- * Preload an icon texture
- * @param iconType - The type of icon to load
- * @returns Promise resolving to the loaded texture
- */
- async preload(iconType: ItemType): Promise<Texture> {
- const cacheKey = iconType
-
- // Return cached texture if available
- if (this.cache.has(cacheKey)) {
- return Promise.resolve(this.cache.get(cacheKey)!)
- }
-
- // Return existing promise if already loading
- if (this.loadingPromises.has(cacheKey)) {
- return this.loadingPromises.get(cacheKey)!
- }
-
- // Load the texture
- const promise = Assets.load(`/icons/${iconType}.svg`)
- .then((texture) => {
- this.cache.set(cacheKey, texture)
- this.loadingPromises.delete(cacheKey)
- return texture
- })
- .catch((error) => {
- this.loadingPromises.delete(cacheKey)
- console.warn(`Failed to load icon: ${iconType}`, error)
- throw new Error(`Failed to load icon: ${iconType}`)
- })
-
- this.loadingPromises.set(cacheKey, promise)
- return promise
- }
-
- /**
- * Get a texture from cache (synchronous)
- * @param iconType - The type of icon
- * @returns The cached texture or undefined
- */
- get(iconType: ItemType): Texture | undefined {
- return this.cache.get(iconType)
- }
-
- /**
- * Check if a texture is cached
- * @param iconType - The type of icon
- * @returns True if the texture is cached
- */
- has(iconType: ItemType): boolean {
- return this.cache.has(iconType)
- }
-
- /**
- * Preload multiple textures in parallel
- * @param iconTypes - Array of icon types to load
- * @returns Promise resolving when all textures are loaded
- */
- async preloadBatch(iconTypes: ItemType[]): Promise<void> {
- const uniqueTypes = Array.from(new Set(iconTypes))
- await Promise.all(
- uniqueTypes.map((type) => this.preload(type).catch(() => null))
- )
- }
-
- /**
- * Clear the cache (useful for memory management)
- */
- clear(): void {
- this.cache.clear()
- this.loadingPromises.clear()
- }
-
- /**
- * Get cache statistics
- * @returns Object with cache size and loading count
- */
- getStats(): { cached: number; loading: number } {
- return {
- cached: this.cache.size,
- loading: this.loadingPromises.size,
- }
- }
-}
-
-// Export singleton instance
-export const textureCache = new TextureCache()
diff --git a/flowsint-app/src/components/sketches/webgl/utils/visibility-calculator.ts b/flowsint-app/src/components/sketches/webgl/utils/visibility-calculator.ts
deleted file mode 100644
index 7951c03c..00000000
--- a/flowsint-app/src/components/sketches/webgl/utils/visibility-calculator.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { GRAPH_CONSTANTS } from '../constants'
-import type { SimulationNode } from '../types/graph.types'
-
-/**
- * Calculate which labels should be visible based on zoom level
- * Uses progressive disclosure: more labels appear as user zooms in
- *
- * @param nodes - Array of simulation nodes
- * @param zoomLevel - Current zoom level (scale factor)
- * @returns Set of node IDs whose labels should be visible
- */
-export function calculateVisibleLabels(
- nodes: SimulationNode[],
- zoomLevel: number
-): Set<string> {
- const totalNodes = nodes.length
- if (totalNodes === 0) return new Set<string>()
-
- // Clamp zoom level to valid range
- const clampedZoom = Math.max(
- GRAPH_CONSTANTS.MIN_ZOOM,
- Math.min(GRAPH_CONSTANTS.MAX_ZOOM, zoomLevel)
- )
-
- // Calculate zoom ratio (0 to 1)
- const zoomRatio =
- (clampedZoom - GRAPH_CONSTANTS.MIN_ZOOM) /
- (GRAPH_CONSTANTS.MAX_ZOOM - GRAPH_CONSTANTS.MIN_ZOOM)
-
- // Calculate maximum labels to show at this zoom level
- const maxLabelsAtZoom = Math.floor(
- GRAPH_CONSTANTS.MIN_VISIBLE_LABELS +
- zoomRatio *
- Math.min(
- totalNodes * 0.5,
- GRAPH_CONSTANTS.MAX_VISIBLE_LABELS_PER_ZOOM * clampedZoom
- )
- )
-
- // Create weight map (nodes sorted by connection count)
- const weightedNodes = nodes
- .map((node) => ({
- id: node.id,
- weight: node.neighbors.length,
- }))
- .sort((a, b) => b.weight - a.weight)
-
- // Select top N nodes based on weight
- const visibleSet = new Set<string>()
- for (let i = 0; i < Math.min(maxLabelsAtZoom, weightedNodes.length); i++) {
- visibleSet.add(weightedNodes[i].id)
- }
-
- return visibleSet
-}
-
-/**
- * Check if zoom level is sufficient to show edge labels
- *
- * @param zoomLevel - Current zoom level
- * @returns True if edge labels should be visible
- */
-export function shouldShowEdgeLabels(zoomLevel: number): boolean {
- return zoomLevel >= GRAPH_CONSTANTS.LOD_EDGE_LABEL_MIN_ZOOM
-}
-
-/**
- * Check if zoom level is sufficient to show node icons
- *
- * @param zoomLevel - Current zoom level
- * @returns True if node icons should be visible
- */
-export function shouldShowNodeIcons(zoomLevel: number): boolean {
- return zoomLevel >= GRAPH_CONSTANTS.LOD_ICON_MIN_ZOOM
-}
-
-/**
- * Check if zoom level is sufficient to show node labels
- *
- * @param zoomLevel - Current zoom level
- * @returns True if node labels should be visible
- */
-export function shouldShowNodeLabels(zoomLevel: number): boolean {
- return zoomLevel >= GRAPH_CONSTANTS.LOD_NODE_LABEL_MIN_ZOOM
-}
-
-/**
- * Check if zoom level is in high detail mode
- * In high detail mode, all features are shown with maximum quality
- *
- * @param zoomLevel - Current zoom level
- * @returns True if in high detail mode
- */
-export function isHighDetailMode(zoomLevel: number): boolean {
- return zoomLevel >= GRAPH_CONSTANTS.LOD_HIGH_DETAIL_ZOOM
-}
-
-/**
- * Get the current Level of Detail based on zoom level
- * Returns a string indicating the current LOD level
- *
- * @param zoomLevel - Current zoom level
- * @returns LOD level: 'minimal', 'low', 'medium', 'high'
- */
-export function getLODLevel(zoomLevel: number): 'minimal' | 'low' | 'medium' | 'high' {
- if (zoomLevel >= GRAPH_CONSTANTS.LOD_HIGH_DETAIL_ZOOM) {
- return 'high' // All features visible
- } else if (zoomLevel >= GRAPH_CONSTANTS.LOD_EDGE_LABEL_MIN_ZOOM) {
- return 'medium' // Nodes, icons, node labels, and edge labels
- } else if (zoomLevel >= GRAPH_CONSTANTS.LOD_ICON_MIN_ZOOM) {
- return 'low' // Nodes, icons, and some node labels
- } else {
- return 'minimal' // Only nodes and edges
- }
-}
-
-/**
- * Calculate font size for node labels based on node size and zoom
- *
- * @param nodeSize - Size of the node
- * @param zoomLevel - Current zoom level
- * @param fontSizeSetting - Font size setting (percentage, default 50)
- * @returns Calculated font size
- */
-export function calculateNodeLabelFontSize(
- nodeSize: number,
- zoomLevel: number,
- fontSizeSetting: number = 50
-): number {
- const baseFontSize = Math.max(
- GRAPH_CONSTANTS.MIN_FONT_SIZE,
- (GRAPH_CONSTANTS.NODE_FONT_SIZE * (nodeSize / 2)) / zoomLevel + 2
- )
- return baseFontSize * (fontSizeSetting / 100)
-}
diff --git a/flowsint-app/src/stores/graph-controls-store.ts b/flowsint-app/src/stores/graph-controls-store.ts
index 88aaa514..d7d28265 100644
--- a/flowsint-app/src/stores/graph-controls-store.ts
+++ b/flowsint-app/src/stores/graph-controls-store.ts
@@ -24,6 +24,7 @@ type GraphControlsStore = {
setView: (view: 'graph' | 'table' | 'map' | 'relationships') => void
setIsSelectorModeActive: (active: boolean) => void
setSelectionMode: (mode: SelectionMode) => void
+ exportToPNG: () => Promise<void>
}
export const useGraphControls = create<GraphControlsStore>()(
@@ -46,7 +47,8 @@ export const useGraphControls = create<GraphControlsStore>()(
setCurrentLayoutType: (layoutType) => set({ currentLayoutType: layoutType }),
setView: (view) => set({ view }),
setIsSelectorModeActive: (active) => set({ isSelectorModeActive: active }),
- setSelectionMode: (mode) => set({ selectionMode: mode })
+ setSelectionMode: (mode) => set({ selectionMode: mode }),
+ exportToPNG: async () => { }
}),
{
name: 'graph-controls-storage',