Fix linting

This commit is contained in:
yangdx
2025-03-14 16:45:02 +08:00
parent de016025ba
commit 20c976584b
3 changed files with 110 additions and 110 deletions

View File

@@ -159,33 +159,33 @@ const PropertyRow = ({
const NodePropertiesView = ({ node }: { node: NodeType }) => { const NodePropertiesView = ({ node }: { node: NodeType }) => {
const { t } = useTranslation() const { t } = useTranslation()
const handleExpandNode = () => { const handleExpandNode = () => {
useGraphStore.getState().triggerNodeExpand(node.id) useGraphStore.getState().triggerNodeExpand(node.id)
} }
const handlePruneNode = () => { const handlePruneNode = () => {
useGraphStore.getState().triggerNodePrune(node.id) useGraphStore.getState().triggerNodePrune(node.id)
} }
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<label className="text-md pl-1 font-bold tracking-wide text-sky-300">{t('graphPanel.propertiesView.node.title')}</label> <label className="text-md pl-1 font-bold tracking-wide text-sky-300">{t('graphPanel.propertiesView.node.title')}</label>
<div className="flex gap-1"> <div className="flex gap-1">
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
className="h-6 w-6" className="h-6 w-6"
onClick={handleExpandNode} onClick={handleExpandNode}
tooltip={t('graphPanel.propertiesView.node.expandNode')} tooltip={t('graphPanel.propertiesView.node.expandNode')}
> >
<GitBranchPlus className="h-4 w-4" /> <GitBranchPlus className="h-4 w-4" />
</Button> </Button>
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
className="h-6 w-6" className="h-6 w-6"
onClick={handlePruneNode} onClick={handlePruneNode}
tooltip={t('graphPanel.propertiesView.node.pruneNode')} tooltip={t('graphPanel.propertiesView.node.pruneNode')}
> >

View File

@@ -336,11 +336,11 @@ const useLightrangeGraph = () => {
useEffect(() => { useEffect(() => {
const handleNodeExpand = async (nodeId: string | null) => { const handleNodeExpand = async (nodeId: string | null) => {
if (!nodeId || !sigmaGraph || !rawGraph) return; if (!nodeId || !sigmaGraph || !rawGraph) return;
try { try {
// Set fetching state // Set fetching state
useGraphStore.getState().setIsFetching(true); useGraphStore.getState().setIsFetching(true);
// Get the node to expand // Get the node to expand
const nodeToExpand = rawGraph.getNode(nodeId); const nodeToExpand = rawGraph.getNode(nodeId);
if (!nodeToExpand) { if (!nodeToExpand) {
@@ -348,7 +348,7 @@ const useLightrangeGraph = () => {
useGraphStore.getState().setIsFetching(false); useGraphStore.getState().setIsFetching(false);
return; return;
} }
// Get the label of the node to expand // Get the label of the node to expand
const label = nodeToExpand.labels[0]; const label = nodeToExpand.labels[0];
if (!label) { if (!label) {
@@ -356,16 +356,16 @@ const useLightrangeGraph = () => {
useGraphStore.getState().setIsFetching(false); useGraphStore.getState().setIsFetching(false);
return; return;
} }
// Fetch the extended subgraph with depth 2 // Fetch the extended subgraph with depth 2
const extendedGraph = await queryGraphs(label, 2, 0); const extendedGraph = await queryGraphs(label, 2, 0);
if (!extendedGraph || !extendedGraph.nodes || !extendedGraph.edges) { if (!extendedGraph || !extendedGraph.nodes || !extendedGraph.edges) {
console.error('Failed to fetch extended graph'); console.error('Failed to fetch extended graph');
useGraphStore.getState().setIsFetching(false); useGraphStore.getState().setIsFetching(false);
return; return;
} }
// Process nodes to add required properties for RawNodeType // Process nodes to add required properties for RawNodeType
const processedNodes: RawNodeType[] = []; const processedNodes: RawNodeType[] = [];
for (const node of extendedGraph.nodes) { for (const node of extendedGraph.nodes) {
@@ -374,7 +374,7 @@ const useLightrangeGraph = () => {
const g = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256);
const color = `rgb(${r}, ${g}, ${b})`; const color = `rgb(${r}, ${g}, ${b})`;
// Create a properly typed RawNodeType // Create a properly typed RawNodeType
processedNodes.push({ processedNodes.push({
id: node.id, id: node.id,
@@ -387,7 +387,7 @@ const useLightrangeGraph = () => {
degree: 0 // Initial degree degree: 0 // Initial degree
}); });
} }
// Process edges to add required properties for RawEdgeType // Process edges to add required properties for RawEdgeType
const processedEdges: RawEdgeType[] = []; const processedEdges: RawEdgeType[] = [];
for (const edge of extendedGraph.edges) { for (const edge of extendedGraph.edges) {
@@ -401,7 +401,7 @@ const useLightrangeGraph = () => {
dynamicId: '' // Will be set when adding to sigma graph dynamicId: '' // Will be set when adding to sigma graph
}); });
} }
// Store current node positions // Store current node positions
const nodePositions: Record<string, {x: number, y: number}> = {}; const nodePositions: Record<string, {x: number, y: number}> = {};
sigmaGraph.forEachNode((node) => { sigmaGraph.forEachNode((node) => {
@@ -410,10 +410,10 @@ const useLightrangeGraph = () => {
y: sigmaGraph.getNodeAttribute(node, 'y') y: sigmaGraph.getNodeAttribute(node, 'y')
}; };
}); });
// Get existing node IDs // Get existing node IDs
const existingNodeIds = new Set(sigmaGraph.nodes()); const existingNodeIds = new Set(sigmaGraph.nodes());
// Check if there are any new nodes that can be connected to the selected node // Check if there are any new nodes that can be connected to the selected node
let hasConnectableNewNodes = false; let hasConnectableNewNodes = false;
for (const newNode of processedNodes) { for (const newNode of processedNodes) {
@@ -421,26 +421,26 @@ const useLightrangeGraph = () => {
if (existingNodeIds.has(newNode.id)) { if (existingNodeIds.has(newNode.id)) {
continue; continue;
} }
// Check if this node is connected to the selected node // Check if this node is connected to the selected node
const isConnected = processedEdges.some( const isConnected = processedEdges.some(
edge => (edge.source === nodeId && edge.target === newNode.id) || edge => (edge.source === nodeId && edge.target === newNode.id) ||
(edge.target === nodeId && edge.source === newNode.id) (edge.target === nodeId && edge.source === newNode.id)
); );
if (isConnected) { if (isConnected) {
hasConnectableNewNodes = true; hasConnectableNewNodes = true;
break; break;
} }
} }
// If no new connectable nodes found, show toast and return // If no new connectable nodes found, show toast and return
if (!hasConnectableNewNodes) { if (!hasConnectableNewNodes) {
toast.info(t('graphPanel.propertiesView.node.noNewNodes')); toast.info(t('graphPanel.propertiesView.node.noNewNodes'));
useGraphStore.getState().setIsFetching(false); useGraphStore.getState().setIsFetching(false);
return; return;
} }
// Get degree range from existing graph for size calculations // Get degree range from existing graph for size calculations
let minDegree = Number.MAX_SAFE_INTEGER; let minDegree = Number.MAX_SAFE_INTEGER;
let maxDegree = 0; let maxDegree = 0;
@@ -449,35 +449,35 @@ const useLightrangeGraph = () => {
minDegree = Math.min(minDegree, degree); minDegree = Math.min(minDegree, degree);
maxDegree = Math.max(maxDegree, degree); maxDegree = Math.max(maxDegree, degree);
}); });
// Calculate size formula parameters // Calculate size formula parameters
const range = maxDegree - minDegree || 1; // Avoid division by zero const range = maxDegree - minDegree || 1; // Avoid division by zero
const scale = Constants.maxNodeSize - Constants.minNodeSize; const scale = Constants.maxNodeSize - Constants.minNodeSize;
// Add new nodes from the processed nodes // Add new nodes from the processed nodes
for (const newNode of processedNodes) { for (const newNode of processedNodes) {
// Skip if node already exists // Skip if node already exists
if (existingNodeIds.has(newNode.id)) { if (existingNodeIds.has(newNode.id)) {
continue; continue;
} }
// Check if this node is connected to the selected node // Check if this node is connected to the selected node
const isConnected = processedEdges.some( const isConnected = processedEdges.some(
edge => (edge.source === nodeId && edge.target === newNode.id) || edge => (edge.source === nodeId && edge.target === newNode.id) ||
(edge.target === nodeId && edge.source === newNode.id) (edge.target === nodeId && edge.source === newNode.id)
); );
if (isConnected) { if (isConnected) {
// Calculate node degree (number of connected edges) // Calculate node degree (number of connected edges)
const nodeDegree = processedEdges.filter(edge => const nodeDegree = processedEdges.filter(edge =>
edge.source === newNode.id || edge.target === newNode.id edge.source === newNode.id || edge.target === newNode.id
).length; ).length;
// Calculate node size using the same formula as in fetchGraph // Calculate node size using the same formula as in fetchGraph
const nodeSize = Math.round( const nodeSize = Math.round(
Constants.minNodeSize + scale * Math.pow((nodeDegree - minDegree) / range, 0.5) Constants.minNodeSize + scale * Math.pow((nodeDegree - minDegree) / range, 0.5)
); );
// Add the new node to the graph with calculated size // Add the new node to the graph with calculated size
sigmaGraph.addNode(newNode.id, { sigmaGraph.addNode(newNode.id, {
label: newNode.labels.join(', '), label: newNode.labels.join(', '),
@@ -488,7 +488,7 @@ const useLightrangeGraph = () => {
borderColor: '#000', borderColor: '#000',
borderSize: 0.2 borderSize: 0.2
}); });
// Add the node to the raw graph // Add the node to the raw graph
if (!rawGraph.getNode(newNode.id)) { if (!rawGraph.getNode(newNode.id)) {
// Update the node size to match the calculated size // Update the node size to match the calculated size
@@ -500,7 +500,7 @@ const useLightrangeGraph = () => {
} }
} }
} }
// Add new edges // Add new edges
for (const newEdge of processedEdges) { for (const newEdge of processedEdges) {
// Only add edges where both source and target exist in the graph // Only add edges where both source and target exist in the graph
@@ -509,12 +509,12 @@ const useLightrangeGraph = () => {
if (sigmaGraph.hasEdge(newEdge.source, newEdge.target)) { if (sigmaGraph.hasEdge(newEdge.source, newEdge.target)) {
continue; continue;
} }
// Add the edge to the sigma graph // Add the edge to the sigma graph
newEdge.dynamicId = sigmaGraph.addDirectedEdge(newEdge.source, newEdge.target, { newEdge.dynamicId = sigmaGraph.addDirectedEdge(newEdge.source, newEdge.target, {
label: newEdge.type || undefined label: newEdge.type || undefined
}); });
// Add the edge to the raw graph // Add the edge to the raw graph
if (!rawGraph.getEdge(newEdge.id, false)) { if (!rawGraph.getEdge(newEdge.id, false)) {
// Add to edges array // Add to edges array
@@ -526,10 +526,10 @@ const useLightrangeGraph = () => {
} }
} }
} }
// Update the dynamic edge map // Update the dynamic edge map
rawGraph.buildDynamicMap(); rawGraph.buildDynamicMap();
// Restore positions for existing nodes // Restore positions for existing nodes
Object.entries(nodePositions).forEach(([id, position]) => { Object.entries(nodePositions).forEach(([id, position]) => {
if (sigmaGraph.hasNode(id)) { if (sigmaGraph.hasNode(id)) {
@@ -537,38 +537,38 @@ const useLightrangeGraph = () => {
sigmaGraph.setNodeAttribute(id, 'y', position.y); sigmaGraph.setNodeAttribute(id, 'y', position.y);
} }
}); });
// Update the size of the expanded node based on its new edge count // Update the size of the expanded node based on its new edge count
if (sigmaGraph.hasNode(nodeId)) { if (sigmaGraph.hasNode(nodeId)) {
// Get the new degree of the expanded node // Get the new degree of the expanded node
const expandedNodeDegree = sigmaGraph.degree(nodeId); const expandedNodeDegree = sigmaGraph.degree(nodeId);
// Calculate new size for the expanded node using the same parameters // Calculate new size for the expanded node using the same parameters
const newSize = Math.round( const newSize = Math.round(
Constants.minNodeSize + scale * Math.pow((expandedNodeDegree - minDegree) / range, 0.5) Constants.minNodeSize + scale * Math.pow((expandedNodeDegree - minDegree) / range, 0.5)
); );
// Update the size in sigma graph // Update the size in sigma graph
sigmaGraph.setNodeAttribute(nodeId, 'size', newSize); sigmaGraph.setNodeAttribute(nodeId, 'size', newSize);
// Update the size in raw graph // Update the size in raw graph
const expandedNodeIndex = rawGraph.nodeIdMap[nodeId]; const expandedNodeIndex = rawGraph.nodeIdMap[nodeId];
if (expandedNodeIndex !== undefined) { if (expandedNodeIndex !== undefined) {
rawGraph.nodes[expandedNodeIndex].size = newSize; rawGraph.nodes[expandedNodeIndex].size = newSize;
} }
} }
// Refresh the layout and store the node ID to reselect after refresh // Refresh the layout and store the node ID to reselect after refresh
const nodeIdToSelect = nodeId; const nodeIdToSelect = nodeId;
useGraphStore.getState().refreshLayout(); useGraphStore.getState().refreshLayout();
// Use setTimeout to reselect the node after the layout refresh is complete // Use setTimeout to reselect the node after the layout refresh is complete
setTimeout(() => { setTimeout(() => {
if (nodeIdToSelect) { if (nodeIdToSelect) {
useGraphStore.getState().setSelectedNode(nodeIdToSelect, true); useGraphStore.getState().setSelectedNode(nodeIdToSelect, true);
} }
}, 2000); // Wait a bit longer than the refreshLayout timeout (which is 10ms) }, 2000); // Wait a bit longer than the refreshLayout timeout (which is 10ms)
} catch (error) { } catch (error) {
console.error('Error expanding node:', error); console.error('Error expanding node:', error);
} finally { } finally {
@@ -576,7 +576,7 @@ const useLightrangeGraph = () => {
useGraphStore.getState().setIsFetching(false); useGraphStore.getState().setIsFetching(false);
} }
}; };
// If there's a node to expand, handle it // If there's a node to expand, handle it
if (nodeToExpand) { if (nodeToExpand) {
handleNodeExpand(nodeToExpand); handleNodeExpand(nodeToExpand);
@@ -586,25 +586,25 @@ const useLightrangeGraph = () => {
}, 0); }, 0);
} }
}, [nodeToExpand, sigmaGraph, rawGraph]); }, [nodeToExpand, sigmaGraph, rawGraph]);
// Helper function to get all nodes that will be deleted // Helper function to get all nodes that will be deleted
const getNodesThatWillBeDeleted = useCallback((nodeId: string, graph: DirectedGraph) => { const getNodesThatWillBeDeleted = useCallback((nodeId: string, graph: DirectedGraph) => {
const nodesToDelete = new Set<string>([nodeId]); const nodesToDelete = new Set<string>([nodeId]);
// Find all nodes that would become isolated after deletion // Find all nodes that would become isolated after deletion
graph.forEachNode((node) => { graph.forEachNode((node) => {
if (node === nodeId) return; // Skip the node being deleted if (node === nodeId) return; // Skip the node being deleted
// Get all neighbors of this node // Get all neighbors of this node
const neighbors = graph.neighbors(node); const neighbors = graph.neighbors(node);
// If this node has only one neighbor and that neighbor is the node being deleted, // If this node has only one neighbor and that neighbor is the node being deleted,
// this node will become isolated, so we should delete it too // this node will become isolated, so we should delete it too
if (neighbors.length === 1 && neighbors[0] === nodeId) { if (neighbors.length === 1 && neighbors[0] === nodeId) {
nodesToDelete.add(node); nodesToDelete.add(node);
} }
}); });
return nodesToDelete; return nodesToDelete;
}, []); }, []);
@@ -612,34 +612,34 @@ const useLightrangeGraph = () => {
useEffect(() => { useEffect(() => {
const handleNodePrune = (nodeId: string | null) => { const handleNodePrune = (nodeId: string | null) => {
if (!nodeId || !sigmaGraph || !rawGraph) return; if (!nodeId || !sigmaGraph || !rawGraph) return;
try { try {
// Check if the node exists // Check if the node exists
if (!sigmaGraph.hasNode(nodeId)) { if (!sigmaGraph.hasNode(nodeId)) {
console.error('Node not found:', nodeId); console.error('Node not found:', nodeId);
return; return;
} }
// Get all nodes that will be deleted (including isolated nodes) // Get all nodes that will be deleted (including isolated nodes)
const nodesToDelete = getNodesThatWillBeDeleted(nodeId, sigmaGraph); const nodesToDelete = getNodesThatWillBeDeleted(nodeId, sigmaGraph);
// Check if we would delete all nodes in the graph // Check if we would delete all nodes in the graph
if (nodesToDelete.size === sigmaGraph.nodes().length) { if (nodesToDelete.size === sigmaGraph.nodes().length) {
toast.error(t('graphPanel.propertiesView.node.deleteAllNodesError')); toast.error(t('graphPanel.propertiesView.node.deleteAllNodesError'));
return; return;
} }
// If the node is selected or focused, clear selection // If the node is selected or focused, clear selection
const state = useGraphStore.getState(); const state = useGraphStore.getState();
if (state.selectedNode === nodeId || state.focusedNode === nodeId) { if (state.selectedNode === nodeId || state.focusedNode === nodeId) {
state.clearSelection(); state.clearSelection();
} }
// Process all nodes that need to be deleted // Process all nodes that need to be deleted
for (const nodeToDelete of nodesToDelete) { for (const nodeToDelete of nodesToDelete) {
// Remove the node from the sigma graph (this will also remove connected edges) // Remove the node from the sigma graph (this will also remove connected edges)
sigmaGraph.dropNode(nodeToDelete); sigmaGraph.dropNode(nodeToDelete);
// Remove the node from the raw graph // Remove the node from the raw graph
const nodeIndex = rawGraph.nodeIdMap[nodeToDelete]; const nodeIndex = rawGraph.nodeIdMap[nodeToDelete];
if (nodeIndex !== undefined) { if (nodeIndex !== undefined) {
@@ -647,7 +647,7 @@ const useLightrangeGraph = () => {
const edgesToRemove = rawGraph.edges.filter( const edgesToRemove = rawGraph.edges.filter(
edge => edge.source === nodeToDelete || edge.target === nodeToDelete edge => edge.source === nodeToDelete || edge.target === nodeToDelete
); );
// Remove edges from raw graph // Remove edges from raw graph
for (const edge of edgesToRemove) { for (const edge of edgesToRemove) {
const edgeIndex = rawGraph.edgeIdMap[edge.id]; const edgeIndex = rawGraph.edgeIdMap[edge.id];
@@ -666,38 +666,38 @@ const useLightrangeGraph = () => {
delete rawGraph.edgeDynamicIdMap[edge.dynamicId]; delete rawGraph.edgeDynamicIdMap[edge.dynamicId];
} }
} }
// Remove node from nodes array // Remove node from nodes array
rawGraph.nodes.splice(nodeIndex, 1); rawGraph.nodes.splice(nodeIndex, 1);
// Update nodeIdMap for all nodes after this one // Update nodeIdMap for all nodes after this one
for (const [id, idx] of Object.entries(rawGraph.nodeIdMap)) { for (const [id, idx] of Object.entries(rawGraph.nodeIdMap)) {
if (idx > nodeIndex) { if (idx > nodeIndex) {
rawGraph.nodeIdMap[id] = idx - 1; rawGraph.nodeIdMap[id] = idx - 1;
} }
} }
// Remove from nodeIdMap // Remove from nodeIdMap
delete rawGraph.nodeIdMap[nodeToDelete]; delete rawGraph.nodeIdMap[nodeToDelete];
} }
} }
// Rebuild the dynamic edge map // Rebuild the dynamic edge map
rawGraph.buildDynamicMap(); rawGraph.buildDynamicMap();
// Show notification if we deleted more than just the selected node // Show notification if we deleted more than just the selected node
if (nodesToDelete.size > 1) { if (nodesToDelete.size > 1) {
toast.info(t('graphPanel.propertiesView.node.nodesRemoved', { count: nodesToDelete.size })); toast.info(t('graphPanel.propertiesView.node.nodesRemoved', { count: nodesToDelete.size }));
} }
// Force a refresh of the graph layout // Force a refresh of the graph layout
useGraphStore.getState().refreshLayout(); useGraphStore.getState().refreshLayout();
} catch (error) { } catch (error) {
console.error('Error pruning node:', error); console.error('Error pruning node:', error);
} }
}; };
// If there's a node to prune, handle it // If there's a node to prune, handle it
if (nodeToPrune) { if (nodeToPrune) {
handleNodePrune(nodeToPrune); handleNodePrune(nodeToPrune);

View File

@@ -96,11 +96,11 @@ interface GraphState {
// Methods to set global flags // Methods to set global flags
setGraphDataFetchAttempted: (attempted: boolean) => void setGraphDataFetchAttempted: (attempted: boolean) => void
setLabelsFetchAttempted: (attempted: boolean) => void setLabelsFetchAttempted: (attempted: boolean) => void
// Event trigger methods for node operations // Event trigger methods for node operations
triggerNodeExpand: (nodeId: string | null) => void triggerNodeExpand: (nodeId: string | null) => void
triggerNodePrune: (nodeId: string | null) => void triggerNodePrune: (nodeId: string | null) => void
// Node operation state // Node operation state
nodeToExpand: string | null nodeToExpand: string | null
nodeToPrune: string | null nodeToPrune: string | null
@@ -201,15 +201,15 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
// Methods to set global flags // Methods to set global flags
setGraphDataFetchAttempted: (attempted: boolean) => set({ graphDataFetchAttempted: attempted }), setGraphDataFetchAttempted: (attempted: boolean) => set({ graphDataFetchAttempted: attempted }),
setLabelsFetchAttempted: (attempted: boolean) => set({ labelsFetchAttempted: attempted }), setLabelsFetchAttempted: (attempted: boolean) => set({ labelsFetchAttempted: attempted }),
// Node operation state // Node operation state
nodeToExpand: null, nodeToExpand: null,
nodeToPrune: null, nodeToPrune: null,
// Event trigger methods for node operations // Event trigger methods for node operations
triggerNodeExpand: (nodeId: string | null) => set({ nodeToExpand: nodeId }), triggerNodeExpand: (nodeId: string | null) => set({ nodeToExpand: nodeId }),
triggerNodePrune: (nodeId: string | null) => set({ nodeToPrune: nodeId }), triggerNodePrune: (nodeId: string | null) => set({ nodeToPrune: nodeId }),
// Legacy node expansion and pruning methods - will be removed after refactoring // Legacy node expansion and pruning methods - will be removed after refactoring
expandNode: async (nodeId: string) => { expandNode: async (nodeId: string) => {
const state = get(); const state = get();
@@ -217,14 +217,14 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
console.error('Cannot expand node: graph or node not available'); console.error('Cannot expand node: graph or node not available');
return; return;
} }
try { try {
// Set fetching state // Set fetching state
state.setIsFetching(true); state.setIsFetching(true);
// Import queryGraphs dynamically to avoid circular dependency // Import queryGraphs dynamically to avoid circular dependency
const { queryGraphs } = await import('@/api/lightrag'); const { queryGraphs } = await import('@/api/lightrag');
// Get the node to expand // Get the node to expand
const nodeToExpand = state.rawGraph.getNode(nodeId); const nodeToExpand = state.rawGraph.getNode(nodeId);
if (!nodeToExpand) { if (!nodeToExpand) {
@@ -232,7 +232,7 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
state.setIsFetching(false); state.setIsFetching(false);
return; return;
} }
// Get the label of the node to expand // Get the label of the node to expand
const label = nodeToExpand.labels[0]; const label = nodeToExpand.labels[0];
if (!label) { if (!label) {
@@ -240,23 +240,23 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
state.setIsFetching(false); state.setIsFetching(false);
return; return;
} }
// Fetch the extended subgraph with depth 2 // Fetch the extended subgraph with depth 2
const extendedGraph = await queryGraphs(label, 2, 0); const extendedGraph = await queryGraphs(label, 2, 0);
if (!extendedGraph || !extendedGraph.nodes || !extendedGraph.edges) { if (!extendedGraph || !extendedGraph.nodes || !extendedGraph.edges) {
console.error('Failed to fetch extended graph'); console.error('Failed to fetch extended graph');
state.setIsFetching(false); state.setIsFetching(false);
return; return;
} }
// Process nodes to add required properties for RawNodeType // Process nodes to add required properties for RawNodeType
const processedNodes: RawNodeType[] = []; const processedNodes: RawNodeType[] = [];
for (const node of extendedGraph.nodes) { for (const node of extendedGraph.nodes) {
// Generate random color // Generate random color
const randomColorValue = () => Math.floor(Math.random() * 256); const randomColorValue = () => Math.floor(Math.random() * 256);
const color = `rgb(${randomColorValue()}, ${randomColorValue()}, ${randomColorValue()})`; const color = `rgb(${randomColorValue()}, ${randomColorValue()}, ${randomColorValue()})`;
// Create a properly typed RawNodeType // Create a properly typed RawNodeType
processedNodes.push({ processedNodes.push({
id: node.id, id: node.id,
@@ -269,7 +269,7 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
degree: 0 // Initial degree degree: 0 // Initial degree
}); });
} }
// Process edges to add required properties for RawEdgeType // Process edges to add required properties for RawEdgeType
const processedEdges: RawEdgeType[] = []; const processedEdges: RawEdgeType[] = [];
for (const edge of extendedGraph.edges) { for (const edge of extendedGraph.edges) {
@@ -283,7 +283,7 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
dynamicId: '' // Will be set when adding to sigma graph dynamicId: '' // Will be set when adding to sigma graph
}); });
} }
// Store current node positions // Store current node positions
const nodePositions: Record<string, {x: number, y: number}> = {}; const nodePositions: Record<string, {x: number, y: number}> = {};
state.sigmaGraph.forEachNode((node) => { state.sigmaGraph.forEachNode((node) => {
@@ -292,35 +292,35 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
y: state.sigmaGraph!.getNodeAttribute(node, 'y') y: state.sigmaGraph!.getNodeAttribute(node, 'y')
}; };
}); });
// Get existing node IDs // Get existing node IDs
const existingNodeIds = new Set(state.sigmaGraph.nodes()); const existingNodeIds = new Set(state.sigmaGraph.nodes());
// Create a map from id to processed node for quick lookup // Create a map from id to processed node for quick lookup
const processedNodeMap = new Map<string, RawNodeType>(); const processedNodeMap = new Map<string, RawNodeType>();
for (const node of processedNodes) { for (const node of processedNodes) {
processedNodeMap.set(node.id, node); processedNodeMap.set(node.id, node);
} }
// Create a map from id to processed edge for quick lookup // Create a map from id to processed edge for quick lookup
const processedEdgeMap = new Map<string, RawEdgeType>(); const processedEdgeMap = new Map<string, RawEdgeType>();
for (const edge of processedEdges) { for (const edge of processedEdges) {
processedEdgeMap.set(edge.id, edge); processedEdgeMap.set(edge.id, edge);
} }
// Add new nodes from the processed nodes // Add new nodes from the processed nodes
for (const newNode of processedNodes) { for (const newNode of processedNodes) {
// Skip if node already exists // Skip if node already exists
if (existingNodeIds.has(newNode.id)) { if (existingNodeIds.has(newNode.id)) {
continue; continue;
} }
// Check if this node is connected to the selected node // Check if this node is connected to the selected node
const isConnected = processedEdges.some( const isConnected = processedEdges.some(
edge => (edge.source === nodeId && edge.target === newNode.id) || edge => (edge.source === nodeId && edge.target === newNode.id) ||
(edge.target === nodeId && edge.source === newNode.id) (edge.target === nodeId && edge.source === newNode.id)
); );
if (isConnected) { if (isConnected) {
// Add the new node to the graph // Add the new node to the graph
state.sigmaGraph.addNode(newNode.id, { state.sigmaGraph.addNode(newNode.id, {
@@ -332,7 +332,7 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
borderColor: '#000', borderColor: '#000',
borderSize: 0.2 borderSize: 0.2
}); });
// Add the node to the raw graph // Add the node to the raw graph
if (!state.rawGraph.getNode(newNode.id)) { if (!state.rawGraph.getNode(newNode.id)) {
// Add to nodes array // Add to nodes array
@@ -342,7 +342,7 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
} }
} }
} }
// Add new edges // Add new edges
for (const newEdge of processedEdges) { for (const newEdge of processedEdges) {
// Only add edges where both source and target exist in the graph // Only add edges where both source and target exist in the graph
@@ -351,12 +351,12 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
if (state.sigmaGraph.hasEdge(newEdge.source, newEdge.target)) { if (state.sigmaGraph.hasEdge(newEdge.source, newEdge.target)) {
continue; continue;
} }
// Add the edge to the sigma graph // Add the edge to the sigma graph
newEdge.dynamicId = state.sigmaGraph.addDirectedEdge(newEdge.source, newEdge.target, { newEdge.dynamicId = state.sigmaGraph.addDirectedEdge(newEdge.source, newEdge.target, {
label: newEdge.type || undefined label: newEdge.type || undefined
}); });
// Add the edge to the raw graph // Add the edge to the raw graph
if (!state.rawGraph.getEdge(newEdge.id, false)) { if (!state.rawGraph.getEdge(newEdge.id, false)) {
// Add to edges array // Add to edges array
@@ -368,10 +368,10 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
} }
} }
} }
// Update the dynamic edge map // Update the dynamic edge map
state.rawGraph.buildDynamicMap(); state.rawGraph.buildDynamicMap();
// Restore positions for existing nodes // Restore positions for existing nodes
Object.entries(nodePositions).forEach(([nodeId, position]) => { Object.entries(nodePositions).forEach(([nodeId, position]) => {
if (state.sigmaGraph!.hasNode(nodeId)) { if (state.sigmaGraph!.hasNode(nodeId)) {
@@ -379,10 +379,10 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
state.sigmaGraph!.setNodeAttribute(nodeId, 'y', position.y); state.sigmaGraph!.setNodeAttribute(nodeId, 'y', position.y);
} }
}); });
// Refresh the layout // Refresh the layout
state.refreshLayout(); state.refreshLayout();
} catch (error) { } catch (error) {
console.error('Error expanding node:', error); console.error('Error expanding node:', error);
} finally { } finally {
@@ -390,29 +390,29 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
state.setIsFetching(false); state.setIsFetching(false);
} }
}, },
pruneNode: (nodeId: string) => { pruneNode: (nodeId: string) => {
const state = get(); const state = get();
if (!state.sigmaGraph || !state.rawGraph || !nodeId) { if (!state.sigmaGraph || !state.rawGraph || !nodeId) {
console.error('Cannot prune node: graph or node not available'); console.error('Cannot prune node: graph or node not available');
return; return;
} }
try { try {
// Check if the node exists // Check if the node exists
if (!state.sigmaGraph.hasNode(nodeId)) { if (!state.sigmaGraph.hasNode(nodeId)) {
console.error('Node not found:', nodeId); console.error('Node not found:', nodeId);
return; return;
} }
// If the node is selected or focused, clear selection // If the node is selected or focused, clear selection
if (state.selectedNode === nodeId || state.focusedNode === nodeId) { if (state.selectedNode === nodeId || state.focusedNode === nodeId) {
state.clearSelection(); state.clearSelection();
} }
// Remove the node from the sigma graph (this will also remove connected edges) // Remove the node from the sigma graph (this will also remove connected edges)
state.sigmaGraph.dropNode(nodeId); state.sigmaGraph.dropNode(nodeId);
// Remove the node from the raw graph // Remove the node from the raw graph
const nodeIndex = state.rawGraph.nodeIdMap[nodeId]; const nodeIndex = state.rawGraph.nodeIdMap[nodeId];
if (nodeIndex !== undefined) { if (nodeIndex !== undefined) {
@@ -420,7 +420,7 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
const edgesToRemove = state.rawGraph.edges.filter( const edgesToRemove = state.rawGraph.edges.filter(
edge => edge.source === nodeId || edge.target === nodeId edge => edge.source === nodeId || edge.target === nodeId
); );
// Remove edges from raw graph // Remove edges from raw graph
for (const edge of edgesToRemove) { for (const edge of edgesToRemove) {
const edgeIndex = state.rawGraph.edgeIdMap[edge.id]; const edgeIndex = state.rawGraph.edgeIdMap[edge.id];
@@ -439,24 +439,24 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
delete state.rawGraph.edgeDynamicIdMap[edge.dynamicId]; delete state.rawGraph.edgeDynamicIdMap[edge.dynamicId];
} }
} }
// Remove node from nodes array // Remove node from nodes array
state.rawGraph.nodes.splice(nodeIndex, 1); state.rawGraph.nodes.splice(nodeIndex, 1);
// Update nodeIdMap for all nodes after this one // Update nodeIdMap for all nodes after this one
for (const [id, idx] of Object.entries(state.rawGraph.nodeIdMap)) { for (const [id, idx] of Object.entries(state.rawGraph.nodeIdMap)) {
if (idx > nodeIndex) { if (idx > nodeIndex) {
state.rawGraph.nodeIdMap[id] = idx - 1; state.rawGraph.nodeIdMap[id] = idx - 1;
} }
} }
// Remove from nodeIdMap // Remove from nodeIdMap
delete state.rawGraph.nodeIdMap[nodeId]; delete state.rawGraph.nodeIdMap[nodeId];
// Rebuild the dynamic edge map // Rebuild the dynamic edge map
state.rawGraph.buildDynamicMap(); state.rawGraph.buildDynamicMap();
} }
} catch (error) { } catch (error) {
console.error('Error pruning node:', error); console.error('Error pruning node:', error);
} }