Created
July 2, 2020 07:48
-
-
Save az674lqs/d131996baf432b7dac6c0c7f66b124cc to your computer and use it in GitHub Desktop.
G6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import G6, { Graph as GGraph } from "@antv/g6/es"; | |
import _ from "lodash"; | |
import memoizeOne from "memoize-one"; | |
import React from "react"; | |
import { useDispatch, useSelector } from "react-redux"; | |
import { updateCurrentDetailAction } from "../../actions"; | |
import { devConfigsSelector, devNodesSelector } from "../../selectors"; | |
import "./index.scss"; | |
import { OpsNodeShapeFactory } from "./ShapeFactory"; | |
const NodeFactory = memoizeOne(() => new OpsNodeShapeFactory())(); | |
export const Graph = () => { | |
const ref = React.useRef<HTMLDivElement | null>(null); | |
const [graph, setGraph] = React.useState<GGraph | undefined>(undefined); | |
const nodes = useSelector(devConfigsSelector); | |
const data = useSelector(devNodesSelector); | |
const dispatch = useDispatch(); | |
React.useEffect(() => { | |
_.each(nodes, node => { | |
G6.registerNode(NodeFactory.getId(node), { | |
draw: NodeFactory.produce(node), | |
}); | |
}); | |
}, [nodes]); | |
const handleNodeClick = React.useCallback( | |
(e: any) => { | |
const id = e.item._cfg.id; | |
const node = _.find(nodes, n => !!n.hostIp && n.hostIp === id); | |
node && | |
dispatch( | |
updateCurrentDetailAction({ | |
detail: node, | |
}), | |
); | |
}, | |
[dispatch, nodes], | |
); | |
React.useEffect(() => { | |
graph && graph.off("node:click"); | |
graph && graph.on("node:click", handleNodeClick); | |
}, [handleNodeClick]); | |
React.useEffect(() => { | |
if (!graph && ref.current) { | |
const g = new G6.Graph({ | |
container: ref.current, | |
width: ref.current.clientWidth, | |
height: ref.current.clientHeight, | |
modes: { | |
default: ["drag-canvas", "zoom-canvas"], | |
}, | |
layout: { | |
type: "dagre", | |
rankdir: "LR", | |
align: "UL", | |
}, | |
}); | |
setGraph(g); | |
} | |
return () => { | |
graph && graph.destroy(); | |
}; | |
}, [ref, graph]); | |
React.useEffect(() => { | |
if (graph) { | |
const tmpNodes = graph.getNodes(); | |
if (tmpNodes && tmpNodes.length) { | |
try { | |
graph.changeData(data as any); | |
// tslint:disable-next-line: no-empty | |
} catch (e) { | |
console.error(e) | |
} | |
} else { | |
graph.read(data as any); | |
graph.moveTo(320, 30); | |
} | |
} | |
}, [graph, nodes]); | |
return <div ref={ref} className="p-homeGraph" id="ops-home" />; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment