Merge branch 'main' into onnodeschange-docstring-update

This commit is contained in:
Moritz Klack
2025-04-07 11:23:13 +02:00
committed by GitHub
50 changed files with 587 additions and 254 deletions

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `useNodesData`, `useReactFlow`, `isNode` and `isEdge`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `useViewport`, `useUpdateNodeInternals`, `useOnSelectionChange`, `useNodesInitialized` hooks and `UseOnSelectionChangeOptions`, `UseNodesInitializedOptions` types

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `ReactFlowProps`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/svelte': patch
---
Fix typo `React Flow` -> `Svelte Flow`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `BaseEdgeProps`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/system': patch
---
Improve TSDoc comments for `type GetSmoothStepPathParams` and `getSmoothStepPath` function

View File

@@ -0,0 +1,5 @@
---
'@xyflow/system': patch
---
Improve TSDoc comments for `getOutgoers`, `getIncomers` and `type GetNodesBoundsParams`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `useConnection` hook

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `useEdges`, `useInternalNode`, `useNodes` and `useNodeId` hooks

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `useNodesState` and `useEdgesState` hook

View File

@@ -0,0 +1,5 @@
---
'@xyflow/system': patch
---
Improve TSDoc comments for `type ReconnectEdgeOptions` and `getViewportForBounds`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `type UseHandleConnectionsParams` and `useHandleConnections` hook

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `type UseNodeConnectionsParams` and `useNodeConnections` hook

View File

@@ -0,0 +1,5 @@
---
'@xyflow/system': patch
---
Improve TSDoc comments for `type GetStraightPathParams` and `getStraightPath` function

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `type UseOnViewportChangeOptions` and `useOnViewportChange` hook

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `useStore` hook

View File

@@ -0,0 +1,5 @@
---
'@xyflow/system': patch
---
Improve TSDoc comments for `type GetBezierPathParams` and `getBezierPath` function

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `interface GetSimpleBezierPathParams` and `getSimpleBezierPath`

View File

@@ -0,0 +1,5 @@
---
'@xyflow/react': patch
---
Improve TSDoc comments for `type UseKeyPressOptions` and `useKeyPress` hook

View File

