Merge branch 'main' into nodesbounds

This commit is contained in:
Moritz Klack
2024-08-29 00:09:57 +02:00
committed by GitHub
44 changed files with 1388 additions and 450 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ export const errorMessages = {
{ id, sourceHandle, targetHandle }: { id: string; sourceHandle: string | null; targetHandle: string | null }
) =>
`Couldn't create edge for ${handleType} handle id: "${
!sourceHandle ? sourceHandle : targetHandle
handleType === 'source' ? sourceHandle : targetHandle
}", edge id: ${id}.`,
error010: () => 'Handle: No node id found. Make sure to only use a Handle inside a custom Node.',
error011: (edgeType: string) => `Edge type "${edgeType}" not found. Using fallback type "default".`,
+8 -8
View File
@@ -69,16 +69,16 @@
.xy-flow__pane {
z-index: 1;
&.selection {
cursor: pointer;
}
&.draggable {
cursor: grab;
}
&.dragging {
cursor: grabbing;
}
&.dragging {
cursor: grabbing;
}
&.selection {
cursor: pointer;
}
}
@@ -113,7 +113,7 @@
fill: none;
}
.xy-flow__edges {
.xy-flow .xy-flow__edges {
position: absolute;
svg {
+2
View File
@@ -32,6 +32,7 @@ export type NodeRemoveChange = {
export type NodeAddChange<NodeType extends NodeBase = NodeBase> = {
item: NodeType;
type: 'add';
index?: number;
};
export type NodeReplaceChange<NodeType extends NodeBase = NodeBase> = {
@@ -57,6 +58,7 @@ export type EdgeRemoveChange = NodeRemoveChange;
export type EdgeAddChange<EdgeType extends EdgeBase = EdgeBase> = {
item: EdgeType;
type: 'add';
index?: number;
};
export type EdgeReplaceChange<EdgeType extends EdgeBase = EdgeBase> = {
+6 -1
View File
@@ -50,7 +50,7 @@ export type OnConnectStartParams = {
export type OnConnectStart = (event: MouseEvent | TouchEvent, params: OnConnectStartParams) => void;
export type OnConnect = (connection: Connection) => void;
export type OnConnectEnd = (event: MouseEvent | TouchEvent) => void;
export type OnConnectEnd = (event: MouseEvent | TouchEvent, connectionState: FinalConnectionState) => void;
export type IsValidConnection = (edge: EdgeBase | Connection) => boolean;
@@ -173,6 +173,11 @@ export type ConnectionState<NodeType extends InternalNodeBase = InternalNodeBase
| ConnectionInProgress<NodeType>
| NoConnection;
export type FinalConnectionState<NodeType extends InternalNodeBase = InternalNodeBase> = Omit<
ConnectionState<NodeType>,
'inProgress'
>;
export type UpdateConnection<NodeType extends InternalNodeBase = InternalNodeBase> = (
params: ConnectionState<NodeType>
) => void;
+7 -6
View File
@@ -196,21 +196,22 @@ export const getNodesInside = <NodeType extends NodeBase = NodeBase>(
const visibleNodes: InternalNodeBase<NodeType>[] = [];
for (const [, node] of nodes) {
for (const node of nodes.values()) {
const { measured, selectable = true, hidden = false } = node;
const width = measured.width ?? node.width ?? node.initialWidth ?? null;
const height = measured.height ?? node.height ?? node.initialHeight ?? null;
if ((excludeNonSelectableNodes && !selectable) || hidden) {
continue;
}
const width = measured.width ?? node.width ?? node.initialWidth ?? null;
const height = measured.height ?? node.height ?? node.initialHeight ?? null;
const overlappingArea = getOverlappingArea(paneRect, nodeToRect(node));
const notInitialized = width === null || height === null;
const area = (width ?? 0) * (height ?? 0);
const partiallyVisible = partially && overlappingArea > 0;
const area = (width ?? 0) * (height ?? 0);
const isVisible = notInitialized || partiallyVisible || overlappingArea >= area;
const forceInitialRender = !node.internals.handleBounds;
const isVisible = forceInitialRender || partiallyVisible || overlappingArea >= area;
if (isVisible || node.dragging) {
visibleNodes.push(node);
+23 -22
View File
@@ -15,7 +15,7 @@ import {
type Connection,
} from '../types';
import { getClosestHandle, isConnectionValid, getHandleLookup, getHandleType } from './utils';
import { getClosestHandle, isConnectionValid, getHandleType, getHandle } from './utils';
import { IsValidParams, OnPointerDownParams, Result, XYHandleInstance } from './types';
const alwaysValid = () => true;
@@ -61,19 +61,17 @@ function onPointerDown(
return;
}
const fromHandleInternal = getHandle(nodeId, handleType, handleId, nodeLookup, connectionMode);
if (!fromHandleInternal) {
return;
}
let position = getEventPosition(event, containerBounds);
let autoPanStarted = false;
let connection: Connection | null = null;
let isValid: boolean | null = false;
let handleDomNode: Element | null = null;
const [handleLookup, fromHandleInternal] = getHandleLookup({
nodeLookup,
nodeId,
handleId,
handleType,
});
// when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas
function autoPan(): void {
if (!autoPanOnConnect || !containerBounds) {
@@ -128,7 +126,8 @@ function onPointerDown(
closestHandle = getClosestHandle(
pointToRendererPoint(position, transform, false, [1, 1]),
connectionRadius,
handleLookup
nodeLookup,
fromHandle
);
if (!autoPanStarted) {
@@ -146,7 +145,7 @@ function onPointerDown(
doc,
lib,
flowId,
handleLookup,
nodeLookup,
});
handleDomNode = result.handleDomNode;
@@ -175,7 +174,9 @@ function onPointerDown(
newConnection.toHandle &&
previousConnection.toHandle.type === newConnection.toHandle.type &&
previousConnection.toHandle.nodeId === newConnection.toHandle.nodeId &&
previousConnection.toHandle.id === newConnection.toHandle.id
previousConnection.toHandle.id === newConnection.toHandle.id &&
previousConnection.to.x === newConnection.to.x &&
previousConnection.to.y === newConnection.to.y
) {
return;
}
@@ -191,10 +192,16 @@ function onPointerDown(
// it's important to get a fresh reference from the store here
// in order to get the latest state of onConnectEnd
onConnectEnd?.(event);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { inProgress, ...connectionState } = previousConnection;
const finalConnectionState = {
...connectionState,
toPosition: previousConnection.toHandle ? previousConnection.toPosition : null,
};
onConnectEnd?.(event, finalConnectionState);
if (edgeUpdaterType) {
onReconnectEnd?.(event);
onReconnectEnd?.(event, finalConnectionState);
}
cancelConnection();
@@ -231,7 +238,7 @@ function isValidHandle(
lib,
flowId,
isValidConnection = alwaysValid,
handleLookup,
nodeLookup,
}: IsValidParams
) {
const isTarget = fromType === 'target';
@@ -259,7 +266,7 @@ function isValidHandle(
const connectable = handleToCheck.classList.contains('connectable');
const connectableEnd = handleToCheck.classList.contains('connectableend');
if (!handleNodeId) {
if (!handleNodeId || !handleType) {
return result;
}
@@ -282,13 +289,7 @@ function isValidHandle(
result.isValid = isValid && isValidConnection(connection);
const toHandle = handleLookup?.get(`${handleNodeId}-${handleType}-${handleId}`);
if (toHandle) {
result.toHandle = {
...toHandle,
};
}
result.toHandle = getHandle(handleNodeId, handleType, handleId, nodeLookup, connectionMode, false);
}
return result;
+4 -2
View File
@@ -11,6 +11,8 @@ import {
type UpdateConnection,
type IsValidConnection,
NodeLookup,
ConnectionState,
FinalConnectionState,
} from '../types';
export type OnPointerDownParams = {
@@ -32,7 +34,7 @@ export type OnPointerDownParams = {
onConnect?: OnConnect;
onConnectEnd?: OnConnectEnd;
isValidConnection?: IsValidConnection;
onReconnectEnd?: (evt: MouseEvent | TouchEvent) => void;
onReconnectEnd?: (evt: MouseEvent | TouchEvent, connectionState: FinalConnectionState) => void;
getTransform: () => Transform;
getFromHandle: () => Handle | null;
autoPanSpeed?: number;
@@ -48,7 +50,7 @@ export type IsValidParams = {
doc: Document | ShadowRoot;
lib: string;
flowId: string | null;
handleLookup?: Map<string, Handle>;
nodeLookup: NodeLookup;
};
export type XYHandleInstance = {
+71 -80
View File
@@ -1,109 +1,100 @@
import { getHandlePosition } from '../utils';
import {
type HandleType,
type NodeHandleBounds,
type XYPosition,
type Handle,
InternalNodeBase,
NodeLookup,
} from '../types';
import { getHandlePosition, getOverlappingArea, nodeToRect } from '../utils';
import type { HandleType, XYPosition, Handle, InternalNodeBase, NodeLookup, ConnectionMode } from '../types';
// this functions collects all handles and adds an absolute position
// so that we can later find the closest handle to the mouse position
function getHandles(
node: InternalNodeBase,
handleBounds: NodeHandleBounds,
type: HandleType,
currentHandle: { nodeId: string; handleId: string | null; handleType: HandleType }
): [Handle[], Handle | null] {
let excludedHandle = null;
const handles = (handleBounds[type] || []).reduce<Handle[]>((res, handle) => {
if (node.id === currentHandle.nodeId && type === currentHandle.handleType && handle.id === currentHandle.handleId) {
excludedHandle = handle;
} else {
const handleXY = getHandlePosition(node, handle, handle.position, true);
res.push({ ...handle, ...handleXY });
function getNodesWithinDistance(position: XYPosition, nodeLookup: NodeLookup, distance: number): InternalNodeBase[] {
const nodes: InternalNodeBase[] = [];
const rect = {
x: position.x - distance,
y: position.y - distance,
width: distance * 2,
height: distance * 2,
};
for (const node of nodeLookup.values()) {
if (getOverlappingArea(rect, nodeToRect(node)) > 0) {
nodes.push(node);
}
return res;
}, []);
return [handles, excludedHandle];
}
return nodes;
}
// this distance is used for the area around the user pointer
// while doing a connection for finding the closest nodes
const ADDITIONAL_DISTANCE = 250;
export function getClosestHandle(
pos: XYPosition,
position: XYPosition,
connectionRadius: number,
handleLookup: Map<string, Handle>
nodeLookup: NodeLookup,
fromHandle: { nodeId: string; type: HandleType; id?: string | null }
): Handle | null {
let closestHandles: Handle[] = [];
let minDistance = Infinity;
for (const handle of handleLookup.values()) {
const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2));
if (distance <= connectionRadius) {
const closeNodes = getNodesWithinDistance(position, nodeLookup, connectionRadius + ADDITIONAL_DISTANCE);
for (const node of closeNodes) {
const allHandles = [...(node.internals.handleBounds?.source ?? []), ...(node.internals.handleBounds?.target ?? [])];
for (const handle of allHandles) {
// if the handle is the same as the fromHandle we skip it
if (fromHandle.nodeId === handle.nodeId && fromHandle.type === handle.type && fromHandle.id === handle.id) {
continue;
}
// determine absolute position of the handle
const { x, y } = getHandlePosition(node, handle, handle.position, true);
const distance = Math.sqrt(Math.pow(x - position.x, 2) + Math.pow(y - position.y, 2));
if (distance > connectionRadius) {
continue;
}
if (distance < minDistance) {
closestHandles = [handle];
closestHandles = [{ ...handle, x, y }];
minDistance = distance;
} else if (distance === minDistance) {
// when multiple handles are on the same distance we collect all of them
closestHandles.push(handle);
closestHandles.push({ ...handle, x, y });
}
minDistance = distance;
}
}
if (!closestHandles.length) {
return null;
}
// when multiple handles overlay each other we prefer the opposite handle
if (closestHandles.length > 1) {
const oppositeHandleType = fromHandle.type === 'source' ? 'target' : 'source';
return closestHandles.find((handle) => handle.type === oppositeHandleType) ?? closestHandles[0];
}
return closestHandles.length === 1
? closestHandles[0]
: // if multiple handles are layouted on top of each other we take the one with type = target because it's more likely that the user wants to connect to this one
closestHandles.find((handle) => handle.type === 'target') || closestHandles[0];
return closestHandles[0];
}
type GetHandleLookupParams = {
nodeLookup: NodeLookup;
nodeId: string;
handleId: string | null;
handleType: HandleType;
};
export function getHandleLookup({
nodeLookup,
nodeId,
handleId,
handleType,
}: GetHandleLookupParams): [Map<string, Handle>, Handle] {
const connectionHandles: Map<string, Handle> = new Map();
const currentHandle = { nodeId, handleId, handleType };
let matchingHandle: Handle | null = null;
for (const node of nodeLookup.values()) {
if (node.internals.handleBounds) {
const [sourceHandles, excludedSource] = getHandles(node, node.internals.handleBounds, 'source', currentHandle);
const [targetHandles, excludedTarget] = getHandles(node, node.internals.handleBounds, 'target', currentHandle);
matchingHandle = matchingHandle ? matchingHandle : excludedSource ?? excludedTarget;
[...sourceHandles, ...targetHandles].forEach((handle) =>
connectionHandles.set(`${handle.nodeId}-${handle.type}-${handle.id}`, handle)
);
}
export function getHandle(
nodeId: string,
handleType: HandleType,
handleId: string | null,
nodeLookup: NodeLookup,
connectionMode: ConnectionMode,
withAbsolutePosition = false
): Handle | null {
const node = nodeLookup.get(nodeId);
if (!node) {
return null;
}
// if the user only works with handles that are type="source" + connectionMode="loose"
// it happens that we can't find a matching handle. The reason for this is, that the
// edge don't know about the handles and always assumes that there is source and a target.
// In this case we need to find the matching handle by switching the handleType
if (!matchingHandle) {
const node = nodeLookup.get(nodeId);
if (node?.internals.handleBounds) {
currentHandle.handleType = handleType === 'source' ? 'target' : 'source';
const [, excluded] = getHandles(node, node.internals.handleBounds, currentHandle.handleType, currentHandle);
matchingHandle = excluded;
}
}
const handles =
connectionMode === 'strict'
? node.internals.handleBounds?.[handleType]
: [...(node.internals.handleBounds?.source ?? []), ...(node.internals.handleBounds?.target ?? [])];
const handle = (handleId ? handles?.find((h) => h.id === handleId) : handles?.[0]) ?? null;
return [connectionHandles, matchingHandle!];
return handle && withAbsolutePosition
? { ...handle, ...getHandlePosition(node, handle, handle.position, true) }
: handle;
}
export function getHandleType(