merge next

This commit is contained in:
peterkogo
2024-01-30 12:36:04 +01:00
54 changed files with 718 additions and 167 deletions

View File

@@ -15,6 +15,7 @@ import {
applyNodeChanges,
OnNodesChange,
OnConnect,
OnBeforeDelete,
} from '@xyflow/react';
import ColorSelectorNode from './ColorSelectorNode';
@@ -142,6 +143,8 @@ const CustomNodeFlow = () => {
[setEdges]
);
const onBeforeDelete: OnBeforeDelete<MyNode> = useCallback(async (params) => true, []);
return (
<ReactFlow
nodes={nodes}
@@ -159,6 +162,7 @@ const CustomNodeFlow = () => {
fitView
minZoom={0.3}
maxZoom={2}
onBeforeDelete={onBeforeDelete}
>
<MiniMap
nodeStrokeColor={(n: MyNode): string => {

View File

@@ -175,6 +175,15 @@ const edgeTypes: EdgeTypes = {
custom2: CustomEdge2,
};
const defaultEdgeOptions = {
markerEnd: {
type: MarkerType.ArrowClosed,
color: 'red',
width: 20,
height: 20,
},
};
const EdgesFlow = () => {
const [nodes, , onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
@@ -197,6 +206,7 @@ const EdgesFlow = () => {
onEdgeMouseMove={onEdgeMouseMove}
onEdgeMouseLeave={onEdgeMouseLeave}
onDelete={console.log}
defaultEdgeOptions={defaultEdgeOptions}
>
<MiniMap />
<Controls />

View File

@@ -13,6 +13,7 @@ import {
MiniMap,
Background,
Panel,
NodeOrigin,
} from '@xyflow/react';
import DebugNode from './DebugNode';
@@ -119,6 +120,7 @@ const initialNodes: Node[] = [
data: { label: 'Node 3' },
position: { x: 400, y: 100 },
className: 'light',
extent: 'parent',
},
];

View File

@@ -18,7 +18,7 @@ import UppercaseNode from './UppercaseNode';
export type TextNode = Node<{ text: string }, 'text'>;
export type ResultNode = Node<{}, 'result'>;
export type UppercaseNode = Node<{}, 'uppercase'>;
export type MyNode = Node<{ text: string }, 'text'> | Node<{}, 'result'> | Node<{}, 'uppercase'>;
export type MyNode = Node | TextNode | ResultNode | UppercaseNode;
const nodeTypes = {
text: TextNode,

View File

@@ -34,7 +34,7 @@
// See of connection landed inside the flow pane
const targetIsPane = (event.target as HTMLDivElement)?.classList.contains('svelte-flow__pane');
if (targetIsPane) {
if (targetIsPane && 'clientX' in event && 'clientY' in event) {
const id = getId();
const position = {
x: event.clientX,

View File

@@ -22,6 +22,7 @@
import CustomEdge from './CustomEdge.svelte';
import '@xyflow/svelte/dist/style.css';
import InitTracker from './InitTracker.svelte';
const nodeTypes: NodeTypes = {
custom: CustomNode,
@@ -148,6 +149,7 @@
selectionMode={SelectionMode.Full}
initialViewport={{ x: 100, y: 100, zoom: 2 }}
snapGrid={[25, 25]}
oninit={() => console.log('on init')}
on:nodeclick={(event) => console.log('on node click', event)}
on:nodemouseenter={(event) => console.log('on node enter', event)}
on:nodemouseleave={(event) => console.log('on node leave', event)}
@@ -207,6 +209,8 @@
}}>hide/unhide</button
>
</Panel>
<InitTracker />
</SvelteFlow>
<style>

View File

@@ -0,0 +1,18 @@
<script lang="ts">
import { useNodesInitialized, useInitialized } from '@xyflow/svelte';
const nodesInitialized = useNodesInitialized();
const initialized = useInitialized();
$: {
if (nodesInitialized) {
console.log('nodes initialized');
}
}
$: {
if (initialized) {
console.log('initialized');
}
}
</script>

View File

@@ -4,7 +4,12 @@
### Patch changes
- selection box is not interrupted by selectionKey being let go
- fix `OnNodeDrag` type
- do not use fallback handle if a specific id is being used
- fix `defaultEdgeOptions` markers not being applied
- fix `getNodesBounds` and add second param for passing options
- fix `expandParent` for child nodes
## 12.0.0-next.7

View File

@@ -1,6 +1,6 @@
{
"name": "@xyflow/react",
"version": "12.0.0-next.7",
"version": "12.0.0-next.8",
"description": "React Flow - A highly customizable React library for building node-based editors and interactive flow charts.",
"keywords": [
"react",

View File

@@ -25,7 +25,8 @@ const selector = (s: ReactFlowState) => {
return {
viewBB,
boundingRect: s.nodes.length > 0 ? getBoundsOfRects(getNodesBounds(s.nodes, s.nodeOrigin), viewBB) : viewBB,
boundingRect:
s.nodes.length > 0 ? getBoundsOfRects(getNodesBounds(s.nodes, { nodeOrigin: s.nodeOrigin }), viewBB) : viewBB,
rfId: s.rfId,
nodeOrigin: s.nodeOrigin,
panZoom: s.panZoom,

View File

@@ -73,7 +73,7 @@ export function NodeToolbar({
return null;
}
const nodeRect: Rect = getNodesBounds(nodes, nodeOrigin);
const nodeRect: Rect = getNodesBounds(nodes, { nodeOrigin });
const zIndex: number = Math.max(...nodes.map((node) => (node[internalsSymbol]?.z || 1) + 1));
const wrapperStyle: CSSProperties = {

View File

@@ -22,7 +22,7 @@ export type NodesSelectionProps = {
const selector = (s: ReactFlowState) => {
const selectedNodes = s.nodes.filter((n) => n.selected);
const { width, height, x, y } = getNodesBounds(selectedNodes, s.nodeOrigin);
const { width, height, x, y } = getNodesBounds(selectedNodes, { nodeOrigin: s.nodeOrigin });
return {
width,

View File

@@ -1,9 +1,8 @@
import { memo, useCallback } from 'react';
import { memo, useMemo } from 'react';
import { type MarkerProps, createMarkerIds } from '@xyflow/system';
import { useStore } from '../../hooks/useStore';
import { useMarkerSymbol } from './MarkerSymbols';
import type { ReactFlowState } from '../../types';
type MarkerDefinitionsProps = {
defaultColor: string;
@@ -43,23 +42,23 @@ const Marker = ({
);
};
const markerSelector =
({ defaultColor, rfId }: { defaultColor: string; rfId?: string }) =>
(s: ReactFlowState) => {
const markers = createMarkerIds(s.edges, { id: rfId, defaultColor });
return markers;
};
const markersEqual = (a: MarkerProps[], b: MarkerProps[]) =>
// the id includes all marker options, so we just need to look at that part of the marker
!(a.length !== b.length || a.some((m, i) => m.id !== b[i].id));
// when you have multiple flows on a page and you hide the first one, the other ones have no markers anymore
// when they do have markers with the same ids. To prevent this the user can pass a unique id to the react flow wrapper
// that we can then use for creating our unique marker ids
const MarkerDefinitions = ({ defaultColor, rfId }: MarkerDefinitionsProps) => {
const markers = useStore(useCallback(markerSelector({ defaultColor, rfId }), [defaultColor, rfId]), markersEqual);
const edges = useStore((s) => s.edges);
const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
const markers = useMemo(() => {
const markers = createMarkerIds(edges, {
id: rfId,
defaultColor,
defaultMarkerStart: defaultEdgeOptions?.markerStart,
defaultMarkerEnd: defaultEdgeOptions?.markerEnd,
});
return markers;
}, [edges, defaultEdgeOptions, rfId, defaultColor]);
if (!markers.length) {
return null;

View File

@@ -28,7 +28,9 @@ export type FlowRendererProps = Omit<
children: ReactNode;
};
const selector = (s: ReactFlowState) => s.nodesSelectionActive;
const selector = (s: ReactFlowState) => {
return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive };
};
const FlowRendererComponent = ({
children,
@@ -67,13 +69,13 @@ const FlowRendererComponent = ({
onViewportChange,
isControlledViewport,
}: FlowRendererProps) => {
const nodesSelectionActive = useStore(selector);
const { nodesSelectionActive, userSelectionActive } = useStore(selector);
const selectionKeyPressed = useKeyPress(selectionKeyCode);
const panActivationKeyPressed = useKeyPress(panActivationKeyCode);
const panOnDrag = panActivationKeyPressed || _panOnDrag;
const panOnScroll = panActivationKeyPressed || _panOnScroll;
const isSelecting = selectionKeyPressed || (selectionOnDrag && panOnDrag !== true);
const isSelecting = selectionKeyPressed || userSelectionActive || (selectionOnDrag && panOnDrag !== true);
useGlobalKeyHandler({ deleteKeyCode, multiSelectionKeyCode });

View File

@@ -10,18 +10,24 @@ const selector = (s: ReactFlowStore) => ({
position: s.connectionStartHandle ? s.connectionPosition : null,
});
type UseConnectionResult = {
/** The start handle where the user interaction started or null */
startHandle: ReactFlowStore['connectionStartHandle'];
/** The target handle that's inside the connection radius or null */
endHandle: ReactFlowStore['connectionEndHandle'];
/** The current connection status 'valid', 'invalid' or null*/
status: ReactFlowStore['connectionStatus'];
/** The current connection position or null */
position: ReactFlowStore['connectionPosition'] | null;
};
/**
* Hook for accessing the ongoing connection.
*
* @public
* @returns ongoing connection: startHandle, endHandle, status, position
* @returns ongoing connection
*/
export function useConnection(): {
startHandle: ReactFlowStore['connectionStartHandle'];
endHandle: ReactFlowStore['connectionEndHandle'];
status: ReactFlowStore['connectionStatus'];
position: ReactFlowStore['connectionPosition'] | null;
} {
export function useConnection(): UseConnectionResult {
const ongoingConnection = useStore(selector, shallow);
return ongoingConnection;

View File

@@ -5,7 +5,7 @@ import { handleNodeClick } from '../components/Nodes/utils';
import { useStoreApi } from './useStore';
type UseDragParams = {
nodeRef: RefObject<Element>;
nodeRef: RefObject<HTMLDivElement>;
disabled?: boolean;
noDragClassName?: string;
handleSelector?: string;
@@ -39,7 +39,7 @@ export function useDrag({
handleNodeClick({
id,
store,
nodeRef: nodeRef as RefObject<HTMLDivElement>,
nodeRef,
});
},
onDragStart: () => {

View File

@@ -13,7 +13,7 @@ type useHandleConnectionsParams = {
};
/**
* Hook to check if a <Handle /> is connected to another <Handle /> and get the connections.
* Hook to check if a <Handle /> is connected to another <Handle /> and get the connections.
*
* @public
* @param param.type - handle type 'source' or 'target'

View File

@@ -1,5 +1,5 @@
import { useCallback } from 'react';
import { XYPosition, calcNextPosition, snapPosition } from '@xyflow/system';
import { calculateNodePosition, snapPosition, type XYPosition } from '@xyflow/system';
import { Node } from '../types';
import { useStoreApi } from './useStore';
@@ -17,7 +17,17 @@ export function useMoveSelectedNodes() {
const store = useStoreApi();
const moveSelectedNodes = useCallback((params: { direction: XYPosition; factor: number }) => {
const { nodeExtent, nodes, snapToGrid, snapGrid, nodesDraggable, onError, updateNodePositions } = store.getState();
const {
nodeExtent,
nodes,
snapToGrid,
snapGrid,
nodesDraggable,
onError,
updateNodePositions,
nodeLookup,
nodeOrigin,
} = store.getState();
const selectedNodes = nodes.filter(selectedAndDraggable(nodesDraggable));
// by default a node moves 5px on each key press
// if snap grid is enabled, we use that for the velocity
@@ -30,27 +40,24 @@ export function useMoveSelectedNodes() {
const nodeUpdates = selectedNodes.map((node) => {
if (node.computed?.positionAbsolute) {
let nextPosition = {
x: node.computed?.positionAbsolute.x + xDiff,
y: node.computed?.positionAbsolute.y + yDiff,
x: node.computed.positionAbsolute.x + xDiff,
y: node.computed.positionAbsolute.y + yDiff,
};
if (snapToGrid) {
nextPosition = snapPosition(nextPosition, snapGrid);
}
const { positionAbsolute, position } = calcNextPosition(
node,
const { position, positionAbsolute } = calculateNodePosition({
nodeId: node.id,
nextPosition,
nodes,
nodeLookup,
nodeExtent,
undefined,
onError
);
nodeOrigin,
onError,
});
node.position = position;
if (!node.computed) {
node.computed = {};
}
node.computed.positionAbsolute = positionAbsolute;
}

View File

@@ -12,9 +12,15 @@ const selector = (options: UseNodesInitializedOptions) => (s: ReactFlowState) =>
return false;
}
return s.nodes
.filter((n) => (options.includeHiddenNodes ? true : !n.hidden))
.every((n) => n[internalsSymbol]?.handleBounds !== undefined);
for (const node of s.nodes) {
if (options.includeHiddenNodes || !node.hidden) {
if (node[internalsSymbol]?.handleBounds === undefined) {
return false;
}
}
}
return true;
};
const defaultOptions = {

View File

@@ -11,7 +11,7 @@ export type UseOnSelectionChangeOptions = {
* Hook for registering an onSelectionChange handler.
*
* @public
* @params params.onChange - The handler to register
* @param params.onChange - The handler to register
*/
export function useOnSelectionChange({ onChange }: UseOnSelectionChangeOptions) {
const store = useStoreApi();

View File

@@ -86,31 +86,31 @@ const useViewportHelper = (): ViewportHelperFunctions => {
panZoom?.setViewport(viewport, { duration: options?.duration });
},
screenToFlowPosition: (position: XYPosition, options: { snapToGrid: boolean } = { snapToGrid: true }) => {
screenToFlowPosition: (clientPosition: XYPosition, options: { snapToGrid: boolean } = { snapToGrid: true }) => {
const { transform, snapGrid, domNode } = store.getState();
if (!domNode) {
return position;
return clientPosition;
}
const { x: domX, y: domY } = domNode.getBoundingClientRect();
const correctedPosition = {
x: position.x - domX,
y: position.y - domY,
x: clientPosition.x - domX,
y: clientPosition.y - domY,
};
return pointToRendererPoint(correctedPosition, transform, options.snapToGrid, snapGrid);
},
flowToScreenPosition: (position: XYPosition) => {
flowToScreenPosition: (flowPosition: XYPosition) => {
const { transform, domNode } = store.getState();
if (!domNode) {
return position;
return flowPosition;
}
const { x: domX, y: domY } = domNode.getBoundingClientRect();
const rendererPosition = rendererPointToPoint(position, transform);
const rendererPosition = rendererPointToPoint(flowPosition, transform);
return {
x: rendererPosition.x + domX,

View File

@@ -79,7 +79,6 @@ export {
type ColorMode,
type ColorModeClass,
type HandleType,
type OnBeforeDelete,
type ShouldResize,
type OnResizeStart,
type OnResize,

View File

@@ -6,6 +6,7 @@ import {
getViewportForBounds,
Transform,
updateConnectionLookup,
devWarn,
} from '@xyflow/system';
import type { Edge, Node, ReactFlowStore } from '../types';
@@ -37,7 +38,8 @@ const getInitialState = ({
if (fitView && width && height) {
const nodesWithDimensions = nextNodes.filter((node) => node.width && node.height);
const bounds = getNodesBounds(nodesWithDimensions, [0, 0]);
// @todo users nodeOrigin should be used here
const bounds = getNodesBounds(nodesWithDimensions, { nodeOrigin: [0, 0] });
const { x, y, zoom } = getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
transform = [x, y, zoom];
}
@@ -100,7 +102,7 @@ const getInitialState = ({
autoPanOnConnect: true,
autoPanOnNodeDrag: true,
connectionRadius: 20,
onError: () => null,
onError: devWarn,
isValidConnection: undefined,
onSelectionChangeHandlers: [],

View File

@@ -21,7 +21,6 @@ import type {
IsValidConnection,
ColorMode,
SnapGrid,
OnBeforeDelete,
} from '@xyflow/system';
import type {
@@ -44,6 +43,7 @@ import type {
SelectionDragHandler,
EdgeMouseHandler,
OnNodeDrag,
OnBeforeDelete,
} from '.';
/**

View File

@@ -11,6 +11,7 @@ import {
FitBounds,
XYPosition,
NodeProps,
OnBeforeDeleteBase,
} from '@xyflow/system';
import type { NodeChange, EdgeChange, Node, Edge, ReactFlowInstance, EdgeProps } from '.';
@@ -46,16 +47,95 @@ export type OnInit<NodeType extends Node = Node, EdgeType extends Edge = Edge> =
) => void;
export type ViewportHelperFunctions = {
/**
* Zooms viewport in by 1.2.
*
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomIn: ZoomInOut;
/**
* Zooms viewport out by 1 / 1.2.
*
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomOut: ZoomInOut;
/**
* Sets the current zoom level.
*
* @param zoomLevel - the zoom level to set
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomTo: ZoomTo;
/**
* Returns the current zoom level.
*
* @returns current zoom as a number
*/
getZoom: GetZoom;
/**
* Sets the current viewport.
*
* @param viewport - the viewport to set
* @param options.duration - optional duration. If set, a transition will be applied
*/
setViewport: SetViewport;
/**
* Returns the current viewport.
*
* @returns Viewport
*/
getViewport: GetViewport;
/**
* Fits the view.
*
* @param options.padding - optional padding
* @param options.includeHiddenNodes - optional includeHiddenNodes
* @param options.minZoom - optional minZoom
* @param options.maxZoom - optional maxZoom
* @param options.duration - optional duration. If set, a transition will be applied
* @param options.nodes - optional nodes to fit the view to
*/
fitView: FitView;
/**
* Sets the center of the view to the given position.
*
* @param x - x position
* @param y - y position
* @param options.zoom - optional zoom
*/
setCenter: SetCenter;
/**
* Fits the view to the given bounds .
*
* @param bounds - the bounds ({ x: number, y: number, width: number, height: number }) to fit the view to
* @param options.padding - optional padding
*/
fitBounds: FitBounds;
screenToFlowPosition: (position: XYPosition, options?: { snapToGrid: boolean }) => XYPosition;
flowToScreenPosition: (position: XYPosition) => XYPosition;
/**
* Converts a screen / client position to a flow position.
*
* @param clientPosition - the screen / client position. When you are working with events you can use event.clientX and event.clientY
* @param options.snapToGrid - if true, the converted position will be snapped to the grid
* @returns position as { x: number, y: number }
*
* @example
* const flowPosition = screenToFlowPosition({ x: event.clientX, y: event.clientY })
*/
screenToFlowPosition: (clientPosition: XYPosition, options?: { snapToGrid: boolean }) => XYPosition;
/**
* Converts a flow position to a screen / client position.
*
* @param flowPosition - the screen / client position. When you are working with events you can use event.clientX and event.clientY
* @returns position as { x: number, y: number }
*
* @example
* const clientPosition = flowToScreenPosition({ x: node.position.x, y: node.position.y })
*/
flowToScreenPosition: (flowPosition: XYPosition) => XYPosition;
viewportInitialized: boolean;
};
export type OnBeforeDelete<NodeType extends Node = Node, EdgeType extends Edge = Edge> = OnBeforeDeleteBase<
NodeType,
EdgeType
>;

View File

@@ -59,19 +59,112 @@ export namespace Instance {
}
export type ReactFlowInstance<NodeType extends Node = Node, EdgeType extends Edge = Edge> = {
/**
* Returns nodes.
*
* @returns nodes array
*/
getNodes: Instance.GetNodes<NodeType>;
/**
* Sets nodes.
*
* @param payload - the nodes to set or a function that receives the current nodes and returns the new nodes
*/
setNodes: Instance.SetNodes<NodeType>;
/**
* Adds nodes.
*
* @param payload - the nodes to add
*/
addNodes: Instance.AddNodes<NodeType>;
/**
* Returns a node by id.
*
* @param id - the node id
* @returns the node or undefined if no node was found
*/
getNode: Instance.GetNode<NodeType>;
/**
* Returns edges.
*
* @returns edges array
*/
getEdges: Instance.GetEdges<EdgeType>;
/**
* Sets edges.
*
* @param payload - the edges to set or a function that receives the current edges and returns the new edges
*/
setEdges: Instance.SetEdges<EdgeType>;
/**
* Adds edges.
*
* @param payload - the edges to add
*/
addEdges: Instance.AddEdges<EdgeType>;
/**
* Returns an edge by id.
*
* @param id - the edge id
* @returns the edge or undefined if no edge was found
*/
getEdge: Instance.GetEdge<EdgeType>;
/**
* Returns the nodes, edges and the viewport as a JSON object.
*
* @returns the nodes, edges and the viewport as a JSON object
*/
toObject: Instance.ToObject<NodeType, EdgeType>;
/**
* Deletes nodes and edges.
*
* @param params.nodes - optional nodes array to delete
* @param params.edges - optional edges array to delete
*
* @returns a promise that resolves with the deleted nodes and edges
*/
deleteElements: Instance.DeleteElements;
/**
* Returns all nodes that intersect with the given node or rect.
*
* @param node - the node or rect to check for intersections
* @param partially - if true, the node is considered to be intersecting if it partially overlaps with the passed node or rect
* @param nodes - optional nodes array to check for intersections
*
* @returns an array of intersecting nodes
*/
getIntersectingNodes: Instance.GetIntersectingNodes<NodeType>;
/**
* Checks if the given node or rect intersects with the passed rect.
*
* @param node - the node or rect to check for intersections
* @param area - the rect to check for intersections
* @param partially - if true, the node is considered to be intersecting if it partially overlaps with the passed react
*
* @returns true if the node or rect intersects with the given area
*/
isNodeIntersecting: Instance.IsNodeIntersecting<NodeType>;
/**
* Updates a node.
*
* @param id - id of the node to update
* @param nodeUpdate - the node update as an object or a function that receives the current node and returns the node update
* @param options.replace - if true, the node is replaced with the node update, otherwise the changes get merged
*
* @example
* updateNode('node-1', (node) => ({ position: { x: node.position.x + 10, y: node.position.y } }));
*/
updateNode: Instance.UpdateNode<NodeType>;
/**
* Updates the data attribute of a node.
*
* @param id - id of the node 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
* updateNodeData('node-1', { label: 'A new label' });
*/
updateNodeData: Instance.UpdateNodeData<NodeType>;
viewportInitialized: boolean;
} & Omit<ViewportHelperFunctions, 'initialized'>;

View File

@@ -26,7 +26,6 @@ import {
type EdgeLookup,
type ConnectionLookup,
type NodeLookup,
OnBeforeDelete,
} from '@xyflow/system';
import type {
@@ -43,6 +42,7 @@ import type {
UnselectNodesAndEdgesParams,
OnDelete,
OnNodeDrag,
OnBeforeDelete,
} from '.';
export type ReactFlowStore = {

View File

@@ -6,10 +6,7 @@ export function handleParentExpand(updatedElements: any[], updateItem: any) {
for (const [index, item] of updatedElements.entries()) {
if (item.id === updateItem.parentNode) {
const parent = { ...item };
if (!parent.computed) {
parent.computed = {};
}
parent.computed ??= {};
const extendWidth = updateItem.position.x + updateItem.computed.width - parent.computed.width;
const extendHeight = updateItem.position.y + updateItem.computed.height - parent.computed.height;

View File

@@ -5,10 +5,15 @@
## Minor changes
- add `getNode`, `getNodes`, `getEdge` and `getEdges` to `useSvelteFlow`
- add `useInitialized` / `useNNodesInitialized` hooks and `oninit` handler
## Patch changes
- selection box is not interrupted by selectionKey being let go
- Edge label has a default background and is clickable
- do not use fallback handle if a specific id is being used
- use correct id for `<Handle />` data-id attribute
- fix `getNodesBounds` and add second param for passing options
## 0.0.34

View File

@@ -1,6 +1,6 @@
{
"name": "@xyflow/svelte",
"version": "0.0.34",
"version": "0.0.35",
"description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.",
"keywords": [
"svelte",

View File

@@ -0,0 +1,14 @@
<script lang="ts">
import { onMount } from 'svelte';
let _onMount: (() => void) | undefined = undefined;
export { _onMount as onMount };
let _onDestroy: (() => void) | undefined = undefined;
export { _onDestroy as onDestroy };
onMount(() => {
_onMount?.();
return _onDestroy;
});
</script>

View File

@@ -0,0 +1 @@
export { default as CallOnMount } from './CallOnMount.svelte';

View File

@@ -134,7 +134,7 @@ The Handle component is the part of a node that can be used to connect nodes.
data-handleid={handleId}
data-nodeid={nodeId}
data-handlepos={position}
data-id="{flowId}-{nodeId}-{id || null}-{type}"
data-id="{$flowId}-{nodeId}-{id || null}-{type}"
class={cc([
'svelte-flow__handle',
`svelte-flow__handle-${position}`,

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { EdgeWrapper } from '$lib/components/EdgeWrapper';
import { CallOnMount } from '$lib/components/CallOnMount';
import { MarkerDefinition } from '$lib/container/EdgeRenderer/MarkerDefinition';
import { useStore } from '$lib/store';
import type { DefaultEdgeOptions } from '$lib/types';
@@ -8,8 +9,8 @@
export let defaultEdgeOptions: DefaultEdgeOptions | undefined;
const {
elementsSelectable,
visibleEdges,
edgesInitialized,
edges: { setDefaultOptions }
} = useStore();
@@ -54,4 +55,15 @@
on:edgecontextmenu
/>
{/each}
{#if $visibleEdges.length > 0}
<CallOnMount
onMount={() => {
$edgesInitialized = true;
}}
onDestroy={() => {
$edgesInitialized = false;
}}
/>
{/if}
</div>

View File

@@ -73,7 +73,8 @@
let selectedNodes: Node[] = [];
$: _panOnDrag = $panActivationKeyPressed || panOnDrag;
$: isSelecting = $selectionKeyPressed || (selectionOnDrag && _panOnDrag !== true);
$: isSelecting =
$selectionKeyPressed || $selectionRect || (selectionOnDrag && _panOnDrag !== true);
$: hasActiveSelection = $elementsSelectable && (isSelecting || $selectionRectMode === 'user');
function onClick(event: MouseEvent | TouchEvent) {

View File

@@ -77,6 +77,7 @@
export let onconnectstart: $$Props['onconnectstart'] = undefined;
export let onconnectend: $$Props['onconnectend'] = undefined;
export let onbeforedelete: $$Props['onbeforedelete'] = undefined;
export let oninit: $$Props['oninit'] = undefined;
export let defaultMarkerColor = '#b1b1b7';
@@ -130,6 +131,16 @@
}
}
// Call oninit once when flow is intialized
const { initialized } = store;
let onInitCalled = false;
$: {
if (!onInitCalled && $initialized) {
oninit?.();
onInitCalled = true;
}
}
// this updates the store for simple changes
// where the prop names equals the store name
$: {

View File

@@ -333,4 +333,6 @@ export type SvelteFlowProps = DOMAttributes<HTMLDivElement> & {
onconnectstart?: OnConnectStart;
/** When a user stops dragging a connection line, this event gets fired. */
onconnectend?: OnConnectEnd;
/** This handler gets called when the flow is finished initializing */
oninit?: () => void;
};

View File

@@ -4,6 +4,7 @@
import { useStore } from '$lib/store';
import zoom from '$lib/actions/zoom';
import type { ZoomProps } from './types';
import { onMount } from 'svelte';
type $$Props = ZoomProps;
@@ -29,12 +30,17 @@
translateExtent,
lib,
panActivationKeyPressed,
zoomActivationKeyPressed
zoomActivationKeyPressed,
viewportInitialized
} = useStore();
$: viewPort = initialViewport || { x: 0, y: 0, zoom: 1 };
$: _panOnDrag = $panActivationKeyPressed || panOnDrag;
$: _panOnScroll = $panActivationKeyPressed || panOnScroll;
onMount(() => {
$viewportInitialized = true;
});
</script>
<div

View File

@@ -0,0 +1,24 @@
import { useStore } from '$lib/store';
import type { Readable } from 'svelte/store';
/**
* Hook for seeing if nodes are initialized
* @returns - nodesInitialized Writable
*/
export function useNodesInitialized() {
const { nodesInitialized } = useStore();
return {
subscribe: nodesInitialized.subscribe
} as Readable<boolean>;
}
/**
* Hook for seeing if the flow is initialized
* @returns - initialized Writable
*/
export function useInitialized() {
const { initialized } = useStore();
return {
subscribe: initialized.subscribe
} as Readable<boolean>;
}

View File

@@ -24,32 +24,136 @@ import { isNode } from '$lib/utils';
* Hook for accessing the ReactFlow instance.
*
* @public
*
* @returns helper functions
*/
export function useSvelteFlow(): {
/**
* Zooms viewport in by 1.2.
*
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomIn: ZoomInOut;
/**
* Zooms viewport out by 1 / 1.2.
*
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomOut: ZoomInOut;
/**
* Returns a node by id.
*
* @param id - the node id
* @returns the node or undefined if no node was found
*/
getNode: (id: string) => Node | undefined;
/**
* Returns nodes.
*
* @returns nodes array
*/
getNodes: (ids?: string[]) => Node[];
/**
* Returns an edge by id.
*
* @param id - the edge id
* @returns the edge or undefined if no edge was found
*/
getEdge: (id: string) => Edge | undefined;
/**
* Returns edges.
*
* @returns edges array
*/
getEdges: (ids?: string[]) => Edge[];
/**
* Sets the current zoom level.
*
* @param zoomLevel - the zoom level to set
* @param options.duration - optional duration. If set, a transition will be applied
*/
setZoom: (zoomLevel: number, options?: ViewportHelperFunctionOptions) => void;
/**
* Returns the current zoom level.
*
* @returns current zoom as a number
*/
getZoom: () => number;
/**
* Sets the center of the view to the given position.
*
* @param x - x position
* @param y - y position
* @param options.zoom - optional zoom
*/
setCenter: (x: number, y: number, options?: SetCenterOptions) => void;
/**
* Sets the current viewport.
*
* @param viewport - the viewport to set
* @param options.duration - optional duration. If set, a transition will be applied
*/
setViewport: (viewport: Viewport, options?: ViewportHelperFunctionOptions) => void;
/**
* Returns the current viewport.
*
* @returns Viewport
*/
getViewport: () => Viewport;
/**
* Fits the view.
*
* @param options.padding - optional padding
* @param options.includeHiddenNodes - optional includeHiddenNodes
* @param options.minZoom - optional minZoom
* @param options.maxZoom - optional maxZoom
* @param options.duration - optional duration. If set, a transition will be applied
* @param options.nodes - optional nodes to fit the view to
*/
fitView: (options?: FitViewOptions) => void;
/**
* Returns all nodes that intersect with the given node or rect.
*
* @param node - the node or rect to check for intersections
* @param partially - if true, the node is considered to be intersecting if it partially overlaps with the passed node or rect
* @param nodes - optional nodes array to check for intersections
*
* @returns an array of intersecting nodes
*/
getIntersectingNodes: (
nodeOrRect: Node | { id: Node['id'] } | Rect,
partially?: boolean,
nodesToIntersect?: Node[]
) => Node[];
/**
* Checks if the given node or rect intersects with the passed rect.
*
* @param node - the node or rect to check for intersections
* @param area - the rect to check for intersections
* @param partially - if true, the node is considered to be intersecting if it partially overlaps with the passed react
*
* @returns true if the node or rect intersects with the given area
*/
isNodeIntersecting: (
nodeOrRect: Node | { id: Node['id'] } | Rect,
area: Rect,
partially?: boolean
) => boolean;
/**
* Fits the view to the given bounds .
*
* @param bounds - the bounds ({ x: number, y: number, width: number, height: number }) to fit the view to
* @param options.padding - optional padding
*/
fitBounds: (bounds: Rect, options?: FitBoundsOptions) => void;
/**
* Deletes nodes and edges.
*
* @param params.nodes - optional nodes array to delete
* @param params.edges - optional edges array to delete
*
* @returns a promise that resolves with the deleted nodes and edges
*/
deleteElements: ({
nodes,
edges
@@ -57,19 +161,66 @@ export function useSvelteFlow(): {
nodes?: (Node | { id: Node['id'] })[];
edges?: (Edge | { id: Edge['id'] })[];
}) => Promise<{ deletedNodes: Node[]; deletedEdges: Edge[] }>;
screenToFlowPosition: (position: XYPosition, options?: { snapToGrid: boolean }) => XYPosition;
flowToScreenPosition: (position: XYPosition) => XYPosition;
/**
* Converts a screen / client position to a flow position.
*
* @param clientPosition - the screen / client position. When you are working with events you can use event.clientX and event.clientY
* @param options.snapToGrid - if true, the converted position will be snapped to the grid
* @returns position as { x: number, y: number }
*
* @example
* const flowPosition = screenToFlowPosition({ x: event.clientX, y: event.clientY })
*/
screenToFlowPosition: (
clientPosition: XYPosition,
options?: { snapToGrid: boolean }
) => XYPosition;
/**
* Converts a flow position to a screen / client position.
*
* @param flowPosition - the screen / client position. When you are working with events you can use event.clientX and event.clientY
* @returns position as { x: number, y: number }
*
* @example
* const clientPosition = flowToScreenPosition({ x: node.position.x, y: node.position.y })
*/
flowToScreenPosition: (flowPosition: XYPosition) => XYPosition;
viewport: Writable<Viewport>;
/**
* Updates a node.
*
* @param id - id of the node to update
* @param nodeUpdate - the node update as an object or a function that receives the current node and returns the node update
* @param options.replace - if true, the node is replaced with the node update, otherwise the changes get merged
*
* @example
* updateNode('node-1', (node) => ({ position: { x: node.position.x + 10, y: node.position.y } }));
*/
updateNode: (
id: string,
nodeUpdate: Partial<Node> | ((node: Node) => Partial<Node>),
options?: { replace: boolean }
) => void;
/**
* Updates the data attribute of a node.
*
* @param id - id of the node 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
* updateNodeData('node-1', { label: 'A new label' });
*/
updateNodeData: (
id: string,
dataUpdate: object | ((node: Node) => object),
options?: { replace: boolean }
) => void;
/**
* Returns the nodes, edges and the viewport as a JSON object.
*
* @returns the nodes, edges and the viewport as a JSON object
*/
toObject: () => { nodes: Node[]; edges: Edge[]; viewport: Viewport };
} {
const {
@@ -263,6 +414,11 @@ export function useSvelteFlow(): {
_snapGrid || [1, 1]
);
},
/**
*
* @param position
* @returns
*/
flowToScreenPosition: (position: XYPosition) => {
const _domNode = get(domNode);
@@ -279,6 +435,7 @@ export function useSvelteFlow(): {
y: rendererPosition.y + domY
};
},
toObject: () => {
return {
nodes: get(nodes).map((node) => ({

View File

@@ -31,6 +31,7 @@ export * from '$lib/hooks/useConnection';
export * from '$lib/hooks/useNodesEdges';
export * from '$lib/hooks/useHandleConnections';
export * from '$lib/hooks/useNodesData';
export { useInitialized, useNodesInitialized } from '$lib/hooks/useInitialized';
// types
export type {

View File

@@ -58,7 +58,7 @@
height: toolbarNode.computed?.height ?? toolbarNode.height ?? 0
};
} else if (toolbarNodes.length > 1) {
nodeRect = getNodesBounds(toolbarNodes, $nodeOrigin);
nodeRect = getNodesBounds(toolbarNodes, { nodeOrigin: $nodeOrigin });
}
if (nodeRect) {

View File

@@ -105,6 +105,10 @@ export function createStore({
}
store.nodes.set(nextNodes);
if (!get(store.nodesInitialized)) {
store.nodesInitialized.set(true);
}
}
function fitView(nodes: Node[], options?: FitViewOptions) {
@@ -347,6 +351,29 @@ export function createStore({
[store.edges, store.defaultMarkerColor, store.flowId],
([edges, defaultColor, id]) => createMarkerIds(edges, { defaultColor, id })
),
initialized: (() => {
let initialized = false;
const initialNodesLength = get(store.nodes).length;
const initialEdgesLength = get(store.edges).length;
return derived(
[store.nodesInitialized, store.edgesInitialized, store.viewportInitialized],
([nodesInitialized, edgesInitialized, viewportInitialized]) => {
// If it was already initialized, return true from then on
if (initialized) return initialized;
// if it hasn't been initialised check if it's now
if (initialNodesLength === 0) {
initialized = viewportInitialized;
} else if (initialEdgesLength === 0) {
initialized = viewportInitialized && nodesInitialized;
} else {
initialized = viewportInitialized && nodesInitialized && edgesInitialized;
}
return initialized;
}
);
})(),
// actions
syncNodeStores: (nodes) => syncNodeStores(store.nodes, nodes),

View File

@@ -23,7 +23,6 @@ import {
type OnConnectStart,
type OnConnectEnd,
type NodeLookup,
type OnBeforeDelete,
type EdgeLookup
} from '@xyflow/system';
@@ -47,7 +46,8 @@ import type {
Edge,
FitViewOptions,
OnDelete,
OnEdgeCreate
OnEdgeCreate,
OnBeforeDelete
} from '$lib/types';
import { createNodesStore, createEdgesStore } from './utils';
import { initConnectionProps, type ConnectionProps } from './derived-connection-props';
@@ -92,7 +92,8 @@ export const getInitialStore = ({
if (fitView && width && height) {
const nodesWithDimensions = nextNodes.filter((node) => node.width && node.height);
const bounds = getNodesBounds(nodesWithDimensions, [0, 0]);
// @todo users nodeOrigin should be used here
const bounds = getNodesBounds(nodesWithDimensions, { nodeOrigin: [0, 0] });
viewport = getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
}
@@ -152,6 +153,10 @@ export const getInitialStore = ({
onconnect: writable<OnConnect>(undefined),
onconnectstart: writable<OnConnectStart>(undefined),
onconnectend: writable<OnConnectEnd>(undefined),
onbeforedelete: writable<OnBeforeDelete>(undefined)
onbeforedelete: writable<OnBeforeDelete>(undefined),
nodesInitialized: writable<boolean>(false),
edgesInitialized: writable<boolean>(false),
viewportInitialized: writable<boolean>(false),
initialized: readable<boolean>(false)
};
};

View File

@@ -5,7 +5,8 @@ import type {
Position,
XYPosition,
ConnectingHandle,
Connection
Connection,
OnBeforeDeleteBase
} from '@xyflow/system';
import type { Node } from './nodes';
@@ -52,3 +53,7 @@ export type FitViewOptions = FitViewOptionsBase<Node>;
export type OnDelete = (params: { nodes: Node[]; edges: Edge[] }) => void;
export type OnEdgeCreate = (connection: Connection) => Edge | Connection | void;
export type OnBeforeDelete<
NodeType extends Node = Node,
EdgeType extends Edge = Edge
> = OnBeforeDeleteBase<NodeType, EdgeType>;

View File

@@ -1,6 +1,6 @@
{
"name": "@xyflow/system",
"version": "0.0.15",
"version": "0.0.16",
"description": "xyflow core system that powers React Flow and Svelte Flow.",
"keywords": [
"node-based UI",

View File

@@ -138,7 +138,7 @@ export type ColorMode = ColorModeClass | 'system';
export type ConnectionLookup = Map<string, Map<string, Connection>>;
export type OnBeforeDelete = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>({
export type OnBeforeDeleteBase<NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase> = ({
nodes,
edges,
}: {

View File

@@ -114,11 +114,6 @@ function getHandle(bounds: HandleElement[], handleId?: string | null): HandleEle
return null;
}
if (bounds.length === 1 || !handleId) {
return bounds[0];
} else if (handleId) {
return bounds.find((d) => d.id === handleId) || null;
}
return null;
// if no handleId is given, we use the first handle, otherwise we check for the id
return (!handleId ? bounds[0] : bounds.find((d) => d.id === handleId)) || null;
}

View File

@@ -198,3 +198,7 @@ export const getViewportForBounds = (
};
export const isMacOs = () => typeof navigator !== 'undefined' && navigator?.userAgent?.indexOf('Mac') >= 0;
export function isCoordinateExtent(extent?: CoordinateExtent | 'parent'): extent is CoordinateExtent {
return extent !== undefined && extent !== 'parent';
}

View File

@@ -4,11 +4,11 @@ import {
clampPosition,
getBoundsOfBoxes,
getOverlappingArea,
isNumeric,
rectToBox,
nodeToRect,
pointToRendererPoint,
getViewportForBounds,
isCoordinateExtent,
} from './general';
import {
type Transform,
@@ -19,10 +19,10 @@ import {
type EdgeBase,
type FitViewParamsBase,
type FitViewOptionsBase,
NodeDragItem,
CoordinateExtent,
OnError,
OnBeforeDelete,
OnBeforeDeleteBase,
NodeLookup,
} from '../types';
import { errorMessages } from '../constants';
@@ -102,11 +102,13 @@ export const getIncomers = <NodeType extends NodeBase = NodeBase, EdgeType exten
export const getNodePositionWithOrigin = (
node: NodeBase | undefined,
nodeOrigin: NodeOrigin = [0, 0]
): XYPosition & { positionAbsolute: XYPosition } => {
): { position: XYPosition; positionAbsolute: XYPosition } => {
if (!node) {
return {
x: 0,
y: 0,
position: {
x: 0,
y: 0,
},
positionAbsolute: {
x: 0,
y: 0,
@@ -123,7 +125,7 @@ export const getNodePositionWithOrigin = (
};
return {
...position,
position,
positionAbsolute: node.computed?.positionAbsolute
? {
x: node.computed.positionAbsolute.x - offsetX,
@@ -133,27 +135,35 @@ export const getNodePositionWithOrigin = (
};
};
export type GetNodesBoundsParams = {
nodeOrigin?: NodeOrigin;
useRelativePosition?: boolean;
};
/**
* Determines a bounding box that contains all given nodes in an array
* @public
* @remarks Useful when combined with {@link getViewportForBounds} to calculate the correct transform to fit the given nodes in a viewport.
* @param nodes - Nodes to calculate the bounds for
* @param nodeOrigin - Origin of the nodes: [0, 0] - top left, [0.5, 0.5] - center
* @param params.nodeOrigin - Origin of the nodes: [0, 0] - top left, [0.5, 0.5] - center
* @param params.useRelativePosition - Whether to use the relative or absolute node positions
* @returns Bounding box enclosing all nodes
*/
export const getNodesBounds = (nodes: NodeBase[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
export const getNodesBounds = (
nodes: NodeBase[],
params: GetNodesBoundsParams = { nodeOrigin: [0, 0], useRelativePosition: false }
): Rect => {
if (nodes.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 };
}
const box = nodes.reduce(
(currBox, node) => {
const { x, y } = getNodePositionWithOrigin(node, node.origin || nodeOrigin);
const nodePos = getNodePositionWithOrigin(node, node.origin || params.nodeOrigin);
return getBoundsOfBoxes(
currBox,
rectToBox({
x,
y,
...nodePos[params.useRelativePosition ? 'position' : 'positionAbsolute'],
width: node.computed?.width ?? node.width ?? 0,
height: node.computed?.height ?? node.height ?? 0,
})
@@ -239,7 +249,7 @@ export function fitView<Params extends FitViewParamsBase<NodeBase>, Options exte
});
if (filteredNodes.length > 0) {
const bounds = getNodesBounds(filteredNodes, nodeOrigin);
const bounds = getNodesBounds(filteredNodes, { nodeOrigin });
const viewport = getViewportForBounds(
bounds,
@@ -258,69 +268,87 @@ export function fitView<Params extends FitViewParamsBase<NodeBase>, Options exte
return false;
}
function clampNodeExtent(node: NodeDragItem | NodeBase, extent?: CoordinateExtent | 'parent') {
/**
* This function clamps the passed extend by the node's width and height.
* This is needed to prevent the node from being dragged outside of its extent.
*
* @param node
* @param extent
* @returns
*/
function clampNodeExtent<NodeType extends NodeBase>(
node: NodeType,
extent?: CoordinateExtent | 'parent'
): CoordinateExtent | 'parent' | undefined {
if (!extent || extent === 'parent') {
return extent;
}
return [extent[0], [extent[1][0] - (node.computed?.width ?? 0), extent[1][1] - (node.computed?.height ?? 0)]];
}
export function calcNextPosition<NodeType extends NodeBase>(
node: NodeDragItem | NodeType,
nextPosition: XYPosition,
nodes: NodeType[],
nodeExtent?: CoordinateExtent,
nodeOrigin: NodeOrigin = [0, 0],
onError?: OnError
): { position: XYPosition; positionAbsolute: XYPosition } {
const clampedNodeExtent = clampNodeExtent(node, node.extent || nodeExtent);
let currentExtent = clampedNodeExtent;
let parentNode: NodeType | null = null;
let parentPos = { x: 0, y: 0 };
if (node.parentNode) {
parentNode = nodes.find((n) => n.id === node.parentNode) || null;
parentPos = parentNode
? getNodePositionWithOrigin(parentNode, parentNode.origin || nodeOrigin).positionAbsolute
: parentPos;
}
/**
* This function calculates the next position of a node, taking into account the node's extent, parent node, and origin.
*
* @internal
* @returns position, positionAbsolute
*/
export function calculateNodePosition<NodeType extends NodeBase>({
nodeId,
nextPosition,
nodeLookup,
nodeOrigin = [0, 0],
nodeExtent,
onError,
}: {
nodeId: string;
nextPosition: XYPosition;
nodeLookup: NodeLookup<NodeType>;
nodeOrigin?: NodeOrigin;
nodeExtent?: CoordinateExtent;
onError?: OnError;
}): { position: XYPosition; positionAbsolute: XYPosition } {
const node = nodeLookup.get(nodeId)!;
const parentNode = node.parentNode ? nodeLookup.get(node.parentNode) : undefined;
const { x: parentX, y: parentY } = parentNode
? getNodePositionWithOrigin(parentNode, parentNode.origin || nodeOrigin).positionAbsolute
: { x: 0, y: 0 };
let currentExtent = clampNodeExtent(node, node.extent || nodeExtent);
if (node.extent === 'parent' && !node.expandParent) {
const nodeWidth = node.computed?.width;
const nodeHeight = node.computed?.height;
if (node.parentNode && nodeWidth && nodeHeight) {
const currNodeOrigin = node.origin || nodeOrigin;
currentExtent =
parentNode && isNumeric(parentNode.computed?.width) && isNumeric(parentNode.computed?.height)
? [
[parentPos.x + nodeWidth * currNodeOrigin[0], parentPos.y + nodeHeight * currNodeOrigin[1]],
[
parentPos.x + (parentNode.computed?.width ?? 0) - nodeWidth + nodeWidth * currNodeOrigin[0],
parentPos.y + (parentNode.computed?.height ?? 0) - nodeHeight + nodeHeight * currNodeOrigin[1],
],
]
: currentExtent;
} else {
if (!parentNode) {
onError?.('005', errorMessages['error005']());
currentExtent = clampedNodeExtent;
} else {
const nodeWidth = node.computed?.width;
const nodeHeight = node.computed?.height;
const parentWidth = parentNode?.computed?.width;
const parentHeight = parentNode?.computed?.height;
if (nodeWidth && nodeHeight && parentWidth && parentHeight) {
const currNodeOrigin = node.origin || nodeOrigin;
const extentX = parentX + nodeWidth * currNodeOrigin[0];
const extentY = parentY + nodeHeight * currNodeOrigin[1];
currentExtent = [
[extentX, extentY],
[extentX + parentWidth - nodeWidth, extentY + parentHeight - nodeHeight],
];
}
}
} else if (node.extent && node.parentNode && node.extent !== 'parent') {
} else if (parentNode && isCoordinateExtent(node.extent)) {
currentExtent = [
[node.extent[0][0] + parentPos.x, node.extent[0][1] + parentPos.y],
[node.extent[1][0] + parentPos.x, node.extent[1][1] + parentPos.y],
[node.extent[0][0] + parentX, node.extent[0][1] + parentY],
[node.extent[1][0] + parentX, node.extent[1][1] + parentY],
];
}
const positionAbsolute =
currentExtent && currentExtent !== 'parent'
? clampPosition(nextPosition, currentExtent as CoordinateExtent)
: nextPosition;
const positionAbsolute = isCoordinateExtent(currentExtent)
? clampPosition(nextPosition, currentExtent)
: nextPosition;
return {
position: {
x: positionAbsolute.x - parentPos.x,
y: positionAbsolute.y - parentPos.y,
x: positionAbsolute.x - parentX,
y: positionAbsolute.y - parentY,
},
positionAbsolute,
};
@@ -347,7 +375,7 @@ export async function getElementsToRemove<NodeType extends NodeBase = NodeBase,
edgesToRemove: Partial<EdgeType>[];
nodes: NodeType[];
edges: EdgeType[];
onBeforeDelete?: OnBeforeDelete;
onBeforeDelete?: OnBeforeDeleteBase<NodeType, EdgeType>;
}): Promise<{
nodes: NodeType[];
edges: EdgeType[];

View File

@@ -19,21 +19,32 @@ export function getMarkerId(marker: EdgeMarkerType | undefined, id?: string | nu
export function createMarkerIds(
edges: EdgeBase[],
{ id, defaultColor }: { id?: string | null; defaultColor?: string }
{
id,
defaultColor,
defaultMarkerStart,
defaultMarkerEnd,
}: {
id?: string | null;
defaultColor?: string;
defaultMarkerStart?: EdgeMarkerType;
defaultMarkerEnd?: EdgeMarkerType;
}
) {
const ids: string[] = [];
const ids = new Set<string>();
return edges
.reduce<MarkerProps[]>((markers, edge) => {
[edge.markerStart, edge.markerEnd].forEach((marker) => {
[edge.markerStart || defaultMarkerStart, edge.markerEnd || defaultMarkerEnd].forEach((marker) => {
if (marker && typeof marker === 'object') {
const markerId = getMarkerId(marker, id);
if (!ids.includes(markerId)) {
if (!ids.has(markerId)) {
markers.push({ id: markerId, color: marker.color || defaultColor, ...marker });
ids.push(markerId);
ids.add(markerId);
}
}
});
return markers;
}, [])
.sort((a, b) => a.id.localeCompare(b.id));

View File

@@ -136,7 +136,7 @@ function calculateXYZPosition<NodeType extends NodeBase>(
}
const parentNode = nodeLookup.get(node.parentNode)!;
const parentNodePosition = getNodePositionWithOrigin(parentNode, parentNode?.origin || nodeOrigin);
const { position: parentNodePosition } = getNodePositionWithOrigin(parentNode, parentNode?.origin || nodeOrigin);
return calculateXYZPosition(
parentNode,

View File

@@ -5,7 +5,7 @@ import {
calcAutoPan,
getEventPosition,
getPointerPosition,
calcNextPosition,
calculateNodePosition,
snapPosition,
getNodesBounds,
rectToBox,
@@ -103,7 +103,6 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
function update({ noDragClassName, handleSelector, domNode, isSelectable, nodeId }: DragUpdateParams) {
function updateNodes({ x, y }: XYPosition) {
const {
nodes,
nodeLookup,
nodeExtent,
snapGrid,
@@ -121,7 +120,7 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
let nodesBox: Box = { x: 0, y: 0, x2: 0, y2: 0 };
if (dragItems.length > 1 && nodeExtent) {
const rect = getNodesBounds(dragItems as unknown as NodeBase[], nodeOrigin);
const rect = getNodesBounds(dragItems as unknown as NodeBase[], { nodeOrigin });
nodesBox = rectToBox(rect);
}
@@ -149,13 +148,20 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
n.computed.positionAbsolute.y + (n.computed?.height ?? 0) - nodesBox.y2 + nodeExtent[1][1];
}
const updatedPos = calcNextPosition(n, nextPosition, nodes, adjustedNodeExtent, nodeOrigin, onError);
const { position, positionAbsolute } = calculateNodePosition({
nodeId: n.id,
nextPosition,
nodeLookup,
nodeExtent: adjustedNodeExtent,
nodeOrigin,
onError,
});
// we want to make sure that we only fire a change event when there is a change
hasChange = hasChange || n.position.x !== updatedPos.position.x || n.position.y !== updatedPos.position.y;
hasChange = hasChange || n.position.x !== position.x || n.position.y !== position.y;
n.position = updatedPos.position;
n.computed.positionAbsolute = updatedPos.positionAbsolute;
n.position = position;
n.computed.positionAbsolute = positionAbsolute;
return n;
});

View File

@@ -260,9 +260,10 @@ function isValidHandle(
}: IsValidParams
) {
const isTarget = fromType === 'target';
const handleDomNode = doc.querySelector(
`.${lib}-flow__handle[data-id="${flowId}-${handle?.nodeId}-${handle?.id}-${handle?.type}"]`
);
const handleDomNode = handle
? doc.querySelector(`.${lib}-flow__handle[data-id="${flowId}-${handle?.nodeId}-${handle?.id}-${handle?.type}"]`)
: null;
const { x, y } = getEventPosition(event);
const handleBelow = doc.elementFromPoint(x, y);
// we always want to prioritize the handle below the mouse cursor over the closest distance handle,