@@ -7,9 +7,11 @@ import type { SimpleBezierEdgeProps } from '../../types';
export interface GetSimpleBezierPathParams {
sourceX: number;
sourceY: number;
/** @default Position.Bottom */
sourcePosition?: Position;
targetX: number;
targetY: number;
/** @default Position.Top */
targetPosition?: Position;
}
@@ -33,6 +35,14 @@ function getControl({ pos, x1, y1, x2, y2 }: GetControlParams): [number, number]
* The `getSimpleBezierPath` util returns everything you need to render a simple
* bezier edge between two nodes.
* @public
* @returns
* - `path`: the path to use in an SVG `<path>` element.
* - `labelX`: the `x` position you can use to render a label for this edge.
* - `labelY`: the `y` position you can use to render a label for this edge.
* - `offsetX`: the absolute difference between the source `x` position and the `x` position of the
* middle of this path.
* - `offsetY`: the absolute difference between the source `y` position and the `y` position of the
* middle of this path.
*/
export function getSimpleBezierPath({
sourceX,
@@ -85,8 +95,8 @@ function createSimpleBezierEdge(params: { isInternal: boolean }) {
sourceY,
targetX,
targetY,
sourcePosition = Position.Bottom,
targetPosition = Position.Top,
sourcePosition,
targetPosition,
label,
labelStyle,
labelShowBg,

View File

@@ -11,7 +11,7 @@ import { useStore, useStoreApi } from '../../hooks/useStore';
import type { Node, Edge, ReactFlowState, ReactFlowProps, FitViewOptions } from '../../types';
import { defaultNodeOrigin } from '../../container/ReactFlow/init-values';
// these fields exist in the global store and we need to keep them up to date
// These fields exist in the global store, and we need to keep them up to date
const reactFlowFieldsToTrack = [
'nodes',
'edges',

View File

@@ -10,7 +10,7 @@ export const Consumer = NodeIdContext.Consumer;
* drill down the id as a prop.
*
* @public
* @returns id of the node
* @returns The id for a node in the flow.
*
* @example
*```jsx

View File

@@ -30,6 +30,10 @@ function getSelector<NodeType extends Node = Node, SelectorReturn = ConnectionSt
* based on a certain condition (e.g. if the connection is valid or not).
*
* @public
* @param connectionSelector - An optional selector function used to extract a slice of the
* `ConnectionState` data. Using a selector can prevent component re-renders where data you don't
* otherwise care about might change. If a selector is not provided, the entire `ConnectionState`
* object is returned unchanged.
* @example
*
* ```tsx

View File

@@ -10,7 +10,7 @@ const edgesSelector = (state: ReactFlowState) => state.edges;
* will re-render **whenever any edge changes**.
*
* @public
* @returns An array of edges
* @returns An array of all edges currently in the flow.
*
* @example
* ```tsx

View File

@@ -10,11 +10,16 @@ import {
import { useStore } from './useStore';
import { useNodeId } from '../contexts/NodeIdContext';
type useHandleConnectionsParams = {
type UseHandleConnectionsParams = {
/** What type of handle connections do you want to observe? */
type: HandleType;
/** The handle id (this is only needed if the node has multiple handles of the same type). */
id?: string | null;
/** If node id is not provided, the node id from the `NodeIdContext` is used. */
nodeId?: string;
/** Gets called when a connection is established. */
onConnect?: (connections: Connection[]) => void;
/** Gets called when a connection is removed. */
onDisconnect?: (connections: Connection[]) => void;
};
@@ -23,12 +28,7 @@ type useHandleConnectionsParams = {
*
* @public
* @deprecated Use `useNodeConnections` instead.
* @param param.type - handle type 'source' or 'target'
* @param param.nodeId - node id - if not provided, the node id from the NodeIdContext is used
* @param param.id - the 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.onDisconnect - gets called when a connection is removed
* @returns an array with handle connections
* @returns An array with handle connections.
*/
export function useHandleConnections({
type,
@@ -36,7 +36,7 @@ export function useHandleConnections({
nodeId,
onConnect,
onDisconnect,
}: useHandleConnectionsParams): HandleConnection[] {
}: UseHandleConnectionsParams): HandleConnection[] {
console.warn(
'[DEPRECATED] `useHandleConnections` is deprecated. Instead use `useNodeConnections` https://reactflow.dev/api-reference/hooks/useNodeConnections'
);

View File

@@ -10,8 +10,8 @@ import type { InternalNode, Node } from '../types';
* including when a node is selected or moved.
*
* @public
* @param id - id of the node
* @returns array with visible node ids
* @param id - The ID of a node you want to observe.
* @returns The `InternalNode` object for the node with the given ID.
*
* @example
* ```tsx

View File

@@ -6,7 +6,15 @@ type PressedKeys = Set<string>;
type KeyOrCode = 'key' | 'code';
export type UseKeyPressOptions = {
/**
* Listen to key presses on a specific element.
* @default document
*/
target?: Window | Document | HTMLElement | ShadowRoot | null;
/**
* You can use this flag to prevent triggering the key press hook when an input field is focused.
* @default true
*/
actInsideInputWithModifier?: boolean;
preventDefault?: boolean;
};
@@ -18,9 +26,7 @@ const defaultDoc = typeof document !== 'undefined' ? document : null;
* currently pressed or not.
*
* @public
* @param param.keyCode - The key code (string or array of strings) to use
* @param param.options - Options
* @returns boolean
* @param options - Options
*
* @example
* ```tsx
@@ -40,11 +46,17 @@ const defaultDoc = typeof document !== 'undefined' ? document : null;
*```
*/
export function useKeyPress(
/*
* the keycode can be a string 'a' or an array of strings ['a', 'a+d']
* a string means a single key 'a' or a combination when '+' is used 'a+d'
* an array means different possibilites. Explainer: ['a', 'd+s'] here the
* user can use the single key 'a' or the combination 'd' + 's'
/**
* The key code (string or array of strings) specifies which key(s) should trigger
* an action.
*
* A **string** can represent:
* - A **single key**, e.g. `'a'`
* - A **key combination**, using `'+'` to separate keys, e.g. `'a+d'`
*
* An **array of strings** represents **multiple possible key inputs**. For example, `['a', 'd+s']`
* means the user can press either the single key `'a'` or the combination of `'d'` and `'s'`.
* @default null
*/
keyCode: KeyCode | null = null,
options: UseKeyPressOptions = { target: defaultDoc, actInsideInputWithModifier: true }

View File

@@ -14,10 +14,15 @@ import { useNodeId } from '../contexts/NodeIdContext';
const error014 = errorMessages['error014']();
type UseNodeConnectionsParams = {
/** ID of the node, filled in automatically if used inside custom node. */
id?: string;
/** What type of handle connections do you want to observe? */
handleType?: HandleType;
/** Filter by handle id (this is only needed if the node has multiple handles of the same type). */
handleId?: string;
/** Gets called when a connection is established. */
onConnect?: (connections: Connection[]) => void;
/** Gets called when a connection is removed. */
onDisconnect?: (connections: Connection[]) => void;
};
@@ -25,12 +30,7 @@ type UseNodeConnectionsParams = {
* This hook returns an array of connections on a specific node, handle type ('source', 'target') or handle ID.
*
* @public
* @param param.id - node id - optional if called inside a custom node
* @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.onConnect - gets called when a connection is established
* @param param.onDisconnect - gets called when a connection is removed
* @returns an array with connections
* @returns An array with connections.
*
* @example
* ```jsx
@@ -73,7 +73,7 @@ export function useNodeConnections({
);
useEffect(() => {
// @todo dicuss if onConnect/onDisconnect should be called when the component mounts/unmounts
// @todo discuss if onConnect/onDisconnect should be called when the component mounts/unmounts
if (prevConnections.current && prevConnections.current !== connections) {
const _connections = connections ?? new Map();
handleConnectionChange(prevConnections.current, _connections, onDisconnect);

View File

@@ -11,7 +11,7 @@ const nodesSelector = (state: ReactFlowState) => state.nodes;
* or moved.
*
* @public
* @returns An array of nodes
* @returns An array of all nodes currently in the flow.
*
* @example
* ```jsx

View File

@@ -8,11 +8,9 @@ import type { Node } from '../types';
* This hook lets you subscribe to changes of a specific nodes `data` object.
*
* @public
* @param nodeId - The id (or ids) of the node to get the data from
* @returns An object (or array of object) with {id, type, data} representing each node
* @returns An object (or array of object) with `id`, `type`, `data` representing each node.
*
* @example
*
*```jsx
*import { useNodesData } from '@xyflow/react';
*
@@ -25,9 +23,13 @@ import type { Node } from '../types';
*```
*/
export function useNodesData<NodeType extends Node = Node>(
/** The id of the node to get the data from. */
nodeId: string
): Pick<NodeType, 'id' | 'type' | 'data'> | null;
export function useNodesData<NodeType extends Node = Node>(nodeIds: string[]): Pick<NodeType, 'id' | 'type' | 'data'>[];
export function useNodesData<NodeType extends Node = Node>(
/** The ids of the nodes to get the data from. */
nodeIds: string[]
): Pick<NodeType, 'id' | 'type' | 'data'>[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useNodesData(nodeIds: any): any {
const nodesData = useStore(

View File

@@ -9,8 +9,16 @@ import type { Node, Edge, OnNodesChange, OnEdgesChange } from '../types';
* like React's `useState` hook with an additional helper callback.
*
* @public
* @param initialNodes
* @returns an array [nodes, setNodes, onNodesChange]
* @returns
* - `nodes`: The current array of nodes. You might pass this directly to the `nodes` prop of your
* `<ReactFlow />` component, or you may want to manipulate it first to perform some layouting,
* for example.
* - `setNodes`: A function that you can use to update the nodes. You can pass it a new array of
* nodes or a callback that receives the current array of nodes and returns a new array of nodes.
* This is the same as the second element of the tuple returned by React's `useState` hook.
* - `onNodesChange`: A handy callback that can take an array of `NodeChanges` and update the nodes
* state accordingly. You'll typically pass this directly to the `onNodesChange` prop of your
* `<ReactFlow />` component.
* @example
*
*```tsx
@@ -42,7 +50,12 @@ import type { Node, Edge, OnNodesChange, OnEdgesChange } from '../types';
*/
export function useNodesState<NodeType extends Node>(
initialNodes: NodeType[]
): [NodeType[], Dispatch<SetStateAction<NodeType[]>>, OnNodesChange<NodeType>] {
): [
//
nodes: NodeType[],
setNodes: Dispatch<SetStateAction<NodeType[]>>,
onNodesChange: OnNodesChange<NodeType>
] {
const [nodes, setNodes] = useState(initialNodes);
const onNodesChange: OnNodesChange<NodeType> = useCallback(
(changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
@@ -58,8 +71,18 @@ export function useNodesState<NodeType extends Node>(
* like React's `useState` hook with an additional helper callback.
*
* @public
* @param initialEdges
* @returns an array [edges, setEdges, onEdgesChange]
* @returns
* - `edges`: The current array of edges. You might pass this directly to the `edges` prop of your
* `<ReactFlow />` component, or you may want to manipulate it first to perform some layouting,
* for example.
*
* - `setEdges`: A function that you can use to update the edges. You can pass it a new array of
* edges or a callback that receives the current array of edges and returns a new array of edges.
* This is the same as the second element of the tuple returned by React's `useState` hook.
*
* - `onEdgesChange`: A handy callback that can take an array of `EdgeChanges` and update the edges
* state accordingly. You'll typically pass this directly to the `onEdgesChange` prop of your
* `<ReactFlow />` component.
* @example
*
*```tsx
@@ -91,7 +114,12 @@ export function useNodesState<NodeType extends Node>(
*/
export function useEdgesState<EdgeType extends Edge = Edge>(
initialEdges: EdgeType[]
): [EdgeType[], Dispatch<SetStateAction<EdgeType[]>>, OnEdgesChange<EdgeType>] {
): [
//
edges: EdgeType[],
setEdges: Dispatch<SetStateAction<EdgeType[]>>,
onEdgesChange: OnEdgesChange<EdgeType>
] {
const [edges, setEdges] = useState(initialEdges);
const onEdgesChange: OnEdgesChange<EdgeType> = useCallback(
(changes) => setEdges((eds) => applyEdgeChanges(changes, eds)),

View File

@@ -4,6 +4,7 @@ import { useStore } from './useStore';
import type { ReactFlowState } from '../types';
export type UseNodesInitializedOptions = {
/** @default false */
includeHiddenNodes?: boolean;
};
@@ -29,8 +30,8 @@ const selector = (options: UseNodesInitializedOptions) => (s: ReactFlowState) =>
*`false` and then `true` again once the node has been measured.
*
* @public
* @param options.includeHiddenNodes - defaults to false
* @returns boolean indicating whether all nodes are initialized
* @returns Whether or not the nodes have been initialized by the `<ReactFlow />` component and
* given a width and height.
*
* @example
* ```jsx

View File

@@ -4,6 +4,7 @@ import { useStoreApi } from './useStore';
import type { OnSelectionChangeFunc, Node, Edge } from '../types';
export type UseOnSelectionChangeOptions<NodeType extends Node = Node, EdgeType extends Edge = Edge> = {
/** The handler to register. */
onChange: OnSelectionChangeFunc<NodeType, EdgeType>;
};
@@ -13,8 +14,6 @@ export type UseOnSelectionChangeOptions<NodeType extends Node = Node, EdgeType e
*_either_ nodes or edges changes.
*
* @public
* @param params.onChange - The handler to register
*
* @example
* ```jsx
*import { useState } from 'react';

View File

@@ -4,21 +4,20 @@ import type { OnViewportChange } from '@xyflow/system';
import { useStoreApi } from './useStore';
export type UseOnViewportChangeOptions = {
/** Gets called when the viewport starts changing. */
onStart?: OnViewportChange;
/** Gets called when the viewport changes. */
onChange?: OnViewportChange;
/** Gets called when the viewport stops changing. */
onEnd?: OnViewportChange;
};
/**
* The `useOnViewportChange` hook lets you listen for changes to the viewport such
*as panning and zooming. You can provide a callback for each phase of a viewport
*change: `onStart`, `onChange`, and `onEnd`.
* as panning and zooming. You can provide a callback for each phase of a viewport
* change: `onStart`, `onChange`, and `onEnd`.
*
* @public
* @param params.onStart - gets called when the viewport starts changing
* @param params.onChange - gets called when the viewport changes
* @param params.onEnd - gets called when the viewport stops changing
*
* @example
* ```jsx
*import { useCallback } from 'react';

View File

@@ -31,8 +31,6 @@ const selector = (s: ReactFlowState) => !!s.panZoom;
* This hook returns a ReactFlowInstance that can be used to update nodes and edges, manipulate the viewport, or query the current state of the flow.
*
* @public
* @returns ReactFlowInstance
*
* @example
* ```jsx
*import { useCallback, useState } from 'react';

View File

@@ -14,9 +14,13 @@ const zustandErrorMessage = errorMessages['error001']();
* state management library, so you should check out their docs for more details.
*
* @public
* @param selector
* @param equalityFn
* @returns The selected state slice
* @param selector - A selector function that returns a slice of the flow's internal state.
* Extracting or transforming just the state you need is a good practice to avoid unnecessary
* re-renders.
* @param equalityFn - A function to compare the previous and next value. This is incredibly useful
* for preventing unnecessary re-renders. Good sensible defaults are using `Object.is` or importing
* `zustand/shallow`, but you can be as granular as you like.
* @returns The selected state slice.
*
* @example
* ```ts
@@ -43,8 +47,7 @@ function useStore<StateSlice = unknown>(
/**
* In some cases, you might need to access the store directly. This hook returns the store object which can be used on demand to access the state or dispatch actions.
*
* @returns The store object
*
* @returns The store object.
* @example
* ```ts
* const store = useStoreApi();

View File

@@ -5,12 +5,13 @@ import { useStoreApi } from '../hooks/useStore';
/**
* When you programmatically add or remove handles to a node or update a node's
*handle position, you need to let React Flow know about it using this hook. This
*will update the internal dimensions of the node and properly reposition handles
*on the canvas if necessary.
* handle position, you need to let React Flow know about it using this hook. This
* will update the internal dimensions of the node and properly reposition handles
* on the canvas if necessary.
*
* @public
* @returns function for updating node internals
* @returns Use this function to tell React Flow to update the internal state of one or more nodes
* that you have changed programmatically.
*
* @example
* ```jsx

View File

@@ -12,11 +12,11 @@ const viewportSelector = (state: ReactFlowState) => ({
/**
* The `useViewport` hook is a convenient way to read the current state of the
*{@link Viewport} in a component. Components that use this hook
*will re-render **whenever the viewport changes**.
* {@link Viewport} in a component. Components that use this hook
* will re-render **whenever the viewport changes**.
*
* @public
* @returns The current viewport
* @returns The current viewport.
*
* @example
*

View File

@@ -54,6 +54,7 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
extends Omit<HTMLAttributes<HTMLDivElement>, 'onError'> {
/**
* An array of nodes to render in a controlled flow.
* @default []
* @example
* const nodes = [
* {
@@ -67,6 +68,7 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
nodes?: NodeType[];
/**
* An array of edges to render in a controlled flow.
* @default []
* @example
* const edges = [
* {
@@ -102,42 +104,57 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
* }
*/
defaultEdgeOptions?: DefaultEdgeOptions;
/** This event handler is called when a user clicks on a node */
/** This event handler is called when a user clicks on a node. */
onNodeClick?: NodeMouseHandler<NodeType>;
/** This event handler is called when a user double clicks on a node */
/** This event handler is called when a user double-clicks on a node. */
onNodeDoubleClick?: NodeMouseHandler<NodeType>;
/** This event handler is called when mouse of a user enters a node */
/** This event handler is called when mouse of a user enters a node. */
onNodeMouseEnter?: NodeMouseHandler<NodeType>;
/** This event handler is called when mouse of a user moves over a node */
/** This event handler is called when mouse of a user moves over a node. */
onNodeMouseMove?: NodeMouseHandler<NodeType>;
/** This event handler is called when mouse of a user leaves a node */
/** This event handler is called when mouse of a user leaves a node. */
onNodeMouseLeave?: NodeMouseHandler<NodeType>;
/** This event handler is called when a user right clicks on a node */
/** This event handler is called when a user right-clicks on a node. */
onNodeContextMenu?: NodeMouseHandler<NodeType>;
/** This event handler is called when a user starts to drag a node */
/** This event handler is called when a user starts to drag a node. */
onNodeDragStart?: OnNodeDrag<NodeType>;
/** This event handler is called when a user drags a node */
/** This event handler is called when a user drags a node. */
onNodeDrag?: OnNodeDrag<NodeType>;
/** This event handler is called when a user stops dragging a node */
/** This event handler is called when a user stops dragging a node. */
onNodeDragStop?: OnNodeDrag<NodeType>;
/** This event handler is called when a user clicks on an edge */
/** This event handler is called when a user clicks on an edge. */
onEdgeClick?: (event: ReactMouseEvent, edge: EdgeType) => void;
/** This event handler is called when a user right clicks on an edge */
/** This event handler is called when a user right-clicks on an edge. */
onEdgeContextMenu?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when mouse of a user enters an edge */
/** This event handler is called when mouse of a user enters an edge. */
onEdgeMouseEnter?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when mouse of a user moves over an edge */
/** This event handler is called when mouse of a user moves over an edge. */
onEdgeMouseMove?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when mouse of a user leaves an edge */
/** This event handler is called when mouse of a user leaves an edge. */
onEdgeMouseLeave?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when a user double clicks on an edge */
/** This event handler is called when a user double-clicks on an edge. */
onEdgeDoubleClick?: EdgeMouseHandler<EdgeType>;
/**
* This handler is called when the source or target of a reconnectable edge is dragged from the
* current node. It will fire even if the edge's source or target do not end up changing.
*
* You can use the `reconnectEdge` utility to convert the connection to a new edge.
*/
onReconnect?: OnReconnect<EdgeType>;
/**
* This event fires when the user begins dragging the source or target of an editable edge.
*/
onReconnectStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
/**
* This event fires when the user releases the source or target of an editable edge. It is called
* even if an edge update does not occur.
*
*/
onReconnectEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
/**
* This event handler is called when a Node is updated
* @example // Use NodesState hook to create nodes and get onNodesChange handler
* Use this event handler to add interactivity to a controlled flow.
* It is called on node drag, select, and move.
* @example // Use NodesState hook to create edges and get onNodesChange handler
* import ReactFlow, { useNodesState } from '@xyflow/react';
* const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
*
@@ -154,7 +171,8 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
*/
onNodesChange?: OnNodesChange<NodeType>;
/**
* This event handler is called when a Edge is updated
* Use this event handler to add interactivity to a controlled flow. It is called on edge select
* and remove.
* @example // Use EdgesState hook to create edges and get onEdgesChange handler
* import ReactFlow, { useEdgesState } from '@xyflow/react';
* const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
@@ -171,25 +189,28 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
* return (<ReactFlow onEdgesChange={onEdgesChange} {...rest} />)
*/
onEdgesChange?: OnEdgesChange<EdgeType>;
/** This event handler gets called when a Node is deleted */
/** This event handler gets called when a node is deleted. */
onNodesDelete?: OnNodesDelete<NodeType>;
/** This event handler gets called when a Edge is deleted */
/** This event handler gets called when an edge is deleted. */
onEdgesDelete?: OnEdgesDelete<EdgeType>;
/** This event handler gets called when a Node or Edge is deleted */
/** This event handler gets called when a node or edge is deleted. */
onDelete?: OnDelete<NodeType, EdgeType>;
/** This event handler gets called when a user starts to drag a selection box */
/** This event handler gets called when a user starts to drag a selection box. */
onSelectionDragStart?: SelectionDragHandler<NodeType>;
/** This event handler gets called when a user drags a selection box */
/** This event handler gets called when a user drags a selection box. */
onSelectionDrag?: SelectionDragHandler<NodeType>;
/** This event handler gets called when a user stops dragging a selection box */
/** This event handler gets called when a user stops dragging a selection box. */
onSelectionDragStop?: SelectionDragHandler<NodeType>;
onSelectionStart?: (event: ReactMouseEvent) => void;
onSelectionEnd?: (event: ReactMouseEvent) => void;
/**
* This event handler is called when a user right-clicks on a node selection.
*/
onSelectionContextMenu?: (event: ReactMouseEvent, nodes: NodeType[]) => void;
/**
* When a connection line is completed and two nodes are connected by the user, this event fires with the new connection.
*
* You can use the addEdge utility to convert the connection to a complete edge.
* You can use the `addEdge` utility to convert the connection to a complete edge.
* @example // Use helper function to update edges onConnect
* import ReactFlow, { addEdge } from '@xyflow/react';
*
@@ -201,50 +222,70 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
* return (<ReactFlow onConnect={onConnect} {...rest} />)
*/
onConnect?: OnConnect;
/** This event handler gets called when a user starts to drag a connection line */
/** This event handler gets called when a user starts to drag a connection line. */
onConnectStart?: OnConnectStart;
/** This event handler gets called when a user stops dragging a connection line */
/**
* This callback will fire regardless of whether a valid connection could be made or not. You can
* use the second `connectionState` parameter to have different behavior when a connection was
* unsuccessful.
*/
onConnectEnd?: OnConnectEnd;
onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd;
/** This event handler gets called when a flow has finished initializing */
/**
* The `onInit` callback is called when the viewport is initialized. At this point you can use the
* instance to call methods like `fitView` or `zoomTo`.
*/
onInit?: OnInit<NodeType, EdgeType>;
/** This event handler is called while the user is either panning or zooming the viewport. */
onMove?: OnMove;
/** This event handler gets called when a user starts to pan or zoom the viewport */
/** This event handler is called when the user begins to pan or zoom the viewport. */
onMoveStart?: OnMoveStart;
/** This event handler gets called when a user stops panning or zooming the viewport */
/**
* This event handler is called when panning or zooming viewport movement stops.
* If the movement is not user-initiated, the event parameter will be `null`.
*/
onMoveEnd?: OnMoveEnd;
/** This event handler gets called when a user changes group of selected elements in the flow */
/** This event handler gets called when a user changes group of selected elements in the flow. */
onSelectionChange?: OnSelectionChangeFunc<NodeType, EdgeType>;
/** This event handler gets called when user scroll inside the pane */
/** This event handler gets called when user scroll inside the pane. */
onPaneScroll?: (event?: WheelEvent) => void;
/** This event handler gets called when user clicks inside the pane */
/** This event handler gets called when user clicks inside the pane. */
onPaneClick?: (event: ReactMouseEvent) => void;
/** This event handler gets called when user right clicks inside the pane */
/** This event handler gets called when user right clicks inside the pane. */
onPaneContextMenu?: (event: ReactMouseEvent | MouseEvent) => void;
/** This event handler gets called when mouse enters the pane */
/** This event handler gets called when mouse enters the pane. */
onPaneMouseEnter?: (event: ReactMouseEvent) => void;
/** This event handler gets called when mouse moves over the pane */
/** This event handler gets called when mouse moves over the pane. */
onPaneMouseMove?: (event: ReactMouseEvent) => void;
/** This event handler gets called when mouse leaves the pane */
/** This event handler gets called when mouse leaves the pane. */
onPaneMouseLeave?: (event: ReactMouseEvent) => void;
/**
* Distance that the mouse can move between mousedown/up that will trigger a click
* Distance that the mouse can move between mousedown/up that will trigger a click.
* @default 0
*/
paneClickDistance?: number;
/**
* Distance that the mouse can move between mousedown/up that will trigger a click
* Distance that the mouse can move between mousedown/up that will trigger a click.
* @default 0
*/
nodeClickDistance?: number;
/** This handler gets called before the user deletes nodes or edges and provides a way to abort the deletion by returning false. */
/**
* This handler is called before nodes or edges are deleted, allowing the deletion to be aborted
* by returning `false` or modified by returning updated nodes and edges.
*/
onBeforeDelete?: OnBeforeDelete<NodeType, EdgeType>;
/**
* Custom node types to be available in a flow.
*
* React Flow matches a node's type to a component in the nodeTypes object.
* React Flow matches a node's type to a component in the `nodeTypes` object.
* @TODO check if @default is correct
* @default {
* input: InputNode,
* default: DefaultNode,
* output: OutputNode,
* group: GroupNode
* }
* @example
* import CustomNode from './CustomNode';
*
@@ -254,7 +295,15 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
/**
* Custom edge types to be available in a flow.
*
* React Flow matches an edge's type to a component in the edgeTypes object.
* React Flow matches an edge's type to a component in the `edgeTypes` object.
* @TODO check if @default is correct
* @default {
* default: BezierEdge,
* straight: StraightEdge,
* step: StepEdge,
* smoothstep: SmoothStepEdge,
* simplebezier: SimpleBezier
* }
* @example
* import CustomEdge from './CustomEdge';
*
@@ -265,91 +314,110 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
* The type of edge path to use for connection lines.
*
* Although created edges can be of any type, React Flow needs to know what type of path to render for the connection line before the edge is created!
* @default ConnectionLineType.Bezier
*/
connectionLineType?: ConnectionLineType;
/** Styles to be applied to the connection line */
/** Styles to be applied to the connection line. */
connectionLineStyle?: CSSProperties;
/** React Component to be used as a connection line */
/** React Component to be used as a connection line. */
connectionLineComponent?: ConnectionLineComponent<NodeType>;
/** Styles to be applied to the container of the connection line */
/** Styles to be applied to the container of the connection line. */
connectionLineContainerStyle?: CSSProperties;
/**
* 'strict' connection mode will only allow you to connect source handles to target handles.
*
* 'loose' connection mode will allow you to connect handles of any type to one another.
* A loose connection mode will allow you to connect handles with differing types, including
* source-to-source connections. However, it does not support target-to-target connections. Strict
* mode allows only connections between source handles and target handles.
* @default 'strict'
*/
connectionMode?: ConnectionMode;
/**
* Pressing down this key deletes all selected nodes & edges.
* If set, pressing the key or chord will delete any selected nodes and edges. Passing an array
* represents multiple keys that can be pressed.
*
* For example, `["Delete", "Backspace"]` will delete selected elements when either key is pressed.
* @default 'Backspace'
*/
deleteKeyCode?: KeyCode | null;
/**
* If a key is set, you can pan the viewport while that key is held down even if panOnScroll is set to false.
* If set, holding this key will let you click and drag to draw a selection box around multiple
* nodes and edges. Passing an array represents multiple keys that can be pressed.
*
* By setting this prop to null you can disable this functionality.
* @default 'Space'
* For example, `["Shift", "Meta"]` will allow you to draw a selection box when either key is
* pressed.
* @default 'Shift'
*/
selectionKeyCode?: KeyCode | null;
/** Select multiple elements with a selection box, without pressing down selectionKey */
/**
* Select multiple elements with a selection box, without pressing down `selectionKey`.
* @default false
*/
selectionOnDrag?: boolean;
/**
* When set to "partial", when the user creates a selection box by click and dragging nodes that are only partially in the box are still selected.
* When set to `"partial"`, when the user creates a selection box by click and dragging nodes that
* are only partially in the box are still selected.
* @default 'full'
*/
selectionMode?: SelectionMode;
/**
* If a key is set, you can pan the viewport while that key is held down even if panOnScroll is set to false.
* If a key is set, you can pan the viewport while that key is held down even if `panOnScroll`
* is set to `false`.
*
* By setting this prop to null you can disable this functionality.
* By setting this prop to `null` you can disable this functionality.
* @default 'Space'
*/
panActivationKeyCode?: KeyCode | null;
/**
* Pressing down this key you can select multiple elements by clicking.
* @default 'Meta' for macOS, "Ctrl" for other systems
* @default "Meta" for macOS, "Control" for other systems
*/
multiSelectionKeyCode?: KeyCode | null;
/**
* If a key is set, you can zoom the viewport while that key is held down even if panOnScroll is set to false.
* If a key is set, you can zoom the viewport while that key is held down even if `panOnScroll`
* is set to `false`.
*
* By setting this prop to null you can disable this functionality.
* @default 'Meta' for macOS, "Ctrl" for other systems
* By setting this prop to `null` you can disable this functionality.
* @default "Meta" for macOS, "Control" for other systems
*
*/
zoomActivationKeyCode?: KeyCode | null;
/** Set this prop to make the flow snap to the grid */
/** When enabled, nodes will snap to the grid when dragged. */
snapToGrid?: boolean;
/**
* Grid all nodes will snap to
* If `snapToGrid` is enabled, this prop configures the grid that nodes will snap to.
* @example [20, 20]
*/
snapGrid?: SnapGrid;
/**
* You can enable this optimisation to instruct Svelte Flow to only render nodes and edges that would be visible in the viewport.
* You can enable this optimisation to instruct React Flow to only render nodes and edges that would be visible in the viewport.
*
* This might improve performance when you have a large number of nodes and edges but also adds an overhead.
* @default false
*/
onlyRenderVisibleElements?: boolean;
/**
* Controls if all nodes should be draggable
* Controls whether all nodes should be draggable or not. Individual nodes can override this
* setting by setting their `draggable` prop. If you want to use the mouse handlers on
* non-draggable nodes, you need to add the `"nopan"` class to those nodes.
* @default true
*/
nodesDraggable?: boolean;
/**
* Controls if all nodes should be connectable to each other
* Controls whether all nodes should be connectable or not. Individual nodes can override this
* setting by setting their `connectable` prop.
* @default true
*/
nodesConnectable?: boolean;
/**
* Controls if all nodes should be focusable
* When `true`, focus between nodes can be cycled with the `Tab` key and selected with the `Enter`
* key. This option can be overridden by individual nodes by setting their `focusable` prop.
* @default true
*/
nodesFocusable?: boolean;
/**
* Defines nodes relative position to its coordinates
* The origin of the node to use when placing it in the flow or looking up its `x` and `y`
* position. An origin of `[0, 0]` means that a node's top left corner will be placed at the `x`
* and `y` position.
* @default [0, 0]
* @example
* [0, 0] // default, top left
* [0.5, 0.5] // center
@@ -357,49 +425,57 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
*/
nodeOrigin?: NodeOrigin;
/**
* Controls if all edges should be focusable
* When `true`, focus between edges can be cycled with the `Tab` key and selected with the `Enter`
* key. This option can be overridden by individual edges by setting their `focusable` prop.
* @default true
*/
edgesFocusable?: boolean;
/**
* Controls if all edges should be updateable
* Whether edges can be updated once they are created. When both this prop is `true` and an
* `onReconnect` handler is provided, the user can drag an existing edge to a new source or
* target. Individual edges can override this value with their reconnectable property.
* @default true
*/
edgesReconnectable?: boolean;
/**
* Controls if all elements should (nodes & edges) be selectable
* When `true`, elements (nodes and edges) can be selected by clicking on them. This option can be
* overridden by individual elements by setting their `selectable` prop.
* @default true
*/
elementsSelectable?: boolean;
/**
* If true, nodes get selected on drag
* If `true`, nodes get selected on drag.
* @default true
*/
selectNodesOnDrag?: boolean;
/**
* Enableing this prop allows users to pan the viewport by clicking and dragging.
* Enabling this prop allows users to pan the viewport by clicking and dragging.
*
* You can also set this prop to an array of numbers to limit which mouse buttons can activate panning.
* @default true
* @example [0, 2] // allows panning with the left and right mouse buttons
* [0, 1, 2, 3, 4] // allows panning with all mouse buttons
*/
panOnDrag?: boolean | number[];
/**
* Minimum zoom level
* Minimum zoom level.
* @default 0.5
*/
minZoom?: number;
/**
* Maximum zoom level
* Maximum zoom level.
* @default 2
*/
maxZoom?: number;
/** Controlled viewport to be used instead of internal one */
/**
* When you pass a `viewport` prop, it's controlled, and you also need to pass `onViewportChange`
* to handle internal changes.
*/
viewport?: Viewport;
/**
* Sets the initial position and zoom of the viewport.
*
* If a default viewport is provided but fitView is enabled, the default viewport will be ignored.
* Sets the initial position and zoom of the viewport. If a default viewport is provided but
* `fitView` is enabled, the default viewport will be ignored.
* @default { x: 0, y: 0, zoom: 1 }
* @example
* const initialViewport = {
* zoom: 0.5,
@@ -408,13 +484,14 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
*/
defaultViewport?: Viewport;
/**
* Gets called when the viewport changes.
* Used when working with a controlled viewport for updating the user viewport state.
*/
onViewportChange?: (viewport: Viewport) => void;
/**
* By default the viewport extends infinitely. You can use this prop to set a boundary.
* By default, the viewport extends infinitely. You can use this prop to set a boundary.
*
* The first pair of coordinates is the top left boundary and the second pair is the bottom right.
* @default [[-∞, -∞], [+∞, +∞]]
* @example [[-1000, -10000], [1000, 1000]]
*/
translateExtent?: CoordinateExtent;
@@ -424,51 +501,86 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
*/
preventScrolling?: boolean;
/**
* By default nodes can be placed on an infinite flow. You can use this prop to set a boundary.
* By default, nodes can be placed on an infinite flow. You can use this prop to set a boundary.
*
* The first pair of coordinates is the top left boundary and the second pair is the bottom right.
* @example [[-1000, -10000], [1000, 1000]]
*/
nodeExtent?: CoordinateExtent;
/**
* Color of edge markers
* @example "#b1b1b7"
* Color of edge markers.
* @default '#b1b1b7'
*/
defaultMarkerColor?: string;
/** Controls if the viewport should zoom by scrolling inside the container */
/**
* Controls if the viewport should zoom by scrolling inside the container.
* @default true
*/
zoomOnScroll?: boolean;
/** Controls if the viewport should zoom by pinching on a touch screen */
/**
* Controls if the viewport should zoom by pinching on a touch screen.
* @default true
*/
zoomOnPinch?: boolean;
/**
* Controls if the viewport should pan by scrolling inside the container
* Controls if the viewport should pan by scrolling inside the container.
*
* Can be limited to a specific direction with panOnScrollMode
* Can be limited to a specific direction with `panOnScrollMode`.
* @default false
*/
panOnScroll?: boolean;
/**
* Controls how fast viewport should be panned on scroll.
*
* Use togther with panOnScroll prop.
* Use together with `panOnScroll` prop.
* @default 0.5
*/
panOnScrollSpeed?: number;
/**
* This prop is used to limit the direction of panning when panOnScroll is enabled.
* This prop is used to limit the direction of panning when `panOnScroll` is enabled.
*
* The "free" option allows panning in any direction.
* The `"free"` option allows panning in any direction.
* @default "free"
* @example "horizontal" | "vertical"
*/
panOnScrollMode?: PanOnScrollMode;
/** Controls if the viewport should zoom by double clicking somewhere on the flow */
/**
* Controls if the viewport should zoom by double-clicking somewhere on the flow.
* @default true
*/
zoomOnDoubleClick?: boolean;
/**
* The radius around an edge connection that can trigger an edge reconnection.
* @default 10
*/
reconnectRadius?: number;
/**
* If a node is draggable, clicking and dragging that node will move it around the canvas. Adding
* the `"nodrag"` class prevents this behavior and this prop allows you to change the name of that
* class.
* @default "nodrag"
*/
noDragClassName?: string;
/**
* Typically, scrolling the mouse wheel when the mouse is over the canvas will zoom the viewport.
* Adding the `"nowheel"` class to an element n the canvas will prevent this behavior and this prop
* allows you to change the name of that class.
* @default "nowheel"
*/
noWheelClassName?: string;
/**
* If an element in the canvas does not stop mouse events from propagating, clicking and dragging
* that element will pan the viewport. Adding the `"nopan"` class prevents this behavior and this
* prop allows you to change the name of that class.
* @default "nopan"
*/
noPanClassName?: string;
/** If set, initial viewport will show all nodes & edges */
/** When `true`, the flow will be zoomed and panned to fit all the nodes initially provided. */
fitView?: boolean;
/**
* Options to be used in combination with fitView
* When you typically call `fitView` on a `ReactFlowInstance`, you can provide an object of
* options to customize its behavior. This prop lets you do the same for the initial `fitView`
* call.
* @example
* const fitViewOptions = {
* padding: 0.1,
@@ -481,15 +593,18 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
*/
fitViewOptions?: FitViewOptions;
/**
*The connectOnClick option lets you click or tap on a source handle to start a connection
* The `connectOnClick` option lets you click or tap on a source handle to start a connection
* and then click on a target handle to complete the connection.
*
* If you set this option to false, users will need to drag the connection line to the target
* If you set this option to `false`, users will need to drag the connection line to the target
* handle to create a connection.
* @default true
*/
connectOnClick?: boolean;
/**
* Set position of the attribution
* By default, React Flow will render a small attribution in the bottom right corner of the flow.
*
* You can use this prop to change its position in case you want to place something else there.
* @default 'bottom-right'
* @example 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right'
*/
@@ -509,21 +624,23 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
elevateNodesOnSelect?: boolean;
/**
* Enabling this option will raise the z-index of edges when they are selected.
* @default true
*/
elevateEdgesOnSelect?: boolean;
/**
* Can be set true if built-in keyboard controls should be disabled.
* You can use this prop to disable keyboard accessibility features such as selecting nodes or
* moving selected nodes with the arrow keys.
* @default false
*/
disableKeyboardA11y?: boolean;
/**
* You can enable this prop to automatically pan the viewport while dragging a node.
* When `true`, the viewport will pan automatically when the cursor moves to the edge of the
* viewport while dragging a node.
* @default true
*/
autoPanOnNodeDrag?: boolean;
/**
* You can enable this prop to automatically pan the viewport while dragging a node.
* When `true`, the viewport will pan automatically when the cursor moves to the edge of the
* viewport while creating a connection.
* @default true
*/
autoPanOnConnect?: boolean;
@@ -533,12 +650,12 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
*/
autoPanSpeed?: number;
/**
* You can enable this prop to automatically pan the viewport while making a new connection.
* @default true
* The radius around a handle where you drop a connection line to create a new edge.
* @default 20
*/
connectionRadius?: number;
/**
* Ocassionally something may happen that causes Svelte Flow to throw an error.
* Occasionally something may happen that causes React Flow to throw an error.
*
* Instead of exploding your application, we log a message to the console and then call this event handler.
* You might use it for additional logging or to show a message to the user.
@@ -547,32 +664,33 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
/**
* This callback can be used to validate a new connection
*
* If you return false, the edge will not be added to your flow.
* If you have custom connection logic its preferred to use this callback over the isValidConnection prop on the handle component for performance reasons.
* @default (connection: Connection) => true
* If you return `false`, the edge will not be added to your flow.
* If you have custom connection logic its preferred to use this callback over the
* `isValidConnection` prop on the handle component for performance reasons.
*/
isValidConnection?: IsValidConnection<EdgeType>;
/**
* With a threshold greater than zero you can control the distinction between node drag and click events.
* With a threshold greater than zero you can delay node drag events.
*
* If threshold equals 1, you need to drag the node 1 pixel before a drag event is fired.
*
* 1 is the default value, so clicks don't trigger drag events.
* @default 1
*/
nodeDragThreshold?: number;
/** Sets a fixed width for the flow */
/** Sets a fixed width for the flow. */
width?: number;
/** Sets a fixed height for the flow */
/** Sets a fixed height for the flow. */
height?: number;
/**
* Controls color scheme used for styling the flow
* @default 'system'
* Controls color scheme used for styling the flow.
* @default 'light'
* @example 'system' | 'light' | 'dark'
*/
colorMode?: ColorMode;
/**
* If set true, some debug information will be logged to the console like which events are fired.
*
* @default undefined
* If set `true`, some debug information will be logged to the console like which events are fired.
* @default false
*/
debug?: boolean;
}

View File

@@ -148,7 +148,7 @@ export type EdgeProps<EdgeType extends Edge = Edge> = Pick<
* @public
* @expand
*/
export type BaseEdgeProps = Omit<SVGAttributes<SVGPathElement>, 'd' | 'path'> &
export type BaseEdgeProps = Omit<SVGAttributes<SVGPathElement>, 'd' | 'path' | 'markerStart' | 'markerEnd'> &
EdgeLabelOptions & {
/**
* The width of the invisible area around the edge that the user can interact with. This is
@@ -166,6 +166,16 @@ export type BaseEdgeProps = Omit<SVGAttributes<SVGPathElement>, 'd' | 'path'> &
* be used to generate this string for you.
*/
path: string;
/**
* The id of the SVG marker to use at the start of the edge. This should be defined in a
* `<defs>` element in a separate SVG document or element.
*/
markerStart?: string;
/**
* The id of the SVG marker to use at the end of the edge. This should be defined in a `<defs>`
* element in a separate SVG document or element.
*/
markerEnd?: string;
};
/**

View File

@@ -147,9 +147,9 @@ function applyChange(change: any, element: any): any {
/**
* Drop in function that applies node changes to an array of nodes.
* @public
* @param changes - Array of changes to apply
* @param nodes - Array of nodes to apply the changes to
* @returns Array of updated nodes
* @param changes - Array of changes to apply.
* @param nodes - Array of nodes to apply the changes to.
* @returns Array of updated nodes.
* @example
*```tsx
*import { useState, useCallback } from 'react';
@@ -185,9 +185,9 @@ export function applyNodeChanges<NodeType extends Node = Node>(
/**
* Drop in function that applies edge changes to an array of edges.
* @public
* @param changes - Array of changes to apply
* @param edges - Array of edge to apply the changes to
* @returns Array of updated edges
* @param changes - Array of changes to apply.
* @param edges - Array of edge to apply the changes to.
* @returns Array of updated edges.
* @example
* ```tsx
*import { useState, useCallback } from 'react';

View File

@@ -4,21 +4,23 @@ import { isNodeBase, isEdgeBase } from '@xyflow/system';
import type { Edge, Node } from '../types';
/**
* Test whether an object is useable as an [`Node`](/api-reference/types/node).
* Test whether an object is usable as an [`Node`](/api-reference/types/node).
* In TypeScript this is a type guard that will narrow the type of whatever you pass in to
* [`Node`](/api-reference/types/node) if it returns `true`.
*
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Node if it returns true
* @param element - The element to test
* @returns A boolean indicating whether the element is an Node
* @param element - The element to test.
* @returns Tests whether the provided value can be used as a `Node`. If you're using TypeScript,
* this function acts as a type guard and will narrow the type of the value to `Node` if it returns
* `true`.
*
* @example
* ```js
*import { isNode } from '@xyflow/react';
*
*if (isNode(node)) {
* // ..
* // ...
*}
*```
*/
@@ -26,21 +28,23 @@ export const isNode = <NodeType extends Node = Node>(element: unknown): element
isNodeBase<NodeType>(element);
/**
* Test whether an object is useable as an [`Edge`](/api-reference/types/edge).
* Test whether an object is usable as an [`Edge`](/api-reference/types/edge).
* In TypeScript this is a type guard that will narrow the type of whatever you pass in to
* [`Edge`](/api-reference/types/edge) if it returns `true`.
*
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Edge if it returns true
* @param element - The element to test
* @returns A boolean indicating whether the element is an Edge
* @returns Tests whether the provided value can be used as an `Edge`. If you're using TypeScript,
* this function acts as a type guard and will narrow the type of the value to `Edge` if it returns
* `true`.
*
* @example
* ```js
*import { isEdge } from '@xyflow/react';
*
*if (isEdge(edge)) {
* // ..
* // ...
*}
*```
*/

View File

@@ -11,8 +11,8 @@ import type {
import type { Node } from '$lib/types';
/**
* An `Edge` is the complete description with everything React Flow needs
*to know in order to render it.
* An `Edge` is the complete description with everything Svelte Flow needs to know in order to
* render it.
* @public
*/
export type Edge<

View File

@@ -3,7 +3,7 @@ import { isNodeBase, isEdgeBase } from '@xyflow/system';
import type { Edge, Node } from '$lib/types';
/**
* Test whether an object is useable as a Node
* Test whether an object is usable as a Node
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Node if it returns true
* @param element - The element to test
@@ -13,7 +13,7 @@ export const isNode = <NodeType extends Node = Node>(element: unknown): element
isNodeBase<NodeType>(element);
/**
* Test whether an object is useable as an Edge
* Test whether an object is usable as an Edge
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Edge if it returns true
* @param element - The element to test

View File

@@ -1,12 +1,28 @@
import { Position } from '../../types';
export type GetBezierPathParams = {
/** The `x` position of the source handle. */
sourceX: number;
/** The `y` position of the source handle. */
sourceY: number;
/**
* The position of the source handle.
* @default Position.Bottom
*/
sourcePosition?: Position;
/** The `x` position of the target handle. */
targetX: number;
/** The `y` position of the target handle. */
targetY: number;
/**
* The position of the target handle.
* @default Position.Top
*/
targetPosition?: Position;
/**
* The curvature of the bezier edge.
* @default 0.25
*/
curvature?: number;
};
@@ -75,14 +91,15 @@ function getControlWithCurvature({ pos, x1, y1, x2, y2, c }: GetControlWithCurva
* The `getBezierPath` util returns everything you need to render a bezier edge
*between two nodes.
* @public
* @param params.sourceX - The x position of the source handle
* @param params.sourceY - The y position of the source handle
* @param params.sourcePosition - The position of the source handle (default: Position.Bottom)
* @param params.targetX - The x position of the target handle
* @param params.targetY - The y position of the target handle
* @param params.targetPosition - The position of the target handle (default: Position.Top)
* @param params.curvature - The curvature of the bezier edge
* @returns A path string you can use in an SVG, the labelX and labelY position (center of path) and offsetX, offsetY between source handle and label
* @returns A path string you can use in an SVG, the `labelX` and `labelY` position (center of path)
* and `offsetX`, `offsetY` between source handle and label.
* - `path`: the path to use in an SVG `<path>` element.
* - `labelX`: the `x` position you can use to render a label for this edge.
* - `labelY`: the `y` position you can use to render a label for this edge.
* - `offsetX`: the absolute difference between the source `x` position and the `x` position of the
* middle of this path.
* - `offsetY`: the absolute difference between the source `y` position and the `y` position of the
* middle of this path.
* @example
* ```js
* const source = { x: 0, y: 20 };

View File

@@ -92,9 +92,9 @@ const connectionExists = (edge: EdgeBase, edges: EdgeBase[]) => {
/**
* 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
* @returns A new array of edges with the new edge added
* @param edgeParams - Either an `Edge` or a `Connection` you want to add.
* @param edges - The array of all current edges.
* @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
*`targetHandle` and `sourceHandle` if those are set), then this util won't add
@@ -137,6 +137,10 @@ export const addEdge = <EdgeType extends EdgeBase>(
};
export type ReconnectEdgeOptions = {
/**
* Should the id of the old edge be replaced with the new connection id.
* @default true
*/
shouldReplaceId?: boolean;
};
@@ -145,11 +149,10 @@ export type ReconnectEdgeOptions = {
*This searches your edge array for an edge with a matching `id` and updates its
*properties with the connection you provide.
* @public
* @param oldEdge - The edge you want to update
* @param newConnection - The new connection you want to update the edge with
* @param edges - The array of all current edges
* @param options.shouldReplaceId - should the id of the old edge be replaced with the new connection id
* @returns the updated edges array
* @param oldEdge - The edge you want to update.
* @param newConnection - The new connection you want to update the edge with.
* @param edges - The array of all current edges.
* @returns The updated edges array.
*
* @example
* ```js

View File

@@ -2,15 +2,29 @@ import { getEdgeCenter } from './general';
import { Position, type XYPosition } from '../../types';
export interface GetSmoothStepPathParams {
/** The `x` position of the source handle. */
sourceX: number;
/** The `y` position of the source handle. */
sourceY: number;
/**
* The position of the source handle.
* @default Position.Bottom
*/
sourcePosition?: Position;
/** The `x` position of the target handle. */
targetX: number;
/** The `y` position of the target handle. */
targetY: number;
/**
* The position of the target handle.
* @default Position.Top
*/
targetPosition?: Position;
/** @default 5 */
borderRadius?: number;
centerX?: number;
centerY?: number;
/** @default 20 */
offset?: number;
}
@@ -39,8 +53,8 @@ const getDirection = ({
const distance = (a: XYPosition, b: XYPosition) => Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
/*
* ith this function we try to mimic a orthogonal edge routing behaviour
* It's not as good as a real orthogonal edge routing but it's faster and good enough as a default for step and smooth step edges
* With this function we try to mimic an orthogonal edge routing behaviour
* It's not as good as a real orthogonal edge routing, but it's faster and good enough as a default for step and smooth step edges
*/
function getPoints({
source,
@@ -198,16 +212,19 @@ function getBend(a: XYPosition, b: XYPosition, c: XYPosition, size: number): str
/**
* The `getSmoothStepPath` util returns everything you need to render a stepped path
*between two nodes. The `borderRadius` property can be used to choose how rounded
*the corners of those steps are.
* between two nodes. The `borderRadius` property can be used to choose how rounded
* the corners of those steps are.
* @public
* @param params.sourceX - The x position of the source handle
* @param params.sourceY - The y position of the source handle
* @param params.sourcePosition - The position of the source handle (default: Position.Bottom)
* @param params.targetX - The x position of the target handle
* @param params.targetY - The y position of the target handle
* @param params.targetPosition - The position of the target handle (default: Position.Top)
* @returns A path string you can use in an SVG, the labelX and labelY position (center of path) and offsetX, offsetY between source handle and label
* @returns A path string you can use in an SVG, the `labelX` and `labelY` position (center of path)
* and `offsetX`, `offsetY` between source handle and label.
*
* - `path`: the path to use in an SVG `<path>` element.
* - `labelX`: the `x` position you can use to render a label for this edge.
* - `labelY`: the `y` position you can use to render a label for this edge.
* - `offsetX`: the absolute difference between the source `x` position and the `x` position of the
* middle of this path.
* - `offsetY`: the absolute difference between the source `y` position and the `y` position of the
* middle of this path.
* @example
* ```js
* const source = { x: 0, y: 20 };

View File

@@ -1,20 +1,29 @@
import { getEdgeCenter } from './general';
export type GetStraightPathParams = {
/** The `x` position of the source handle. */
sourceX: number;
/** The `y` position of the source handle. */
sourceY: number;
/** The `x` position of the target handle. */
targetX: number;
/** The `y` position of the target handle. */
targetY: number;
};
/**
* Calculates the straight line path between two points.
* @public
* @param params.sourceX - The x position of the source handle
* @param params.sourceY - The y position of the source handle
* @param params.targetX - The x position of the target handle
* @param params.targetY - The y position of the target handle
* @returns A path string you can use in an SVG, the labelX and labelY position (center of path) and offsetX, offsetY between source handle and label
* @returns A path string you can use in an SVG, the `labelX` and `labelY` position (center of path)
* and `offsetX`, `offsetY` between source handle and label.
*
* - `path`: the path to use in an SVG `<path>` element.
* - `labelX`: the `x` position you can use to render a label for this edge.
* - `labelY`: the `y` position you can use to render a label for this edge.
* - `offsetX`: the absolute difference between the source `x` position and the `x` position of the
* middle of this path.
* - `offsetY`: the absolute difference between the source `y` position and the `y` position of the
* middle of this path.
* @example
* ```js
* const source = { x: 0, y: 20 };

View File

@@ -275,16 +275,16 @@ function calculateAppliedPaddings(bounds: Rect, x: number, y: number, zoom: numb
}
/**
* Returns a viewport that encloses the given bounds with optional padding.
* Returns a viewport that encloses the given bounds with padding.
* @public
* @remarks You can determine bounds of nodes with {@link getNodesBounds} and {@link getBoundsOfRects}
* @param bounds - Bounds to fit inside viewport
* @param width - Width of the viewport
* @param height - Height of the viewport
* @param minZoom - Minimum zoom level of the resulting viewport
* @param maxZoom - Maximum zoom level of the resulting viewport
* @param padding - Optional padding around the bounds
* @returns A transforned {@link Viewport} that encloses the given bounds which you can pass to e.g. {@link setViewport}
* @param bounds - Bounds to fit inside viewport.
* @param width - Width of the viewport.
* @param height - Height of the viewport.
* @param minZoom - Minimum zoom level of the resulting viewport.
* @param maxZoom - Maximum zoom level of the resulting viewport.
* @param padding - Padding around the bounds.
* @returns A transformed {@link Viewport} that encloses the given bounds which you can pass to e.g. {@link setViewport}.
* @example
* const { x, y, zoom } = getViewportForBounds(
* { x: 0, y: 0, width: 100, height: 100},

View File

@@ -30,7 +30,7 @@ import {
import { errorMessages } from '../constants';
/**
* Test whether an object is useable as an Edge
* Test whether an object is usable as an Edge
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Edge if it returns true
* @param element - The element to test
@@ -40,7 +40,7 @@ export const isEdgeBase = <EdgeType extends EdgeBase = EdgeBase>(element: any):
'id' in element && 'source' in element && 'target' in element;
/**
* Test whether an object is useable as a Node
* Test whether an object is usable as a Node
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Node if it returns true
* @param element - The element to test
@@ -57,10 +57,10 @@ export const isInternalNodeBase = <NodeType extends InternalNodeBase = InternalN
* This util is used to tell you what nodes, if any, are connected to the given node
* as the _target_ of an edge.
* @public
* @param node - The node to get the connected nodes from
* @param nodes - The array of all nodes
* @param edges - The array of all edges
* @returns An array of nodes that are connected over eges where the source is the given node
* @param node - The node to get the connected nodes from.
* @param nodes - The array of all nodes.
* @param edges - The array of all edges.
* @returns An array of nodes that are connected over edges where the source is the given node.
*
* @example
* ```ts
@@ -99,10 +99,10 @@ export const getOutgoers = <NodeType extends NodeBase = NodeBase, EdgeType exten
* This util is used to tell you what nodes, if any, are connected to the given node
* as the _source_ of an edge.
* @public
* @param node - The node to get the connected nodes from
* @param nodes - The array of all nodes
* @param edges - The array of all edges
* @returns An array of nodes that are connected over eges where the target is the given node
* @param node - The node to get the connected nodes from.
* @param nodes - The array of all nodes.
* @param edges - The array of all edges.
* @returns An array of nodes that are connected over edges where the target is the given node.
*
* @example
* ```ts
@@ -149,6 +149,10 @@ export const getNodePositionWithOrigin = (node: NodeBase, nodeOrigin: NodeOrigin
};
export type GetNodesBoundsParams<NodeType extends NodeBase = NodeBase> = {
/**
* Origin of the nodes: `[0, 0]` for top-left, `[0.5, 0.5]` for center.
* @default [0, 0]
*/
nodeOrigin?: NodeOrigin;
nodeLookup?: NodeLookup<InternalNodeBase<NodeType>>;
};
@@ -159,9 +163,8 @@ export type GetNodesBoundsParams<NodeType extends NodeBase = NodeBase> = {
* to calculate the correct transform to fit the given nodes in a viewport.
* @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 params.nodeOrigin - Origin of the nodes: [0, 0] - top left, [0.5, 0.5] - center
* @returns Bounding box enclosing all nodes
* @param nodes - Nodes to calculate the bounds for.
* @returns Bounding box enclosing all nodes.
*
* @remarks This function was previously called `getRectOfNodes`
*
@@ -191,7 +194,7 @@ export type GetNodesBoundsParams<NodeType extends NodeBase = NodeBase> = {
*/
export const getNodesBounds = <NodeType extends NodeBase = NodeBase>(
nodes: (NodeType | InternalNodeBase<NodeType> | string)[],
params: GetNodesBoundsParams<NodeType> = { nodeOrigin: [0, 0], nodeLookup: undefined }
params: GetNodesBoundsParams<NodeType> = { nodeOrigin: [0, 0] }
): Rect => {
if (process.env.NODE_ENV === 'development' && !params.nodeLookup) {
console.warn(
@@ -299,9 +302,9 @@ export const getNodesInside = <NodeType extends NodeBase = NodeBase>(
* This utility filters an array of edges, keeping only those where either the source or target
* node is present in the given array of nodes.
* @public
* @param nodes - Nodes you want to get the connected edges for
* @param edges - All edges
* @returns Array of edges that connect any of the given nodes with each other
* @param nodes - Nodes you want to get the connected edges for.
* @param edges - All edges.
* @returns Array of edges that connect any of the given nodes with each other.
*
* @example
* ```js