Optimize graph state management & performance for tab switching visibility

• Reset graph data without recreating instance
• Fix search result caching on graph updates
This commit is contained in:
yangdx
2025-03-13 21:56:31 +08:00
parent e30162e50a
commit b4d3da3b39
6 changed files with 170 additions and 93 deletions

View File

@@ -103,6 +103,22 @@ const GraphLabels = () => {
if (newLabel === '...') { if (newLabel === '...') {
newLabel = '*' newLabel = '*'
} }
// Reset the fetch attempted flag to force a new data fetch
useGraphStore.getState().setGraphDataFetchAttempted(false)
// Clear current graph data to ensure complete reload when label changes
if (newLabel !== currentLabel) {
const graphStore = useGraphStore.getState();
graphStore.clearSelection();
// Reset the graph state but preserve the instance
if (graphStore.sigmaGraph) {
const nodes = Array.from(graphStore.sigmaGraph.nodes());
nodes.forEach(node => graphStore.sigmaGraph?.dropNode(node));
}
}
if (newLabel === currentLabel && newLabel !== '*') { if (newLabel === currentLabel && newLabel !== '*') {
// 选择相同标签时切换到'*' // 选择相同标签时切换到'*'
useSettingsStore.getState().setQueryLabel('*') useSettingsStore.getState().setQueryLabel('*')

View File

@@ -1,4 +1,4 @@
import { FC, useCallback, useMemo } from 'react' import { FC, useCallback, useEffect, useMemo } from 'react'
import { import {
EdgeById, EdgeById,
NodeById, NodeById,
@@ -28,6 +28,7 @@ function OptionComponent(item: OptionItem) {
} }
const messageId = '__message_item' const messageId = '__message_item'
// Reset this cache when graph changes to ensure fresh search results
const lastGraph: any = { const lastGraph: any = {
graph: null, graph: null,
searchEngine: null searchEngine: null
@@ -48,6 +49,15 @@ export const GraphSearchInput = ({
const { t } = useTranslation() const { t } = useTranslation()
const graph = useGraphStore.use.sigmaGraph() const graph = useGraphStore.use.sigmaGraph()
// Force reset the cache when graph changes
useEffect(() => {
if (graph) {
// Reset cache to ensure fresh search results with new graph data
lastGraph.graph = null;
lastGraph.searchEngine = null;
}
}, [graph]);
const searchEngine = useMemo(() => { const searchEngine = useMemo(() => {
if (lastGraph.graph == graph) { if (lastGraph.graph == graph) {
return lastGraph.searchEngine return lastGraph.searchEngine

View File

@@ -45,6 +45,8 @@ const TabsContent = React.forwardRef<
'ring-offset-background focus-visible:ring-ring mt-2 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none', 'ring-offset-background focus-visible:ring-ring mt-2 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none',
className className
)} )}
// We no longer force mounting of inactive tabs
// This prevents the Graph component from being mounted when it's not the active tab
{...props} {...props}
/> />
)) ))

View File

@@ -128,12 +128,21 @@ const GraphViewer = () => {
const enableNodeDrag = useSettingsStore.use.enableNodeDrag() const enableNodeDrag = useSettingsStore.use.enableNodeDrag()
const renderEdgeLabels = useSettingsStore.use.showEdgeLabel() const renderEdgeLabels = useSettingsStore.use.showEdgeLabel()
// Ensure rendering is enabled when tab becomes visible // Handle component mount/unmount and tab visibility
useEffect(() => { useEffect(() => {
// When component mounts or tab becomes visible
if (isGraphTabVisible && !shouldRender && !isFetching && !initAttemptedRef.current) { if (isGraphTabVisible && !shouldRender && !isFetching && !initAttemptedRef.current) {
// If tab is visible but graph is not rendering, try to enable rendering // If tab is visible but graph is not rendering, try to enable rendering
useGraphStore.getState().setShouldRender(true) useGraphStore.getState().setShouldRender(true)
initAttemptedRef.current = true initAttemptedRef.current = true
console.log('Graph viewer initialized')
}
// Cleanup function when component unmounts
return () => {
// If we're navigating away from the graph tab completely (not just switching tabs)
// we would clean up here, but for now we want to preserve the WebGL context
console.log('Graph viewer cleanup')
} }
}, [isGraphTabVisible, shouldRender, isFetching]) }, [isGraphTabVisible, shouldRender, isFetching])
@@ -165,67 +174,72 @@ const GraphViewer = () => {
[selectedNode] [selectedNode]
) )
// If we shouldn't render, show loading state or empty state // Only render the SigmaContainer when the tab is visible
if (!shouldRender) {
return (
<div className="flex h-full w-full items-center justify-center bg-background">
{isFetching ? (
<div className="text-center">
<div className="mb-2 h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"></div>
<p>Reloading Graph Data...</p>
</div>
) : (
<div className="text-center text-muted-foreground">
{/* Empty or hint message */}
</div>
)}
</div>
)
}
return ( return (
<SigmaContainer <div className="relative h-full w-full">
settings={sigmaSettings} {isGraphTabVisible ? (
className="!bg-background !size-full overflow-hidden" // Only render SigmaContainer when tab is visible
ref={sigmaRef} <SigmaContainer
> settings={sigmaSettings}
<GraphControl /> className="!bg-background !size-full overflow-hidden"
ref={sigmaRef}
>
<GraphControl />
{enableNodeDrag && <GraphEvents />} {enableNodeDrag && <GraphEvents />}
<FocusOnNode node={autoFocusedNode} move={moveToSelectedNode} /> <FocusOnNode node={autoFocusedNode} move={moveToSelectedNode} />
<div className="absolute top-2 left-2 flex items-start gap-2"> <div className="absolute top-2 left-2 flex items-start gap-2">
<GraphLabels /> <GraphLabels />
{showNodeSearchBar && ( {showNodeSearchBar && (
<GraphSearch <GraphSearch
value={searchInitSelectedNode} value={searchInitSelectedNode}
onFocus={onSearchFocus} onFocus={onSearchFocus}
onChange={onSearchSelect} onChange={onSearchSelect}
/> />
)} )}
</div> </div>
<div className="bg-background/60 absolute bottom-2 left-2 flex flex-col rounded-xl border-2 backdrop-blur-lg"> <div className="bg-background/60 absolute bottom-2 left-2 flex flex-col rounded-xl border-2 backdrop-blur-lg">
<Settings /> <Settings />
<ZoomControl /> <ZoomControl />
<LayoutsControl /> <LayoutsControl />
<FullScreenControl /> <FullScreenControl />
{/* <ThemeToggle /> */} {/* <ThemeToggle /> */}
</div> </div>
{showPropertyPanel && ( {showPropertyPanel && (
<div className="absolute top-2 right-2"> <div className="absolute top-2 right-2">
<PropertiesView /> <PropertiesView />
</div>
)}
{/* <div className="absolute bottom-2 right-2 flex flex-col rounded-xl border-2">
<MiniMap width="100px" height="100px" />
</div> */}
<SettingsDisplay />
</SigmaContainer>
) : (
// Placeholder when tab is not visible
<div className="flex h-full w-full items-center justify-center">
<div className="text-center text-muted-foreground">
{/* Placeholder content */}
</div>
</div> </div>
)} )}
{/* <div className="absolute bottom-2 right-2 flex flex-col rounded-xl border-2"> {/* Loading overlay - shown when data is loading */}
<MiniMap width="100px" height="100px" /> {isFetching && (
</div> */} <div className="absolute inset-0 flex items-center justify-center bg-background/80 z-10">
<div className="text-center">
<SettingsDisplay /> <div className="mb-2 h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"></div>
</SigmaContainer> <p>Loading Graph Data...</p>
</div>
</div>
)}
</div>
) )
} }

View File

@@ -137,15 +137,23 @@ const fetchGraph = async (label: string, maxDepth: number, minDegree: number) =>
return rawGraph return rawGraph
} }
// Create a new graph instance with the raw graph data
const createSigmaGraph = (rawGraph: RawGraph | null) => { const createSigmaGraph = (rawGraph: RawGraph | null) => {
// Always create a new graph instance
const graph = new DirectedGraph() const graph = new DirectedGraph()
// Add nodes from raw graph data
for (const rawNode of rawGraph?.nodes ?? []) { for (const rawNode of rawGraph?.nodes ?? []) {
// Ensure we have fresh random positions for nodes
seedrandom(rawNode.id + Date.now().toString(), { global: true })
const x = Math.random()
const y = Math.random()
graph.addNode(rawNode.id, { graph.addNode(rawNode.id, {
label: rawNode.labels.join(', '), label: rawNode.labels.join(', '),
color: rawNode.color, color: rawNode.color,
x: rawNode.x, x: x,
y: rawNode.y, y: y,
size: rawNode.size, size: rawNode.size,
// for node-border // for node-border
borderColor: Constants.nodeBorderColor, borderColor: Constants.nodeBorderColor,
@@ -153,6 +161,7 @@ const createSigmaGraph = (rawGraph: RawGraph | null) => {
}) })
} }
// Add edges from raw graph data
for (const rawEdge of rawGraph?.edges ?? []) { for (const rawEdge of rawGraph?.edges ?? []) {
rawEdge.dynamicId = graph.addDirectedEdge(rawEdge.source, rawEdge.target, { rawEdge.dynamicId = graph.addDirectedEdge(rawEdge.source, rawEdge.target, {
label: rawEdge.type || undefined label: rawEdge.type || undefined
@@ -204,21 +213,19 @@ const useLightrangeGraph = () => {
// Track if a fetch is in progress to prevent multiple simultaneous fetches // Track if a fetch is in progress to prevent multiple simultaneous fetches
const fetchInProgressRef = useRef(false) const fetchInProgressRef = useRef(false)
// Data fetching logic - use a separate effect with minimal dependencies to prevent multiple triggers // Data fetching logic - simplified but preserving TAB visibility check
useEffect(() => { useEffect(() => {
// Skip if fetch is already in progress // Skip if fetch is already in progress
if (fetchInProgressRef.current) { if (fetchInProgressRef.current) {
return return
} }
// If there's no query label, reset the graph only if it hasn't been reset already // If there's no query label, reset the graph
if (!queryLabel) { if (!queryLabel) {
if (rawGraph !== null || sigmaGraph !== null) { if (rawGraph !== null || sigmaGraph !== null) {
const state = useGraphStore.getState() const state = useGraphStore.getState()
state.reset() state.reset()
state.setSigmaGraph(new DirectedGraph())
state.setGraphLabels(['*']) state.setGraphLabels(['*'])
// Reset fetch attempt flags when resetting graph
state.setGraphDataFetchAttempted(false) state.setGraphDataFetchAttempted(false)
state.setLabelsFetchAttempted(false) state.setLabelsFetchAttempted(false)
} }
@@ -227,21 +234,21 @@ const useLightrangeGraph = () => {
return return
} }
// Check if we've already attempted to fetch this data in this session // Check if parameters have changed
const graphDataFetchAttempted = useGraphStore.getState().graphDataFetchAttempted if (!isFetching && !fetchInProgressRef.current &&
(paramsChanged || !useGraphStore.getState().graphDataFetchAttempted)) {
// Fetch data if:
// 1. We're not already fetching // Only fetch data if the Graph tab is visible
// 2. We haven't attempted to fetch in this session OR parameters have changed if (!isGraphTabVisible) {
if (!isFetching && !fetchInProgressRef.current && (!graphDataFetchAttempted || paramsChanged)) { console.log('Graph tab not visible, skipping data fetch');
// Set flag to prevent multiple fetches return;
}
// Set flags
fetchInProgressRef.current = true fetchInProgressRef.current = true
// Set global flag to indicate we've attempted to fetch in this session
useGraphStore.getState().setGraphDataFetchAttempted(true) useGraphStore.getState().setGraphDataFetchAttempted(true)
const state = useGraphStore.getState() const state = useGraphStore.getState()
// Set rendering control state
state.setIsFetching(true) state.setIsFetching(true)
state.setShouldRender(false) // Disable rendering during data loading state.setShouldRender(false) // Disable rendering during data loading
@@ -256,25 +263,29 @@ const useLightrangeGraph = () => {
// Update parameter reference // Update parameter reference
prevParamsRef.current = { queryLabel, maxQueryDepth, minDegree } prevParamsRef.current = { queryLabel, maxQueryDepth, minDegree }
console.log('Fetching graph data (once per session unless params change)...') console.log('Fetching graph data...')
// Use a local copy of the parameters to avoid closure issues // Use a local copy of the parameters
const currentQueryLabel = queryLabel const currentQueryLabel = queryLabel
const currentMaxQueryDepth = maxQueryDepth const currentMaxQueryDepth = maxQueryDepth
const currentMinDegree = minDegree const currentMinDegree = minDegree
// Fetch graph data
fetchGraph(currentQueryLabel, currentMaxQueryDepth, currentMinDegree).then((data) => { fetchGraph(currentQueryLabel, currentMaxQueryDepth, currentMinDegree).then((data) => {
const state = useGraphStore.getState() const state = useGraphStore.getState()
// Reset state
state.reset()
// Create and set new graph directly
const newSigmaGraph = createSigmaGraph(data) const newSigmaGraph = createSigmaGraph(data)
data?.buildDynamicMap() data?.buildDynamicMap()
// Update all graph data at once to minimize UI flicker // Set new graph data
state.clearSelection()
state.setMoveToSelectedNode(false)
state.setSigmaGraph(newSigmaGraph) state.setSigmaGraph(newSigmaGraph)
state.setRawGraph(data) state.setRawGraph(data)
// Extract labels from current graph data for local use // Extract labels from current graph data
if (data) { if (data) {
const labelSet = new Set<string>() const labelSet = new Set<string>()
for (const node of data.nodes) { for (const node of data.nodes) {
@@ -290,16 +301,15 @@ const useLightrangeGraph = () => {
const sortedLabels = Array.from(labelSet).sort() const sortedLabels = Array.from(labelSet).sort()
state.setGraphLabels(['*', ...sortedLabels]) state.setGraphLabels(['*', ...sortedLabels])
} else { } else {
// Ensure * is there eventhough there is no graph data
state.setGraphLabels(['*']) state.setGraphLabels(['*'])
} }
// Mark data as loaded and initial load completed // Update flags
dataLoadedRef.current = true dataLoadedRef.current = true
initialLoadRef.current = true initialLoadRef.current = true
fetchInProgressRef.current = false fetchInProgressRef.current = false
// Reset camera view by triggering FocusOnNode component // Reset camera view
state.setMoveToSelectedNode(true) state.setMoveToSelectedNode(true)
// Enable rendering if the tab is visible // Enable rendering if the tab is visible
@@ -307,30 +317,42 @@ const useLightrangeGraph = () => {
state.setIsFetching(false) state.setIsFetching(false)
}).catch((error) => { }).catch((error) => {
console.error('Error fetching graph data:', error) console.error('Error fetching graph data:', error)
// Reset fetching state and remove flag in case of error
// Reset state on error
const state = useGraphStore.getState() const state = useGraphStore.getState()
state.setIsFetching(false) state.setIsFetching(false)
state.setShouldRender(isGraphTabVisible) // Restore rendering state state.setShouldRender(isGraphTabVisible)
dataLoadedRef.current = false // Allow retry dataLoadedRef.current = false
fetchInProgressRef.current = false fetchInProgressRef.current = false
// Reset global flag to allow retry
state.setGraphDataFetchAttempted(false) state.setGraphDataFetchAttempted(false)
}) })
} }
}, [queryLabel, maxQueryDepth, minDegree, isFetching, paramsChanged, isGraphTabVisible, rawGraph, sigmaGraph]) // Added missing dependencies }, [queryLabel, maxQueryDepth, minDegree, isFetching, paramsChanged, isGraphTabVisible, rawGraph, sigmaGraph])
// Update rendering state when tab visibility changes // Update rendering state and handle tab visibility changes
useEffect(() => { useEffect(() => {
// Only update rendering state if data is loaded and not fetching // When tab becomes visible
if (rawGraph) { if (isGraphTabVisible) {
useGraphStore.getState().setShouldRender(isGraphTabVisible) // If we have data, enable rendering
if (rawGraph) {
useGraphStore.getState().setShouldRender(true)
}
// We no longer reset the fetch attempted flag here to prevent continuous API calls
} else {
// When tab becomes invisible, disable rendering
useGraphStore.getState().setShouldRender(false)
} }
}, [isGraphTabVisible, rawGraph]) }, [isGraphTabVisible, rawGraph])
const lightrageGraph = useCallback(() => { const lightrageGraph = useCallback(() => {
// If we already have a graph instance, return it
if (sigmaGraph) { if (sigmaGraph) {
return sigmaGraph as Graph<NodeType, EdgeType> return sigmaGraph as Graph<NodeType, EdgeType>
} }
// If no graph exists yet, create a new one and store it
console.log('Creating new Sigma graph instance')
const graph = new DirectedGraph() const graph = new DirectedGraph()
useGraphStore.getState().setSigmaGraph(graph) useGraphStore.getState().setSigmaGraph(graph)
return graph as Graph<NodeType, EdgeType> return graph as Graph<NodeType, EdgeType>

View File

@@ -144,25 +144,38 @@ const useGraphStoreBase = create<GraphState>()((set, get) => ({
selectedEdge: null, selectedEdge: null,
focusedEdge: null focusedEdge: null
}), }),
reset: () => reset: () => {
// Get the existing graph
const existingGraph = get().sigmaGraph;
// If we have an existing graph, clear it by removing all nodes
if (existingGraph) {
const nodes = Array.from(existingGraph.nodes());
nodes.forEach(node => existingGraph.dropNode(node));
}
set({ set({
selectedNode: null, selectedNode: null,
focusedNode: null, focusedNode: null,
selectedEdge: null, selectedEdge: null,
focusedEdge: null, focusedEdge: null,
rawGraph: null, rawGraph: null,
sigmaGraph: null, // Keep the existing graph instance but with cleared data
graphLabels: ['*'], graphLabels: ['*'],
moveToSelectedNode: false, moveToSelectedNode: false,
shouldRender: false shouldRender: false
}), });
},
setRawGraph: (rawGraph: RawGraph | null) => setRawGraph: (rawGraph: RawGraph | null) =>
set({ set({
rawGraph rawGraph
}), }),
setSigmaGraph: (sigmaGraph: DirectedGraph | null) => set({ sigmaGraph }), setSigmaGraph: (sigmaGraph: DirectedGraph | null) => {
// 直接替换图形实例不尝试保留WebGL上下文
set({ sigmaGraph });
},
setGraphLabels: (labels: string[]) => set({ graphLabels: labels }), setGraphLabels: (labels: string[]) => set({ graphLabels: labels }),