Merge pull request #2561 from wbkd/fix/selection-rect

fix(nodeOrigin): repair multi selection and fitView
This commit is contained in:
Moritz Klack
2022-11-15 16:12:23 +01:00
committed by GitHub
7 changed files with 79 additions and 40 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@reactflow/core': patch
---
Fix multi selection and fitView when nodeOrigin is used
@@ -8,6 +8,7 @@ import ReactFlow, {
Node, Node,
Edge, Edge,
useReactFlow, useReactFlow,
NodeOrigin,
} from 'reactflow'; } from 'reactflow';
const onNodeDrag = (_: MouseEvent, node: Node) => console.log('drag', node); const onNodeDrag = (_: MouseEvent, node: Node) => console.log('drag', node);
@@ -47,6 +48,8 @@ const initialEdges: Edge[] = [
{ id: 'e1-3', source: '1', target: '3' }, { id: 'e1-3', source: '1', target: '3' },
]; ];
const nodeOrigin: NodeOrigin = [0.5, 0.5];
const defaultEdgeOptions = { zIndex: 0 }; const defaultEdgeOptions = { zIndex: 0 };
const BasicFlow = () => { const BasicFlow = () => {
@@ -91,6 +94,7 @@ const BasicFlow = () => {
fitView fitView
defaultEdgeOptions={defaultEdgeOptions} defaultEdgeOptions={defaultEdgeOptions}
selectNodesOnDrag={false} selectNodesOnDrag={false}
nodeOrigin={nodeOrigin}
> >
<Background variant={BackgroundVariant.Dots} /> <Background variant={BackgroundVariant.Dots} />
<MiniMap /> <MiniMap />
@@ -106,7 +110,9 @@ const BasicFlow = () => {
<button onClick={toggleClassnames} style={{ marginRight: 5 }}> <button onClick={toggleClassnames} style={{ marginRight: 5 }}>
toggle classnames toggle classnames
</button> </button>
<button onClick={logToObject} style={{ marginRight: 5 }}>toObject</button> <button onClick={logToObject} style={{ marginRight: 5 }}>
toObject
</button>
</div> </div>
</ReactFlow> </ReactFlow>
); );
@@ -24,12 +24,11 @@ export interface NodesSelectionProps {
const selector = (s: ReactFlowState) => ({ const selector = (s: ReactFlowState) => ({
transformString: `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]})`, transformString: `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]})`,
userSelectionActive: s.userSelectionActive, userSelectionActive: s.userSelectionActive,
...getRectOfNodes(Array.from(s.nodeInternals.values()).filter((n) => n.selected)),
}); });
const bboxSelector = (s: ReactFlowState) => { const bboxSelector = (s: ReactFlowState) => {
const selectedNodes = Array.from(s.nodeInternals.values()).filter((n) => n.selected); const selectedNodes = Array.from(s.nodeInternals.values()).filter((n) => n.selected);
return getRectOfNodes(selectedNodes); return getRectOfNodes(selectedNodes, s.nodeOrigin);
}; };
function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }: NodesSelectionProps) { function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }: NodesSelectionProps) {
@@ -101,9 +101,9 @@ const UserSelection = memo(({ selectionKeyPressed }: UserSelectionProps) => {
height: Math.abs(mousePos.y - startY), height: Math.abs(mousePos.y - startY),
}; };
const { nodeInternals, edges, transform, onNodesChange, onEdgesChange } = store.getState(); const { nodeInternals, edges, transform, onNodesChange, onEdgesChange, nodeOrigin } = store.getState();
const nodes = Array.from(nodeInternals.values()); const nodes = Array.from(nodeInternals.values());
const selectedNodes = getNodesInside(nodeInternals, nextUserSelectRect, transform, false, true); const selectedNodes = getNodesInside(nodeInternals, nextUserSelectRect, transform, false, true, nodeOrigin);
const selectedEdgeIds = getConnectedEdges(selectedNodes, edges).map((e) => e.id); const selectedEdgeIds = getConnectedEdges(selectedNodes, edges).map((e) => e.id);
const selectedNodeIds = selectedNodes.map((n) => n.id); const selectedNodeIds = selectedNodes.map((n) => n.id);
+13 -3
View File
@@ -100,8 +100,18 @@ type InternalFitViewOptions = {
} & FitViewOptions; } & FitViewOptions;
export function fitView(get: StoreApi<ReactFlowState>['getState'], options: InternalFitViewOptions = {}) { export function fitView(get: StoreApi<ReactFlowState>['getState'], options: InternalFitViewOptions = {}) {
const { nodeInternals, width, height, minZoom, maxZoom, d3Zoom, d3Selection, fitViewOnInitDone, fitViewOnInit } = const {
get(); nodeInternals,
width,
height,
minZoom,
maxZoom,
d3Zoom,
d3Selection,
fitViewOnInitDone,
fitViewOnInit,
nodeOrigin,
} = get();
if ((options.initial && !fitViewOnInitDone && fitViewOnInit) || !options.initial) { if ((options.initial && !fitViewOnInitDone && fitViewOnInit) || !options.initial) {
if (d3Zoom && d3Selection) { if (d3Zoom && d3Selection) {
@@ -112,7 +122,7 @@ export function fitView(get: StoreApi<ReactFlowState>['getState'], options: Inte
const nodesInitialized = nodes.every((n) => n.width && n.height); const nodesInitialized = nodes.every((n) => n.width && n.height);
if (nodes.length > 0 && nodesInitialized) { if (nodes.length > 0 && nodesInitialized) {
const bounds = getRectOfNodes(nodes); const bounds = getRectOfNodes(nodes, nodeOrigin);
const [x, y, zoom] = getTransformForBounds( const [x, y, zoom] = getTransformForBounds(
bounds, bounds,
width, width,
+30 -10
View File
@@ -2,7 +2,17 @@
import type { Selection as D3Selection } from 'd3'; import type { Selection as D3Selection } from 'd3';
import { boxToRect, clamp, devWarn, getBoundsOfBoxes, getOverlappingArea, rectToBox } from '../utils'; import { boxToRect, clamp, devWarn, getBoundsOfBoxes, getOverlappingArea, rectToBox } from '../utils';
import type { Node, Edge, Connection, EdgeMarkerType, Transform, XYPosition, Rect, NodeInternals } from '../types'; import type {
Node,
Edge,
Connection,
EdgeMarkerType,
Transform,
XYPosition,
Rect,
NodeInternals,
NodeOrigin,
} from '../types';
export const isEdge = (element: Node | Connection | Edge): element is Edge => export const isEdge = (element: Node | Connection | Edge): element is Edge =>
'id' in element && 'source' in element && 'target' in element; 'id' in element && 'source' in element && 'target' in element;
@@ -131,22 +141,26 @@ export const pointToRendererPoint = (
return position; return position;
}; };
export const getRectOfNodes = (nodes: Node[]): Rect => { export const getRectOfNodes = (nodes: Node[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
if (nodes.length === 0) { if (nodes.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 }; return { x: 0, y: 0, width: 0, height: 0 };
} }
const box = nodes.reduce( const box = nodes.reduce(
(currBox, { positionAbsolute, position, width, height }) => (currBox, { positionAbsolute, position, width, height }) => {
getBoundsOfBoxes( const nodeX = positionAbsolute ? positionAbsolute.x : position.x;
const nodeY = positionAbsolute ? positionAbsolute.y : position.y;
return getBoundsOfBoxes(
currBox, currBox,
rectToBox({ rectToBox({
x: positionAbsolute ? positionAbsolute.x : position.x, x: nodeX - nodeOrigin[0] * (width || 0),
y: positionAbsolute ? positionAbsolute.y : position.y, y: nodeY - nodeOrigin[1] * (height || 0),
width: width || 0, width: width || 0,
height: height || 0, height: height || 0,
}) })
), );
},
{ x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity } { x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }
); );
@@ -159,7 +173,8 @@ export const getNodesInside = (
[tx, ty, tScale]: Transform = [0, 0, 1], [tx, ty, tScale]: Transform = [0, 0, 1],
partially = false, partially = false,
// set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute // set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute
excludeNonSelectableNodes = false excludeNonSelectableNodes = false,
nodeOrigin: NodeOrigin = [0, 0]
): Node[] => { ): Node[] => {
const paneRect = { const paneRect = {
x: (rect.x - tx) / tScale, x: (rect.x - tx) / tScale,
@@ -171,13 +186,18 @@ export const getNodesInside = (
const visibleNodes: Node[] = []; const visibleNodes: Node[] = [];
nodeInternals.forEach((node) => { nodeInternals.forEach((node) => {
const { positionAbsolute = { x: 0, y: 0 }, width, height, selectable = true } = node; const { width, height, selectable = true, positionAbsolute = { x: 0, y: 0 } } = node;
if (excludeNonSelectableNodes && !selectable) { if (excludeNonSelectableNodes && !selectable) {
return false; return false;
} }
const nodeRect = { ...positionAbsolute, width: width || 0, height: height || 0 }; const nodeRect = {
x: positionAbsolute.x - nodeOrigin[0] * (width || 0),
y: positionAbsolute.y - nodeOrigin[1] * (height || 0),
width: width || 0,
height: height || 0,
};
const overlappingArea = getOverlappingArea(paneRect, nodeRect); const overlappingArea = getOverlappingArea(paneRect, nodeRect);
const notInitialized = const notInitialized =
typeof width === 'undefined' || typeof height === 'undefined' || width === null || height === null; typeof width === 'undefined' || typeof height === 'undefined' || width === null || height === null;
+21 -22
View File
@@ -30,8 +30,9 @@ const selector = (s: ReactFlowState) => {
return { return {
nodes: nodes.filter((node) => !node.hidden && node.width && node.height), nodes: nodes.filter((node) => !node.hidden && node.width && node.height),
viewBB, viewBB,
boundingRect: nodes.length > 0 ? getBoundsOfRects(getRectOfNodes(nodes), viewBB) : viewBB, boundingRect: nodes.length > 0 ? getBoundsOfRects(getRectOfNodes(nodes, s.nodeOrigin), viewBB) : viewBB,
rfId: s.rfId, rfId: s.rfId,
nodeOrigin: s.nodeOrigin,
}; };
}; };
@@ -56,7 +57,7 @@ function MiniMap({
}: MiniMapProps) { }: MiniMapProps) {
const store = useStoreApi(); const store = useStoreApi();
const svg = useRef<SVGSVGElement>(null); const svg = useRef<SVGSVGElement>(null);
const { boundingRect, viewBB, nodes, rfId } = useStore(selector, shallow); const { boundingRect, viewBB, nodes, rfId, nodeOrigin } = useStore(selector, shallow);
const elementWidth = (style?.width as number) ?? defaultWidth; const elementWidth = (style?.width as number) ?? defaultWidth;
const elementHeight = (style?.height as number) ?? defaultHeight; const elementHeight = (style?.height as number) ?? defaultHeight;
const nodeColorFunc = getAttrFunction(nodeColor); const nodeColorFunc = getAttrFunction(nodeColor);
@@ -156,26 +157,24 @@ function MiniMap({
onClick={onSvgClick} onClick={onSvgClick}
> >
{ariaLabel && <title id={labelledBy}>{ariaLabel}</title>} {ariaLabel && <title id={labelledBy}>{ariaLabel}</title>}
{nodes.map((node) => { {nodes.map((node) => (
return ( <MiniMapNode
<MiniMapNode key={node.id}
key={node.id} x={(node.positionAbsolute?.x ?? 0) - nodeOrigin[0] * (node.width ?? 0)}
x={node.positionAbsolute?.x ?? 0} y={(node.positionAbsolute?.y ?? 0) - nodeOrigin[1] * (node.height ?? 0)}
y={node.positionAbsolute?.y ?? 0} width={node.width!}
width={node.width!} height={node.height!}
height={node.height!} style={node.style}
style={node.style} className={nodeClassNameFunc(node)}
className={nodeClassNameFunc(node)} color={nodeColorFunc(node)}
color={nodeColorFunc(node)} borderRadius={nodeBorderRadius}
borderRadius={nodeBorderRadius} strokeColor={nodeStrokeColorFunc(node)}
strokeColor={nodeStrokeColorFunc(node)} strokeWidth={nodeStrokeWidth}
strokeWidth={nodeStrokeWidth} shapeRendering={shapeRendering}
shapeRendering={shapeRendering} onClick={onSvgNodeClick}
onClick={onSvgNodeClick} id={node.id}
id={node.id} />
/> ))}
);
})}
<path <path
className="react-flow__minimap-mask" className="react-flow__minimap-mask"
d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z