feat: add events for when selection starts and ends.

This commit is contained in:
Jack Fishwick
2022-11-22 11:04:01 +00:00
parent 4e874b90a8
commit 1de6de1f96
4 changed files with 150 additions and 123 deletions
@@ -19,6 +19,8 @@ type EventHandlers = { [key: string]: React.MouseEventHandler | React.WheelEvent
type UserSelectionProps = { type UserSelectionProps = {
isSelectionMode: boolean; isSelectionMode: boolean;
onSelectionStart?: (e: React.MouseEvent) => void;
onSelectionEnd?: (e: React.MouseEvent) => void;
onClick?: (e: React.MouseEvent) => void; onClick?: (e: React.MouseEvent) => void;
onContextMenu?: (e: React.MouseEvent) => void; onContextMenu?: (e: React.MouseEvent) => void;
onWheel?: (e: React.WheelEvent) => void; onWheel?: (e: React.WheelEvent) => void;
@@ -55,144 +57,159 @@ const selector = (s: ReactFlowState) => ({
elementsSelectable: s.elementsSelectable, elementsSelectable: s.elementsSelectable,
}); });
const UserSelection = memo(({ isSelectionMode, onClick, onContextMenu, onWheel, children }: UserSelectionProps) => { const UserSelection = memo(
const container = useRef<HTMLDivElement | null>(null); ({
const store = useStoreApi(); isSelectionMode,
const prevSelectedNodesCount = useRef<number>(0); onSelectionStart,
const prevSelectedEdgesCount = useRef<number>(0); onSelectionEnd,
const containerBounds = useRef<DOMRect>(); onClick,
const [userSelectionRect, setUserSelectionRect] = useState<SelectionRect | null>(null); onContextMenu,
const { userSelectionActive, elementsSelectable } = useStore(selector, shallow); onWheel,
children,
}: UserSelectionProps) => {
const container = useRef<HTMLDivElement | null>(null);
const store = useStoreApi();
const prevSelectedNodesCount = useRef<number>(0);
const prevSelectedEdgesCount = useRef<number>(0);
const containerBounds = useRef<DOMRect>();
const [userSelectionRect, setUserSelectionRect] = useState<SelectionRect | null>(null);
const { userSelectionActive, elementsSelectable } = useStore(selector, shallow);
const resetUserSelection = () => { const resetUserSelection = () => {
setUserSelectionRect(null); setUserSelectionRect(null);
store.setState({ userSelectionActive: false }); store.setState({ userSelectionActive: false });
prevSelectedNodesCount.current = 0; prevSelectedNodesCount.current = 0;
prevSelectedEdgesCount.current = 0; prevSelectedEdgesCount.current = 0;
};
const onMouseDown = (event: React.MouseEvent): void => {
if (!elementsSelectable || !isSelectionMode || event.button !== 0 || event.target !== container.current) {
return;
}
store.getState().resetSelectedElements();
const reactFlowNode = (event.target as Element).closest('.react-flow')!;
containerBounds.current = reactFlowNode.getBoundingClientRect();
const mousePos = getMousePosition(event, containerBounds.current!);
setUserSelectionRect({
width: 0,
height: 0,
startX: mousePos.x,
startY: mousePos.y,
x: mousePos.x,
y: mousePos.y,
});
};
const onMouseMove = (event: React.MouseEvent): void => {
if (!isSelectionMode || !containerBounds.current || !userSelectionRect) {
return;
}
store.setState({ userSelectionActive: true, nodesSelectionActive: false });
const mousePos = getMousePosition(event, containerBounds.current!);
const startX = userSelectionRect.startX ?? 0;
const startY = userSelectionRect.startY ?? 0;
const nextUserSelectRect = {
...userSelectionRect,
x: mousePos.x < startX ? mousePos.x : startX,
y: mousePos.y < startY ? mousePos.y : startY,
width: Math.abs(mousePos.x - startX),
height: Math.abs(mousePos.y - startY),
draw: true,
}; };
const { nodeInternals, edges, transform, onNodesChange, onEdgesChange, nodeOrigin } = store.getState(); const onMouseDown = (event: React.MouseEvent): void => {
const nodes = Array.from(nodeInternals.values()); if (!elementsSelectable || !isSelectionMode || event.button !== 0 || event.target !== container.current) {
const selectedNodes = getNodesInside(nodeInternals, nextUserSelectRect, transform, true, true, nodeOrigin); return;
const selectedEdgeIds = getConnectedEdges(selectedNodes, edges).map((e) => e.id);
const selectedNodeIds = selectedNodes.map((n) => n.id);
if (prevSelectedNodesCount.current !== selectedNodeIds.length) {
prevSelectedNodesCount.current = selectedNodeIds.length;
const changes = getSelectionChanges(nodes, selectedNodeIds) as NodeChange[];
if (changes.length) {
onNodesChange?.(changes);
} }
}
if (prevSelectedEdgesCount.current !== selectedEdgeIds.length) { store.getState().resetSelectedElements();
prevSelectedEdgesCount.current = selectedEdgeIds.length;
const changes = getSelectionChanges(edges, selectedEdgeIds) as EdgeChange[]; const reactFlowNode = (event.target as Element).closest('.react-flow')!;
if (changes.length) { containerBounds.current = reactFlowNode.getBoundingClientRect();
onEdgesChange?.(changes);
const mousePos = getMousePosition(event, containerBounds.current!);
setUserSelectionRect({
width: 0,
height: 0,
startX: mousePos.x,
startY: mousePos.y,
x: mousePos.x,
y: mousePos.y,
});
onSelectionStart?.(event);
};
const onMouseMove = (event: React.MouseEvent): void => {
if (!isSelectionMode || !containerBounds.current || !userSelectionRect) {
return;
} }
}
setUserSelectionRect(nextUserSelectRect); store.setState({ userSelectionActive: true, nodesSelectionActive: false });
};
const onMouseUp = (event: React.MouseEvent) => { const mousePos = getMousePosition(event, containerBounds.current!);
// We only want to trigger click functions when in selection mode if const startX = userSelectionRect.startX ?? 0;
// the user did not move the mouse. const startY = userSelectionRect.startY ?? 0;
if (!userSelectionActive && userSelectionRect && event.target === container.current) {
onClick?.(event);
}
store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 }); const nextUserSelectRect = {
...userSelectionRect,
x: mousePos.x < startX ? mousePos.x : startX,
y: mousePos.y < startY ? mousePos.y : startY,
width: Math.abs(mousePos.x - startX),
height: Math.abs(mousePos.y - startY),
draw: true,
};
resetUserSelection(); const { nodeInternals, edges, transform, onNodesChange, onEdgesChange, nodeOrigin } = store.getState();
}; const nodes = Array.from(nodeInternals.values());
const selectedNodes = getNodesInside(nodeInternals, nextUserSelectRect, transform, true, true, nodeOrigin);
const selectedEdgeIds = getConnectedEdges(selectedNodes, edges).map((e) => e.id);
const selectedNodeIds = selectedNodes.map((n) => n.id);
const onMouseLeave = () => { if (prevSelectedNodesCount.current !== selectedNodeIds.length) {
if (userSelectionActive) { prevSelectedNodesCount.current = selectedNodeIds.length;
store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 }); const changes = getSelectionChanges(nodes, selectedNodeIds) as NodeChange[];
} if (changes.length) {
resetUserSelection(); onNodesChange?.(changes);
};
const eventHandlers =
elementsSelectable && (isSelectionMode || userSelectionActive)
? {
...wrapHandlers({ onContextMenu, onWheel }, container),
onMouseDown,
onMouseMove,
onMouseUp,
onMouseLeave,
} }
: wrapHandlers( }
{
onClick,
onContextMenu,
onWheel,
},
container
);
return ( if (prevSelectedEdgesCount.current !== selectedEdgeIds.length) {
<div className="react-flow__pane react-flow__container" {...eventHandlers} ref={container}> prevSelectedEdgesCount.current = selectedEdgeIds.length;
{children} const changes = getSelectionChanges(edges, selectedEdgeIds) as EdgeChange[];
{userSelectionActive && userSelectionRect && ( if (changes.length) {
<div onEdgesChange?.(changes);
className="react-flow__selection react-flow__container" }
style={{ }
width: userSelectionRect.width,
height: userSelectionRect.height, setUserSelectionRect(nextUserSelectRect);
transform: `translate(${userSelectionRect.x}px, ${userSelectionRect.y}px)`, };
}}
/> const onMouseUp = (event: React.MouseEvent) => {
)} // We only want to trigger click functions when in selection mode if
</div> // the user did not move the mouse.
); if (!userSelectionActive && userSelectionRect && event.target === container.current) {
}); onClick?.(event);
}
store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 });
resetUserSelection();
onSelectionEnd?.(event);
};
const onMouseLeave = (event: React.MouseEvent) => {
if (userSelectionActive) {
store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 });
onSelectionEnd?.(event);
}
resetUserSelection();
};
const eventHandlers =
elementsSelectable && (isSelectionMode || userSelectionActive)
? {
...wrapHandlers({ onContextMenu, onWheel }, container),
onMouseDown,
onMouseMove,
onMouseUp,
onMouseLeave,
}
: wrapHandlers(
{
onClick,
onContextMenu,
onWheel,
},
container
);
return (
<div className="react-flow__pane react-flow__container" {...eventHandlers} ref={container}>
{children}
{userSelectionActive && userSelectionRect && (
<div
className="react-flow__selection react-flow__container"
style={{
width: userSelectionRect.width,
height: userSelectionRect.height,
transform: `translate(${userSelectionRect.x}px, ${userSelectionRect.y}px)`,
}}
/>
)}
</div>
);
}
);
UserSelection.displayName = 'UserSelection'; UserSelection.displayName = 'UserSelection';
@@ -45,6 +45,8 @@ const FlowRenderer = ({
onMoveEnd, onMoveEnd,
selectionKeyCode, selectionKeyCode,
selectBoxOnDrag, selectBoxOnDrag,
onSelectionStart,
onSelectionEnd,
multiSelectionKeyCode, multiSelectionKeyCode,
zoomActivationKeyCode, zoomActivationKeyCode,
elementsSelectable, elementsSelectable,
@@ -112,6 +114,8 @@ const FlowRenderer = ({
noPanClassName={noPanClassName} noPanClassName={noPanClassName}
> >
<UserSelection <UserSelection
onSelectionStart={onSelectionStart}
onSelectionEnd={onSelectionEnd}
onClick={onClick} onClick={onClick}
onMouseEnter={onPaneMouseEnter} onMouseEnter={onPaneMouseEnter}
onMouseMove={onPaneMouseMove} onMouseMove={onPaneMouseMove}
@@ -92,6 +92,8 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
onSelectionDrag, onSelectionDrag,
onSelectionDragStop, onSelectionDragStop,
onSelectionContextMenu, onSelectionContextMenu,
onSelectionStart,
onSelectionEnd,
connectionMode = ConnectionMode.Strict, connectionMode = ConnectionMode.Strict,
connectionLineType = ConnectionLineType.Bezier, connectionLineType = ConnectionLineType.Bezier,
connectionLineStyle, connectionLineStyle,
@@ -219,6 +221,8 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
onPaneScroll={onPaneScroll} onPaneScroll={onPaneScroll}
onPaneContextMenu={onPaneContextMenu} onPaneContextMenu={onPaneContextMenu}
onSelectionContextMenu={onSelectionContextMenu} onSelectionContextMenu={onSelectionContextMenu}
onSelectionStart={onSelectionStart}
onSelectionEnd={onSelectionEnd}
onEdgeUpdate={onEdgeUpdate} onEdgeUpdate={onEdgeUpdate}
onEdgeContextMenu={onEdgeContextMenu} onEdgeContextMenu={onEdgeContextMenu}
onEdgeDoubleClick={onEdgeDoubleClick} onEdgeDoubleClick={onEdgeDoubleClick}
@@ -68,6 +68,8 @@ export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
onSelectionDragStart?: SelectionDragHandler; onSelectionDragStart?: SelectionDragHandler;
onSelectionDrag?: SelectionDragHandler; onSelectionDrag?: SelectionDragHandler;
onSelectionDragStop?: SelectionDragHandler; onSelectionDragStop?: SelectionDragHandler;
onSelectionStart?: (event: ReactMouseEvent) => void;
onSelectionEnd?: (event: ReactMouseEvent) => void;
onSelectionContextMenu?: (event: ReactMouseEvent, nodes: Node[]) => void; onSelectionContextMenu?: (event: ReactMouseEvent, nodes: Node[]) => void;
onConnect?: OnConnect; onConnect?: OnConnect;
onConnectStart?: OnConnectStart; onConnectStart?: OnConnectStart;