update useNodeConnections
This commit is contained in:
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
'@xyflow/react': patch
|
||||||
|
'@xyflow/system': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Optimize selections and take into account if edges connected to selected nodes are actually selectable.
|
||||||
@@ -12,7 +12,7 @@ function CustomHandle({ nodeId, ...handleProps }: HandleProps & { nodeId: string
|
|||||||
[nodeId]
|
[nodeId]
|
||||||
);
|
);
|
||||||
const connections = useNodeConnections({
|
const connections = useNodeConnections({
|
||||||
type: handleProps.type,
|
handleType: handleProps.type,
|
||||||
handleId: handleProps.id,
|
handleId: handleProps.id,
|
||||||
onConnect,
|
onConnect,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ function CustomHandle({ nodeId, ...handleProps }: HandleProps & { nodeId: string
|
|||||||
[nodeId]
|
[nodeId]
|
||||||
);
|
);
|
||||||
const connections = useNodeConnections({
|
const connections = useNodeConnections({
|
||||||
type: handleProps.type,
|
handleType: handleProps.type,
|
||||||
handleId: handleProps.id,
|
handleId: handleProps.id,
|
||||||
onConnect,
|
onConnect,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { isTextNode, type MyNode } from '.';
|
|||||||
|
|
||||||
function ResultNode() {
|
function ResultNode() {
|
||||||
const connections = useNodeConnections({
|
const connections = useNodeConnections({
|
||||||
type: 'target',
|
handleType: 'target',
|
||||||
});
|
});
|
||||||
const nodesData = useNodesData<MyNode>(connections.map((connection) => connection.source));
|
const nodesData = useNodesData<MyNode>(connections.map((connection) => connection.source));
|
||||||
const textNodes = nodesData.filter(isTextNode);
|
const textNodes = nodesData.filter(isTextNode);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { isTextNode, type TextNode, type MyNode } from '.';
|
|||||||
function UppercaseNode({ id }: NodeProps) {
|
function UppercaseNode({ id }: NodeProps) {
|
||||||
const { updateNodeData } = useReactFlow();
|
const { updateNodeData } = useReactFlow();
|
||||||
const connections = useNodeConnections({
|
const connections = useNodeConnections({
|
||||||
type: 'target',
|
handleType: 'target',
|
||||||
});
|
});
|
||||||
const nodesData = useNodesData<MyNode>(connections[0]?.source);
|
const nodesData = useNodesData<MyNode>(connections[0]?.source);
|
||||||
const textNode = isTextNode(nodesData) ? nodesData : null;
|
const textNode = isTextNode(nodesData) ? nodesData : null;
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
let { id }: NodeProps = $props();
|
let { id }: NodeProps = $props();
|
||||||
|
|
||||||
const connections = useNodeConnections({
|
const connections = useNodeConnections({
|
||||||
nodeId: id,
|
id: id,
|
||||||
type: 'target'
|
handleType: 'target'
|
||||||
});
|
});
|
||||||
|
|
||||||
let nodeData = $derived(
|
let nodeData = $derived(
|
||||||
|
|||||||
@@ -15,8 +15,8 @@
|
|||||||
|
|
||||||
const { updateNodeData } = useSvelteFlow();
|
const { updateNodeData } = useSvelteFlow();
|
||||||
const connections = useNodeConnections({
|
const connections = useNodeConnections({
|
||||||
nodeId: id,
|
id: id,
|
||||||
type: 'target'
|
handleType: 'target'
|
||||||
});
|
});
|
||||||
|
|
||||||
let nodeData = $derived(useNodesData<MyNode>(connections.current[0]?.source));
|
let nodeData = $derived(useNodesData<MyNode>(connections.current[0]?.source));
|
||||||
|
|||||||
@@ -10,7 +10,14 @@ import {
|
|||||||
} from 'react';
|
} from 'react';
|
||||||
import { shallow } from 'zustand/shallow';
|
import { shallow } from 'zustand/shallow';
|
||||||
import cc from 'classcat';
|
import cc from 'classcat';
|
||||||
import { getNodesInside, getEventPosition, SelectionMode, type NodeChange, type EdgeChange } from '@xyflow/system';
|
import {
|
||||||
|
getNodesInside,
|
||||||
|
getEventPosition,
|
||||||
|
SelectionMode,
|
||||||
|
areSetsEqual,
|
||||||
|
type NodeChange,
|
||||||
|
type EdgeChange,
|
||||||
|
} from '@xyflow/system';
|
||||||
|
|
||||||
import { UserSelection } from '../../components/UserSelection';
|
import { UserSelection } from '../../components/UserSelection';
|
||||||
import { containerStyle } from '../../styles/utils';
|
import { containerStyle } from '../../styles/utils';
|
||||||
@@ -73,27 +80,20 @@ export function Pane({
|
|||||||
onPaneMouseLeave,
|
onPaneMouseLeave,
|
||||||
children,
|
children,
|
||||||
}: PaneProps) {
|
}: PaneProps) {
|
||||||
const container = useRef<HTMLDivElement | null>(null);
|
|
||||||
const store = useStoreApi();
|
const store = useStoreApi();
|
||||||
const prevSelectedNodesCount = useRef<number>(0);
|
|
||||||
const prevSelectedEdgesCount = useRef<number>(0);
|
|
||||||
const containerBounds = useRef<DOMRect>();
|
|
||||||
const edgeIdLookup = useRef<Map<string, Set<string>>>(new Map());
|
|
||||||
|
|
||||||
const { userSelectionActive, elementsSelectable, dragging } = useStore(selector, shallow);
|
const { userSelectionActive, elementsSelectable, dragging } = useStore(selector, shallow);
|
||||||
const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive);
|
const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive);
|
||||||
|
|
||||||
|
const container = useRef<HTMLDivElement | null>(null);
|
||||||
|
const containerBounds = useRef<DOMRect>();
|
||||||
|
|
||||||
|
const selectedNodeIds = useRef<Set<string>>(new Set());
|
||||||
|
const selectedEdgeIds = useRef<Set<string>>(new Set());
|
||||||
|
|
||||||
// Used to prevent click events when the user lets go of the selectionKey during a selection
|
// Used to prevent click events when the user lets go of the selectionKey during a selection
|
||||||
const selectionInProgress = useRef<boolean>(false);
|
const selectionInProgress = useRef<boolean>(false);
|
||||||
const selectionStarted = useRef<boolean>(false);
|
const selectionStarted = useRef<boolean>(false);
|
||||||
|
|
||||||
const resetUserSelection = () => {
|
|
||||||
store.setState({ userSelectionActive: false, userSelectionRect: null });
|
|
||||||
|
|
||||||
prevSelectedNodesCount.current = 0;
|
|
||||||
prevSelectedEdgesCount.current = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
const onClick = (event: ReactMouseEvent) => {
|
const onClick = (event: ReactMouseEvent) => {
|
||||||
// We prevent click events when the user let go of the selectionKey during a selection
|
// We prevent click events when the user let go of the selectionKey during a selection
|
||||||
if (selectionInProgress.current) {
|
if (selectionInProgress.current) {
|
||||||
@@ -118,7 +118,7 @@ export function Pane({
|
|||||||
const onWheel = onPaneScroll ? (event: React.WheelEvent) => onPaneScroll(event) : undefined;
|
const onWheel = onPaneScroll ? (event: React.WheelEvent) => onPaneScroll(event) : undefined;
|
||||||
|
|
||||||
const onPointerDown = (event: ReactPointerEvent): void => {
|
const onPointerDown = (event: ReactPointerEvent): void => {
|
||||||
const { resetSelectedElements, domNode, edgeLookup } = store.getState();
|
const { resetSelectedElements, domNode } = store.getState();
|
||||||
containerBounds.current = domNode?.getBoundingClientRect();
|
containerBounds.current = domNode?.getBoundingClientRect();
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -135,12 +135,6 @@ export function Pane({
|
|||||||
|
|
||||||
selectionStarted.current = true;
|
selectionStarted.current = true;
|
||||||
selectionInProgress.current = false;
|
selectionInProgress.current = false;
|
||||||
edgeIdLookup.current = new Map();
|
|
||||||
|
|
||||||
for (const [id, edge] of edgeLookup) {
|
|
||||||
edgeIdLookup.current.set(edge.source, edgeIdLookup.current.get(edge.source)?.add(id) || new Set([id]));
|
|
||||||
edgeIdLookup.current.set(edge.target, edgeIdLookup.current.get(edge.target)?.add(id) || new Set([id]));
|
|
||||||
}
|
|
||||||
|
|
||||||
const { x, y } = getEventPosition(event.nativeEvent, containerBounds.current);
|
const { x, y } = getEventPosition(event.nativeEvent, containerBounds.current);
|
||||||
|
|
||||||
@@ -161,8 +155,16 @@ export function Pane({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onPointerMove = (event: ReactPointerEvent): void => {
|
const onPointerMove = (event: ReactPointerEvent): void => {
|
||||||
const { userSelectionRect, edgeLookup, transform, nodeLookup, triggerNodeChanges, triggerEdgeChanges } =
|
const {
|
||||||
store.getState();
|
userSelectionRect,
|
||||||
|
transform,
|
||||||
|
nodeLookup,
|
||||||
|
edgeLookup,
|
||||||
|
connectionLookup,
|
||||||
|
triggerNodeChanges,
|
||||||
|
triggerEdgeChanges,
|
||||||
|
defaultEdgeOptions,
|
||||||
|
} = store.getState();
|
||||||
|
|
||||||
if (!containerBounds.current || !userSelectionRect) {
|
if (!containerBounds.current || !userSelectionRect) {
|
||||||
return;
|
return;
|
||||||
@@ -182,38 +184,37 @@ export function Pane({
|
|||||||
height: Math.abs(mouseY - startY),
|
height: Math.abs(mouseY - startY),
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectedNodes = getNodesInside(
|
const prevSelectedNodeIds = selectedNodeIds.current;
|
||||||
nodeLookup,
|
const prevSelectedEdgeIds = selectedEdgeIds.current;
|
||||||
nextUserSelectRect,
|
|
||||||
transform,
|
selectedNodeIds.current = new Set(
|
||||||
selectionMode === SelectionMode.Partial,
|
getNodesInside(nodeLookup, nextUserSelectRect, transform, selectionMode === SelectionMode.Partial, true).map(
|
||||||
true
|
(node) => node.id
|
||||||
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
const selectedEdgeIds = new Set<string>();
|
selectedEdgeIds.current = new Set();
|
||||||
const selectedNodeIds = new Set<string>();
|
const edgesSelectable = defaultEdgeOptions?.selectable ?? true;
|
||||||
|
|
||||||
for (const selectedNode of selectedNodes) {
|
// We look for all edges connected to the selected nodes
|
||||||
selectedNodeIds.add(selectedNode.id);
|
for (const nodeId of selectedNodeIds.current) {
|
||||||
|
const connections = connectionLookup.get(nodeId);
|
||||||
const edgeIds = edgeIdLookup.current.get(selectedNode.id);
|
if (!connections) continue;
|
||||||
|
for (const { edgeId } of connections.values()) {
|
||||||
if (edgeIds) {
|
const edge = edgeLookup.get(edgeId);
|
||||||
for (const edgeId of edgeIds) {
|
if (edge && (edge.selectable ?? edgesSelectable)) {
|
||||||
selectedEdgeIds.add(edgeId);
|
selectedEdgeIds.current.add(edgeId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prevSelectedNodesCount.current !== selectedNodeIds.size) {
|
if (!areSetsEqual(prevSelectedNodeIds, selectedNodeIds.current)) {
|
||||||
prevSelectedNodesCount.current = selectedNodeIds.size;
|
const changes = getSelectionChanges(nodeLookup, selectedNodeIds.current, true) as NodeChange[];
|
||||||
const changes = getSelectionChanges(nodeLookup, selectedNodeIds, true) as NodeChange[];
|
|
||||||
triggerNodeChanges(changes);
|
triggerNodeChanges(changes);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prevSelectedEdgesCount.current !== selectedEdgeIds.size) {
|
if (!areSetsEqual(prevSelectedEdgeIds, selectedEdgeIds.current)) {
|
||||||
prevSelectedEdgesCount.current = selectedEdgeIds.size;
|
const changes = getSelectionChanges(edgeLookup, selectedEdgeIds.current) as EdgeChange[];
|
||||||
const changes = getSelectionChanges(edgeLookup, selectedEdgeIds) as EdgeChange[];
|
|
||||||
triggerEdgeChanges(changes);
|
triggerEdgeChanges(changes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,17 +232,18 @@ export function Pane({
|
|||||||
|
|
||||||
(event.target as Element)?.releasePointerCapture?.(event.pointerId);
|
(event.target as Element)?.releasePointerCapture?.(event.pointerId);
|
||||||
const { userSelectionRect } = store.getState();
|
const { userSelectionRect } = store.getState();
|
||||||
|
|
||||||
// We only want to trigger click functions when in selection mode if
|
// We only want to trigger click functions when in selection mode if
|
||||||
// the user did not move the mouse.
|
// the user did not move the mouse.
|
||||||
if (!userSelectionActive && userSelectionRect && event.target === container.current) {
|
if (!userSelectionActive && userSelectionRect && event.target === container.current) {
|
||||||
onClick?.(event);
|
onClick?.(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prevSelectedNodesCount.current > 0) {
|
store.setState({
|
||||||
store.setState({ nodesSelectionActive: true });
|
userSelectionActive: false,
|
||||||
}
|
userSelectionRect: null,
|
||||||
|
nodesSelectionActive: selectedNodeIds.current.size > 0,
|
||||||
resetUserSelection();
|
});
|
||||||
onSelectionEnd?.(event);
|
onSelectionEnd?.(event);
|
||||||
|
|
||||||
// If the user kept holding the selectionKey during the selection,
|
// If the user kept holding the selectionKey during the selection,
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ import { useNodeId } from '../contexts/NodeIdContext';
|
|||||||
const error014 = errorMessages['error014']();
|
const error014 = errorMessages['error014']();
|
||||||
|
|
||||||
type UseNodeConnectionsParams = {
|
type UseNodeConnectionsParams = {
|
||||||
type?: HandleType;
|
id?: string;
|
||||||
|
handleType?: HandleType;
|
||||||
handleId?: string;
|
handleId?: string;
|
||||||
nodeId?: string;
|
|
||||||
onConnect?: (connections: Connection[]) => void;
|
onConnect?: (connections: Connection[]) => void;
|
||||||
onDisconnect?: (connections: Connection[]) => void;
|
onDisconnect?: (connections: Connection[]) => void;
|
||||||
};
|
};
|
||||||
@@ -25,22 +25,22 @@ type UseNodeConnectionsParams = {
|
|||||||
* Hook to retrieve all edges connected to a node. Can be filtered by handle type and id.
|
* Hook to retrieve all edges connected to a node. Can be filtered by handle type and id.
|
||||||
*
|
*
|
||||||
* @public
|
* @public
|
||||||
* @param param.nodeId - node id - optional if called inside a custom node
|
* @param param.id - node id - optional if called inside a custom node
|
||||||
* @param param.type - filter by handle type 'source' or 'target'
|
* @param param.handleType - filter by handle type 'source' or 'target'
|
||||||
* @param param.handleId - filter by handle id (this is only needed if the node has multiple handles of the same type)
|
* @param param.handleId - filter by handle id (this is only needed if the node has multiple handles of the same type)
|
||||||
* @param param.onConnect - gets called when a connection is established
|
* @param param.onConnect - gets called when a connection is established
|
||||||
* @param param.onDisconnect - gets called when a connection is removed
|
* @param param.onDisconnect - gets called when a connection is removed
|
||||||
* @returns an array with connections
|
* @returns an array with connections
|
||||||
*/
|
*/
|
||||||
export function useNodeConnections({
|
export function useNodeConnections({
|
||||||
type,
|
id,
|
||||||
|
handleType,
|
||||||
handleId,
|
handleId,
|
||||||
nodeId,
|
|
||||||
onConnect,
|
onConnect,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
}: UseNodeConnectionsParams = {}): NodeConnection[] {
|
}: UseNodeConnectionsParams = {}): NodeConnection[] {
|
||||||
const _nodeId = useNodeId();
|
const nodeId = useNodeId();
|
||||||
const currentNodeId = nodeId ?? _nodeId;
|
const currentNodeId = id ?? nodeId;
|
||||||
|
|
||||||
if (!currentNodeId) {
|
if (!currentNodeId) {
|
||||||
throw new Error(error014);
|
throw new Error(error014);
|
||||||
@@ -50,7 +50,9 @@ export function useNodeConnections({
|
|||||||
|
|
||||||
const connections = useStore(
|
const connections = useStore(
|
||||||
(state) =>
|
(state) =>
|
||||||
state.connectionLookup.get(`${currentNodeId}${type ? (handleId ? `-${type}-${handleId}` : `-${type}`) : ''}`),
|
state.connectionLookup.get(
|
||||||
|
`${currentNodeId}${handleType ? (handleId ? `-${handleType}-${handleId}` : `-${handleType}`) : ''}`
|
||||||
|
),
|
||||||
areConnectionMapsEqual
|
areConnectionMapsEqual
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { useStore } from '$lib/store';
|
|||||||
import { getContext } from 'svelte';
|
import { getContext } from 'svelte';
|
||||||
|
|
||||||
type UseNodeConnectionsParams = {
|
type UseNodeConnectionsParams = {
|
||||||
type?: HandleType;
|
id?: string;
|
||||||
|
handleType?: HandleType;
|
||||||
handleId?: string;
|
handleId?: string;
|
||||||
nodeId?: string;
|
|
||||||
// TODO: Svelte 5
|
// TODO: Svelte 5
|
||||||
// onConnect?: (connections: Connection[]) => void;
|
// onConnect?: (connections: Connection[]) => void;
|
||||||
// onDisconnect?: (connections: Connection[]) => void;
|
// onDisconnect?: (connections: Connection[]) => void;
|
||||||
@@ -18,22 +18,18 @@ const initialConnections: NodeConnection[] = [];
|
|||||||
* Hook to retrieve all edges connected to a node. Can be filtered by handle type and id.
|
* Hook to retrieve all edges connected to a node. Can be filtered by handle type and id.
|
||||||
*
|
*
|
||||||
* @public
|
* @public
|
||||||
* @param param.nodeId - node id - optional if called inside a custom node
|
* @param param.id - node id - optional if called inside a custom node
|
||||||
* @param param.type - filter by handle type 'source' or 'target'
|
* @param param.handleType - filter by handle type 'source' or 'target'
|
||||||
* @param param.handleId - filter by handle id (this is only needed if the node has multiple handles of the same type)
|
* @param param.handleId - filter by handle id (this is only needed if the node has multiple handles of the same type)
|
||||||
* @todo @param param.onConnect - gets called when a connection is established
|
* @todo @param param.onConnect - gets called when a connection is established
|
||||||
* @todo @param param.onDisconnect - gets called when a connection is removed
|
* @todo @param param.onDisconnect - gets called when a connection is removed
|
||||||
* @returns an array with connections
|
* @returns an array with connections
|
||||||
*/
|
*/
|
||||||
export function useNodeConnections({
|
export function useNodeConnections({ id, handleType, handleId }: UseNodeConnectionsParams = {}) {
|
||||||
type,
|
|
||||||
nodeId: _nodeId,
|
|
||||||
handleId
|
|
||||||
}: UseNodeConnectionsParams = {}) {
|
|
||||||
const { edges, connectionLookup } = $derived(useStore());
|
const { edges, connectionLookup } = $derived(useStore());
|
||||||
|
|
||||||
const contextNodeId = getContext<string>('svelteflow__node_id');
|
const contextNodeId = getContext<string>('svelteflow__node_id');
|
||||||
const nodeId = _nodeId ?? contextNodeId;
|
const nodeId = id ?? contextNodeId;
|
||||||
|
|
||||||
let prevConnections: Map<string, NodeConnection> | undefined = new Map();
|
let prevConnections: Map<string, NodeConnection> | undefined = new Map();
|
||||||
let connectionsArray: NodeConnection[] = initialConnections;
|
let connectionsArray: NodeConnection[] = initialConnections;
|
||||||
@@ -42,7 +38,7 @@ export function useNodeConnections({
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
||||||
edges;
|
edges;
|
||||||
const nextConnections = connectionLookup.get(
|
const nextConnections = connectionLookup.get(
|
||||||
`${nodeId}-${type}${handleId ? `-${handleId}` : ''}`
|
`${nodeId}${handleType ? (handleId ? `-${handleType}-${handleId}` : `-${handleType}`) : ''}`
|
||||||
);
|
);
|
||||||
if (!areConnectionMapsEqual(nextConnections, prevConnections)) {
|
if (!areConnectionMapsEqual(nextConnections, prevConnections)) {
|
||||||
prevConnections = nextConnections;
|
prevConnections = nextConnections;
|
||||||
|
|||||||
@@ -263,3 +263,17 @@ export function evaluateAbsolutePosition(
|
|||||||
|
|
||||||
return positionAbsolute;
|
return positionAbsolute;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function areSetsEqual(a: Set<string>, b: Set<string>) {
|
||||||
|
if (a.size !== b.size) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const item of a) {
|
||||||
|
if (!b.has(item)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user