refactor: 重构前端代码并增加注释
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import type { GraphData, Node, SearchNode } from '../types/graph';
|
||||
import { graphApi } from '../services/graphApi';
|
||||
import { SAMPLE_GRAPH_DATA } from '../config/sampleData';
|
||||
|
||||
/**
|
||||
* 知识图谱数据管理 Hook
|
||||
* 负责图谱数据的加载、搜索和节点选择
|
||||
*/
|
||||
export const useGraphData = () => {
|
||||
const [graphData, setGraphData] = useState<GraphData>({ nodes: [], edges: [] });
|
||||
const [selectedNode, setSelectedNode] = useState<Node | null>(null);
|
||||
const [hoveredNode, setHoveredNode] = useState<Node | null>(null);
|
||||
const [searchResults, setSearchResults] = useState<SearchNode[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// 从后端加载图谱数据
|
||||
const loadGraphData = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await graphApi.getData();
|
||||
|
||||
// 如果后端返回空数据,使用示例数据
|
||||
if (data.nodes.length === 0) {
|
||||
setGraphData(SAMPLE_GRAPH_DATA);
|
||||
} else {
|
||||
setGraphData(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load graph data:', error);
|
||||
// API 失败时使用示例数据作为降级方案
|
||||
setGraphData(SAMPLE_GRAPH_DATA);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 搜索节点(前端过滤,可根据需要切换到后端搜索)
|
||||
const handleSearch = useCallback((query: string) => {
|
||||
const results = graphData.nodes
|
||||
.filter((node: Node) =>
|
||||
node.label.toLowerCase().includes(query.toLowerCase()) ||
|
||||
node.id.toLowerCase().includes(query.toLowerCase())
|
||||
)
|
||||
.map((node: Node) => ({
|
||||
id: node.id,
|
||||
label: node.label,
|
||||
type: node.type,
|
||||
matched: true,
|
||||
}));
|
||||
setSearchResults(results);
|
||||
}, [graphData]);
|
||||
|
||||
// 通过 ID 选择节点(用于搜索结果点击)
|
||||
const handleNodeSelectById = useCallback((nodeId: string) => {
|
||||
const node = graphData.nodes.find((n: Node) => n.id === nodeId);
|
||||
if (node) {
|
||||
setSelectedNode(node);
|
||||
}
|
||||
}, [graphData.nodes]);
|
||||
|
||||
// 选择节点(用于图谱点击)
|
||||
const handleNodeSelect = useCallback((node: Node) => {
|
||||
setSelectedNode(node);
|
||||
}, []);
|
||||
|
||||
// 组件挂载时加载数据
|
||||
useEffect(() => {
|
||||
loadGraphData();
|
||||
}, [loadGraphData]);
|
||||
|
||||
return {
|
||||
graphData,
|
||||
selectedNode,
|
||||
hoveredNode,
|
||||
searchResults,
|
||||
loading,
|
||||
setHoveredNode,
|
||||
setSelectedNode,
|
||||
setSearchResults,
|
||||
handleSearch,
|
||||
handleNodeSelectById,
|
||||
handleNodeSelect,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user