refactor(nodes): use relative positions for children

This commit is contained in:
moklick
2021-11-02 18:58:47 +01:00
parent 8cd969dd84
commit 248b563231
8 changed files with 168 additions and 80 deletions
+4 -4
View File
@@ -35,14 +35,14 @@ const initialNodes: Node[] = [
{ {
id: '4a', id: '4a',
data: { label: 'Node 4a' }, data: { label: 'Node 4a' },
position: { x: 115, y: 215 }, position: { x: 15, y: 15 },
className: 'light', className: 'light',
parentNode: '4', parentNode: '4',
}, },
{ {
id: '4b', id: '4b',
data: { label: 'Node 4b' }, data: { label: 'Node 4b' },
position: { x: 250, y: 250 }, position: { x: 80, y: 80 },
className: 'light', className: 'light',
style: { backgroundColor: 'rgba(255, 0, 0, .2)' }, style: { backgroundColor: 'rgba(255, 0, 0, .2)' },
parentNode: '4', parentNode: '4',
@@ -52,14 +52,14 @@ const initialNodes: Node[] = [
{ {
id: '4b1', id: '4b1',
data: { label: 'Node 4b1' }, data: { label: 'Node 4b1' },
position: { x: 270, y: 270 }, position: { x: 20, y: 20 },
className: 'light', className: 'light',
parentNode: '4b', parentNode: '4b',
}, },
{ {
id: '4b2', id: '4b2',
data: { label: 'Node 4b2' }, data: { label: 'Node 4b2' },
position: { x: 500, y: 400 }, position: { x: 100, y: 100 },
className: 'light', className: 'light',
parentNode: '4b', parentNode: '4b',
}, },
+1 -1
View File
@@ -211,7 +211,7 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
if (nodeElement.current && (!isHidden || !isInitialized)) { if (nodeElement.current && (!isHidden || !isInitialized)) {
updateNodeDimensions([{ id, nodeElement: nodeElement.current, forceUpdate: true }]); updateNodeDimensions([{ id, nodeElement: nodeElement.current, forceUpdate: true }]);
} }
}, [id, isHidden, sourcePosition, targetPosition, isInitialized]); }, [id, isHidden, sourcePosition, targetPosition, type, isInitialized]);
useEffect(() => { useEffect(() => {
if (nodeElement.current) { if (nodeElement.current) {
+10 -7
View File
@@ -4,7 +4,7 @@ import shallow from 'zustand/shallow';
import { useStore } from '../../store'; import { useStore } from '../../store';
import ConnectionLine from '../../components/ConnectionLine/index'; import ConnectionLine from '../../components/ConnectionLine/index';
import MarkerDefinitions from './MarkerDefinitions'; import MarkerDefinitions from './MarkerDefinitions';
import { getEdgePositions, getHandle, getSourceTargetNodes } from './utils'; import { getEdgePositions, getHandle } from './utils';
import { import {
Position, Position,
Edge, Edge,
@@ -17,6 +17,7 @@ import {
NodeHandleBounds, NodeHandleBounds,
} from '../../types'; } from '../../types';
import useVisibleEdges from '../../hooks/useVisibleEdges'; import useVisibleEdges from '../../hooks/useVisibleEdges';
import useNodeLookup from '../../hooks/useNodeLookup';
interface EdgeRendererProps { interface EdgeRendererProps {
edgeTypes: any; edgeTypes: any;
@@ -232,8 +233,8 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
width, width,
height, height,
connectionMode, connectionMode,
nodes,
} = useStore(selector, shallow); } = useStore(selector, shallow);
const nodeLookup = useNodeLookup();
const edges = useVisibleEdges(props.onlyRenderVisibleElements); const edges = useVisibleEdges(props.onlyRenderVisibleElements);
@@ -250,20 +251,22 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
<g transform={`translate(${transform[0]},${transform[1]}) scale(${transform[2]})`}> <g transform={`translate(${transform[0]},${transform[1]}) scale(${transform[2]})`}>
{edges.map((edge: Edge) => { {edges.map((edge: Edge) => {
// @todo: getSourceTargetNodes is called many times during dragging/creating edges // @todo: getSourceTargetNodes is called many times during dragging/creating edges
const { sourceNode, targetNode } = getSourceTargetNodes(edge, nodes); const sourceNode = nodeLookup.current.get(edge.source);
const targetNode = nodeLookup.current.get(edge.target);
return ( return (
<Edge <Edge
key={edge.id} key={edge.id}
edge={edge} edge={edge}
sourceNodeWidth={sourceNode?.width} sourceNodeWidth={sourceNode?.width}
sourceNodeHeight={sourceNode?.height} sourceNodeHeight={sourceNode?.height}
sourceNodeX={sourceNode?.position.x} sourceNodeX={sourceNode?.positionAbsolute?.x}
sourceNodeY={sourceNode?.position.y} sourceNodeY={sourceNode?.positionAbsolute?.y}
sourceNodeHandleBounds={sourceNode?.handleBounds} sourceNodeHandleBounds={sourceNode?.handleBounds}
targetNodeWidth={targetNode?.width} targetNodeWidth={targetNode?.width}
targetNodeHeight={targetNode?.height} targetNodeHeight={targetNode?.height}
targetNodeX={targetNode?.position.x} targetNodeX={targetNode?.positionAbsolute?.x}
targetNodeY={targetNode?.position.y} targetNodeY={targetNode?.positionAbsolute?.y}
targetNodeHandleBounds={targetNode?.handleBounds} targetNodeHandleBounds={targetNode?.handleBounds}
elementsSelectable={elementsSelectable} elementsSelectable={elementsSelectable}
onEdgeContextMenu={props.onEdgeContextMenu} onEdgeContextMenu={props.onEdgeContextMenu}
+35 -9
View File
@@ -2,8 +2,17 @@ import React, { memo, useMemo, ComponentType, MouseEvent, Fragment } from 'react
import shallow from 'zustand/shallow'; import shallow from 'zustand/shallow';
import { useStore } from '../../store'; import { useStore } from '../../store';
import { Node, NodeTypesType, ReactFlowState, WrapNodeProps, SnapGrid } from '../../types'; import {
Node,
NodeTypesType,
ReactFlowState,
WrapNodeProps,
SnapGrid,
NodeRendererNode,
NodeLookup,
} from '../../types';
import useVisibleNodes from '../../hooks/useVisibleNodes'; import useVisibleNodes from '../../hooks/useVisibleNodes';
import useNodeLookup from '../../hooks/useNodeLookup';
interface NodeRendererProps { interface NodeRendererProps {
nodeTypes: NodeTypesType; nodeTypes: NodeTypesType;
selectNodesOnDrag: boolean; selectNodesOnDrag: boolean;
@@ -27,10 +36,12 @@ const selector = (s: ReactFlowState) => ({
updateNodeDimensions: s.updateNodeDimensions, updateNodeDimensions: s.updateNodeDimensions,
snapGrid: s.snapGrid, snapGrid: s.snapGrid,
snapToGrid: s.snapToGrid, snapToGrid: s.snapToGrid,
nodeLookup: s.nodeLookup,
}); });
interface NodesProps extends NodeRendererProps { interface NodesProps extends NodeRendererProps {
nodes: Node[]; nodes: NodeRendererNode[];
nodeLookup: NodeLookup;
isDraggable?: boolean; isDraggable?: boolean;
resizeObserver: ResizeObserver | null; resizeObserver: ResizeObserver | null;
scale: number; scale: number;
@@ -43,13 +54,17 @@ interface NodesProps extends NodeRendererProps {
parentId?: string; parentId?: string;
} }
interface NodeProps extends Omit<NodesProps, 'nodes'> { interface NodeProps extends Omit<NodesProps, 'nodes' | 'nodeLookup'> {
node: Node; node: Node;
nodeType: string; nodeType: string;
childNodes?: NodeRendererNode[];
positionAbsoluteX?: number;
positionAbsoluteY?: number;
} }
function Node({ function Node({
node, node,
childNodes,
nodeType, nodeType,
isDraggable, isDraggable,
resizeObserver, resizeObserver,
@@ -60,6 +75,8 @@ function Node({
nodesConnectable, nodesConnectable,
elementsSelectable, elementsSelectable,
recursionDepth, recursionDepth,
positionAbsoluteX,
positionAbsoluteY,
...props ...props
}: NodeProps) { }: NodeProps) {
// const onNodesChange = useStore((s) => s.onNodesChange); // const onNodesChange = useStore((s) => s.onNodesChange);
@@ -76,7 +93,7 @@ function Node({
typeof node.width !== 'undefined' && typeof node.width !== 'undefined' &&
typeof node.height !== 'undefined'; typeof node.height !== 'undefined';
const isParentNode = !!node.childNodes?.length; const isParentNode = !!childNodes?.length;
return ( return (
<NodeComponent <NodeComponent
@@ -88,8 +105,8 @@ function Node({
sourcePosition={node.sourcePosition} sourcePosition={node.sourcePosition}
targetPosition={node.targetPosition} targetPosition={node.targetPosition}
isHidden={node.isHidden} isHidden={node.isHidden}
xPos={node.position.x} xPos={positionAbsoluteX || 0}
yPos={node.position.y} yPos={positionAbsoluteY || 0}
width={node.width} width={node.width}
height={node.height} height={node.height}
isDragging={node.isDragging} isDragging={node.isDragging}
@@ -121,6 +138,7 @@ function Node({
function Nodes({ function Nodes({
nodes, nodes,
nodeLookup,
isDraggable, isDraggable,
resizeObserver, resizeObserver,
scale, scale,
@@ -132,8 +150,9 @@ function Nodes({
recursionDepth, recursionDepth,
...props ...props
}: NodesProps): any { }: NodesProps): any {
return nodes.map((node) => { return nodes.map(({ node, childNodes }) => {
const nodeType = node.type || 'default'; const nodeType = node.type || 'default';
const lookupNode = nodeLookup.get(node.id);
if (!props.nodeTypes[nodeType]) { if (!props.nodeTypes[nodeType]) {
console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`); console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`);
@@ -143,6 +162,7 @@ function Nodes({
<Fragment key={node.id}> <Fragment key={node.id}>
<Node <Node
node={node} node={node}
childNodes={childNodes}
nodeType={nodeType} nodeType={nodeType}
parentId={node.id} parentId={node.id}
snapToGrid={snapToGrid} snapToGrid={snapToGrid}
@@ -153,11 +173,14 @@ function Nodes({
elementsSelectable={elementsSelectable} elementsSelectable={elementsSelectable}
scale={scale} scale={scale}
recursionDepth={recursionDepth} recursionDepth={recursionDepth}
positionAbsoluteX={lookupNode?.positionAbsolute?.x}
positionAbsoluteY={lookupNode?.positionAbsolute?.y}
{...props} {...props}
/> />
{node.childNodes && node.childNodes.length > 0 && ( {childNodes && childNodes.length > 0 && (
<MemoizedNodes <MemoizedNodes
nodes={node.childNodes} nodes={childNodes}
nodeLookup={nodeLookup}
parentId={node.id} parentId={node.id}
snapToGrid={snapToGrid} snapToGrid={snapToGrid}
snapGrid={snapGrid} snapGrid={snapGrid}
@@ -187,6 +210,8 @@ const NodeRenderer = (props: NodeRendererProps) => {
snapGrid, snapGrid,
snapToGrid, snapToGrid,
} = useStore(selector, shallow); } = useStore(selector, shallow);
const nodeLookup = useNodeLookup();
const nodes = useVisibleNodes(props.onlyRenderVisibleElements); const nodes = useVisibleNodes(props.onlyRenderVisibleElements);
const transformStyle = useMemo( const transformStyle = useMemo(
@@ -215,6 +240,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
<div className="react-flow__nodes" style={transformStyle}> <div className="react-flow__nodes" style={transformStyle}>
<MemoizedNodes <MemoizedNodes
nodes={nodes} nodes={nodes}
nodeLookup={nodeLookup.current}
snapToGrid={snapToGrid} snapToGrid={snapToGrid}
snapGrid={snapGrid} snapGrid={snapGrid}
nodesDraggable={nodesDraggable} nodesDraggable={nodesDraggable}
+12
View File
@@ -0,0 +1,12 @@
import { useRef } from 'react';
import { useStoreApi } from '../store';
function useNodeLookup() {
const store = useStoreApi();
const nodeLookup = useRef(store.getState().nodeLookup);
return nodeLookup;
}
export default useNodeLookup;
+5 -5
View File
@@ -2,23 +2,23 @@ import { useCallback } from 'react';
import { useStore } from '../store'; import { useStore } from '../store';
import { getNodesInside } from '../utils/graph'; import { getNodesInside } from '../utils/graph';
import { ReactFlowState, Node } from '../types'; import { ReactFlowState, Node, NodeRendererNode } from '../types';
function getChildNodes(nodes: Node[], parent?: Node): Node[] { function getChildNodes(nodes: Node[], parent?: Node): NodeRendererNode[] {
const children: Node[] = []; const children: NodeRendererNode[] = [];
const remaining: Node[] = []; const remaining: Node[] = [];
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
const n = nodes[i]; const n = nodes[i];
if ((!parent && !n.parentNode) || n.parentNode === parent?.id) { if ((!parent && !n.parentNode) || n.parentNode === parent?.id) {
children.push(n); children.push({ node: n });
} else { } else {
remaining.push(n); remaining.push(n);
} }
} }
return children.map((child) => { return children.map((child) => {
child.childNodes = getChildNodes(remaining, child); child.childNodes = getChildNodes(remaining, child.node);
return child; return child;
}); });
} }
+84 -54
View File
@@ -26,6 +26,8 @@ import {
OnEdgesChange, OnEdgesChange,
EdgeChange, EdgeChange,
NodeDimensionChange, NodeDimensionChange,
NodeLookup,
NodeLookupItem,
} from '../types'; } from '../types';
import { isNode, isEdge, getRectOfNodes, getNodesInside, getConnectedEdges } from '../utils/graph'; import { isNode, isEdge, getRectOfNodes, getNodesInside, getConnectedEdges } from '../utils/graph';
import { getHandleBounds } from '../components/Nodes/utils'; import { getHandleBounds } from '../components/Nodes/utils';
@@ -39,36 +41,53 @@ const createNodeOrEdgeSelectionChange = (isSelected: boolean) => (item: Node | E
}); });
// @todo needs refactoring / improvements // @todo needs refactoring / improvements
function findMatchingNodes(id: string | undefined, nodes: Node[]): Node[] { // function findMatchingNodes(id: string | undefined, nodes: Node[]): Node[] {
if (!id) { // if (!id) {
return nodes.filter((n) => !!n.isSelected); // return nodes.filter((n) => !!n.isSelected);
// }
// const result = [];
// const children = [];
// for (let i = 0; i < nodes.length; i++) {
// const n = nodes[i];
// if (n.id === id) {
// result.push(n);
// }
// if (n.parentNode === id) {
// children.push(n);
// }
// }
// for (let i = 0; i < children.length; i++) {
// const n = children[i];
// const matches = findMatchingNodes(n.id, nodes);
// for (let j = 0; j < matches.length; j++) {
// result.push(matches[j]);
// }
// }
// return result;
// }
function addPositions(posA: XYPosition, posB: XYPosition): XYPosition {
return {
x: (posA.x ?? 0) + (posB.x ?? 0),
y: (posA.y ?? 0) + (posB.y ?? 0),
};
}
function getAbsolutePosition(node: NodeLookupItem, nodeLookup: NodeLookup, result: XYPosition): XYPosition {
const parentNode = node.parentNode ? nodeLookup.get(node.parentNode) : false;
if (!parentNode) {
return result;
} }
const result = []; return getAbsolutePosition(parentNode, nodeLookup, addPositions(result, parentNode.position || { x: 0, y: 0 }));
const children = [];
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
if (n.id === id) {
result.push(n);
}
if (n.parentNode === id) {
children.push(n);
}
}
for (let i = 0; i < children.length; i++) {
const n = children[i];
const matches = findMatchingNodes(n.id, nodes);
for (let j = 0; j < matches.length; j++) {
result.push(matches[j]);
}
}
return result;
} }
const createStore = () => const createStore = () =>
@@ -127,36 +146,45 @@ const createStore = () =>
reactFlowVersion: typeof __REACT_FLOW_VERSION__ !== 'undefined' ? __REACT_FLOW_VERSION__ : '-', reactFlowVersion: typeof __REACT_FLOW_VERSION__ !== 'undefined' ? __REACT_FLOW_VERSION__ : '-',
setNodes: (propNodes: Node[]) => { nodeLookup: new Map(),
const { nodes } = get();
const nextNodes = propNodes.map((propNode: Node) => { setNodes: (nodes: Node[]) => {
const storeNode = nodes.find((node) => node.id === propNode.id); const { nodeLookup } = get();
if (storeNode) { nodes.forEach((node) => {
if (typeof propNode.type !== 'undefined' && propNode.type !== storeNode.type) { const lookupNode = {
// we reset the elements dimensions here in order to force a re-calculation of the bounds. ...nodeLookup.get(node.id),
// When the type of a node changes it is possible that the number or positions of handles changes too. width: node.width || null,
return { height: node.height || null,
...propNode, position: node.position,
width: null, positionAbsolute: node.position,
height: null, };
}; if (node.parentNode) {
} lookupNode.parentNode = node.parentNode;
} }
nodeLookup.set(node.id, lookupNode);
return propNode;
}); });
set({ nodes
nodes: nextNodes, .filter((node) => node.parentNode)
}); .forEach((node) => {
const positionAbsolute = getAbsolutePosition(node, nodeLookup, node.position);
if (positionAbsolute) {
nodeLookup.set(node.id, {
...nodeLookup.get(node.id),
positionAbsolute,
});
}
});
set({ nodes });
}, },
setEdges: (edges: Edge[]) => { setEdges: (edges: Edge[]) => {
set({ edges }); set({ edges });
}, },
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => { updateNodeDimensions: (updates: NodeDimensionUpdate[]) => {
const { onNodesChange, nodes, transform } = get(); const { onNodesChange, nodes, transform, nodeLookup } = get();
const nodesToChange: NodeChange[] = updates.reduce<NodeChange[]>((res, update) => { const nodesToChange: NodeChange[] = updates.reduce<NodeChange[]>((res, update) => {
const node = nodes.find((n) => n.id === update.id); const node = nodes.find((n) => n.id === update.id);
@@ -170,6 +198,8 @@ const createStore = () =>
if (doUpdate) { if (doUpdate) {
const handleBounds = getHandleBounds(update.nodeElement, transform[2]); const handleBounds = getHandleBounds(update.nodeElement, transform[2]);
nodeLookup.set(node.id, { ...nodeLookup.get(node.id), handleBounds });
const change = { const change = {
id: node.id, id: node.id,
type: 'dimensions', type: 'dimensions',
@@ -189,13 +219,13 @@ const createStore = () =>
const { onNodesChange, nodes, nodeExtent } = get(); const { onNodesChange, nodes, nodeExtent } = get();
if (onNodesChange) { if (onNodesChange) {
const matchingNodes = findMatchingNodes(id, nodes); const matchingNodes = nodes.filter((n) => !!n.isSelected || n.id === id);
if (matchingNodes?.length) { if (matchingNodes?.length) {
onNodesChange( onNodesChange(
matchingNodes.map((n) => { matchingNodes.map((node) => {
const change: NodeDimensionChange = { const change: NodeDimensionChange = {
id: n.id, id: node.id,
type: 'dimensions', type: 'dimensions',
isDragging: !!isDragging, isDragging: !!isDragging,
}; };
@@ -204,12 +234,12 @@ const createStore = () =>
change.position = nodeExtent change.position = nodeExtent
? clampPosition( ? clampPosition(
{ {
x: n.position.x + diff.x, x: node.position.x + diff.x,
y: n.position.y + diff.y, y: node.position.y + diff.y,
}, },
nodeExtent nodeExtent
) )
: { x: n.position.x + diff.x, y: n.position.y + diff.y }; : { x: node.position.x + diff.x, y: node.position.y + diff.y };
} }
return change; return change;
+17
View File
@@ -458,11 +458,23 @@ export type InitD3ZoomPayload = {
export type OnNodesChange = (nodes: NodeChange[]) => void; export type OnNodesChange = (nodes: NodeChange[]) => void;
export type OnEdgesChange = (nodes: EdgeChange[]) => void; export type OnEdgesChange = (nodes: EdgeChange[]) => void;
export type NodeLookupItem = {
width?: number | null;
height?: number | null;
parentNode?: ElementId;
position?: XYPosition;
positionAbsolute?: XYPosition;
handleBounds?: NodeHandleBounds;
};
export type NodeLookup = Map<ElementId, NodeLookupItem>;
export interface ReactFlowState { export interface ReactFlowState {
width: number; width: number;
height: number; height: number;
transform: Transform; transform: Transform;
nodes: Node[]; nodes: Node[];
nodeLookup: NodeLookup;
edges: Edge[]; edges: Edge[];
selectedNodesBbox: Rect; selectedNodesBbox: Rect;
onNodesChange: OnNodesChange | null; onNodesChange: OnNodesChange | null;
@@ -542,3 +554,8 @@ export interface ReactFlowState {
export type UpdateNodeInternals = (nodeId: ElementId) => void; export type UpdateNodeInternals = (nodeId: ElementId) => void;
export type OnSelectionChangeFunc = (params: { nodes: Node[]; edges: Edge[] }) => void; export type OnSelectionChangeFunc = (params: { nodes: Node[]; edges: Edge[] }) => void;
export type NodeRendererNode = {
childNodes?: NodeRendererNode[];
node: Node;
};