Merge pull request #725 from wbkd/refactor/element-updates

Refactor/element updates
This commit is contained in:
Moritz Klack
2020-11-26 14:28:16 +01:00
committed by GitHub
9 changed files with 150 additions and 192 deletions
+22 -5
View File
@@ -6,10 +6,10 @@ const onNodeDragStop = (event, node) => console.log('drag stop', node);
const onElementClick = (event, element) => console.log('click', element); const onElementClick = (event, element) => console.log('click', element);
const initialElements = [ const initialElements = [
{ id: '1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 } }, { id: '1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 }, className: 'light' },
{ id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 } }, { id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 }, className: 'light' },
{ id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 } }, { id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 }, className: 'light' },
{ id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 } }, { id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 }, className: 'light' },
{ id: 'e1-2', source: '1', target: '2', animated: true }, { id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3' }, { id: 'e1-3', source: '1', target: '3' },
]; ];
@@ -40,9 +40,23 @@ const BasicFlow = () => {
}; };
const logToObject = () => console.log(rfInstance.toObject()); const logToObject = () => console.log(rfInstance.toObject());
const resetTransform = () => rfInstance.setTransform({ x: 0, y: 0, zoom: 1 }); const resetTransform = () => rfInstance.setTransform({ x: 0, y: 0, zoom: 1 });
const toggleClassnames = () => {
setElements((elms) => {
return elms.map((el) => {
if (isNode(el)) {
return {
...el,
className: el.className === 'light' ? 'dark' : 'light',
};
}
return el;
});
});
};
return ( return (
<ReactFlow <ReactFlow
elements={elements} elements={elements}
@@ -65,6 +79,9 @@ const BasicFlow = () => {
<button onClick={updatePos} style={{ marginRight: 5 }}> <button onClick={updatePos} style={{ marginRight: 5 }}>
change pos change pos
</button> </button>
<button onClick={toggleClassnames} style={{ marginRight: 5 }}>
toggle classnames
</button>
<button onClick={logToObject}>toObject</button> <button onClick={logToObject}>toObject</button>
</div> </div>
</ReactFlow> </ReactFlow>
+5
View File
@@ -140,6 +140,11 @@ nav a.active:before {
color: #f8f8f8; color: #f8f8f8;
} }
.react-flow__node.dark {
background: #557;
color: #f8f8f8;
}
.react-flow__node-selectorNode { .react-flow__node-selectorNode {
font-size: 12px; font-size: 12px;
background: #f0f2f3; background: #f0f2f3;
+4 -133
View File
@@ -1,147 +1,18 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import isEqual from 'fast-deep-equal';
import { useStoreState, useStoreActions } from '../../store/hooks'; import { useStoreActions } from '../../store/hooks';
import { parseElement, isNode, isEdge } from '../../utils/graph'; import { Elements } from '../../types';
import { Elements, Node, Edge, FlowElement } from '../../types';
interface ElementUpdaterProps { interface ElementUpdaterProps {
elements: Elements; elements: Elements;
} }
const ElementUpdater = ({ elements }: ElementUpdaterProps) => { const ElementUpdater = ({ elements }: ElementUpdaterProps) => {
const stateElements = useStoreState((state) => state.elements);
const setElements = useStoreActions((actions) => actions.setElements); const setElements = useStoreActions((actions) => actions.setElements);
useEffect(() => { useEffect(() => {
const nextElements: Elements = elements.map((propElement) => { setElements(elements);
const existingElement = stateElements.find((el) => el.id === propElement.id?.toString()); }, [elements]);
if (existingElement) {
const data = !isEqual(existingElement.data, propElement.data)
? { ...existingElement.data, ...propElement.data }
: existingElement.data;
const style = !isEqual(existingElement.style, propElement.style)
? { ...existingElement.style, ...propElement.style }
: existingElement.style;
const elementProps = {
...existingElement,
};
if (typeof data !== 'undefined') {
elementProps.data = data;
}
if (typeof style !== 'undefined') {
elementProps.style = style;
}
if (typeof propElement.className !== 'undefined') {
elementProps.className = propElement.className;
}
if (typeof propElement.isHidden !== 'undefined') {
elementProps.isHidden = propElement.isHidden;
}
if (typeof propElement.type !== 'undefined') {
elementProps.type = propElement.type;
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
if (isNode(existingElement) && propElement.type !== existingElement.type) {
existingElement.__rf.width = null;
existingElement.__rf.height = null;
}
}
if (isNode(existingElement)) {
const propNode = propElement as Node;
const nodeProps = elementProps as Node;
const positionChanged =
existingElement.position.x !== propNode.position.x || existingElement.position.y !== propNode.position.y;
if (positionChanged) {
nodeProps.__rf = {
...existingElement.__rf,
position: propNode.position,
};
nodeProps.position = propNode.position;
}
if (typeof propNode.draggable !== 'undefined') {
nodeProps.draggable = propNode.draggable;
}
if (typeof propNode.selectable !== 'undefined') {
nodeProps.selectable = propNode.selectable;
}
if (typeof propNode.connectable !== 'undefined') {
nodeProps.connectable = propNode.connectable;
}
return nodeProps;
} else if (isEdge(existingElement)) {
const propEdge = propElement as Edge;
const edgeProps = elementProps as Edge;
const labelStyle = !isEqual(existingElement.labelStyle, propEdge.labelStyle)
? { ...existingElement.labelStyle, ...propEdge.labelStyle }
: existingElement.labelStyle;
const labelBgStyle = !isEqual(existingElement.labelBgStyle, propEdge.labelBgStyle)
? { ...existingElement.labelBgStyle, ...propEdge.labelBgStyle }
: existingElement.labelBgStyle;
if (typeof propEdge.label !== 'undefined') {
edgeProps.label = propEdge.label;
}
if (typeof labelStyle !== 'undefined') {
edgeProps.labelStyle = labelStyle;
}
if (typeof propEdge.labelShowBg !== 'undefined') {
edgeProps.labelShowBg = propEdge.labelShowBg;
}
if (typeof propEdge.labelBgPadding !== 'undefined') {
edgeProps.labelBgPadding = propEdge.labelBgPadding;
}
if (typeof propEdge.labelBgBorderRadius !== 'undefined') {
edgeProps.labelBgBorderRadius = propEdge.labelBgBorderRadius;
}
if (typeof labelBgStyle !== 'undefined') {
edgeProps.labelBgStyle = labelBgStyle;
}
if (typeof propEdge.animated !== 'undefined') {
edgeProps.animated = propEdge.animated;
}
if (typeof propEdge.arrowHeadType !== 'undefined') {
edgeProps.arrowHeadType = propEdge.arrowHeadType;
}
return edgeProps;
}
}
return parseElement(propElement) as FlowElement;
});
const elementsChanged: boolean = !isEqual(stateElements, nextElements);
if (elementsChanged) {
setElements(nextElements);
}
}, [elements, stateElements]);
return null; return null;
}; };
+10 -1
View File
@@ -1,7 +1,16 @@
import { HandleElement, Position } from '../../types'; import { HandleElement, Position } from '../../types';
import { getDimensions } from '../../utils'; import { getDimensions } from '../../utils';
export const getHandleBounds = ( export const getHandleBounds = (nodeElement: HTMLDivElement, scale: number) => {
const bounds = nodeElement.getBoundingClientRect();
return {
source: getHandleBoundsByHandleType('.source', nodeElement, bounds, scale),
target: getHandleBoundsByHandleType('.target', nodeElement, bounds, scale),
};
};
export const getHandleBoundsByHandleType = (
selector: string, selector: string,
nodeElement: HTMLDivElement, nodeElement: HTMLDivElement,
parentBounds: ClientRect | DOMRect, parentBounds: ClientRect | DOMRect,
+10 -13
View File
@@ -35,6 +35,7 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
snapToGrid, snapToGrid,
snapGrid, snapGrid,
isDragging, isDragging,
resizeObserver,
}: WrapNodeProps) => { }: WrapNodeProps) => {
const updateNodeDimensions = useStoreActions((actions) => actions.updateNodeDimensions); const updateNodeDimensions = useStoreActions((actions) => actions.updateNodeDimensions);
const addSelectedElements = useStoreActions((actions) => actions.addSelectedElements); const addSelectedElements = useStoreActions((actions) => actions.addSelectedElements);
@@ -160,24 +161,19 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
useEffect(() => { useEffect(() => {
if (nodeElement.current && !isHidden) { if (nodeElement.current && !isHidden) {
updateNodeDimensions({ id, nodeElement: nodeElement.current }); updateNodeDimensions({ id, nodeElement: nodeElement.current });
}
}, [id, isHidden]);
const resizeObserver = new ResizeObserver(() => { useEffect(() => {
if (nodeElement.current) { if (nodeElement.current) {
updateNodeDimensions({ id, nodeElement: nodeElement.current }); const currNode = nodeElement.current;
} resizeObserver.observe(currNode);
});
resizeObserver.observe(nodeElement.current); return () => resizeObserver.unobserve(currNode);
return () => {
if (resizeObserver && nodeElement.current) {
resizeObserver.unobserve(nodeElement.current);
}
};
} }
return; return;
}, [id, isHidden]); }, []);
if (isHidden) { if (isHidden) {
return null; return null;
@@ -213,6 +209,7 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
onMouseLeave={onMouseLeaveHandler} onMouseLeave={onMouseLeaveHandler}
onContextMenu={onContextMenuHandler} onContextMenu={onContextMenuHandler}
onClick={onSelectNodeHandler} onClick={onSelectNodeHandler}
data-id={id}
> >
<Provider value={id}> <Provider value={id}>
<NodeComponent <NodeComponent
+16 -1
View File
@@ -1,7 +1,7 @@
import React, { memo, useMemo, ComponentType, MouseEvent } from 'react'; import React, { memo, useMemo, ComponentType, MouseEvent } from 'react';
import { getNodesInside } from '../../utils/graph'; import { getNodesInside } from '../../utils/graph';
import { useStoreState } from '../../store/hooks'; import { useStoreState, useStoreActions } from '../../store/hooks';
import { Node, NodeTypesType, WrapNodeProps, Edge } from '../../types'; import { Node, NodeTypesType, WrapNodeProps, Edge } from '../../types';
interface NodeRendererProps { interface NodeRendererProps {
@@ -27,6 +27,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
const elementsSelectable = useStoreState((state) => state.elementsSelectable); const elementsSelectable = useStoreState((state) => state.elementsSelectable);
const viewportBox = useStoreState((state) => state.viewportBox); const viewportBox = useStoreState((state) => state.viewportBox);
const nodes = useStoreState((state) => state.nodes); const nodes = useStoreState((state) => state.nodes);
const batchUpdateNodeDimensions = useStoreActions((actions) => actions.batchUpdateNodeDimensions);
const visibleNodes = props.onlyRenderVisibleElements ? getNodesInside(nodes, viewportBox, transform, true) : nodes; const visibleNodes = props.onlyRenderVisibleElements ? getNodesInside(nodes, viewportBox, transform, true) : nodes;
@@ -37,6 +38,19 @@ const NodeRenderer = (props: NodeRendererProps) => {
[transform[0], transform[1], transform[2]] [transform[0], transform[1], transform[2]]
); );
const resizeObserver = useMemo(
() =>
new ResizeObserver((entries) => {
const updates = entries.map((entry) => ({
id: entry.target.getAttribute('data-id') as string,
nodeElement: entry.target as HTMLDivElement,
}));
batchUpdateNodeDimensions({ updates });
}),
[]
);
return ( return (
<div className="react-flow__nodes" style={transformStyle}> <div className="react-flow__nodes" style={transformStyle}>
{visibleNodes.map((node) => { {visibleNodes.map((node) => {
@@ -81,6 +95,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
isDraggable={isDraggable} isDraggable={isDraggable}
isSelectable={isSelectable} isSelectable={isSelectable}
isConnectable={isConnectable} isConnectable={isConnectable}
resizeObserver={resizeObserver}
/> />
); );
})} })}
+79 -38
View File
@@ -1,9 +1,9 @@
import { createStore, Action, action, ActionOn, actionOn, Thunk, thunk, computed, Computed } from 'easy-peasy'; import { createStore, Action, action, Thunk, thunk, computed, Computed } from 'easy-peasy';
import isEqual from 'fast-deep-equal'; import isEqual from 'fast-deep-equal';
import { Selection as D3Selection, ZoomBehavior } from 'd3'; import { Selection as D3Selection, ZoomBehavior } from 'd3';
import { getDimensions } from '../utils'; import { getDimensions } from '../utils';
import { getNodesInside, getConnectedEdges, getRectOfNodes, isNode, isEdge } from '../utils/graph'; import { getNodesInside, getConnectedEdges, getRectOfNodes, isNode, isEdge, parseElement } from '../utils/graph';
import { getHandleBounds } from '../components/Nodes/utils'; import { getHandleBounds } from '../components/Nodes/utils';
import { import {
@@ -33,6 +33,10 @@ type NodeDimensionUpdate = {
nodeElement: HTMLDivElement; nodeElement: HTMLDivElement;
}; };
type NodeDimensionUpdates = {
updates: NodeDimensionUpdate[];
};
type InitD3Zoom = { type InitD3Zoom = {
d3Zoom: ZoomBehavior<Element, unknown>; d3Zoom: ZoomBehavior<Element, unknown>;
d3Selection: D3Selection<Element, unknown, null, undefined>; d3Selection: D3Selection<Element, unknown, null, undefined>;
@@ -90,8 +94,8 @@ export interface StoreModel {
setElements: Action<StoreModel, Elements>; setElements: Action<StoreModel, Elements>;
batchUpdateNodeDimensions: Action<StoreModel, NodeDimensionUpdates>;
updateNodeDimensions: Action<StoreModel, NodeDimensionUpdate>; updateNodeDimensions: Action<StoreModel, NodeDimensionUpdate>;
updateNodeHandlePositions: ActionOn<StoreModel>;
updateNodePos: Action<StoreModel, NodePosUpdate>; updateNodePos: Action<StoreModel, NodePosUpdate>;
updateNodePosDiff: Action<StoreModel, NodeDiffUpdate>; updateNodePosDiff: Action<StoreModel, NodeDiffUpdate>;
@@ -196,54 +200,91 @@ export const storeModel: StoreModel = {
state.onConnectEnd = onConnectEnd; state.onConnectEnd = onConnectEnd;
}), }),
setElements: action((state, elements) => { setElements: action((state, propElements) => {
state.elements = elements; // remove deleted elements
}), for (let i = 0; i < state.elements.length; i++) {
const se = state.elements[i];
const elementExistsInProps = propElements.find((pe) => pe.id === se.id);
updateNodeDimensions: action((state, { id, nodeElement }) => { if (!elementExistsInProps) {
const dimensions = getDimensions(nodeElement); state.elements.splice(i, 1);
const matchingNode = state.nodes.find((n) => n.id === id); i--;
}
// only update when size change
if (
!matchingNode ||
(matchingNode.__rf.width === dimensions.width && matchingNode.__rf.height === dimensions.height)
) {
return;
} }
state.elements.forEach((n) => { propElements.forEach((el) => {
if (n.id === id && isNode(n)) { const storeElementIndex = state.elements.findIndex((se) => se.id === el.id);
n.__rf.width = dimensions.width;
n.__rf.height = dimensions.height; // update existing element
if (storeElementIndex !== -1) {
const storeElement = state.elements[storeElementIndex];
if (isNode(storeElement)) {
const propNode = el as Node;
const positionChanged =
storeElement.position.x !== propNode.position.x || storeElement.position.y !== propNode.position.y;
const typeChanged = typeof propNode.type !== 'undefined' && propNode.type !== storeElement.type;
state.elements[storeElementIndex] = {
...storeElement,
...propNode,
};
if (positionChanged) {
(state.elements[storeElementIndex] as Node).__rf.position = propNode.position;
}
if (typeChanged) {
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
(state.elements[storeElementIndex] as Node).__rf.width = null;
}
} else {
state.elements[storeElementIndex] = {
...storeElement,
...el,
};
}
} else {
// add new element
state.elements.push(parseElement(el));
} }
}); });
}), }),
updateNodeHandlePositions: actionOn( batchUpdateNodeDimensions: action((state, { updates }) => {
(actions) => actions.updateNodeDimensions, updates.forEach((update) => {
(state, target) => { const dimensions = getDimensions(update.nodeElement);
const { nodeElement, id } = target.payload; const matchingIndex = state.elements.findIndex((n) => n.id === update.id);
const matchingNode = state.nodes.find((n) => n.id === id); const matchingNode = state.elements[matchingIndex] as Node;
if (!matchingNode) { if (
return; matchingIndex !== -1 &&
dimensions.width &&
dimensions.height &&
(matchingNode.__rf.width !== dimensions.width || matchingNode.__rf.height !== dimensions.height)
) {
const handleBounds = getHandleBounds(update.nodeElement, state.transform[2]);
(state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
(state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
(state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
} }
});
}),
const bounds = nodeElement.getBoundingClientRect(); updateNodeDimensions: action((state, { id, nodeElement }) => {
const dimensions = getDimensions(nodeElement);
const matchingIndex = state.elements.findIndex((n) => n.id === id);
const handleBounds = { if (matchingIndex !== -1 && dimensions.width && dimensions.height) {
source: getHandleBounds('.source', nodeElement, bounds, state.transform[2]), const handleBounds = getHandleBounds(nodeElement, state.transform[2]);
target: getHandleBounds('.target', nodeElement, bounds, state.transform[2]),
};
state.elements.forEach((n) => { (state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
if (n.id === id && isNode(n)) { (state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
n.__rf.handleBounds = handleBounds; (state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
}
});
} }
), }),
updateNodePos: action((state, { id, pos }) => { updateNodePos: action((state, { id, pos }) => {
let position: XYPosition = pos; let position: XYPosition = pos;
+1
View File
@@ -224,6 +224,7 @@ export interface WrapNodeProps {
snapToGrid?: boolean; snapToGrid?: boolean;
snapGrid?: SnapGrid; snapGrid?: SnapGrid;
isDragging?: boolean; isDragging?: boolean;
resizeObserver: ResizeObserver;
} }
export type FitViewParams = { export type FitViewParams = {
+3 -1
View File
@@ -1,6 +1,8 @@
import { DraggableEvent } from 'react-draggable'; import { DraggableEvent } from 'react-draggable';
import { MouseEvent as ReactMouseEvent } from 'react'; import { MouseEvent as ReactMouseEvent } from 'react';
import { Dimensions } from '../types';
export const isInputDOMNode = (e: ReactMouseEvent | DraggableEvent | KeyboardEvent) => { export const isInputDOMNode = (e: ReactMouseEvent | DraggableEvent | KeyboardEvent) => {
const target = e?.target as HTMLElement; const target = e?.target as HTMLElement;
@@ -9,7 +11,7 @@ export const isInputDOMNode = (e: ReactMouseEvent | DraggableEvent | KeyboardEve
); );
}; };
export const getDimensions = (node: HTMLDivElement) => ({ export const getDimensions = (node: HTMLDivElement): Dimensions => ({
width: node.offsetWidth, width: node.offsetWidth,
height: node.offsetHeight, height: node.offsetHeight,
}); });