feat(elementUpdater): apply position and style changes #220
This commit is contained in:
@@ -6,7 +6,7 @@ import { parseElement, isNode, isEdge } from '../utils/graph';
|
||||
import { Elements, Node, Edge } from '../types';
|
||||
|
||||
const useElementUpdater = (elements: Elements): void => {
|
||||
const state = useStoreState(s => ({
|
||||
const state = useStoreState((s) => ({
|
||||
nodes: s.nodes,
|
||||
edges: s.edges,
|
||||
transform: s.transform,
|
||||
@@ -14,37 +14,51 @@ const useElementUpdater = (elements: Elements): void => {
|
||||
snapGrid: s.snapGrid,
|
||||
}));
|
||||
|
||||
const setNodes = useStoreActions(a => a.setNodes);
|
||||
const setEdges = useStoreActions(a => a.setEdges);
|
||||
const setNodes = useStoreActions((a) => a.setNodes);
|
||||
const setEdges = useStoreActions((a) => a.setEdges);
|
||||
|
||||
useEffect(() => {
|
||||
const nodes = elements.filter(isNode) as Node[];
|
||||
const edges = elements
|
||||
.filter(isEdge)
|
||||
.map(e =>
|
||||
parseElement(e, state.transform, state.snapToGrid, state.snapGrid)
|
||||
) as Edge[];
|
||||
.map((e) => parseElement(e, state.transform, state.snapToGrid, state.snapGrid)) as Edge[];
|
||||
|
||||
const nextNodes = nodes.map(propNode => {
|
||||
const existingNode = state.nodes.find(n => n.id === propNode.id);
|
||||
const nextNodes = nodes.map((propNode) => {
|
||||
const existingNode = state.nodes.find((n) => n.id === propNode.id);
|
||||
|
||||
if (existingNode) {
|
||||
const data = !isEqual(existingNode.data, propNode.data)
|
||||
? { ...existingNode.data, ...propNode.data }
|
||||
: existingNode.data;
|
||||
|
||||
const style = !isEqual(existingNode.style, propNode.style)
|
||||
? { ...existingNode.style, ...propNode.style }
|
||||
: existingNode.style;
|
||||
|
||||
const positionChanged =
|
||||
existingNode.position.x !== propNode.position.x || existingNode.position.y !== propNode.position.y;
|
||||
|
||||
if (positionChanged) {
|
||||
return {
|
||||
...existingNode,
|
||||
__rg: {
|
||||
...existingNode.__rg,
|
||||
position: propNode.position,
|
||||
},
|
||||
position: propNode.position,
|
||||
data,
|
||||
style,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...existingNode,
|
||||
data,
|
||||
style,
|
||||
};
|
||||
}
|
||||
|
||||
return parseElement(
|
||||
propNode,
|
||||
state.transform,
|
||||
state.snapToGrid,
|
||||
state.snapGrid
|
||||
);
|
||||
return parseElement(propNode, state.transform, state.snapToGrid, state.snapGrid);
|
||||
}) as Node[];
|
||||
|
||||
const nodesChanged: boolean = !isEqual(state.nodes, nextNodes);
|
||||
@@ -57,7 +71,7 @@ const useElementUpdater = (elements: Elements): void => {
|
||||
if (edgesChanged) {
|
||||
setEdges(edges);
|
||||
}
|
||||
});
|
||||
}, [elements, state.nodes, state.edges]);
|
||||
};
|
||||
|
||||
export default useElementUpdater;
|
||||
|
||||
Reference in New Issue
Block a user