Merge branch 'next' into absolute-origin

This commit is contained in:
Moritz Klack
2024-06-24 12:57:24 +02:00
committed by GitHub
91 changed files with 8822 additions and 7060 deletions
@@ -39,7 +39,7 @@ const ConnectionLine = ({
CustomComponent,
connectionStatus,
}: ConnectionLineProps) => {
const { fromNode, handleId, toX, toY, connectionMode } = useStore(
const { fromNode, handleId, toX, toY, connectionMode, endPosition, isValid } = useStore(
useCallback(
(s: ReactFlowStore) => ({
fromNode: s.nodeLookup.get(nodeId),
@@ -47,11 +47,14 @@ const ConnectionLine = ({
toX: (s.connectionPosition.x - s.transform[0]) / s.transform[2],
toY: (s.connectionPosition.y - s.transform[1]) / s.transform[2],
connectionMode: s.connectionMode,
endPosition: s.connectionEndHandle?.position,
isValid: s.connectionStatus === 'valid',
}),
[nodeId]
),
shallow
);
const fromHandleBounds = fromNode?.internals.handleBounds;
let handleBounds = fromHandleBounds?.[handleType];
@@ -69,7 +72,7 @@ const ConnectionLine = ({
const fromX = fromNode.internals.positionAbsolute.x + fromHandleX;
const fromY = fromNode.internals.positionAbsolute.y + fromHandleY;
const fromPosition = fromHandle?.position;
const toPosition = fromPosition ? oppositePosition[fromPosition] : null;
const toPosition = isValid && endPosition ? endPosition : fromPosition ? oppositePosition[fromPosition] : null;
if (!fromPosition || !toPosition) {
return null;
@@ -1,4 +1,4 @@
// Updatable edges have a anchors around their handles to update the edge.
// Reconnectable edges have a anchors around their handles to reconnect the edge.
import { XYHandle, type Connection, EdgePosition } from '@xyflow/system';
import { EdgeAnchor } from '../Edges/EdgeAnchor';
@@ -7,20 +7,20 @@ import { useStoreApi } from '../../hooks/useStore';
type EdgeUpdateAnchorsProps<EdgeType extends Edge = Edge> = {
edge: EdgeType;
isUpdatable: boolean | 'source' | 'target';
edgeUpdaterRadius: EdgeWrapperProps['edgeUpdaterRadius'];
isReconnectable: boolean | 'source' | 'target';
reconnectRadius: EdgeWrapperProps['reconnectRadius'];
sourceHandleId: Edge['sourceHandle'];
targetHandleId: Edge['targetHandle'];
onEdgeUpdate: EdgeWrapperProps<EdgeType>['onEdgeUpdate'];
onEdgeUpdateStart: EdgeWrapperProps<EdgeType>['onEdgeUpdateStart'];
onEdgeUpdateEnd: EdgeWrapperProps<EdgeType>['onEdgeUpdateEnd'];
onReconnect: EdgeWrapperProps<EdgeType>['onReconnect'];
onReconnectStart: EdgeWrapperProps<EdgeType>['onReconnectStart'];
onReconnectEnd: EdgeWrapperProps<EdgeType>['onReconnectEnd'];
setUpdateHover: (hover: boolean) => void;
setUpdating: (updating: boolean) => void;
setReconnecting: (updating: boolean) => void;
} & EdgePosition;
export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
isUpdatable,
edgeUpdaterRadius,
isReconnectable,
reconnectRadius,
edge,
targetHandleId,
sourceHandleId,
@@ -30,10 +30,10 @@ export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
targetY,
sourcePosition,
targetPosition,
onEdgeUpdate,
onEdgeUpdateStart,
onEdgeUpdateEnd,
setUpdating,
onReconnect,
onReconnectStart,
onReconnectEnd,
setReconnecting,
setUpdateHover,
}: EdgeUpdateAnchorsProps<EdgeType>) {
const store = useStoreApi();
@@ -65,15 +65,15 @@ export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
const isTarget = isSourceHandle;
setUpdating(true);
onEdgeUpdateStart?.(event, edge, handleType);
setReconnecting(true);
onReconnectStart?.(event, edge, handleType);
const _onEdgeUpdateEnd = (evt: MouseEvent | TouchEvent) => {
setUpdating(false);
onEdgeUpdateEnd?.(evt, edge, handleType);
const _onReconnectEnd = (evt: MouseEvent | TouchEvent) => {
setReconnecting(false);
onReconnectEnd?.(evt, edge, handleType);
};
const onConnectEdge = (connection: Connection) => onEdgeUpdate?.(edge, connection);
const onConnectEdge = (connection: Connection) => onReconnect?.(edge, connection);
XYHandle.onPointerDown(event.nativeEvent, {
autoPanOnConnect,
@@ -93,43 +93,43 @@ export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
onConnect: onConnectEdge,
onConnectStart,
onConnectEnd,
onEdgeUpdateEnd: _onEdgeUpdateEnd,
onReconnectEnd: _onReconnectEnd,
updateConnection,
getTransform: () => store.getState().transform,
getConnectionStartHandle: () => store.getState().connectionStartHandle,
});
};
const onEdgeUpdaterSourceMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
const onReconnectSourceMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
handleEdgeUpdater(event, true);
const onEdgeUpdaterTargetMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
const onReconnectTargetMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
handleEdgeUpdater(event, false);
const onEdgeUpdaterMouseEnter = () => setUpdateHover(true);
const onEdgeUpdaterMouseOut = () => setUpdateHover(false);
const onReconnectMouseEnter = () => setUpdateHover(true);
const onReconnectMouseOut = () => setUpdateHover(false);
return (
<>
{(isUpdatable === 'source' || isUpdatable === true) && (
{(isReconnectable === 'source' || isReconnectable === true) && (
<EdgeAnchor
position={sourcePosition}
centerX={sourceX}
centerY={sourceY}
radius={edgeUpdaterRadius}
onMouseDown={onEdgeUpdaterSourceMouseDown}
onMouseEnter={onEdgeUpdaterMouseEnter}
onMouseOut={onEdgeUpdaterMouseOut}
radius={reconnectRadius}
onMouseDown={onReconnectSourceMouseDown}
onMouseEnter={onReconnectMouseEnter}
onMouseOut={onReconnectMouseOut}
type="source"
/>
)}
{(isUpdatable === 'target' || isUpdatable === true) && (
{(isReconnectable === 'target' || isReconnectable === true) && (
<EdgeAnchor
position={targetPosition}
centerX={targetX}
centerY={targetY}
radius={edgeUpdaterRadius}
onMouseDown={onEdgeUpdaterTargetMouseDown}
onMouseEnter={onEdgeUpdaterMouseEnter}
onMouseOut={onEdgeUpdaterMouseOut}
radius={reconnectRadius}
onMouseDown={onReconnectTargetMouseDown}
onMouseEnter={onReconnectMouseEnter}
onMouseOut={onReconnectMouseOut}
type="target"
/>
)}
@@ -18,7 +18,7 @@ import type { Edge, EdgeWrapperProps } from '../../types';
export function EdgeWrapper<EdgeType extends Edge = Edge>({
id,
edgesFocusable,
edgesUpdatable,
edgesReconnectable,
elementsSelectable,
onClick,
onDoubleClick,
@@ -26,10 +26,10 @@ export function EdgeWrapper<EdgeType extends Edge = Edge>({
onMouseEnter,
onMouseMove,
onMouseLeave,
edgeUpdaterRadius,
onEdgeUpdate,
onEdgeUpdateStart,
onEdgeUpdateEnd,
reconnectRadius,
onReconnect,
onReconnectStart,
onReconnectEnd,
rfId,
edgeTypes,
noPanClassName,
@@ -50,14 +50,14 @@ export function EdgeWrapper<EdgeType extends Edge = Edge>({
}
const isFocusable = !!(edge.focusable || (edgesFocusable && typeof edge.focusable === 'undefined'));
const isUpdatable =
typeof onEdgeUpdate !== 'undefined' &&
(edge.updatable || (edgesUpdatable && typeof edge.updatable === 'undefined'));
const isReconnectable =
typeof onReconnect !== 'undefined' &&
(edge.reconnectable || (edgesReconnectable && typeof edge.reconnectable === 'undefined'));
const isSelectable = !!(edge.selectable || (elementsSelectable && typeof edge.selectable === 'undefined'));
const edgeRef = useRef<SVGGElement>(null);
const [updateHover, setUpdateHover] = useState<boolean>(false);
const [updating, setUpdating] = useState<boolean>(false);
const [reconnecting, setReconnecting] = useState<boolean>(false);
const store = useStoreApi();
const { zIndex, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = useStore(
@@ -207,7 +207,7 @@ export function EdgeWrapper<EdgeType extends Edge = Edge>({
aria-describedby={isFocusable ? `${ARIA_EDGE_DESC_KEY}-${rfId}` : undefined}
ref={edgeRef}
>
{!updating && (
{!reconnecting && (
<EdgeComponent
id={id}
source={edge.source}
@@ -215,6 +215,8 @@ export function EdgeWrapper<EdgeType extends Edge = Edge>({
type={edge.type}
selected={edge.selected}
animated={edge.animated}
selectable={isSelectable}
deletable={edge.deletable ?? true}
label={edge.label}
labelStyle={edge.labelStyle}
labelShowBg={edge.labelShowBg}
@@ -237,14 +239,14 @@ export function EdgeWrapper<EdgeType extends Edge = Edge>({
interactionWidth={edge.interactionWidth}
/>
)}
{isUpdatable && (
{isReconnectable && (
<EdgeUpdateAnchors<EdgeType>
edge={edge}
isUpdatable={isUpdatable}
edgeUpdaterRadius={edgeUpdaterRadius}
onEdgeUpdate={onEdgeUpdate}
onEdgeUpdateStart={onEdgeUpdateStart}
onEdgeUpdateEnd={onEdgeUpdateEnd}
isReconnectable={isReconnectable}
reconnectRadius={reconnectRadius}
onReconnect={onReconnect}
onReconnectStart={onReconnectStart}
onReconnectEnd={onReconnectEnd}
sourceX={sourceX}
sourceY={sourceY}
targetX={targetX}
@@ -252,7 +254,7 @@ export function EdgeWrapper<EdgeType extends Edge = Edge>({
sourcePosition={sourcePosition}
targetPosition={targetPosition}
setUpdateHover={setUpdateHover}
setUpdating={setUpdating}
setReconnecting={setReconnecting}
sourceHandleId={edge.sourceHandle}
targetHandleId={edge.targetHandle}
/>
@@ -1,4 +1,4 @@
import { memo, useState, useCallback } from 'react';
import { memo, useState, useEffect, useRef } from 'react';
import cc from 'classcat';
import type { Rect } from '@xyflow/system';
@@ -19,19 +19,20 @@ function EdgeTextComponent({
}: EdgeTextProps) {
const [edgeTextBbox, setEdgeTextBbox] = useState<Rect>({ x: 1, y: 0, width: 0, height: 0 });
const edgeTextClasses = cc(['react-flow__edge-textwrapper', className]);
const edgeTextRef = useRef<SVGTextElement | null>(null);
const onEdgeTextRefChange = useCallback((edgeRef: SVGTextElement) => {
if (edgeRef === null) return;
useEffect(() => {
if (edgeTextRef.current) {
const textBbox = edgeTextRef.current.getBBox();
const textBbox = edgeRef.getBBox();
setEdgeTextBbox({
x: textBbox.x,
y: textBbox.y,
width: textBbox.width,
height: textBbox.height,
});
}, []);
setEdgeTextBbox({
x: textBbox.x,
y: textBbox.y,
width: textBbox.width,
height: textBbox.height,
});
}
}, [label]);
if (typeof label === 'undefined' || !label) {
return null;
@@ -60,7 +61,7 @@ function EdgeTextComponent({
className="react-flow__edge-text"
y={edgeTextBbox.height / 2}
dy="0.3em"
ref={onEdgeTextRefChange}
ref={edgeTextRef}
style={labelStyle}
>
{label}
@@ -202,12 +202,16 @@ export function NodeWrapper<NodeType extends Node>({
positionAbsoluteX={clampedPosition.x}
positionAbsoluteY={clampedPosition.y}
selected={node.selected}
selectable={isSelectable}
draggable={isDraggable}
deletable={node.deletable ?? true}
isConnectable={isConnectable}
sourcePosition={node.sourcePosition}
targetPosition={node.targetPosition}
dragging={dragging}
dragHandle={node.dragHandle}
zIndex={internals.z}
parentId={node.parentId}
{...nodeDimensions}
/>
</Provider>
@@ -26,17 +26,17 @@ export function useNodeObserver({
const prevSourcePosition = useRef(node.sourcePosition);
const prevTargetPosition = useRef(node.targetPosition);
const prevType = useRef(nodeType);
const isInitialized = hasDimensions && !!node.internals.handleBounds && !node.hidden;
const isInitialized = hasDimensions && !!node.internals.handleBounds;
useEffect(() => {
if (nodeRef.current && (!isInitialized || observedNode.current !== nodeRef.current)) {
if (nodeRef.current && !node.hidden && (!isInitialized || observedNode.current !== nodeRef.current)) {
if (observedNode.current) {
resizeObserver?.unobserve(observedNode.current);
}
resizeObserver?.observe(nodeRef.current);
observedNode.current = nodeRef.current;
}
}, [isInitialized]);
}, [isInitialized, node.hidden]);
useEffect(() => {
return () => {
@@ -26,7 +26,7 @@ const reactFlowFieldsToTrack = [
'nodesConnectable',
'nodesFocusable',
'edgesFocusable',
'edgesUpdatable',
'edgesReconnectable',
'elevateNodesOnSelect',
'elevateEdgesOnSelect',
'minZoom',
@@ -14,14 +14,14 @@ type EdgeRendererProps<EdgeType extends Edge = Edge> = Pick<
| 'onEdgeDoubleClick'
| 'defaultMarkerColor'
| 'onlyRenderVisibleElements'
| 'onEdgeUpdate'
| 'onReconnect'
| 'onEdgeContextMenu'
| 'onEdgeMouseEnter'
| 'onEdgeMouseMove'
| 'onEdgeMouseLeave'
| 'onEdgeUpdateStart'
| 'onEdgeUpdateEnd'
| 'edgeUpdaterRadius'
| 'onReconnectStart'
| 'onReconnectEnd'
| 'reconnectRadius'
| 'noPanClassName'
| 'rfId'
| 'disableKeyboardA11y'
@@ -34,7 +34,7 @@ const selector = (s: ReactFlowState) => ({
width: s.width,
height: s.height,
edgesFocusable: s.edgesFocusable,
edgesUpdatable: s.edgesUpdatable,
edgesReconnectable: s.edgesReconnectable,
elementsSelectable: s.elementsSelectable,
connectionMode: s.connectionMode,
onError: s.onError,
@@ -46,19 +46,19 @@ function EdgeRendererComponent<EdgeType extends Edge = Edge>({
rfId,
edgeTypes,
noPanClassName,
onEdgeUpdate,
onReconnect,
onEdgeContextMenu,
onEdgeMouseEnter,
onEdgeMouseMove,
onEdgeMouseLeave,
onEdgeClick,
edgeUpdaterRadius,
reconnectRadius,
onEdgeDoubleClick,
onEdgeUpdateStart,
onEdgeUpdateEnd,
onReconnectStart,
onReconnectEnd,
disableKeyboardA11y,
}: EdgeRendererProps<EdgeType>) {
const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
const { edgesFocusable, edgesReconnectable, elementsSelectable, onError } = useStore(selector, shallow);
const edgeIds = useVisibleEdgeIds(onlyRenderVisibleElements);
return (
@@ -71,19 +71,19 @@ function EdgeRendererComponent<EdgeType extends Edge = Edge>({
key={id}
id={id}
edgesFocusable={edgesFocusable}
edgesUpdatable={edgesUpdatable}
edgesReconnectable={edgesReconnectable}
elementsSelectable={elementsSelectable}
noPanClassName={noPanClassName}
onEdgeUpdate={onEdgeUpdate}
onReconnect={onReconnect}
onContextMenu={onEdgeContextMenu}
onMouseEnter={onEdgeMouseEnter}
onMouseMove={onEdgeMouseMove}
onMouseLeave={onEdgeMouseLeave}
onClick={onEdgeClick}
edgeUpdaterRadius={edgeUpdaterRadius}
reconnectRadius={reconnectRadius}
onDoubleClick={onEdgeDoubleClick}
onEdgeUpdateStart={onEdgeUpdateStart}
onEdgeUpdateEnd={onEdgeUpdateEnd}
onReconnectStart={onReconnectStart}
onReconnectEnd={onReconnectEnd}
rfId={rfId}
onError={onError}
edgeTypes={edgeTypes}
@@ -28,6 +28,8 @@ export type FlowRendererProps<NodeType extends Node = Node> = Omit<
children: ReactNode;
};
const win = typeof window !== 'undefined' ? window : undefined;
const selector = (s: ReactFlowState) => {
return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive };
};
@@ -70,8 +72,8 @@ function FlowRendererComponent<NodeType extends Node = Node>({
isControlledViewport,
}: FlowRendererProps<NodeType>) {
const { nodesSelectionActive, userSelectionActive } = useStore(selector);
const selectionKeyPressed = useKeyPress(selectionKeyCode);
const panActivationKeyPressed = useKeyPress(panActivationKeyCode);
const selectionKeyPressed = useKeyPress(selectionKeyCode, { target: win });
const panActivationKeyPressed = useKeyPress(panActivationKeyCode, { target: win });
const panOnDrag = panActivationKeyPressed || _panOnDrag;
const panOnScroll = panActivationKeyPressed || _panOnScroll;
@@ -113,6 +115,7 @@ function FlowRendererComponent<NodeType extends Node = Node>({
panOnDrag={panOnDrag}
isSelecting={!!isSelecting}
selectionMode={selectionMode}
selectionKeyPressed={selectionKeyPressed}
>
{children}
{nodesSelectionActive && (
@@ -85,14 +85,14 @@ function GraphViewComponent<NodeType extends Node = Node, EdgeType extends Edge
onPaneMouseLeave,
onPaneScroll,
onPaneContextMenu,
onEdgeUpdate,
onEdgeContextMenu,
onEdgeMouseEnter,
onEdgeMouseMove,
onEdgeMouseLeave,
edgeUpdaterRadius,
onEdgeUpdateStart,
onEdgeUpdateEnd,
reconnectRadius,
onReconnect,
onReconnectStart,
onReconnectEnd,
noDragClassName,
noWheelClassName,
noPanClassName,
@@ -153,15 +153,15 @@ function GraphViewComponent<NodeType extends Node = Node, EdgeType extends Edge
edgeTypes={edgeTypes}
onEdgeClick={onEdgeClick}
onEdgeDoubleClick={onEdgeDoubleClick}
onEdgeUpdate={onEdgeUpdate}
onReconnect={onReconnect}
onReconnectStart={onReconnectStart}
onReconnectEnd={onReconnectEnd}
onlyRenderVisibleElements={onlyRenderVisibleElements}
onEdgeContextMenu={onEdgeContextMenu}
onEdgeMouseEnter={onEdgeMouseEnter}
onEdgeMouseMove={onEdgeMouseMove}
onEdgeMouseLeave={onEdgeMouseLeave}
onEdgeUpdateStart={onEdgeUpdateStart}
onEdgeUpdateEnd={onEdgeUpdateEnd}
edgeUpdaterRadius={edgeUpdaterRadius}
reconnectRadius={reconnectRadius}
defaultMarkerColor={defaultMarkerColor}
noPanClassName={noPanClassName}
disableKeyboardA11y={disableKeyboardA11y}
@@ -20,6 +20,7 @@ export function useResizeObserver() {
updates.set(id, {
id,
nodeElement: entry.target as HTMLDivElement,
force: true,
});
});
+35 -19
View File
@@ -2,7 +2,12 @@
* The user selection rectangle gets displayed when a user drags the mouse while pressing shift
*/
import { useRef, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react';
import {
useRef,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from 'react';
import { shallow } from 'zustand/shallow';
import cc from 'classcat';
import { getNodesInside, getEventPosition, SelectionMode, type NodeChange, type EdgeChange } from '@xyflow/system';
@@ -15,6 +20,7 @@ import type { ReactFlowProps, ReactFlowState } from '../../types';
type PaneProps = {
isSelecting: boolean;
selectionKeyPressed: boolean;
children: ReactNode;
} & Partial<
Pick<
@@ -52,6 +58,7 @@ const selector = (s: ReactFlowState) => ({
export function Pane({
isSelecting,
selectionKeyPressed,
selectionMode = SelectionMode.Full,
panOnDrag,
onSelectionStart,
@@ -72,6 +79,10 @@ export function Pane({
const edgeIdLookup = useRef<Map<string, Set<string>>>(new Map());
const { userSelectionActive, elementsSelectable, dragging } = useStore(selector, shallow);
const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive);
// Used to prevent click events when the user lets go of the selectionKey during a selection
const selectionInProgress = useRef<boolean>(false);
const resetUserSelection = () => {
store.setState({ userSelectionActive: false, userSelectionRect: null });
@@ -81,6 +92,12 @@ export function Pane({
};
const onClick = (event: ReactMouseEvent) => {
// We prevent click events when the user let go of the selectionKey during a selection
if (selectionInProgress.current) {
selectionInProgress.current = false;
return;
}
onPaneClick?.(event);
store.getState().resetSelectedElements();
store.setState({ nodesSelectionActive: false });
@@ -97,9 +114,10 @@ export function Pane({
const onWheel = onPaneScroll ? (event: React.WheelEvent) => onPaneScroll(event) : undefined;
const onMouseDown = (event: ReactMouseEvent): void => {
const onPointerDown = (event: ReactPointerEvent): void => {
const { resetSelectedElements, domNode, edgeLookup } = store.getState();
containerBounds.current = domNode?.getBoundingClientRect();
container.current?.setPointerCapture(event.pointerId);
if (
!elementsSelectable ||
@@ -136,14 +154,16 @@ export function Pane({
onSelectionStart?.(event);
};
const onMouseMove = (event: ReactMouseEvent): void => {
const onPointerMove = (event: ReactPointerEvent): void => {
const { userSelectionRect, edgeLookup, transform, nodeOrigin, nodeLookup, triggerNodeChanges, triggerEdgeChanges } =
store.getState();
if (!isSelecting || !containerBounds.current || !userSelectionRect) {
if (!containerBounds.current || !userSelectionRect) {
return;
}
selectionInProgress.current = true;
const { x: mouseX, y: mouseY } = getEventPosition(event.nativeEvent, containerBounds.current);
const { startX, startY } = userSelectionRect;
@@ -199,10 +219,11 @@ export function Pane({
});
};
const onMouseUp = (event: ReactMouseEvent) => {
const onPointerUp = (event: ReactPointerEvent) => {
if (event.button !== 0) {
return;
}
container.current?.releasePointerCapture(event.pointerId);
const { userSelectionRect } = store.getState();
// We only want to trigger click functions when in selection mode if
// the user did not move the mouse.
@@ -214,30 +235,25 @@ export function Pane({
resetUserSelection();
onSelectionEnd?.(event);
};
const onMouseLeave = (event: ReactMouseEvent) => {
if (userSelectionActive) {
store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 });
onSelectionEnd?.(event);
// If the user kept holding the selectionKey during the selection,
// we need to reset the selectionInProgress, so the next click event is not prevented
if (selectionKeyPressed) {
selectionInProgress.current = false;
}
resetUserSelection();
};
const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive);
return (
<div
className={cc(['react-flow__pane', { draggable: panOnDrag, dragging, selection: isSelecting }])}
onClick={hasActiveSelection ? undefined : wrapHandler(onClick, container)}
onContextMenu={wrapHandler(onContextMenu, container)}
onWheel={wrapHandler(onWheel, container)}
onMouseEnter={hasActiveSelection ? undefined : onPaneMouseEnter}
onMouseDown={hasActiveSelection ? onMouseDown : undefined}
onMouseMove={hasActiveSelection ? onMouseMove : onPaneMouseMove}
onMouseUp={hasActiveSelection ? onMouseUp : undefined}
onMouseLeave={hasActiveSelection ? onMouseLeave : onPaneMouseLeave}
onPointerEnter={hasActiveSelection ? undefined : onPaneMouseEnter}
onPointerDown={hasActiveSelection ? onPointerDown : onPaneMouseMove}
onPointerMove={hasActiveSelection ? onPointerMove : onPaneMouseMove}
onPointerUp={hasActiveSelection ? onPointerUp : undefined}
onPointerLeave={onPaneMouseLeave}
ref={container}
style={containerStyle}
>
@@ -81,7 +81,7 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
nodesFocusable,
nodeOrigin = defaultNodeOrigin,
edgesFocusable,
edgesUpdatable,
edgesReconnectable,
elementsSelectable = true,
defaultViewport = initViewport,
minZoom = 0.5,
@@ -104,15 +104,15 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onPaneScroll,
onPaneContextMenu,
children,
onEdgeUpdate,
onReconnect,
onReconnectStart,
onReconnectEnd,
onEdgeContextMenu,
onEdgeDoubleClick,
onEdgeMouseEnter,
onEdgeMouseMove,
onEdgeMouseLeave,
onEdgeUpdateStart,
onEdgeUpdateEnd,
edgeUpdaterRadius = 10,
reconnectRadius = 10,
onNodesChange,
onEdgesChange,
noDragClassName = 'nodrag',
@@ -202,15 +202,15 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onSelectionContextMenu={onSelectionContextMenu}
onSelectionStart={onSelectionStart}
onSelectionEnd={onSelectionEnd}
onEdgeUpdate={onEdgeUpdate}
onReconnect={onReconnect}
onReconnectStart={onReconnectStart}
onReconnectEnd={onReconnectEnd}
onEdgeContextMenu={onEdgeContextMenu}
onEdgeDoubleClick={onEdgeDoubleClick}
onEdgeMouseEnter={onEdgeMouseEnter}
onEdgeMouseMove={onEdgeMouseMove}
onEdgeMouseLeave={onEdgeMouseLeave}
onEdgeUpdateStart={onEdgeUpdateStart}
onEdgeUpdateEnd={onEdgeUpdateEnd}
edgeUpdaterRadius={edgeUpdaterRadius}
reconnectRadius={reconnectRadius}
defaultMarkerColor={defaultMarkerColor}
noDragClassName={noDragClassName}
noWheelClassName={noWheelClassName}
@@ -236,7 +236,7 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
nodesConnectable={nodesConnectable}
nodesFocusable={nodesFocusable}
edgesFocusable={edgesFocusable}
edgesUpdatable={edgesUpdatable}
edgesReconnectable={edgesReconnectable}
elementsSelectable={elementsSelectable}
elevateNodesOnSelect={elevateNodesOnSelect}
elevateEdgesOnSelect={elevateEdgesOnSelect}
@@ -9,6 +9,7 @@ import { Edge, Node } from '../types';
const selected = (item: Node | Edge) => item.selected;
const deleteKeyOptions: UseKeyPressOptions = { actInsideInputWithModifier: false };
const win = typeof window !== 'undefined' ? window : undefined;
/**
* Hook for handling global key events.
@@ -26,7 +27,7 @@ export function useGlobalKeyHandler({
const { deleteElements } = useReactFlow();
const deleteKeyPressed = useKeyPress(deleteKeyCode, deleteKeyOptions);
const multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode);
const multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode, { target: win });
useEffect(() => {
if (deleteKeyPressed) {
+34 -4
View File
@@ -13,7 +13,7 @@ import {
import useViewportHelper from './useViewportHelper';
import { useStore, useStoreApi } from './useStore';
import { useBatchContext } from '../components/BatchProvider';
import { elementToRemoveChange, isNode } from '../utils';
import { elementToRemoveChange, isEdge, isNode } from '../utils';
import type { ReactFlowInstance, Node, Edge, InternalNode, ReactFlowState, GeneralHelpers } from '../types';
const selector = (s: ReactFlowState) => !!s.panZoom;
@@ -41,6 +41,10 @@ export function useReactFlow<NodeType extends Node = Node, EdgeType extends Edge
batchContext.nodeQueue.push(payload as NodeType[]);
};
const setEdges: GeneralHelpers<NodeType, EdgeType>['setEdges'] = (payload) => {
batchContext.edgeQueue.push(payload as EdgeType[]);
};
const getNodeRect = (node: NodeType | { id: string }): Rect | null => {
const { nodeLookup, nodeOrigin } = store.getState();
@@ -77,6 +81,23 @@ export function useReactFlow<NodeType extends Node = Node, EdgeType extends Edge
);
};
const updateEdge: GeneralHelpers<NodeType, EdgeType>['updateEdge'] = (
id,
edgeUpdate,
options = { replace: false }
) => {
setEdges((prevEdges) =>
prevEdges.map((edge) => {
if (edge.id === id) {
const nextEdge = typeof edgeUpdate === 'function' ? edgeUpdate(edge as EdgeType) : edgeUpdate;
return options.replace && isEdge(nextEdge) ? (nextEdge as EdgeType) : { ...edge, ...nextEdge };
}
return edge;
})
);
};
return {
getNodes: () => store.getState().nodes.map((n) => ({ ...n })) as NodeType[],
getNode: (id) => getInternalNode(id)?.internals.userNode as NodeType,
@@ -87,9 +108,7 @@ export function useReactFlow<NodeType extends Node = Node, EdgeType extends Edge
},
getEdge: (id) => store.getState().edgeLookup.get(id) as EdgeType,
setNodes,
setEdges: (payload) => {
batchContext.edgeQueue.push(payload as EdgeType[]);
},
setEdges,
addNodes: (payload) => {
const newNodes = Array.isArray(payload) ? payload : [payload];
batchContext.nodeQueue.push((nodes) => [...nodes, ...newNodes]);
@@ -200,6 +219,17 @@ export function useReactFlow<NodeType extends Node = Node, EdgeType extends Edge
options
);
},
updateEdge,
updateEdgeData: (id, dataUpdate, options = { replace: false }) => {
updateEdge(
id,
(edge) => {
const nextData = typeof dataUpdate === 'function' ? dataUpdate(edge) : dataUpdate;
return options.replace ? { ...edge, data: nextData } : { ...edge, data: { ...edge.data, ...nextData } };
},
options
);
},
};
}, []);
+1 -1
View File
@@ -116,6 +116,6 @@ export {
getIncomers,
getOutgoers,
addEdge,
updateEdge,
reconnectEdge,
getConnectedEdges,
} from '@xyflow/system';
+1 -1
View File
@@ -92,7 +92,7 @@ const getInitialState = ({
nodesConnectable: true,
nodesFocusable: true,
edgesFocusable: true,
edgesUpdatable: true,
edgesReconnectable: true,
elementsSelectable: true,
elevateNodesOnSelect: true,
elevateEdgesOnSelect: false,
+6 -6
View File
@@ -29,7 +29,7 @@ import type {
Node,
Edge,
ConnectionLineComponent,
OnEdgeUpdateFunc,
OnReconnect,
OnInit,
DefaultEdgeOptions,
FitViewOptions,
@@ -129,9 +129,9 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
onEdgeMouseLeave?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when a user double clicks on an edge */
onEdgeDoubleClick?: EdgeMouseHandler<EdgeType>;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdate?: OnEdgeUpdateFunc<EdgeType>;
onReconnect?: OnReconnect<EdgeType>;
onReconnectStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onReconnectEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
/** This event handler is called when a Node is updated
* @example // Use NodesState hook to create edges and get onNodesChange handler
* import ReactFlow, { useNodesState } from '@xyflow/react';
@@ -330,7 +330,7 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
/** Controls if all edges should be updateable
* @default true
*/
edgesUpdatable?: boolean;
edgesReconnectable?: boolean;
/** Controls if all elements should (nodes & edges) be selectable
* @default true
*/
@@ -413,7 +413,7 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
panOnScrollMode?: PanOnScrollMode;
/** Controls if the viewport should zoom by double clicking somewhere on the flow */
zoomOnDoubleClick?: boolean;
edgeUpdaterRadius?: number;
reconnectRadius?: number;
noDragClassName?: string;
noWheelClassName?: string;
noPanClassName?: string;
+11 -11
View File
@@ -28,8 +28,6 @@ export type EdgeLabelOptions = {
labelBgBorderRadius?: number;
};
export type EdgeUpdatable = boolean | HandleType;
/**
* The Edge type is mainly used for the `edges` that get passed to the ReactFlow component
* @public
@@ -41,7 +39,7 @@ export type Edge<
EdgeLabelOptions & {
style?: CSSProperties;
className?: string;
updatable?: EdgeUpdatable;
reconnectable?: boolean | HandleType;
focusable?: boolean;
};
@@ -60,26 +58,28 @@ type StepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>
pathOptions?: StepPathOptions;
};
export type BuiltInEdge = SmoothStepEdge | BezierEdge | StepEdge;
type StraightEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<EdgeData, 'straight'>;
export type BuiltInEdge = SmoothStepEdge | BezierEdge | StepEdge | StraightEdge;
export type EdgeMouseHandler<EdgeType extends Edge = Edge> = (event: ReactMouseEvent, edge: EdgeType) => void;
export type EdgeWrapperProps<EdgeType extends Edge = Edge> = {
id: string;
edgesFocusable: boolean;
edgesUpdatable: boolean;
edgesReconnectable: boolean;
elementsSelectable: boolean;
noPanClassName: string;
onClick?: EdgeMouseHandler<EdgeType>;
onDoubleClick?: EdgeMouseHandler<EdgeType>;
onEdgeUpdate?: OnEdgeUpdateFunc<EdgeType>;
onReconnect?: OnReconnect<EdgeType>;
onContextMenu?: EdgeMouseHandler<EdgeType>;
onMouseEnter?: EdgeMouseHandler<EdgeType>;
onMouseMove?: EdgeMouseHandler<EdgeType>;
onMouseLeave?: EdgeMouseHandler<EdgeType>;
edgeUpdaterRadius?: number;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
reconnectRadius?: number;
onReconnectStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onReconnectEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
rfId?: string;
edgeTypes?: EdgeTypes;
onError?: OnError;
@@ -100,7 +100,7 @@ export type EdgeTextProps = HTMLAttributes<SVGElement> &
*/
export type EdgeProps<EdgeType extends Edge = Edge> = Pick<
EdgeType,
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target' | 'selectable' | 'deletable'
> &
EdgePosition &
EdgeLabelOptions & {
@@ -189,7 +189,7 @@ export type StraightEdgeProps = Omit<EdgeComponentProps, 'sourcePosition' | 'tar
*/
export type SimpleBezierEdgeProps = EdgeComponentProps;
export type OnEdgeUpdateFunc<EdgeType extends Edge = Edge> = (oldEdge: EdgeType, newConnection: Connection) => void;
export type OnReconnect<EdgeType extends Edge = Edge> = (oldEdge: EdgeType, newConnection: Connection) => void;
export type ConnectionLineComponentProps = {
connectionLineStyle?: CSSProperties;
+31 -1
View File
@@ -140,7 +140,37 @@ export type GeneralHelpers<NodeType extends Node = Node, EdgeType extends Edge =
*/
updateNodeData: (
id: string,
dataUpdate: object | ((node: NodeType) => object),
dataUpdate: Partial<NodeType['data']> | ((node: NodeType) => Partial<NodeType['data']>),
options?: { replace: boolean }
) => void;
/**
* Updates an edge.
*
* @param id - id of the edge to update
* @param edgeUpdate - the edge update as an object or a function that receives the current edge and returns the edge update
* @param options.replace - if true, the edge is replaced with the edge update, otherwise the changes get merged
*
* @example
* updateEdge('edge-1', (edge) => ({ label: 'A new label' }));
*/
updateEdge: (
id: string,
edgeUpdate: Partial<EdgeType> | ((edge: EdgeType) => Partial<EdgeType>),
options?: { replace: boolean }
) => void;
/**
* Updates the data attribute of a edge.
*
* @param id - id of the edge to update
* @param dataUpdate - the data update as an object or a function that receives the current data and returns the data update
* @param options.replace - if true, the data is replaced with the data update, otherwise the changes get merged
*
* @example
* updateEdgeData('edge-1', { label: 'A new label' });
*/
updateEdgeData: (
id: string,
dataUpdate: Partial<EdgeType['data']> | ((edge: EdgeType) => Partial<EdgeType['data']>),
options?: { replace: boolean }
) => void;
};
+1 -1
View File
@@ -89,7 +89,7 @@ export type ReactFlowStore<NodeType extends Node = Node, EdgeType extends Edge =
nodesConnectable: boolean;
nodesFocusable: boolean;
edgesFocusable: boolean;
edgesUpdatable: boolean;
edgesReconnectable: boolean;
elementsSelectable: boolean;
elevateNodesOnSelect: boolean;
elevateEdgesOnSelect: boolean;