Skip to content

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

feat(app): save nodes positions

dextmorgn877f52bca171
diff --git a/flowsint-app/src/components/graphs/graph-main.tsx b/flowsint-app/src/components/graphs/graph-main.tsx
index 5797c467..893bc663 100644
--- a/flowsint-app/src/components/graphs/graph-main.tsx
+++ b/flowsint-app/src/components/graphs/graph-main.tsx
@@ -3,7 +3,6 @@ import React, { useRef, useCallback } from 'react'
// import GraphViewer from './graph-viewer'
// import WebGLGraphViewer from './webgl'
import ContextMenu from './context-menu'
-import { useGraphControls } from '@/stores/graph-controls-store'
import GraphViewer from './graph-viewer'
import { useParams } from '@tanstack/react-router'
@@ -13,7 +12,6 @@ const GraphMain = () => {
const filteredEdges = useGraphStore((s) => s.filteredEdges)
const toggleNodeSelection = useGraphStore((s) => s.toggleNodeSelection)
const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)
- const layoutMode = useGraphControls((s) => s.layoutMode)
const graphRef = useRef<any>(null)
const containerRef = useRef<HTMLDivElement>(null)
diff --git a/flowsint-app/src/components/graphs/graph-viewer.tsx b/flowsint-app/src/components/graphs/graph-viewer.tsx
index 63145f5c..1f65c33f 100644
--- a/flowsint-app/src/components/graphs/graph-viewer.tsx
+++ b/flowsint-app/src/components/graphs/graph-viewer.tsx
@@ -10,9 +10,7 @@ import { useTheme } from '@/components/theme-provider'
import { Info, Plus, Share2, Type, Upload } from 'lucide-react'
import Lasso from './lasso'
import { GraphNode, GraphEdge } from '@/types'
-import { sketchService } from '@/api/sketch-service'
-import { useDebounce } from '@/hooks/use-debounce'
-import { toast } from 'sonner'
+import { useSaveNodePositions } from '@/hooks/use-save-node-positions'
function truncateText(text: string, limit: number = 16) {
if (text.length <= limit) return text
@@ -165,9 +163,9 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
const zoomRef = useRef({ k: 1, x: 0, y: 0 })
const hoverFrameRef = useRef<number | null>(null)
- // Node position tracking for saving
- const [changedNodePositions, setChangedNodePositions] = useState<Map<string, { x: number; y: number }>>(new Map())
- const [isStabilizing, setIsStabilizing] = useState(true)
+ // Use the dedicated hook for saving node positions
+ const { saveAllNodePositions, markAsStabilized, markAsStabilizing } = useSaveNodePositions(sketchId)
+
// The ref for the node weighlist.
const labelRenderingCompound = useRef<LabelRenderingCompound>({
weightList: new Map(),
@@ -194,9 +192,6 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
const setOpenMainDialog = useGraphStore((state) => state.setOpenMainDialog)
const setImportModalOpen = useGraphSettingsStore((s) => s.setImportModalOpen)
- // Debounced value to trigger save
- const debouncedChangedPositions = useDebounce(changedNodePositions, 1000)
-
const shouldUseSimpleRendering = useMemo(
() => nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || currentZoom < 1.5,
[nodes.length, currentZoom]
@@ -428,7 +423,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
// Apply the calculated positions to the graph nodes
layoutedNodes.forEach((layoutedNode: any) => {
- const graphNode = graphData.nodes.find((n: any) => n.id === layoutedNode.id)
+ const graphNode = graphData.nodes.find((n: any) => n.id === layoutedNode.id) as any
if (graphNode && layoutedNode.x !== undefined && layoutedNode.y !== undefined) {
graphNode.x = layoutedNode.x
graphNode.y = layoutedNode.y
@@ -436,6 +431,9 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
graphNode.fy = layoutedNode.y
}
})
+
+ // Save all node positions immediately after hierarchy layout (force save)
+ saveAllNodePositions(graphData.nodes, true)
} else {
// Force layout: reheat the simulation to recalculate positions
if (typeof graphRef.current.d3ReheatSimulation !== 'function') {
@@ -443,7 +441,19 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
throw new Error('d3ReheatSimulation method is not available')
}
+ // Mark as stabilizing to prevent saving during force simulation
+ markAsStabilizing()
graphRef.current.d3ReheatSimulation()
+
+ // For force layout, save positions after simulation stabilizes
+ const warmupTicks = forceSettings?.warmupTicks?.value ?? 0
+ const stabilizationTime = warmupTicks * 10 + 1500 // Wait for simulation to stabilize
+
+ setTimeout(() => {
+ markAsStabilized()
+ // Force save all positions after stabilization
+ saveAllNodePositions(graphData.nodes, true)
+ }, stabilizationTime)
}
// Zoom to fit after a delay to see the new layout
@@ -452,7 +462,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
graphRef.current.zoomToFit(400)
}
}, 500)
- }, [graphData])
+ }, [graphData, sketchId, forceSettings, saveAllNodePositions, markAsStabilized, markAsStabilizing])
// Optimized graph initialization callback
const initializeGraph = useCallback(
@@ -547,20 +557,17 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
setImportModalOpen(true)
}, [setImportModalOpen])
- // Handle node drag end with position tracking
+ // Handle node drag end - save ALL node positions
const handleNodeDragEnd = useCallback((node: any) => {
node.fx = node.x
node.fy = node.y
- // Track position changes for saving (only if not stabilizing and sketchId exists)
- if (!isStabilizing && sketchId && node.x !== undefined && node.y !== undefined) {
- setChangedNodePositions(prev => {
- const newMap = new Map(prev)
- newMap.set(node.id, { x: node.x!, y: node.y! })
- return newMap
- })
+ // Save positions of ALL nodes when one node is dragged
+ // In a force-directed graph, moving one node can affect others
+ if (graphData?.nodes) {
+ saveAllNodePositions(graphData.nodes)
}
- }, [isStabilizing, sketchId])
+ }, [graphData, saveAllNodePositions])
// Throttled hover handlers using RAF for better performance
@@ -994,48 +1001,22 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
}
}, [])
- // Mark graph as stabilized after warmupTicks
+ // Mark graph as stabilizing on initial load
useEffect(() => {
const warmupTicks = forceSettings?.warmupTicks?.value ?? 0
if (warmupTicks > 0) {
- setIsStabilizing(true)
+ markAsStabilizing()
// Wait for warmup + a small buffer to ensure graph has stabilized
const timeout = setTimeout(() => {
- setIsStabilizing(false)
+ markAsStabilized()
}, warmupTicks * 10 + 500) // Approximate time for warmup ticks
return () => clearTimeout(timeout)
} else {
- setIsStabilizing(false)
+ // No warmup, mark as stabilized immediately
+ markAsStabilized()
}
- }, [forceSettings?.warmupTicks?.value, nodes.length, edges.length])
-
- // Save positions when debounced value changes
- useEffect(() => {
- if (isStabilizing || !sketchId || debouncedChangedPositions.size === 0) {
- return
- }
-
- const positions = Array.from(debouncedChangedPositions.entries()).map(([nodeId, pos]) => ({
- nodeId,
- x: pos.x,
- y: pos.y
- }))
-
- const savePromise = sketchService.updateNodePositions(sketchId, positions)
-
- toast.promise(savePromise, {
- loading: `Saving positions for ${positions.length} node${positions.length > 1 ? 's' : ''}...`,
- success: (result) => {
- setChangedNodePositions(new Map())
- return `Successfully saved ${result.count || positions.length} node position${positions.length > 1 ? 's' : ''}`
- },
- error: (error) => {
- console.error('[Graph] Failed to save node positions:', error)
- return 'Failed to save node positions. Please try again.'
- }
- })
- }, [debouncedChangedPositions, isStabilizing, sketchId])
+ }, [forceSettings?.warmupTicks?.value, nodes.length, edges.length, markAsStabilized, markAsStabilizing])
// Empty state
if (!nodes.length) {
diff --git a/flowsint-app/src/components/graphs/index.tsx b/flowsint-app/src/components/graphs/index.tsx
index 4c3ba0f4..82ce788e 100644
--- a/flowsint-app/src/components/graphs/index.tsx
+++ b/flowsint-app/src/components/graphs/index.tsx
@@ -133,7 +133,7 @@ const GraphPanel = ({ graphData, isLoading }: GraphPanelProps) => {
}
>
<>
- {['force', 'hierarchy'].includes(view) && <GraphMain />}
+ {view === 'graph' && <GraphMain />}
{view === 'table' && <NodesTable />}
{view === 'map' && <MapPanel />}
{view === 'relationships' && <RelationshipsTable />}
diff --git a/flowsint-app/src/components/graphs/save-status-indicator.tsx b/flowsint-app/src/components/graphs/save-status-indicator.tsx
new file mode 100644
index 00000000..91609d60
--- /dev/null
+++ b/flowsint-app/src/components/graphs/save-status-indicator.tsx
@@ -0,0 +1,72 @@
+import { memo } from 'react'
+import { Cloud, CloudOff, Loader2, Check, AlertCircle } from 'lucide-react'
+import { SaveStatus } from '@/hooks/use-save-node-positions'
+import { cn } from '@/lib/utils'
+
+interface SaveStatusIndicatorProps {
+ status: SaveStatus
+}
+
+export const SaveStatusIndicator = memo(({ status }: SaveStatusIndicatorProps) => {
+ const getStatusConfig = () => {
+ switch (status) {
+ case 'idle':
+ return {
+ icon: Cloud,
+ text: 'All changes saved',
+ className: 'text-muted-foreground/60 bg-muted/30 border-muted'
+ }
+ case 'pending':
+ return {
+ icon: Cloud,
+ text: 'Pending...',
+ className: 'text-muted-foreground bg-muted/50 border-muted'
+ }
+ case 'saving':
+ return {
+ icon: Loader2,
+ text: 'Saving...',
+ className: 'text-blue-600 bg-blue-50 dark:bg-blue-950/30 dark:text-blue-400 border-blue-200 dark:border-blue-800',
+ iconClassName: 'animate-spin'
+ }
+ case 'saved':
+ return {
+ icon: Check,
+ text: 'Saved',
+ className: 'text-green-600 bg-green-50 dark:bg-green-950/30 dark:text-green-400 border-green-200 dark:border-green-800'
+ }
+ case 'error':
+ return {
+ icon: AlertCircle,
+ text: 'Error saving',
+ className: 'text-red-600 bg-red-50 dark:bg-red-950/30 dark:text-red-400 border-red-200 dark:border-red-800'
+ }
+ default:
+ return {
+ icon: CloudOff,
+ text: 'Unknown',
+ className: 'text-muted-foreground bg-muted/50 border-muted'
+ }
+ }
+ }
+
+ const config = getStatusConfig()
+ const Icon = config.icon
+
+ return (
+ <div
+ className={cn(
+ 'flex items-center gap-1.5 px-2.5 py-1.5',
+ 'rounded-md border shadow-sm',
+ 'text-xs font-medium',
+ 'transition-all duration-200',
+ config.className
+ )}
+ >
+ <Icon className={cn('h-3.5 w-3.5', config.iconClassName)} />
+ <span>{config.text}</span>
+ </div>
+ )
+})
+
+SaveStatusIndicator.displayName = 'SaveStatusIndicator'
diff --git a/flowsint-app/src/components/graphs/toolbar.tsx b/flowsint-app/src/components/graphs/toolbar.tsx
index 03529a92..ea754692 100644
--- a/flowsint-app/src/components/graphs/toolbar.tsx
+++ b/flowsint-app/src/components/graphs/toolbar.tsx
@@ -14,7 +14,8 @@ import {
FunnelPlus,
GitPullRequestArrow,
LassoSelect,
- Merge
+ Merge,
+ Network
} from 'lucide-react'
import { memo, useCallback } from 'react'
import { toast } from 'sonner'
@@ -22,6 +23,8 @@ import { cn } from '@/lib/utils'
import Filters from './filters'
import { useGraphStore } from '@/stores/graph-store'
import { useConfirm } from '@/components/use-confirm-dialog'
+import { useGraphSaveStatus } from '@/stores/graph-save-status-store'
+import { SaveStatusIndicator } from './save-status-indicator'
// Tooltip wrapper component to avoid repetition
export const ToolbarButton = memo(function ToolbarButton({
@@ -82,6 +85,7 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)
const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)
const filters = useGraphStore((s) => s.filters)
+ const saveStatus = useGraphSaveStatus((s) => s.saveStatus)
const handleRefresh = useCallback(() => {
try {
@@ -91,68 +95,54 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
}
}, [refetchGraph])
- const handleRegenerateForceLayout = useCallback(async () => {
- console.log('[Toolbar] handleRegenerateForceLayout called')
- console.log('[Toolbar] regenerateLayout function:', regenerateLayout)
- console.log('[Toolbar] regenerateLayout is function?', typeof regenerateLayout === 'function')
+ const handleApplyForceLayout = useCallback(async () => {
+ console.log('[Toolbar] handleApplyForceLayout called')
const confirmed = await confirm({
- title: 'Regenerate force layout?',
+ 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.'
})
if (!confirmed) {
- console.log('[Toolbar] User cancelled regeneration')
+ console.log('[Toolbar] User cancelled layout change')
return
}
console.log('[Toolbar] Calling regenerateLayout with force')
try {
regenerateLayout('force')
- console.log('[Toolbar] regenerateLayout completed successfully')
- toast.success('Force layout regenerated successfully')
+ console.log('[Toolbar] Force layout applied successfully')
+ toast.success('Force layout applied successfully')
} catch (error) {
- console.error('[Toolbar] Failed to regenerate layout:', error)
- toast.error(`Failed to regenerate layout: ${error instanceof Error ? error.message : 'Unknown error'}`)
+ console.error('[Toolbar] Failed to apply layout:', error)
+ toast.error(`Failed to apply layout: ${error instanceof Error ? error.message : 'Unknown error'}`)
}
}, [confirm, regenerateLayout])
- const handleRegenerateHierarchyLayout = useCallback(async () => {
- console.log('[Toolbar] handleRegenerateHierarchyLayout called')
+ const handleApplyHierarchyLayout = useCallback(async () => {
+ console.log('[Toolbar] handleApplyHierarchyLayout called')
const confirmed = await confirm({
- title: 'Regenerate hierarchy layout?',
+ title: 'Apply hierarchy layout?',
message: 'This will reset all node positions and regenerate them using the hierarchical layout algorithm. Current positions will be lost.'
})
if (!confirmed) {
- console.log('[Toolbar] User cancelled regeneration')
+ console.log('[Toolbar] User cancelled layout change')
return
}
console.log('[Toolbar] Calling regenerateLayout with hierarchy')
try {
regenerateLayout('hierarchy')
- console.log('[Toolbar] regenerateLayout completed successfully')
- toast.success('Hierarchy layout regenerated successfully')
+ console.log('[Toolbar] Hierarchy layout applied successfully')
+ toast.success('Hierarchy layout applied successfully')
} catch (error) {
- console.error('[Toolbar] Failed to regenerate layout:', error)
- toast.error(`Failed to regenerate layout: ${error instanceof Error ? error.message : 'Unknown error'}`)
+ console.error('[Toolbar] Failed to apply layout:', error)
+ toast.error(`Failed to apply layout: ${error instanceof Error ? error.message : 'Unknown error'}`)
}
}, [confirm, regenerateLayout])
- const handleTableLayout = useCallback(() => {
- setView('table')
- }, [setView])
-
- const handleMapLayout = useCallback(() => {
- setView('map')
- }, [setView])
-
- const handleRelationshipsLayout = useCallback(() => {
- setView('relationships')
- }, [setView])
-
const handleOpenAddRelationDialog = useCallback(() => {
setOpenAddRelationDialog(true)
}, [setOpenAddRelationDialog])
@@ -174,8 +164,8 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
)
return (
- <div className="flex w-full justify-between gap-2 items-center">
- <div className="flex items-center gap-2">
+ <>
+ <div className='absolute flex items-center gap-2 left-2 top-2'>
<TooltipProvider>
<ToolbarButton
icon={<GitPullRequestArrow className="h-4 w-4 opacity-70" />}
@@ -195,26 +185,26 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
icon={<ZoomIn className="h-4 w-4 opacity-70" />}
tooltip="Zoom In"
onClick={zoomIn}
- disabled={view !== 'force' || isLassoActive}
+ disabled={view !== 'graph' || isLassoActive}
/>
<ToolbarButton
icon={<Minus className="h-4 w-4 opacity-70" />}
tooltip="Zoom Out"
onClick={zoomOut}
- disabled={view !== 'force' || isLassoActive}
+ disabled={view !== 'graph' || isLassoActive}
/>
<ToolbarButton
icon={<Maximize className="h-4 w-4 opacity-70" />}
tooltip="Fit to View"
onClick={zoomToFit}
- disabled={view !== 'force' || isLassoActive}
+ disabled={view !== 'graph' || isLassoActive}
/>
<ToolbarButton
icon={<LassoSelect className="h-4 w-4 opacity-70" />}
tooltip={'Lasso select'}
onClick={handleLassoSelect}
toggled={isLassoActive}
- disabled={view !== 'force'}
+ disabled={view !== 'graph'}
/>
<Filters>
<ToolbarButton
@@ -231,41 +221,109 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean
tooltip="Refresh"
/>
</TooltipProvider>
- </div>
- <div className="flex items-center gap-2">
+ </div >
+
+ {/* Center: View Toggle Group */}
+ <div className="flex-1 flex justify-center absolute left-1/2 top-2 -translate-x-1/2" >
+ <div className="flex items-center bg-muted/40 p-1 gap-0.5 rounded-md">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setView('graph')}
+ className={cn(
+ 'h-7 px-2 rounded-sm',
+ view === 'graph'
+ ? 'bg-background text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-background/50'
+ )}
+ >
+ <Network className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Graph view</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setView('table')}
+ className={cn(
+ 'h-7 px-2 rounded-sm',
+ view === 'table'
+ ? 'bg-background text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-background/50'
+ )}
+ >
+ <List className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Table view</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setView('relationships')}
+ className={cn(
+ 'h-7 px-2 rounded-sm',
+ view === 'relationships'
+ ? 'bg-background text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-background/50'
+ )}
+ >
+ <ArrowRightLeft className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Relationships view</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setView('map')}
+ className={cn(
+ 'h-7 px-2 rounded-sm',
+ view === 'map'
+ ? 'bg-background text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-background/50'
+ )}
+ >
+ <MapPin className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Map view</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div >
+
+ < div className="flex items-center gap-2 absolute right-2 top-2" >
<TooltipProvider>
- <ToolbarButton
- icon={<GitFork className="h-4 w-4 opacity-70 rotate-180" />}
- tooltip={'Regenerate hierarchy layout'}
- onClick={handleRegenerateHierarchyLayout}
- disabled={isLoading}
- />
- <ToolbarButton
- icon={<Waypoints className="h-4 w-4 opacity-70" />}
- tooltip={'Regenerate force layout'}
- onClick={handleRegenerateForceLayout}
- disabled={isLoading}
- />
- <ToolbarButton
- icon={<List className="h-4 w-4 opacity-70" />}
- tooltip={'Table view'}
- toggled={['table'].includes(view)}
- onClick={handleTableLayout}
- />
- <ToolbarButton
- icon={<ArrowRightLeft className="h-4 w-4 opacity-70" />}
- tooltip={'Relationships view'}
- toggled={['relationships'].includes(view)}
- onClick={handleRelationshipsLayout}
- />
- <ToolbarButton
- icon={<MapPin className="h-4 w-4 opacity-70" />}
- tooltip={'Map view'}
- toggled={['map'].includes(view)}
- onClick={handleMapLayout}
- />
+ {view === 'graph' && (
+ <>
+ <ToolbarButton
+ icon={<Waypoints className="h-4 w-4 opacity-70" />}
+ tooltip={'Force layout'}
+ onClick={handleApplyForceLayout}
+ disabled={isLoading}
+ />
+ <ToolbarButton
+ icon={<GitFork className="h-4 w-4 opacity-70 rotate-180" />}
+ tooltip={'Hierarchy layout'}
+ onClick={handleApplyHierarchyLayout}
+ disabled={isLoading}
+ />
+ </>
+ )}
</TooltipProvider>
- </div>
- </div>
+ <SaveStatusIndicator status={saveStatus} />
+ </div >
+ </ >
)
})
\ No newline at end of file
diff --git a/flowsint-app/src/hooks/use-save-node-positions.ts b/flowsint-app/src/hooks/use-save-node-positions.ts
new file mode 100644
index 00000000..ab45d202
--- /dev/null
+++ b/flowsint-app/src/hooks/use-save-node-positions.ts
@@ -0,0 +1,118 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { useDebounce } from './use-debounce'
+import { sketchService } from '@/api/sketch-service'
+import { useGraphSaveStatus } from '@/stores/graph-save-status-store'
+
+interface NodePosition {
+ x: number
+ y: number
+}
+
+export type SaveStatus = 'idle' | 'pending' | 'saving' | 'saved' | 'error'
+
+/**
+ * Hook to save node positions to the backend
+ * Handles debouncing and batch updates for all nodes
+ */
+export function useSaveNodePositions(sketchId?: string) {
+ const [changedNodePositions, setChangedNodePositions] = useState<Map<string, NodePosition>>(new Map())
+ const isStabilizingRef = useRef(false) // Start as false, mark as true only during layout regeneration
+ const setSaveStatus = useGraphSaveStatus((state) => state.setSaveStatus)
+
+ // Debounced value to trigger save (2 seconds)
+ const debouncedChangedPositions = useDebounce(changedNodePositions, 2000)
+
+ // Initialize status on mount
+ useEffect(() => {
+ setSaveStatus('idle')
+ }, [setSaveStatus])
+
+ /**
+ * Mark the graph as stabilized (can start saving positions)
+ */
+ const markAsStabilized = useCallback(() => {
+ isStabilizingRef.current = false
+ }, [])
+
+ /**
+ * Mark the graph as stabilizing (prevent saving positions)
+ */
+ const markAsStabilizing = useCallback(() => {
+ isStabilizingRef.current = true
+ }, [])
+
+ /**
+ * Save positions for all nodes
+ * @param nodes - Array of nodes or graphData.nodes
+ * @param force - Force save even if stabilizing (for layout regeneration)
+ */
+ const saveAllNodePositions = useCallback((nodes: any[], force = false) => {
+ if (!sketchId) {
+ return
+ }
+
+ if (!force && isStabilizingRef.current) {
+ return
+ }
+
+ const newMap = new Map<string, NodePosition>()
+
+ nodes.forEach((node: any) => {
+ if (node.x !== undefined && node.y !== undefined) {
+ // Fix node position to prevent force simulation from moving it
+ node.fx = node.x
+ node.fy = node.y
+ newMap.set(node.id, { x: node.x, y: node.y })
+ }
+ })
+
+ if (newMap.size > 0) {
+ setChangedNodePositions(newMap)
+ setSaveStatus('pending')
+ }
+ }, [sketchId])
+
+ /**
+ * Clear pending changes (useful when switching sketches)
+ */
+ const clearPendingChanges = useCallback(() => {
+ setChangedNodePositions(new Map())
+ }, [])
+
+ // Save positions when debounced value changes
+ useEffect(() => {
+ if (!sketchId || debouncedChangedPositions.size === 0) {
+ return
+ }
+
+ const positions = Array.from(debouncedChangedPositions.entries()).map(([nodeId, pos]) => ({
+ nodeId,
+ x: pos.x,
+ y: pos.y
+ }))
+
+ setSaveStatus('saving')
+
+ sketchService.updateNodePositions(sketchId, positions)
+ .then(() => {
+ setChangedNodePositions(new Map())
+ setSaveStatus('saved')
+ // Reset to idle after 2 seconds
+ setTimeout(() => setSaveStatus('idle'), 2000)
+ })
+ .catch((error) => {
+ console.error('[useSaveNodePositions] Failed to save:', error)
+ setSaveStatus('error')
+ // Reset to idle after 3 seconds
+ setTimeout(() => setSaveStatus('idle'), 3000)
+ })
+ }, [debouncedChangedPositions, sketchId, setSaveStatus])
+
+ return {
+ saveAllNodePositions,
+ markAsStabilized,
+ markAsStabilizing,
+ clearPendingChanges,
+ hasPendingChanges: changedNodePositions.size > 0
+ }
+}
diff --git a/flowsint-app/src/lib/utils.ts b/flowsint-app/src/lib/utils.ts
index 29d73ad2..d6caff12 100644
--- a/flowsint-app/src/lib/utils.ts
+++ b/flowsint-app/src/lib/utils.ts
@@ -26,21 +26,41 @@ export const getDagreLayoutedElements = (nodes: GraphNode[],
},) => {
const g = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
- g.setGraph({ rankdir: options.direction });
- edges.forEach((edge) => g.setEdge(edge.source, edge.target));
+
+ // Configure dagre with proper spacing
+ g.setGraph({
+ rankdir: options.direction,
+ nodesep: 80, // Horizontal spacing between nodes
+ ranksep: 120, // Vertical spacing between ranks
+ marginx: 20,
+ marginy: 20
+ });
+
+ // Set node dimensions first - use a consistent size for all nodes
+ const nodeWidth = 50;
+ const nodeHeight = 50;
+
nodes.forEach((node) =>
g.setNode(node.id, {
- ...node,
- width: node.nodeSize ?? 0,
- height: node.nodeSize ?? 0,
+ width: nodeWidth,
+ height: nodeHeight,
}),
);
+
+ // Then add edges
+ edges.forEach((edge: GraphEdge) => {
+ const source = edge.source;
+ const target = edge.target;
+ g.setEdge(source, target);
+ });
+
Dagre.layout(g);
+
return {
nodes: nodes.map((node) => {
const position = g.node(node.id);
- const x = position.x - (node.nodeSize ?? 0) / 2;
- const y = position.y - (node.nodeSize ?? 0) / 2;
+ const x = position.x;
+ const y = position.y;
return { ...node, x, y };
}),
edges,
@@ -183,9 +203,9 @@ export const getAllNodeTypes = (actionItems: any[]) => {
const types: string[] = []
actionItems.forEach(item => {
if (item.children) {
- item.children.forEach(child => {
- if (child.type && !types.includes(child.type)) {
- types.push(child.type)
+ item.children.forEach((child: GraphNode) => {
+ if (child.data.type && !types.includes(child.data.type)) {
+ types.push(child.data.type)
}
})
} else if (item.type && !types.includes(item.type)) {
diff --git a/flowsint-app/src/stores/graph-controls-store.ts b/flowsint-app/src/stores/graph-controls-store.ts
index 407f1787..0551601a 100644
--- a/flowsint-app/src/stores/graph-controls-store.ts
+++ b/flowsint-app/src/stores/graph-controls-store.ts
@@ -1,7 +1,7 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
-type ViewType = 'hierarchy' | 'force' | 'table' | 'map' | 'relationships'
+type ViewType = 'graph' | 'table' | 'map' | 'relationships'
type GraphControlsStore = {
view: ViewType
@@ -13,14 +13,14 @@ type GraphControlsStore = {
setActions: (actions: Partial<GraphControlsStore>) => void
refetchGraph: () => void
regenerateLayout: (layoutType: 'force' | 'hierarchy') => void
- setView: (view: 'force' | 'hierarchy' | 'table' | 'map' | 'relationships') => void
+ setView: (view: 'graph' | 'table' | 'map' | 'relationships') => void
setIsLassoActive: (active: boolean) => void
}
export const useGraphControls = create<GraphControlsStore>()(
persist(
(set) => ({
- view: 'force',
+ view: 'graph',
isLassoActive: false,
zoomToFit: () => { },
zoomIn: () => { },
diff --git a/flowsint-app/src/stores/graph-save-status-store.ts b/flowsint-app/src/stores/graph-save-status-store.ts
new file mode 100644
index 00000000..7373df92
--- /dev/null
+++ b/flowsint-app/src/stores/graph-save-status-store.ts
@@ -0,0 +1,12 @@
+import { create } from 'zustand'
+import { SaveStatus } from '@/hooks/use-save-node-positions'
+
+interface GraphSaveStatusStore {
+ saveStatus: SaveStatus
+ setSaveStatus: (status: SaveStatus) => void
+}
+
+export const useGraphSaveStatus = create<GraphSaveStatusStore>((set) => ({
+ saveStatus: 'idle',
+ setSaveStatus: (status) => set({ saveStatus: status })
+}))