diff --git a/.changeset/curly-snails-do.md b/.changeset/curly-snails-do.md new file mode 100644 index 00000000..5560b33b --- /dev/null +++ b/.changeset/curly-snails-do.md @@ -0,0 +1,5 @@ +--- +'@xyflow/react': patch +--- + +Prevent unnecessary re-render in `FlowRenderer` diff --git a/.changeset/custom-edge-id-generator.md b/.changeset/custom-edge-id-generator.md new file mode 100644 index 00000000..439d729c --- /dev/null +++ b/.changeset/custom-edge-id-generator.md @@ -0,0 +1,5 @@ +--- +'@xyflow/system': patch +--- + +Allow custom `getEdgeId` function in `addEdge` and `reconnectEdge` options to enable custom edge ID schemes. diff --git a/.changeset/dry-seahorses-deliver.md b/.changeset/dry-seahorses-deliver.md new file mode 100644 index 00000000..1125ea3e --- /dev/null +++ b/.changeset/dry-seahorses-deliver.md @@ -0,0 +1,5 @@ +--- +'@xyflow/react': patch +--- + +Always create a new measured object in apply changes. diff --git a/.changeset/selfish-nails-sing.md b/.changeset/selfish-nails-sing.md new file mode 100644 index 00000000..9cbc5b81 --- /dev/null +++ b/.changeset/selfish-nails-sing.md @@ -0,0 +1,5 @@ +--- +'@xyflow/react': minor +--- + +Add `experimental_useOnNodesChangeMiddleware` hook diff --git a/.changeset/sharp-toys-cheer.md b/.changeset/sharp-toys-cheer.md deleted file mode 100644 index 885eebcc..00000000 --- a/.changeset/sharp-toys-cheer.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@xyflow/react': minor -'@xyflow/svelte': minor -'@xyflow/system': patch ---- - -Pass current pointer position to connection diff --git a/.changeset/young-roses-shout.md b/.changeset/young-roses-shout.md new file mode 100644 index 00000000..f1f6a888 --- /dev/null +++ b/.changeset/young-roses-shout.md @@ -0,0 +1,7 @@ +--- +'@xyflow/react': patch +'@xyflow/svelte': patch +'@xyflow/system': patch +--- + +Update an ongoing connection when user moves node with keyboard. diff --git a/README.md b/README.md index 3ed80c4b..116e99c7 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ For releasing packages we are using [changesets](https://github.com/changesets/c 1. create PRs for new features, updates and fixes (with a changeset if relevant for changelog) 2. merge into main -3. changset creates a PR that bumps all packages based on the changesets +3. changeset creates a PR that bumps all packages based on the changesets 4. merge changeset PR if you want to release to Github and npm ## Built by [xyflow](https://xyflow.com) diff --git a/examples/react/src/App/routes.ts b/examples/react/src/App/routes.ts index 886eecbd..4cf4b57b 100644 --- a/examples/react/src/App/routes.ts +++ b/examples/react/src/App/routes.ts @@ -60,6 +60,7 @@ import DevTools from '../examples/DevTools'; import Redux from '../examples/Redux'; import MovingHandles from '../examples/MovingHandles'; import DetachedHandle from '../examples/DetachedHandle'; +import Middlewares from '../examples/Middlewares'; export interface IRoute { name: string; @@ -238,6 +239,11 @@ const routes: IRoute[] = [ path: 'layouting', component: Layouting, }, + { + name: 'Middlewares', + path: 'middlewares', + component: Middlewares, + }, { name: 'Multi setNodes', path: 'multi-setnodes', diff --git a/examples/react/src/examples/Middlewares/RestrictExtent.tsx b/examples/react/src/examples/Middlewares/RestrictExtent.tsx new file mode 100644 index 00000000..7a447414 --- /dev/null +++ b/examples/react/src/examples/Middlewares/RestrictExtent.tsx @@ -0,0 +1,54 @@ +import { NodeChange, experimental_useOnNodesChangeMiddleware } from '@xyflow/react'; +import { useCallback, useState } from 'react'; + +export function RestrictExtent({ + label = 'Restrict Extent', + minX = -Infinity, + minY = -Infinity, + maxX = Infinity, + maxY = Infinity, +}: { + label?: string; + minX?: number; + minY?: number; + maxX?: number; + maxY?: number; +}) { + const [isEnabled, setIsEnabled] = useState(false); + experimental_useOnNodesChangeMiddleware( + useCallback( + (changes: NodeChange[]) => { + if (!isEnabled) return changes; + return changes.map((change) => { + const { type } = change; + if (type === 'position') { + const { position } = change; + if (position) { + position.x = Math.min(Math.max(position.x, minX), maxX); + position.y = Math.min(Math.max(position.y, minY), maxY); + change.position = position; + } + } else if (type === 'add' || type === 'replace') { + const { item } = change; + if (item) { + item.position.x = Math.min(Math.max(item.position.x, minX), maxX); + item.position.y = Math.min(Math.max(item.position.y, minY), maxY); + change.item = item; + } + } + return change; + }); + }, + [minX, minY, maxX, maxY, isEnabled] + ) + ); + + return ( +
+ +
+ ); +} diff --git a/examples/react/src/examples/Middlewares/index.tsx b/examples/react/src/examples/Middlewares/index.tsx new file mode 100644 index 00000000..c7a05770 --- /dev/null +++ b/examples/react/src/examples/Middlewares/index.tsx @@ -0,0 +1,85 @@ +import { useCallback } from 'react'; +import { + ReactFlow, + MiniMap, + Background, + BackgroundVariant, + Controls, + ReactFlowProvider, + Edge, + useReactFlow, + Panel, + useNodesState, + useEdgesState, + addEdge, + Connection, +} from '@xyflow/react'; +import { initialNodes, initialEdges } from '../CancelConnection/data'; +import { RestrictExtent } from './RestrictExtent'; + +const a = { id: 'a', data: { label: 'A' }, position: { x: 250, y: 5 } }; +const b = { id: 'b', data: { label: 'B' }, position: { x: 100, y: 100 } }; +const c = { id: 'c', data: { label: 'C' }, position: { x: 400, y: 100 } }; + +const SetNotesBatchingFlow = () => { + const { setNodes, updateNode } = useReactFlow(); + + const [nodes, , onNodesChange] = useNodesState(initialNodes); + const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges); + const onConnect = useCallback((params: Connection | Edge) => setEdges((eds) => addEdge(params, eds)), [setEdges]); + + const triggerMultipleSetNodes = useCallback(() => { + setNodes([a]); + setNodes((nodes) => [...nodes, b]); + setNodes((nodes) => [...nodes, c]); + setNodes((nodes) => + nodes.map((node) => + node.id === 'a' ? { ...node, position: { x: node.position.x + 2000, y: node.position.y + 20 } } : node + ) + ); + }, []); + + const triggerMultipleUpdateNodes = useCallback(() => { + triggerMultipleSetNodes(); + updateNode('a', (a) => ({ position: { x: a.position.x + 20, y: a.position.y + 20 } })); + updateNode('b', (b) => ({ position: { x: b.position.x + 20, y: b.position.y + 20 } })); + updateNode('c', (c) => ({ position: { x: c.position.x + 20, y: c.position.y + 20 } })); + updateNode('a', (a) => ({ data: { ...a.data, label: `A ${Date.now()}` } })); + updateNode('b', (b) => ({ data: { ...b.data, label: `B ${Date.now()}` } })); + updateNode('c', (c) => ({ data: { ...c.data, label: `C ${Date.now()}` } })); + }, []); + + return ( + + + + + + + + + + + + + + ); +}; + +export default function App() { + return ( + + + + ); +} diff --git a/packages/react/CHANGELOG.md b/packages/react/CHANGELOG.md index 700256b5..9197dd9f 100644 --- a/packages/react/CHANGELOG.md +++ b/packages/react/CHANGELOG.md @@ -1,5 +1,16 @@ # @xyflow/react +## 12.9.3 + +### Patch Changes + +- [#5621](https://github.com/xyflow/xyflow/pull/5621) [`c1304dba7`](https://github.com/xyflow/xyflow/commit/c1304dba7a20bb8d74c7aceb23cd80b56e4c0482) Thanks [@moklick](https://github.com/moklick)! - Set `paneClickDistance` default value to `1`. + +- [#5578](https://github.com/xyflow/xyflow/pull/5578) [`00bcb9f5f`](https://github.com/xyflow/xyflow/commit/00bcb9f5f45f49814b9ac19b3f55cfe069ee3773) Thanks [@peterkogo](https://github.com/peterkogo)! - Pass current pointer position to connection + +- Updated dependencies [[`00bcb9f5f`](https://github.com/xyflow/xyflow/commit/00bcb9f5f45f49814b9ac19b3f55cfe069ee3773)]: + - @xyflow/system@0.0.73 + ## 12.9.2 ### Patch Changes diff --git a/packages/react/package.json b/packages/react/package.json index 18074467..0514e3b4 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -1,6 +1,6 @@ { "name": "@xyflow/react", - "version": "12.9.2", + "version": "12.9.3", "description": "React Flow - A highly customizable React library for building node-based editors and interactive flow charts.", "keywords": [ "react", diff --git a/packages/react/src/components/BatchProvider/index.tsx b/packages/react/src/components/BatchProvider/index.tsx index b2ed270f..f6c6436c 100644 --- a/packages/react/src/components/BatchProvider/index.tsx +++ b/packages/react/src/components/BatchProvider/index.tsx @@ -28,7 +28,15 @@ export function BatchProvider(); const nodeQueueHandler = useCallback((queueItems: QueueItem[]) => { - const { nodes = [], setNodes, hasDefaultNodes, onNodesChange, nodeLookup, fitViewQueued } = store.getState(); + const { + nodes = [], + setNodes, + hasDefaultNodes, + onNodesChange, + nodeLookup, + fitViewQueued, + onNodesChangeMiddlewareMap, + } = store.getState(); /* * This is essentially an `Array.reduce` in imperative clothing. Processing @@ -40,11 +48,15 @@ export function BatchProvider[]; + for (const middleware of onNodesChangeMiddlewareMap.values()) { + changes = middleware(changes); + } + if (hasDefaultNodes) { setNodes(next); } diff --git a/packages/react/src/container/FlowRenderer/index.tsx b/packages/react/src/container/FlowRenderer/index.tsx index d5083d80..2198ce5e 100644 --- a/packages/react/src/container/FlowRenderer/index.tsx +++ b/packages/react/src/container/FlowRenderer/index.tsx @@ -1,4 +1,5 @@ import { memo, type ReactNode } from 'react'; +import { shallow } from 'zustand/shallow'; import { useStore } from '../../hooks/useStore'; import { useGlobalKeyHandler } from '../../hooks/useGlobalKeyHandler'; @@ -72,7 +73,7 @@ function FlowRendererComponent({ onViewportChange, isControlledViewport, }: FlowRendererProps) { - const { nodesSelectionActive, userSelectionActive } = useStore(selector); + const { nodesSelectionActive, userSelectionActive } = useStore(selector, shallow); const selectionKeyPressed = useKeyPress(selectionKeyCode, { target: win }); const panActivationKeyPressed = useKeyPress(panActivationKeyCode, { target: win }); diff --git a/packages/react/src/container/ReactFlow/index.tsx b/packages/react/src/container/ReactFlow/index.tsx index bd20242f..f01af831 100644 --- a/packages/react/src/container/ReactFlow/index.tsx +++ b/packages/react/src/container/ReactFlow/index.tsx @@ -104,7 +104,7 @@ function ReactFlow( onPaneMouseLeave, onPaneScroll, onPaneContextMenu, - paneClickDistance = 0, + paneClickDistance = 1, nodeClickDistance = 0, children, onReconnect, diff --git a/packages/react/src/hooks/useOnEdgesChangeMiddleware.ts b/packages/react/src/hooks/useOnEdgesChangeMiddleware.ts new file mode 100644 index 00000000..d79d6773 --- /dev/null +++ b/packages/react/src/hooks/useOnEdgesChangeMiddleware.ts @@ -0,0 +1,30 @@ +import { useEffect, useState } from 'react'; +import type { EdgeChange } from '@xyflow/system'; + +import { useStoreApi } from './useStore'; +import type { Edge, Node } from '../types'; + +/** + * Registers a middleware function to transform edge changes. + * + * @public + * @param fn - Middleware function. Should be memoized with useCallback to avoid re-registration. + */ +export function experimental_useOnEdgesChangeMiddleware( + fn: (changes: EdgeChange[]) => EdgeChange[] +) { + const store = useStoreApi(); + const [symbol] = useState(() => Symbol()); + + useEffect(() => { + const { onEdgesChangeMiddlewareMap } = store.getState(); + onEdgesChangeMiddlewareMap.set(symbol, fn); + }, [fn]); + + useEffect(() => { + const { onEdgesChangeMiddlewareMap } = store.getState(); + return () => { + onEdgesChangeMiddlewareMap.delete(symbol); + }; + }, []); +} diff --git a/packages/react/src/hooks/useOnNodesChangeMiddleware.ts b/packages/react/src/hooks/useOnNodesChangeMiddleware.ts new file mode 100644 index 00000000..fe7ea6f6 --- /dev/null +++ b/packages/react/src/hooks/useOnNodesChangeMiddleware.ts @@ -0,0 +1,30 @@ +import { useEffect, useState } from 'react'; +import type { NodeChange } from '@xyflow/system'; + +import { useStoreApi } from './useStore'; +import type { Edge, Node } from '../types'; + +/** + * Registers a middleware function to transform node changes. + * + * @public + * @param fn - Middleware function. Should be memoized with useCallback to avoid re-registration. + */ +export function experimental_useOnNodesChangeMiddleware( + fn: (changes: NodeChange[]) => NodeChange[] +) { + const store = useStoreApi(); + const [symbol] = useState(() => Symbol()); + + useEffect(() => { + const { onNodesChangeMiddlewareMap } = store.getState(); + onNodesChangeMiddlewareMap.set(symbol, fn); + }, [fn]); + + useEffect(() => { + const { onNodesChangeMiddlewareMap } = store.getState(); + return () => { + onNodesChangeMiddlewareMap.delete(symbol); + }; + }, []); +} diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index b4a67f2e..f251ba5d 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -30,6 +30,9 @@ export { useConnection } from './hooks/useConnection'; export { useInternalNode } from './hooks/useInternalNode'; export { useNodeId } from './contexts/NodeIdContext'; +export { experimental_useOnNodesChangeMiddleware } from './hooks/useOnNodesChangeMiddleware'; +export { experimental_useOnEdgesChangeMiddleware } from './hooks/useOnEdgesChangeMiddleware'; + export { applyNodeChanges, applyEdgeChanges } from './utils/changes'; export { isNode, isEdge } from './utils/general'; diff --git a/packages/react/src/store/index.ts b/packages/react/src/store/index.ts index 3254bdfa..fa1b5e3d 100644 --- a/packages/react/src/store/index.ts +++ b/packages/react/src/store/index.ts @@ -14,6 +14,8 @@ import { NodeOrigin, CoordinateExtent, fitViewport, + getHandlePosition, + Position, } from '@xyflow/system'; import { applyEdgeChanges, applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes'; @@ -175,8 +177,8 @@ const createStore = ({ }, updateNodePositions: (nodeDragItems, dragging = false) => { const parentExpandChildren: ParentExpandChild[] = []; - const changes = []; - const { nodeLookup, triggerNodeChanges } = get(); + let changes = []; + const { nodeLookup, triggerNodeChanges, connection, updateConnection, onNodesChangeMiddlewareMap } = get(); for (const [id, dragItem] of nodeDragItems) { // we are using the nodelookup to be sure to use the current expandParent and parentId value @@ -195,6 +197,11 @@ const createStore = ({ dragging, }; + if (node && connection.inProgress && connection.fromNode.id === node.id) { + const updatedFrom = getHandlePosition(node, connection.fromHandle, Position.Left, true); + updateConnection({ ...connection, from: updatedFrom }); + } + if (expandParent && node.parentId) { parentExpandChildren.push({ id, @@ -216,6 +223,10 @@ const createStore = ({ changes.push(...parentExpandChanges); } + for (const middleware of onNodesChangeMiddlewareMap.values()) { + changes = middleware(changes); + } + triggerNodeChanges(changes); }, triggerNodeChanges: (changes) => { diff --git a/packages/react/src/store/initialState.ts b/packages/react/src/store/initialState.ts index 3e561ce9..c7ddda17 100644 --- a/packages/react/src/store/initialState.ts +++ b/packages/react/src/store/initialState.ts @@ -146,6 +146,9 @@ const getInitialState = ({ lib: 'react', debug: false, ariaLabelConfig: defaultAriaLabelConfig, + + onNodesChangeMiddlewareMap: new Map(), + onEdgesChangeMiddlewareMap: new Map(), }; }; diff --git a/packages/react/src/types/store.ts b/packages/react/src/types/store.ts index 59a05127..717961ec 100644 --- a/packages/react/src/types/store.ts +++ b/packages/react/src/types/store.ts @@ -152,6 +152,9 @@ export type ReactFlowStore[]) => NodeChange[]>; + onEdgesChangeMiddlewareMap: Map[]) => EdgeChange[]>; }; export type ReactFlowActions = { diff --git a/packages/react/src/utils/changes.ts b/packages/react/src/utils/changes.ts index f2d9bdd3..de05236a 100644 --- a/packages/react/src/utils/changes.ts +++ b/packages/react/src/utils/changes.ts @@ -125,9 +125,9 @@ function applyChange(change: any, element: any): any { case 'dimensions': { if (typeof change.dimensions !== 'undefined') { - element.measured ??= {}; - element.measured.width = change.dimensions.width; - element.measured.height = change.dimensions.height; + element.measured = { + ...change.dimensions, + }; if (change.setAttributes) { if (change.setAttributes === true || change.setAttributes === 'width') { diff --git a/packages/svelte/CHANGELOG.md b/packages/svelte/CHANGELOG.md index fc6877d6..5cfe8b02 100644 --- a/packages/svelte/CHANGELOG.md +++ b/packages/svelte/CHANGELOG.md @@ -1,5 +1,18 @@ # @xyflow/svelte +## 1.4.2 + +### Patch Changes + +- [#5603](https://github.com/xyflow/xyflow/pull/5603) [`17a175791`](https://github.com/xyflow/xyflow/commit/17a175791b2420b32d55a8fcbbb35649862b85cf) Thanks [@peterkogo](https://github.com/peterkogo)! - Fix onPaneClick always firing when moving the viewport + +- [#5615](https://github.com/xyflow/xyflow/pull/5615) [`8b35c77eb`](https://github.com/xyflow/xyflow/commit/8b35c77ebe5a4f6cba33c597d94eba1ead64fdfc) Thanks [@peterkogo](https://github.com/peterkogo)! - Fix wrong positions when resizing nodes with a non-default node-origin + +- [#5578](https://github.com/xyflow/xyflow/pull/5578) [`00bcb9f5f`](https://github.com/xyflow/xyflow/commit/00bcb9f5f45f49814b9ac19b3f55cfe069ee3773) Thanks [@peterkogo](https://github.com/peterkogo)! - Pass current pointer position to connection + +- Updated dependencies [[`00bcb9f5f`](https://github.com/xyflow/xyflow/commit/00bcb9f5f45f49814b9ac19b3f55cfe069ee3773)]: + - @xyflow/system@0.0.73 + ## 1.4.1 ### Patch Changes diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 61bff298..76d5b532 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -1,6 +1,6 @@ { "name": "@xyflow/svelte", - "version": "1.4.1", + "version": "1.4.2", "description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.", "keywords": [ "svelte", diff --git a/packages/svelte/src/lib/container/SvelteFlow/SvelteFlow.svelte b/packages/svelte/src/lib/container/SvelteFlow/SvelteFlow.svelte index d92ff2d6..ab9378b8 100644 --- a/packages/svelte/src/lib/container/SvelteFlow/SvelteFlow.svelte +++ b/packages/svelte/src/lib/container/SvelteFlow/SvelteFlow.svelte @@ -61,7 +61,7 @@ panOnScroll = false, panOnScrollSpeed = 0.5, panOnDrag = true, - selectionOnDrag = true, + selectionOnDrag = false, connectionLineComponent, connectionLineStyle, connectionLineContainerStyle, diff --git a/packages/svelte/src/lib/plugins/NodeResizer/ResizeControl.svelte b/packages/svelte/src/lib/plugins/NodeResizer/ResizeControl.svelte index f53fa7a7..ae9632f7 100644 --- a/packages/svelte/src/lib/plugins/NodeResizer/ResizeControl.svelte +++ b/packages/svelte/src/lib/plugins/NodeResizer/ResizeControl.svelte @@ -75,14 +75,11 @@ }, onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => { // eslint-disable-next-line svelte/prefer-svelte-reactivity - const changes = new Map>(); - let position = change.x && change.y ? { x: change.x, y: change.y } : undefined; - changes.set(id, { ...change, position }); + const changes = new Map(); + changes.set(id, change); for (const childChange of childChanges) { - changes.set(childChange.id, { - position: childChange.position - }); + changes.set(childChange.id, {x: childChange.position.x, y: childChange.position.y }); } store.nodes = store.nodes.map((node) => { @@ -91,11 +88,11 @@ const vertical = !resizeDirection || resizeDirection === 'vertical'; if (change) { - return { + return { ...node, position: { - x: horizontal ? (change.position?.x ?? node.position.x) : node.position.x, - y: vertical ? (change.position?.y ?? node.position.y) : node.position.y + x: horizontal ? (change.x ?? node.position.x) : node.position.x, + y: vertical ? (change.y ?? node.position.y) : node.position.y }, width: horizontal ? (change.width ?? node.width) : node.width, height: vertical ? (change.height ?? node.height) : node.height diff --git a/packages/svelte/src/lib/store/index.ts b/packages/svelte/src/lib/store/index.ts index 798e87d8..30bcafc1 100644 --- a/packages/svelte/src/lib/store/index.ts +++ b/packages/svelte/src/lib/store/index.ts @@ -15,7 +15,9 @@ import { updateAbsolutePositions, snapPosition, calculateNodePosition, - type SetCenterOptions + type SetCenterOptions, + getHandlePosition, + Position } from '@xyflow/system'; import type { EdgeTypes, NodeTypes, Node, Edge, FitViewOptions } from '$lib/types'; @@ -51,6 +53,15 @@ export function createStore { store.nodes = store.nodes.map((node) => { + if (store.connection.inProgress && store.connection.fromNode.id === node.id) { + const internalNode = store.nodeLookup.get(node.id); + if (internalNode) { + store.connection = { + ...store.connection, + from: getHandlePosition(internalNode, store.connection.fromHandle, Position.Left, true) + }; + } + } const dragItem = nodeDragItems.get(node.id); return dragItem ? { ...node, position: dragItem.position, dragging } : node; }); diff --git a/packages/system/CHANGELOG.md b/packages/system/CHANGELOG.md index ea065959..5bbc621e 100644 --- a/packages/system/CHANGELOG.md +++ b/packages/system/CHANGELOG.md @@ -1,5 +1,11 @@ # @xyflow/system +## 0.0.73 + +### Patch Changes + +- [#5578](https://github.com/xyflow/xyflow/pull/5578) [`00bcb9f5f`](https://github.com/xyflow/xyflow/commit/00bcb9f5f45f49814b9ac19b3f55cfe069ee3773) Thanks [@peterkogo](https://github.com/peterkogo)! - Pass current pointer position to connection + ## 0.0.72 ### Patch Changes diff --git a/packages/system/package.json b/packages/system/package.json index 55b2e164..6ee8e327 100644 --- a/packages/system/package.json +++ b/packages/system/package.json @@ -1,6 +1,6 @@ { "name": "@xyflow/system", - "version": "0.0.72", + "version": "0.0.73", "description": "xyflow core system that powers React Flow and Svelte Flow.", "keywords": [ "node-based UI", diff --git a/packages/system/src/utils/edges/general.ts b/packages/system/src/utils/edges/general.ts index 58139394..515a285a 100644 --- a/packages/system/src/utils/edges/general.ts +++ b/packages/system/src/utils/edges/general.ts @@ -84,7 +84,19 @@ export function isEdgeVisible({ sourceNode, targetNode, width, height, transform return getOverlappingArea(viewRect, boxToRect(edgeBox)) > 0; } -const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection | EdgeBase): string => +/** + * Type for a custom edge ID generator function. + * @public + */ +export type GetEdgeId = (params: Connection | EdgeBase) => string; + +/** + * The default edge ID generator function. Generates an ID based on the source, target, and handles. + * @public + * @param params - The connection or edge to generate an ID for. + * @returns The generated edge ID. + */ +export const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection | EdgeBase): string => `xy-edge__${source}${sourceHandle || ''}-${target}${targetHandle || ''}`; const connectionExists = (edge: EdgeBase, edges: EdgeBase[]) => { @@ -97,11 +109,19 @@ const connectionExists = (edge: EdgeBase, edges: EdgeBase[]) => { ); }; +export type AddEdgeOptions = { + /** + * Custom function to generate edge IDs. If not provided, the default `getEdgeId` function is used. + */ + getEdgeId?: GetEdgeId; +}; + /** * This util is a convenience function to add a new Edge to an array of edges. It also performs some validation to make sure you don't add an invalid edge or duplicate an existing one. * @public * @param edgeParams - Either an `Edge` or a `Connection` you want to add. * @param edges - The array of all current edges. + * @param options - Optional configuration object. * @returns A new array of edges with the new edge added. * * @remarks If an edge with the same `target` and `source` already exists (and the same @@ -111,7 +131,8 @@ const connectionExists = (edge: EdgeBase, edges: EdgeBase[]) => { */ export const addEdge = ( edgeParams: EdgeType | Connection, - edges: EdgeType[] + edges: EdgeType[], + options: AddEdgeOptions = {} ): EdgeType[] => { if (!edgeParams.source || !edgeParams.target) { devWarn('006', errorMessages['error006']()); @@ -119,13 +140,15 @@ export const addEdge = ( return edges; } + const edgeIdGenerator = options.getEdgeId || getEdgeId; + let edge: EdgeType; if (isEdgeBase(edgeParams)) { edge = { ...edgeParams }; } else { edge = { ...edgeParams, - id: getEdgeId(edgeParams), + id: edgeIdGenerator(edgeParams), } as EdgeType; } @@ -150,6 +173,10 @@ export type ReconnectEdgeOptions = { * @default true */ shouldReplaceId?: boolean; + /** + * Custom function to generate edge IDs. If not provided, the default `getEdgeId` function is used. + */ + getEdgeId?: GetEdgeId; }; /** @@ -190,10 +217,12 @@ export const reconnectEdge = ( return edges; } + const edgeIdGenerator = options.getEdgeId || getEdgeId; + // Remove old edge and create the new edge with parameters of old edge. const edge = { ...rest, - id: options.shouldReplaceId ? getEdgeId(newConnection) : oldEdgeId, + id: options.shouldReplaceId ? edgeIdGenerator(newConnection) : oldEdgeId, source: newConnection.source, target: newConnection.target, sourceHandle: newConnection.sourceHandle, diff --git a/packages/system/src/xyhandle/XYHandle.ts b/packages/system/src/xyhandle/XYHandle.ts index 2e714e8b..b8edf767 100644 --- a/packages/system/src/xyhandle/XYHandle.ts +++ b/packages/system/src/xyhandle/XYHandle.ts @@ -93,8 +93,8 @@ function onPointerDown( position: fromHandleInternal.position, }; - const fromNodeInternal = nodeLookup.get(nodeId)!; - const from = getHandlePosition(fromNodeInternal, fromHandle, Position.Left, true); + const fromInternalNode = nodeLookup.get(nodeId)!; + const from = getHandlePosition(fromInternalNode, fromHandle, Position.Left, true); let previousConnection: ConnectionInProgress = { inProgress: true, @@ -103,7 +103,7 @@ function onPointerDown( from, fromHandle, fromPosition: fromHandle.position, - fromNode: fromNodeInternal, + fromNode: fromInternalNode, to: position, toHandle: null, @@ -172,9 +172,14 @@ function onPointerDown( connection = result.connection; isValid = isConnectionValid(!!closestHandle, result.isValid); + const fromInternalNode = nodeLookup.get(nodeId); + const from = fromInternalNode + ? getHandlePosition(fromInternalNode, fromHandle, Position.Left, true) + : previousConnection.from; + const newConnection: ConnectionInProgress = { - // from stays the same ...previousConnection, + from, isValid, to: result.toHandle && isValid