refactor(nodes): use one resize observer for all nodes #723

This commit is contained in:
moklick
2020-11-26 14:25:39 +01:00
parent 32415077fc
commit e88dfdb650
6 changed files with 70 additions and 53 deletions
+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}
/> />
); );
})} })}
+30 -37
View File
@@ -1,4 +1,4 @@
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';
@@ -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>;
@@ -248,50 +252,39 @@ export const storeModel: StoreModel = {
}); });
}), }),
updateNodeDimensions: action((state, { id, nodeElement }) => { batchUpdateNodeDimensions: action((state, { updates }) => {
const dimensions = getDimensions(nodeElement); updates.forEach((update) => {
const matchingNode = state.nodes.find((n) => n.id === id); const dimensions = getDimensions(update.nodeElement);
const matchingIndex = state.elements.findIndex((n) => n.id === update.id);
const matchingNode = state.elements[matchingIndex] as Node;
// only update when size change if (
if ( matchingIndex !== -1 &&
!matchingNode || dimensions.width &&
(matchingNode.__rf.width === dimensions.width && matchingNode.__rf.height === dimensions.height) dimensions.height &&
) { (matchingNode.__rf.width !== dimensions.width || matchingNode.__rf.height !== dimensions.height)
return; ) {
} const handleBounds = getHandleBounds(update.nodeElement, 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.width = dimensions.width; (state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
n.__rf.height = dimensions.height;
} }
}); });
}), }),
updateNodeHandlePositions: actionOn( updateNodeDimensions: action((state, { id, nodeElement }) => {
(actions) => actions.updateNodeDimensions, const dimensions = getDimensions(nodeElement);
(state, target) => { const matchingIndex = state.elements.findIndex((n) => n.id === id);
const { nodeElement, id } = target.payload;
const matchingNode = state.nodes.find((n) => n.id === id);
if (!matchingNode) { if (matchingIndex !== -1 && dimensions.width && dimensions.height) {
return; const handleBounds = getHandleBounds(nodeElement, state.transform[2]);
}
const bounds = nodeElement.getBoundingClientRect(); (state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
(state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
const handleBounds = { (state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
source: getHandleBounds('.source', nodeElement, bounds, state.transform[2]),
target: getHandleBounds('.target', nodeElement, bounds, state.transform[2]),
};
state.elements.forEach((n) => {
if (n.id === id && isNode(n)) {
n.__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,
}); });