Merge branch 'feat/node-toolbar' of github.com:wbkd/react-flow into feat/node-toolbar

This commit is contained in:
Christopher Möller
2022-11-16 13:55:55 +01:00
16 changed files with 183 additions and 57 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@reactflow/core': patch
---
Fix multi selection and fitView when nodeOrigin is used
+5
View File
@@ -0,0 +1,5 @@
---
'@reactflow/minimap': minor
---
add a new property "ariaLabel" to configure or remove the aria-label of the minimap component
+5
View File
@@ -0,0 +1,5 @@
---
'@reactflow/core': patch
---
Core: Always elevate zIndex when node is selected
+5
View File
@@ -0,0 +1,5 @@
---
'@reactflow/core': patch
---
EdgeLabelRenderer: handle multiple instances on a page
@@ -0,0 +1,63 @@
import ReactFlow, { BaseEdge, EdgeLabelRenderer, EdgeProps, getSmoothStepPath, ReactFlowProvider } from 'reactflow';
import * as simpleflow from '../../fixtures/simpleflow';
function CustomEdge(props: EdgeProps) {
const [path, labelX, labelY] = getSmoothStepPath(props);
return (
<>
<BaseEdge path={path} labelX={labelX} labelY={labelY} />
<EdgeLabelRenderer>
<div className="label">{props.id}</div>
</EdgeLabelRenderer>
</>
);
}
const simpleflow1 = { ...simpleflow };
simpleflow1.edges = [...simpleflow1.edges];
simpleflow1.edges[0] = { ...simpleflow1.edges[0], id: 'edge1' };
const simpleflow2 = { ...simpleflow };
simpleflow2.edges = [...simpleflow2.edges];
simpleflow2.edges[0] = { ...simpleflow2.edges[0], id: 'edge2' };
describe('<ReactFlow />: Multiple Instances', () => {
describe('render EdgeLabelRenderer', () => {
beforeEach(() => {
cy.mount(
<>
<ReactFlowProvider>
<ReactFlow
defaultNodes={simpleflow1.nodes}
edgeTypes={{ default: CustomEdge }}
defaultEdges={simpleflow1.edges}
/>
</ReactFlowProvider>
<ReactFlowProvider>
<ReactFlow
defaultNodes={simpleflow2.nodes}
edgeTypes={{ default: CustomEdge }}
defaultEdges={simpleflow2.edges}
/>
</ReactFlowProvider>
</>
);
});
it('Each ReactFlow instance has one edge label in EdgeLabelRenderer', () => {
cy.get('.react-flow__edgelabel-renderer').should('have.length', 2);
cy.get('.react-flow__edgelabel-renderer')
.eq(0)
.within(() => {
cy.get('.label').should('have.length', 1).should('contain.text', 'edge1');
});
cy.get('.react-flow__edgelabel-renderer')
.eq(1)
.within(() => {
cy.get('.label').should('have.length', 1).should('contain.text', 'edge2');
});
});
});
});
@@ -8,6 +8,7 @@ import ReactFlow, {
Node,
Edge,
useReactFlow,
NodeOrigin,
} from 'reactflow';
const onNodeDrag = (_: MouseEvent, node: Node) => console.log('drag', node);
@@ -47,6 +48,8 @@ const initialEdges: Edge[] = [
{ id: 'e1-3', source: '1', target: '3' },
];
const nodeOrigin: NodeOrigin = [0.5, 0.5];
const defaultEdgeOptions = { zIndex: 0 };
const BasicFlow = () => {
@@ -91,6 +94,7 @@ const BasicFlow = () => {
fitView
defaultEdgeOptions={defaultEdgeOptions}
selectNodesOnDrag={false}
nodeOrigin={nodeOrigin}
>
<Background variant={BackgroundVariant.Dots} />
<MiniMap />
@@ -106,7 +110,9 @@ const BasicFlow = () => {
<button onClick={toggleClassnames} style={{ marginRight: 5 }}>
toggle classnames
</button>
<button onClick={logToObject} style={{ marginRight: 5 }}>toObject</button>
<button onClick={logToObject} style={{ marginRight: 5 }}>
toObject
</button>
</div>
</ReactFlow>
);
@@ -7,6 +7,7 @@ import ReactFlow, {
Edge,
NodeTypes,
Position,
NodeOrigin,
} from 'reactflow';
import CustomNode from './CustomNode';
@@ -20,14 +21,14 @@ const initialNodes: Node[] = [
id: '1',
type: 'custom',
data: { label: 'toolbar top', toolbarPosition: Position.Top },
position: { x: 0, y: 0 },
position: { x: 0, y: 50 },
className: 'react-flow__node-default',
},
{
id: '2',
type: 'custom',
data: { label: 'toolbar right', toolbarPosition: Position.Right },
position: { x: 400, y: 0 },
position: { x: 300, y: 0 },
className: 'react-flow__node-default',
},
{
@@ -48,7 +49,7 @@ const initialNodes: Node[] = [
id: '5',
type: 'custom',
data: { label: 'toolbar always open', toolbarPosition: Position.Top, toolbarVisible: true },
position: { x: 0, y: 150 },
position: { x: 0, y: 200 },
className: 'react-flow__node-default',
},
];
@@ -60,6 +61,7 @@ const initialEdges: Edge[] = [
];
const defaultEdgeOptions = { zIndex: 0 };
const nodeOrigin: NodeOrigin = [0.5, 0.5];
export default function NodeToolbarExample() {
return (
@@ -72,6 +74,7 @@ export default function NodeToolbarExample() {
fitView
defaultEdgeOptions={defaultEdgeOptions}
nodeTypes={nodeTypes}
nodeOrigin={nodeOrigin}
>
<Background variant={BackgroundVariant.Dots} />
<MiniMap />
@@ -1,15 +1,18 @@
import { useRef } from 'react';
import type { ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useStore } from '../../hooks/useStore';
import { ReactFlowState } from '../../types';
const selector = (s: ReactFlowState) => s.domNode?.querySelector('.react-flow__edgelabel-renderer');
function EdgeLabelRenderer({ children }: { children: ReactNode }) {
const wrapperRef = useRef(document.getElementById('edgelabel-portal'));
const edgeLabelRenderer = useStore(selector);
if (!wrapperRef.current) {
if (!edgeLabelRenderer) {
return null;
}
return createPortal(children, wrapperRef.current);
return createPortal(children, edgeLabelRenderer);
}
export default EdgeLabelRenderer;
@@ -24,12 +24,11 @@ export interface NodesSelectionProps {
const selector = (s: ReactFlowState) => ({
transformString: `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]})`,
userSelectionActive: s.userSelectionActive,
...getRectOfNodes(Array.from(s.nodeInternals.values()).filter((n) => n.selected)),
});
const bboxSelector = (s: ReactFlowState) => {
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) {
@@ -101,9 +101,9 @@ const UserSelection = memo(({ selectionKeyPressed }: UserSelectionProps) => {
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 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 selectedNodeIds = selectedNodes.map((n) => n.id);
@@ -158,7 +158,7 @@ const GraphView = ({
disableKeyboardA11y={disableKeyboardA11y}
rfId={rfId}
/>
<div className="react-flow__edgelabel-renderer" id="edgelabel-portal" />
<div className="react-flow__edgelabel-renderer" />
<NodeRenderer
nodeTypes={nodeTypes}
+14 -4
View File
@@ -39,7 +39,7 @@ export function createNodeInternals(nodes: Node[], nodeInternals: NodeInternals)
const parentNodes: ParentNodes = {};
nodes.forEach((node) => {
const z = isNumeric(node.zIndex) ? node.zIndex : node.selected ? 1000 : 0;
const z = (isNumeric(node.zIndex) ? node.zIndex : 0) + (node.selected ? 1000 : 0);
const currInternals = nodeInternals.get(node.id);
const internals: Node = {
@@ -100,8 +100,18 @@ type InternalFitViewOptions = {
} & FitViewOptions;
export function fitView(get: StoreApi<ReactFlowState>['getState'], options: InternalFitViewOptions = {}) {
const { nodeInternals, width, height, minZoom, maxZoom, d3Zoom, d3Selection, fitViewOnInitDone, fitViewOnInit } =
get();
const {
nodeInternals,
width,
height,
minZoom,
maxZoom,
d3Zoom,
d3Selection,
fitViewOnInitDone,
fitViewOnInit,
nodeOrigin,
} = get();
if ((options.initial && !fitViewOnInitDone && fitViewOnInit) || !options.initial) {
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);
if (nodes.length > 0 && nodesInitialized) {
const bounds = getRectOfNodes(nodes);
const bounds = getRectOfNodes(nodes, nodeOrigin);
const [x, y, zoom] = getTransformForBounds(
bounds,
width,
+31 -10
View File
@@ -2,7 +2,17 @@
import type { Selection as D3Selection } from 'd3';
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 =>
'id' in element && 'source' in element && 'target' in element;
@@ -131,22 +141,26 @@ export const pointToRendererPoint = (
return position;
};
export const getRectOfNodes = (nodes: Node[]): Rect => {
export const getRectOfNodes = (nodes: Node[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
if (nodes.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 };
}
const box = nodes.reduce(
(currBox, { positionAbsolute, position, width, height }) =>
getBoundsOfBoxes(
(currBox, { positionAbsolute, position, width, height }) => {
const nodeX = positionAbsolute ? positionAbsolute.x : position.x;
const nodeY = positionAbsolute ? positionAbsolute.y : position.y;
return getBoundsOfBoxes(
currBox,
rectToBox({
x: positionAbsolute ? positionAbsolute.x : position.x,
y: positionAbsolute ? positionAbsolute.y : position.y,
x: nodeX - nodeOrigin[0] * (width || 0),
y: nodeY - nodeOrigin[1] * (height || 0),
width: width || 0,
height: height || 0,
})
),
);
},
{ x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }
);
@@ -159,7 +173,8 @@ export const getNodesInside = (
[tx, ty, tScale]: Transform = [0, 0, 1],
partially = false,
// set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute
excludeNonSelectableNodes = false
excludeNonSelectableNodes = false,
nodeOrigin: NodeOrigin = [0, 0]
): Node[] => {
const paneRect = {
x: (rect.x - tx) / tScale,
@@ -171,13 +186,18 @@ export const getNodesInside = (
const visibleNodes: 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) {
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 notInitialized =
typeof width === 'undefined' || typeof height === 'undefined' || width === null || height === null;
@@ -223,3 +243,4 @@ export const getTransformForBounds = (
export const getD3Transition = (selection: D3Selection<Element, unknown, null, undefined>, duration = 0) => {
return selection.transition().duration(duration);
};
+23 -24
View File
@@ -30,15 +30,15 @@ const selector = (s: ReactFlowState) => {
return {
nodes: nodes.filter((node) => !node.hidden && node.width && node.height),
viewBB,
boundingRect: nodes.length > 0 ? getBoundsOfRects(getRectOfNodes(nodes), viewBB) : viewBB,
boundingRect: nodes.length > 0 ? getBoundsOfRects(getRectOfNodes(nodes, s.nodeOrigin), viewBB) : viewBB,
rfId: s.rfId,
nodeOrigin: s.nodeOrigin,
};
};
const getAttrFunction = (func: any): GetMiniMapNodeAttribute => (func instanceof Function ? func : () => func);
const ARIA_LABEL_KEY = 'react-flow__minimap-desc';
function MiniMap({
style,
className,
@@ -53,10 +53,11 @@ function MiniMap({
onNodeClick,
pannable = false,
zoomable = false,
ariaLabel = 'React Flow mini map',
}: MiniMapProps) {
const store = useStoreApi();
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 elementHeight = (style?.height as number) ?? defaultHeight;
const nodeColorFunc = getAttrFunction(nodeColor);
@@ -155,27 +156,25 @@ function MiniMap({
ref={svg}
onClick={onSvgClick}
>
<title id={labelledBy}>React Flow mini map</title>
{nodes.map((node) => {
return (
<MiniMapNode
key={node.id}
x={node.positionAbsolute?.x ?? 0}
y={node.positionAbsolute?.y ?? 0}
width={node.width!}
height={node.height!}
style={node.style}
className={nodeClassNameFunc(node)}
color={nodeColorFunc(node)}
borderRadius={nodeBorderRadius}
strokeColor={nodeStrokeColorFunc(node)}
strokeWidth={nodeStrokeWidth}
shapeRendering={shapeRendering}
onClick={onSvgNodeClick}
id={node.id}
/>
);
})}
{ariaLabel && <title id={labelledBy}>{ariaLabel}</title>}
{nodes.map((node) => (
<MiniMapNode
key={node.id}
x={(node.positionAbsolute?.x ?? 0) - nodeOrigin[0] * (node.width ?? 0)}
y={(node.positionAbsolute?.y ?? 0) - nodeOrigin[1] * (node.height ?? 0)}
width={node.width!}
height={node.height!}
style={node.style}
className={nodeClassNameFunc(node)}
color={nodeColorFunc(node)}
borderRadius={nodeBorderRadius}
strokeColor={nodeStrokeColorFunc(node)}
strokeWidth={nodeStrokeWidth}
shapeRendering={shapeRendering}
onClick={onSvgNodeClick}
id={node.id}
/>
))}
<path
className="react-flow__minimap-mask"
d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z
+1
View File
@@ -16,4 +16,5 @@ export type MiniMapProps<NodeData = any> = Omit<HTMLAttributes<SVGSVGElement>, '
onNodeClick?: (event: MouseEvent, node: Node<NodeData>) => void;
pannable?: boolean;
zoomable?: boolean;
ariaLabel?: string | null;
};
+7 -6
View File
@@ -25,9 +25,11 @@ const nodeEqualityFn = (a: SelectedNode, b: SelectedNode) =>
a?.selected === b?.selected &&
a?.[internalsSymbol]?.z === b?.[internalsSymbol]?.z;
const transformSelector = (state: ReactFlowState): Transform => state.transform;
const selectedNodesCountSelector = (state: ReactFlowState): number =>
Array.from(state.nodeInternals.values()).filter((node) => node.selected).length;
const storeSelector = (state: ReactFlowState) => ({
transform: state.transform,
nodeOrigin: state.nodeOrigin,
selectedNodesCount: Array.from(state.nodeInternals.values()).filter((node) => node.selected).length,
});
function getTransform(nodeRect: Rect, transform: Transform, position: Position, offset: number): string {
// position === Position.Top
@@ -70,15 +72,14 @@ function NodeToolbar({
}: NodeToolbarProps) {
const nodeSelector = useCallback((state: ReactFlowState): SelectedNode => state.nodeInternals.get(nodeId), [nodeId]);
const node = useStore(nodeSelector, nodeEqualityFn);
const transform = useStore(transformSelector, shallow);
const selectedNodesCount = useStore(selectedNodesCountSelector);
const { transform, nodeOrigin, selectedNodesCount } = useStore(storeSelector, shallow);
const isActive = typeof isVisible === 'boolean' ? isVisible : node?.selected && selectedNodesCount === 1;
if (!isActive || !node) {
return null;
}
const nodeRect: Rect = getRectOfNodes([node]);
const nodeRect: Rect = getRectOfNodes([node], nodeOrigin);
const wrapperStyle: CSSProperties = {
transform: getTransform(nodeRect, transform, position, offset),