refactor(react/svelte): cleanup types

This commit is contained in:
moklick
2023-02-28 18:16:51 +01:00
parent dda21e1fd2
commit 63bb2045f4
96 changed files with 899 additions and 847 deletions

View File

@@ -1,7 +1,7 @@
import { CSSProperties } from 'react';
import type { ReactFlowState } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import type { ReactFlowState } from '../../types';
const style: CSSProperties = { display: 'none' };
const ariaLiveStyle: CSSProperties = {

View File

@@ -6,16 +6,14 @@ import {
Position,
ConnectionLineType,
ConnectionMode,
type ConnectionLineComponent,
type ConnectionStatus,
type HandleType,
type ReactFlowState,
type ReactFlowStore,
} from '@reactflow/system';
import { getBezierPath, getSmoothStepPath } from '@reactflow/edge-utils';
import { useStore } from '../../hooks/useStore';
import { getSimpleBezierPath } from '../Edges/SimpleBezierEdge';
import type { ConnectionLineComponent, ReactFlowState, ReactFlowStore } from '../../types';
type ConnectionLineProps = {
nodeId: string;

View File

@@ -1,8 +1,8 @@
import type { ReactNode } from 'react';
import { createPortal } from 'react-dom';
import type { ReactFlowState } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import type { ReactFlowState } from '../../types';
const selector = (s: ReactFlowState) => s.domNode?.querySelector('.react-flow__edgelabel-renderer');

View File

@@ -1,5 +1,6 @@
import { isNumeric } from '@reactflow/utils';
import type { BaseEdgeProps } from '@reactflow/system';
import type { BaseEdgeProps } from '../../types';
import EdgeText from './EdgeText';

View File

@@ -1,8 +1,9 @@
import { memo } from 'react';
import { Position, type BezierEdgeProps } from '@reactflow/system';
import { Position } from '@reactflow/system';
import { getBezierPath } from '@reactflow/edge-utils';
import BaseEdge from './BaseEdge';
import type { BezierEdgeProps } from '../../types';
const BezierEdge = memo(
({

View File

@@ -1,7 +1,8 @@
import { memo, useRef, useState, useEffect } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { memo, useRef, useState, useEffect, type FC, type PropsWithChildren } from 'react';
import cc from 'classcat';
import { EdgeTextProps, Rect } from '@reactflow/system';
import type { Rect } from '@reactflow/system';
import type { EdgeTextProps } from '../../types';
const EdgeText: FC<PropsWithChildren<EdgeTextProps>> = ({
x,

View File

@@ -1,8 +1,9 @@
import { memo } from 'react';
import { Position, type EdgeProps } from '@reactflow/system';
import { Position } from '@reactflow/system';
import { getBezierEdgeCenter } from '@reactflow/edge-utils';
import BaseEdge from './BaseEdge';
import type { EdgeProps } from '../../types';
export interface GetSimpleBezierPathParams {
sourceX: number;

View File

@@ -1,8 +1,9 @@
import { memo } from 'react';
import { Position, type SmoothStepEdgeProps } from '@reactflow/system';
import { Position } from '@reactflow/system';
import { getSmoothStepPath } from '@reactflow/edge-utils';
import BaseEdge from './BaseEdge';
import type { SmoothStepEdgeProps } from '../../types';
const SmoothStepEdge = memo(
({

View File

@@ -1,7 +1,7 @@
import { memo, useMemo } from 'react';
import type { SmoothStepEdgeProps } from '@reactflow/system';
import SmoothStepEdge from './SmoothStepEdge';
import type { SmoothStepEdgeProps } from '../../types';
const StepEdge = memo((props: SmoothStepEdgeProps) => (
<SmoothStepEdge

View File

@@ -1,8 +1,8 @@
import { memo } from 'react';
import type { EdgeProps } from '@reactflow/system';
import { getStraightPath } from '@reactflow/edge-utils';
import BaseEdge from './BaseEdge';
import type { EdgeProps } from '../../types';
const StraightEdge = memo(
({

View File

@@ -1,6 +1,7 @@
import { MouseEvent as ReactMouseEvent } from 'react';
import { StoreApi } from 'zustand';
import type { Edge, ReactFlowState } from '@reactflow/system';
import type { Edge, ReactFlowState } from '../../types';
export function getMouseHandler(
id: string,

View File

@@ -1,14 +1,14 @@
import { memo, useState, useMemo, useRef } from 'react';
import type { ComponentType, KeyboardEvent } from 'react';
import { memo, useState, useMemo, useRef, type ComponentType, type KeyboardEvent } from 'react';
import cc from 'classcat';
import { getMarkerId, elementSelectionKeys } from '@reactflow/utils';
import type { EdgeProps, WrapEdgeProps, Connection } from '@reactflow/system';
import type { Connection } from '@reactflow/system';
import { useStoreApi } from '../../hooks/useStore';
import { ARIA_EDGE_DESC_KEY } from '../A11yDescriptions';
import { handlePointerDown } from '../Handle/handler';
import { EdgeAnchor } from './EdgeAnchor';
import { getMouseHandler } from './utils';
import type { EdgeProps, WrapEdgeProps } from '../../types';
export default (EdgeComponent: ComponentType<EdgeProps>) => {
const EdgeWrapper = ({

View File

@@ -7,7 +7,7 @@ import {
pointToRendererPoint,
rendererPointToPoint,
} from '@reactflow/utils';
import type { OnConnect, HandleType, ReactFlowState, Connection } from '@reactflow/system';
import type { OnConnect, HandleType, Connection } from '@reactflow/system';
import {
ConnectionHandle,
@@ -19,6 +19,7 @@ import {
resetRecentHandle,
ValidConnectionFunc,
} from './utils';
import type { ReactFlowState } from '../../types';
export function handlePointerDown({
event,

View File

@@ -1,13 +1,15 @@
import { memo, HTMLAttributes, forwardRef, MouseEvent as ReactMouseEvent, TouchEvent as ReactTouchEvent } from 'react';
import cc from 'classcat';
import { shallow } from 'zustand/shallow';
import { errorMessages, Position, type HandleProps, type Connection, type ReactFlowState } from '@reactflow/system';
import { getHostForElement, isMouseEvent, addEdge } from '@reactflow/utils';
import { errorMessages, Position, type HandleProps, type Connection } from '@reactflow/system';
import { getHostForElement, isMouseEvent } from '@reactflow/utils';
import { useStore, useStoreApi } from '../../hooks/useStore';
import { useNodeId } from '../../contexts/NodeIdContext';
import { handlePointerDown } from './handler';
import { isValidHandle } from './utils';
import { addEdge } from '../../utils';
import type { ReactFlowState } from '../../types';
const alwaysValid = () => true;

View File

@@ -1,8 +1,17 @@
import { MouseEvent as ReactMouseEvent, TouchEvent as ReactTouchEvent } from 'react';
import { internalsSymbol, ConnectionMode, ConnectionStatus } from '@reactflow/system';
import type { Connection, HandleType, XYPosition, Node, NodeHandleBounds } from '@reactflow/system';
import {
internalsSymbol,
ConnectionMode,
ConnectionStatus,
type Connection,
type HandleType,
type XYPosition,
type NodeHandleBounds,
} from '@reactflow/system';
import { getEventPosition } from '@reactflow/utils';
import type { Node } from '../../types';
export type ConnectionHandle = {
id: string | null;
type: HandleType;

View File

@@ -1,7 +1,9 @@
import { MouseEvent } from 'react';
import { StoreApi } from 'zustand';
import { getDimensions } from '@reactflow/utils';
import { Position, type HandleElement, type Node, type NodeOrigin, type ReactFlowState } from '@reactflow/system';
import { Position, type HandleElement, type NodeOrigin } from '@reactflow/system';
import type { Node, ReactFlowState } from '../../types';
export const getHandleBounds = (
selector: string,

View File

@@ -1,8 +1,7 @@
import { useEffect, useRef, memo } from 'react';
import type { ComponentType, MouseEvent, KeyboardEvent } from 'react';
import { useEffect, useRef, memo, type ComponentType, type MouseEvent, type KeyboardEvent } from 'react';
import cc from 'classcat';
import { elementSelectionKeys, isInputDOMNode } from '@reactflow/utils';
import type { NodeProps, WrapNodeProps, XYPosition } from '@reactflow/system';
import type { NodeProps, XYPosition } from '@reactflow/system';
import { useStoreApi } from '../../hooks/useStore';
import { Provider } from '../../contexts/NodeIdContext';
@@ -10,6 +9,7 @@ import { ARIA_NODE_DESC_KEY } from '../A11yDescriptions';
import useDrag from '../../hooks/useDrag';
import useUpdateNodePositions from '../../hooks/useUpdateNodePositions';
import { getMouseHandler, handleNodeClick } from './utils';
import type { WrapNodeProps } from '../../types';
export const arrowKeyDiffs: Record<string, XYPosition> = {
ArrowUp: { x: 0, y: -1 },

View File

@@ -8,12 +8,12 @@ import type { MouseEvent, KeyboardEvent } from 'react';
import cc from 'classcat';
import { shallow } from 'zustand/shallow';
import { getRectOfNodes } from '@reactflow/utils';
import type { Node, ReactFlowState } from '@reactflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore';
import useDrag from '../../hooks/useDrag';
import { arrowKeyDiffs } from '../Nodes/wrapNode';
import useUpdateNodePositions from '../../hooks/useUpdateNodePositions';
import type { Node, ReactFlowState } from '../../types';
export interface NodesSelectionProps {
onSelectionContextMenu?: (event: MouseEvent, nodes: Node[]) => void;

View File

@@ -1,8 +1,9 @@
import type { HTMLAttributes, ReactNode } from 'react';
import cc from 'classcat';
import type { PanelPosition, ReactFlowState } from '@reactflow/system';
import type { PanelPosition } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import type { ReactFlowState } from '../../types';
export type PanelProps = HTMLAttributes<HTMLDivElement> & {
position: PanelPosition;

View File

@@ -1,10 +1,9 @@
import { useRef } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { useRef, type FC, type PropsWithChildren } from 'react';
import { StoreApi } from 'zustand';
import type { ReactFlowState } from '@reactflow/system';
import { Provider } from '../../contexts/RFStoreContext';
import { createRFStore } from '../../store';
import type { ReactFlowState } from '../../types';
const ReactFlowProvider: FC<PropsWithChildren<unknown>> = ({ children }) => {
const storeRef = useRef<StoreApi<ReactFlowState> | null>(null);

View File

@@ -1,8 +1,8 @@
import { memo, useEffect } from 'react';
import { shallow } from 'zustand/shallow';
import type { ReactFlowState, OnSelectionChangeFunc, Node, Edge } from '@reactflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore';
import type { ReactFlowState, OnSelectionChangeFunc, Node, Edge } from '../../types';
type SelectionListenerProps = {
onSelectionChange?: OnSelectionChangeFunc;

View File

@@ -1,9 +1,10 @@
import { useEffect } from 'react';
import { StoreApi } from 'zustand';
import { shallow } from 'zustand/shallow';
import type { Node, Edge, ReactFlowState, CoordinateExtent, ReactFlowProps, ReactFlowStore } from '@reactflow/system';
import type { CoordinateExtent } from '@reactflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore';
import type { Node, Edge, ReactFlowState, ReactFlowProps, ReactFlowStore } from '../../types';
type StoreUpdaterProps = Pick<
ReactFlowProps,

View File

@@ -1,7 +1,7 @@
import { shallow } from 'zustand/shallow';
import type { ReactFlowState } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import type { ReactFlowState } from '../../types';
const selector = (s: ReactFlowState) => ({
userSelectionActive: s.userSelectionActive,

View File

@@ -1,9 +1,10 @@
import { memo, useCallback } from 'react';
import type { EdgeMarker, ReactFlowState } from '@reactflow/system';
import type { EdgeMarker } from '@reactflow/system';
import { getMarkerId } from '@reactflow/utils';
import { useStore } from '../../hooks/useStore';
import { useMarkerSymbol } from './MarkerSymbols';
import type { ReactFlowState } from '../../types';
type MarkerProps = EdgeMarker & {
id: string;

View File

@@ -1,14 +1,14 @@
import { memo, ReactNode } from 'react';
import { shallow } from 'zustand/shallow';
import cc from 'classcat';
import { errorMessages, ConnectionMode, Position, type Edge, type ReactFlowState } from '@reactflow/system';
import { errorMessages, ConnectionMode, Position } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import useVisibleEdges from '../../hooks/useVisibleEdges';
import MarkerDefinitions from './MarkerDefinitions';
import { getEdgePositions, getHandle, getNodeData } from './utils';
import { GraphViewProps } from '../GraphView';
import type { Edge, ReactFlowState } from '../../types';
type EdgeRendererProps = Pick<
GraphViewProps,

View File

@@ -2,12 +2,8 @@ import type { ComponentType } from 'react';
import {
internalsSymbol,
Position,
type EdgeProps,
type EdgeTypes,
type EdgeTypesWrapped,
type HandleElement,
type NodeHandleBounds,
type Node,
type Rect,
type Transform,
type XYPosition,
@@ -16,6 +12,7 @@ import { rectToBox } from '@reactflow/utils';
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge, SimpleBezierEdge } from '../../components/Edges';
import wrapEdge from '../../components/Edges/wrapEdge';
import type { EdgeProps, EdgeTypes, EdgeTypesWrapped, Node } from '../../types';
export type CreateEdgeTypes = (edgeTypes: EdgeTypes) => EdgeTypesWrapped;

View File

@@ -1,5 +1,4 @@
import { memo, type ReactNode } from 'react';
import type { ReactFlowState } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import useGlobalKeyHandler from '../../hooks/useGlobalKeyHandler';
@@ -8,6 +7,7 @@ import { GraphViewProps } from '../GraphView';
import ZoomPane from '../ZoomPane';
import Pane from '../Pane';
import NodesSelection from '../../components/NodesSelection';
import type { ReactFlowState } from '../../types';
export type FlowRendererProps = Omit<
GraphViewProps,

View File

@@ -1,5 +1,4 @@
import { memo } from 'react';
import type { EdgeTypesWrapped, NodeTypesWrapped, ReactFlowProps } from '@reactflow/system';
import FlowRenderer from '../FlowRenderer';
import NodeRenderer from '../NodeRenderer';
@@ -7,6 +6,7 @@ import EdgeRenderer from '../EdgeRenderer';
import ViewportWrapper from '../Viewport';
import useOnInitHandler from '../../hooks/useOnInitHandler';
import ConnectionLine from '../../components/ConnectionLine';
import type { EdgeTypesWrapped, NodeTypesWrapped, ReactFlowProps } from '../../types';
export type GraphViewProps = Omit<ReactFlowProps, 'onSelectionChange' | 'nodes' | 'edges' | 'nodeTypes' | 'edgeTypes'> &
Required<

View File

@@ -1,7 +1,6 @@
import { memo, useMemo, useEffect, useRef } from 'react';
import type { ComponentType } from 'react';
import { memo, useMemo, useEffect, useRef, type ComponentType } from 'react';
import { shallow } from 'zustand/shallow';
import { internalsSymbol, errorMessages, Position, type ReactFlowState, type WrapNodeProps } from '@reactflow/system';
import { internalsSymbol, errorMessages, Position } from '@reactflow/system';
import { clampPosition } from '@reactflow/utils';
import useVisibleNodes from '../../hooks/useVisibleNodes';
@@ -9,6 +8,7 @@ import { useStore } from '../../hooks/useStore';
import { containerStyle } from '../../styles';
import { GraphViewProps } from '../GraphView';
import { getPositionWithOrigin } from './utils';
import type { ReactFlowState, WrapNodeProps } from '../../types';
type NodeRendererProps = Pick<
GraphViewProps,

View File

@@ -1,11 +1,12 @@
import type { ComponentType } from 'react';
import type { NodeTypes, NodeProps, NodeTypesWrapped, NodeOrigin, XYPosition } from '@reactflow/system';
import type { NodeProps, NodeOrigin, XYPosition } from '@reactflow/system';
import DefaultNode from '../../components/Nodes/DefaultNode';
import InputNode from '../../components/Nodes/InputNode';
import OutputNode from '../../components/Nodes/OutputNode';
import GroupNode from '../../components/Nodes/GroupNode';
import wrapNode from '../../components/Nodes/wrapNode';
import type { NodeTypes, NodeTypesWrapped } from '../../types';
export type CreateNodeTypes = (nodeTypes: NodeTypes) => NodeTypesWrapped;

View File

@@ -2,22 +2,17 @@
* The user selection rectangle gets displayed when a user drags the mouse while pressing shift
*/
import { memo, useRef, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
import { memo, useRef, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react';
import { shallow } from 'zustand/shallow';
import cc from 'classcat';
import { getConnectedEdges, getNodesInside, getEventPosition } from '@reactflow/utils';
import {
SelectionMode,
type ReactFlowProps,
type ReactFlowState,
type NodeChange,
type EdgeChange,
} from '@reactflow/system';
import { getNodesInside, getEventPosition } from '@reactflow/utils';
import { SelectionMode } from '@reactflow/system';
import UserSelection from '../../components/UserSelection';
import { containerStyle } from '../../styles';
import { useStore, useStoreApi } from '../../hooks/useStore';
import { getSelectionChanges } from '../../utils/changes';
import { getSelectionChanges, getConnectedEdges } from '../../utils';
import type { ReactFlowProps, ReactFlowState, NodeChange, EdgeChange, Node } from '../../types';
type PaneProps = {
isSelecting: boolean;
@@ -135,7 +130,7 @@ const Pane = memo(
};
const onMouseMove = (event: ReactMouseEvent): void => {
const { userSelectionRect, nodeInternals, edges, transform, onNodesChange, onEdgesChange, nodeOrigin, getNodes } =
const { userSelectionRect, edges, transform, onNodesChange, onEdgesChange, nodeOrigin, getNodes } =
store.getState();
if (!isSelecting || !containerBounds.current || !userSelectionRect) {
return;
@@ -156,8 +151,8 @@ const Pane = memo(
};
const nodes = getNodes();
const selectedNodes = getNodesInside(
nodeInternals,
const selectedNodes = getNodesInside<Node>(
nodes,
nextUserSelectRect,
transform,
selectionMode === SelectionMode.Partial,

View File

@@ -1,20 +1,14 @@
import { forwardRef } from 'react';
import type { CSSProperties } from 'react';
import { forwardRef, type CSSProperties } from 'react';
import cc from 'classcat';
import {
ConnectionLineType,
ConnectionMode,
PanOnScrollMode,
SelectionMode,
type EdgeTypes,
type EdgeTypesWrapped,
type NodeOrigin,
type NodeTypes,
type NodeTypesWrapped,
type ReactFlowProps,
type ReactFlowRefType,
type Viewport,
} from '@reactflow/system';
import { infiniteExtent } from '@reactflow/utils';
import Attribution from '../../components/Attribution';
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge, SimpleBezierEdge } from '../../components/Edges';
@@ -29,8 +23,15 @@ import { createEdgeTypes } from '../EdgeRenderer/utils';
import { createNodeTypes } from '../NodeRenderer/utils';
import GraphView from '../GraphView';
import Wrapper from './Wrapper';
import { infiniteExtent } from '../../store/initialState';
import { useNodeOrEdgeTypes } from './utils';
import type {
EdgeTypes,
EdgeTypesWrapped,
NodeTypes,
NodeTypesWrapped,
ReactFlowProps,
ReactFlowRefType,
} from '../../types';
const defaultNodeTypes: NodeTypes = {
input: InputNode,

View File

@@ -1,16 +1,11 @@
import { useMemo, useRef } from 'react';
import { shallow } from 'zustand/shallow';
import {
errorMessages,
type EdgeTypes,
type EdgeTypesWrapped,
type NodeTypes,
type NodeTypesWrapped,
} from '@reactflow/system';
import { errorMessages } from '@reactflow/system';
import { devWarn } from '@reactflow/utils';
import { CreateEdgeTypes } from '../EdgeRenderer/utils';
import { CreateNodeTypes } from '../NodeRenderer/utils';
import type { EdgeTypes, EdgeTypesWrapped, NodeTypes, NodeTypesWrapped } from '../../types';
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: NodeTypes, createTypes: CreateNodeTypes): NodeTypesWrapped;
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: EdgeTypes, createTypes: CreateEdgeTypes): EdgeTypesWrapped;

View File

@@ -1,7 +1,7 @@
import type { ReactNode } from 'react';
import type { ReactFlowState } from '@reactflow/system';
import { useStore } from '../../hooks/useStore';
import type { ReactFlowState } from '../../types';
const selector = (s: ReactFlowState) => `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]})`;

View File

@@ -1,17 +1,17 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef } from 'react';
import { zoom, zoomIdentity } from 'd3-zoom';
import type { D3ZoomEvent } from 'd3-zoom';
import { zoom, zoomIdentity, type D3ZoomEvent } from 'd3-zoom';
import { select, pointer } from 'd3-selection';
import { shallow } from 'zustand/shallow';
import { clamp } from '@reactflow/utils';
import { type Viewport, type ReactFlowState, CoordinateExtent, PanOnScrollMode } from '@reactflow/system';
import { CoordinateExtent, PanOnScrollMode, type Viewport } from '@reactflow/system';
import useKeyPress from '../../hooks/useKeyPress';
import useResizeHandler from '../../hooks/useResizeHandler';
import { useStore, useStoreApi } from '../../hooks/useStore';
import { containerStyle } from '../../styles';
import type { FlowRendererProps } from '../FlowRenderer';
import type { ReactFlowState } from '../../types';
type ZoomPaneProps = Omit<
FlowRendererProps,

View File

@@ -1,14 +1,14 @@
import { useEffect, useRef, useState } from 'react';
import type { RefObject, MouseEvent } from 'react';
import { useEffect, useRef, useState, type RefObject, type MouseEvent } from 'react';
import { drag } from 'd3-drag';
import { select } from 'd3-selection';
import { calcAutoPan, getEventPosition } from '@reactflow/utils';
import type { NodeDragItem, Node, SelectionDragHandler, UseDragEvent, XYPosition } from '@reactflow/system';
import type { NodeDragItem, UseDragEvent, XYPosition } from '@reactflow/system';
import { useStoreApi } from '../../hooks/useStore';
import { getDragItems, getEventHandlerParams, hasSelector, calcNextPosition } from './utils';
import { handleNodeClick } from '../../components/Nodes/utils';
import useGetPointerPosition from '../useGetPointerPosition';
import type { Node, SelectionDragHandler } from '../../types';
export type UseDragData = { dx: number; dy: number };

View File

@@ -2,15 +2,15 @@ import type { RefObject } from 'react';
import {
errorMessages,
type CoordinateExtent,
type Node,
type NodeDragItem,
type NodeInternals,
type NodeOrigin,
type OnError,
type XYPosition,
} from '@reactflow/system';
import { clampPosition, isNumeric, getNodePositionWithOrigin } from '@reactflow/utils';
import type { Node, NodeInternals } from '../../types';
export function isParentSelected(node: Node, nodeInternals: NodeInternals): boolean {
if (!node.parentNode) {
return false;

View File

@@ -1,6 +1,5 @@
import type { Edge, ReactFlowState } from '@reactflow/system';
import { useStore } from '../hooks/useStore';
import type { Edge, ReactFlowState } from '../types';
const edgesSelector = (state: ReactFlowState) => state.edges;

View File

@@ -1,5 +1,6 @@
import { useStore } from '../hooks/useStore';
import type { Node, ReactFlowState } from '@reactflow/system';
import type { Node, ReactFlowState } from '../types';
const nodesSelector = (state: ReactFlowState) => state.getNodes();

View File

@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useCallback, type SetStateAction, type Dispatch } from 'react';
import type { Node, NodeChange, Edge, EdgeChange } from '@reactflow/system';
import { applyNodeChanges, applyEdgeChanges } from '../utils/changes';
import type { Node, NodeChange, Edge, EdgeChange } from '../types';
type ApplyChanges<ItemType, ChangesType> = (changes: ChangesType[], items: ItemType[]) => ItemType[];
type OnChange<ChangesType> = (changes: ChangesType[]) => void;

View File

@@ -1,6 +1,7 @@
import { internalsSymbol, type ReactFlowState } from '@reactflow/system';
import { internalsSymbol } from '@reactflow/system';
import { useStore } from './useStore';
import type { ReactFlowState } from '../types';
const selector = (s: ReactFlowState) => {
if (s.nodeInternals.size === 0) {

View File

@@ -1,7 +1,7 @@
import { useEffect, useRef } from 'react';
import type { OnInit } from '@reactflow/system';
import useReactFlow from './useReactFlow';
import type { OnInit } from '../types';
function useOnInitHandler(onInit: OnInit | undefined) {
const rfInstance = useReactFlow();

View File

@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import type { OnSelectionChangeFunc } from '@reactflow/system';
import { useStoreApi } from './useStore';
import type { OnSelectionChangeFunc } from '../types';
export type UseOnSelectionChangeOptions = {
onChange?: OnSelectionChangeFunc;

View File

@@ -1,5 +1,10 @@
import { useCallback, useMemo } from 'react';
import { getConnectedEdges, getOverlappingArea, isRectObject, nodeToRect } from '@reactflow/utils';
import { getOverlappingArea, isRectObject, nodeToRect } from '@reactflow/utils';
import type { Rect } from '@reactflow/system';
import useViewportHelper from './useViewportHelper';
import { useStoreApi } from '../hooks/useStore';
import { getConnectedEdges } from '../utils';
import type {
ReactFlowInstance,
Instance,
@@ -11,11 +16,7 @@ import type {
EdgeRemoveChange,
NodeChange,
Node,
Rect,
} from '@reactflow/system';
import useViewportHelper from './useViewportHelper';
import { useStoreApi } from '../hooks/useStore';
} from '../types';
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export default function useReactFlow<NodeData = any, EdgeData = any>(): ReactFlowInstance<NodeData, EdgeData> {

View File

@@ -1,8 +1,9 @@
import { useContext, useMemo } from 'react';
import { useStore as useZustandStore, type StoreApi } from 'zustand';
import { errorMessages, type ReactFlowState } from '@reactflow/system';
import { errorMessages } from '@reactflow/system';
import StoreContext from '../contexts/RFStoreContext';
import type { ReactFlowState } from '../types';
const zustandErrorMessage = errorMessages['001']();

View File

@@ -1,7 +1,8 @@
import { shallow } from 'zustand/shallow';
import type { Viewport, ReactFlowState } from '@reactflow/system';
import type { Viewport } from '@reactflow/system';
import { useStore } from '../hooks/useStore';
import type { ReactFlowState } from '../types';
const viewportSelector = (state: ReactFlowState) => ({
x: state.transform[0],

View File

@@ -2,9 +2,10 @@ import { useMemo } from 'react';
import { zoomIdentity } from 'd3-zoom';
import { shallow } from 'zustand/shallow';
import { pointToRendererPoint, getTransformForBounds, getD3Transition, fitView } from '@reactflow/utils';
import type { ViewportHelperFunctions, ReactFlowState, XYPosition } from '@reactflow/system';
import type { XYPosition } from '@reactflow/system';
import { useStoreApi, useStore } from '../hooks/useStore';
import type { ViewportHelperFunctions, ReactFlowState } from '../types';
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};

View File

@@ -1,9 +1,10 @@
import { useCallback } from 'react';
import { internalsSymbol, type ReactFlowState, type NodeInternals, type Edge } from '@reactflow/system';
import { internalsSymbol } from '@reactflow/system';
import { isNumeric } from '@reactflow/utils';
import { useStore } from '../hooks/useStore';
import { isEdgeVisible } from '../container/EdgeRenderer/utils';
import { type ReactFlowState, type NodeInternals, type Edge } from '../types';
const defaultEdgeTree = [{ level: 0, isMaxLevel: true, edges: [] }];

View File

@@ -1,15 +1,15 @@
import { useCallback } from 'react';
import { getNodesInside } from '@reactflow/utils';
import type { ReactFlowState } from '@reactflow/system';
import { useStore } from '../hooks/useStore';
import type { Node, ReactFlowState } from '../types';
function useVisibleNodes(onlyRenderVisible: boolean) {
const nodes = useStore(
useCallback(
(s: ReactFlowState) =>
onlyRenderVisible
? getNodesInside(s.nodeInternals, { x: 0, y: 0, width: s.width, height: s.height }, s.transform, true)
? getNodesInside<Node>(s.getNodes(), { x: 0, y: 0, width: s.width, height: s.height }, s.transform, true)
: s.getNodes(),
[onlyRenderVisible]
)

View File

@@ -8,22 +8,6 @@ export { default as SimpleBezierEdge, getSimpleBezierPath } from './components/E
export { default as SmoothStepEdge } from './components/Edges/SmoothStepEdge';
export { default as BaseEdge } from './components/Edges/BaseEdge';
export {
isNode,
isEdge,
addEdge,
getOutgoers,
getIncomers,
getConnectedEdges,
updateEdge,
getTransformForBounds,
getRectOfNodes,
getNodePositionWithOrigin,
rectToBox,
boxToRect,
getBoundsOfRects,
} from '@reactflow/utils';
export { applyNodeChanges, applyEdgeChanges } from './utils/changes';
export { default as ReactFlowProvider } from './components/ReactFlowProvider';
export { default as Panel } from './components/Panel';
export { default as EdgeLabelRenderer } from './components/EdgeLabelRenderer';
@@ -41,7 +25,18 @@ export { default as useOnSelectionChange } from './hooks/useOnSelectionChange';
export { default as useNodesInitialized } from './hooks/useNodesInitialized';
export { default as useGetPointerPosition } from './hooks/useGetPointerPosition';
export { useNodeId } from './contexts/NodeIdContext';
export * from '@reactflow/system';
export * from '@reactflow/edge-utils';
export * from '@reactflow/system';
export {
getTransformForBounds,
getRectOfNodes,
getNodePositionWithOrigin,
rectToBox,
boxToRect,
getBoundsOfRects,
} from '@reactflow/utils';
// export * from './types';
export { applyNodeChanges, applyEdgeChanges } from './utils/changes';
export { isNode, isEdge, getIncomers, getOutgoers, addEdge, updateEdge, getConnectedEdges } from './utils/general';
export * from './types';

View File

@@ -3,18 +3,9 @@ import { zoomIdentity } from 'd3-zoom';
import { clampPosition, getDimensions, fitView } from '@reactflow/utils';
import {
internalsSymbol,
type ReactFlowState,
type Node,
type Edge,
type NodeDimensionUpdate,
type CoordinateExtent,
type NodeDimensionChange,
type EdgeSelectionChange,
type NodeSelectionChange,
type NodePositionChange,
type NodeDragItem,
type UnselectNodesAndEdgesParams,
type NodeChange,
type XYPosition,
} from '@reactflow/system';
@@ -22,6 +13,17 @@ import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '..
import { getHandleBounds } from '../components/Nodes/utils';
import { createNodeInternals, updateAbsoluteNodePositions, updateNodesAndEdgesSelections } from './utils';
import initialState from './initialState';
import type {
ReactFlowState,
Node,
Edge,
NodeDimensionChange,
EdgeSelectionChange,
NodeSelectionChange,
NodePositionChange,
UnselectNodesAndEdgesParams,
NodeChange,
} from '../types';
const createRFStore = () =>
createStore<ReactFlowState>((set, get) => ({

View File

@@ -1,10 +1,7 @@
import { devWarn } from '@reactflow/utils';
import { ConnectionMode, type CoordinateExtent, type ReactFlowStore } from '@reactflow/system';
import { devWarn, infiniteExtent } from '@reactflow/utils';
import { ConnectionMode } from '@reactflow/system';
export const infiniteExtent: CoordinateExtent = [
[Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY],
[Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY],
];
import type { ReactFlowStore } from '../types';
const initialState: ReactFlowStore = {
rfId: '1',

View File

@@ -1,17 +1,9 @@
import type { StoreApi } from 'zustand';
import {
internalsSymbol,
type Edge,
type EdgeSelectionChange,
type Node,
type NodeInternals,
type NodeSelectionChange,
type ReactFlowState,
type XYZPosition,
type NodeOrigin,
} from '@reactflow/system';
import { internalsSymbol, type XYZPosition, type NodeOrigin } from '@reactflow/system';
import { isNumeric, getNodePositionWithOrigin } from '@reactflow/utils';
import type { Edge, EdgeSelectionChange, Node, NodeInternals, NodeSelectionChange, ReactFlowState } from '../types';
type ParentNodes = Record<string, boolean>;
function calculateXYZPosition(

View File

@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { XYPosition, Dimensions } from './utils';
import type { Node } from './nodes';
import type { Edge } from './edges';
import type { XYPosition, Dimensions } from '@reactflow/system';
import type { Node, Edge } from '.';
export type NodeDimensionChange = {
id: string;

View File

@@ -1,4 +1,22 @@
import type { CSSProperties, HTMLAttributes, MouseEvent as ReactMouseEvent, WheelEvent } from 'react';
import type {
ConnectionMode,
ConnectionLineType,
OnConnect,
CoordinateExtent,
KeyCode,
PanOnScrollMode,
ProOptions,
PanelPosition,
OnMove,
OnMoveStart,
OnMoveEnd,
Viewport,
NodeOrigin,
HandleType,
SelectionMode,
OnError,
} from '@reactflow/system';
import type {
OnSelectionChangeFunc,
@@ -6,37 +24,21 @@ import type {
EdgeTypes,
Node,
Edge,
ConnectionMode,
ConnectionLineType,
ConnectionLineComponent,
OnConnectStart,
OnConnectEnd,
OnConnect,
CoordinateExtent,
KeyCode,
PanOnScrollMode,
OnEdgeUpdateFunc,
OnInit,
ProOptions,
PanelPosition,
DefaultEdgeOptions,
FitViewOptions,
OnNodesDelete,
OnEdgesDelete,
OnNodesChange,
OnEdgesChange,
OnMove,
OnMoveStart,
OnMoveEnd,
NodeDragHandler,
NodeMouseHandler,
SelectionDragHandler,
Viewport,
NodeOrigin,
EdgeMouseHandler,
HandleType,
SelectionMode,
OnError,
} from '.';
export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {

View File

@@ -0,0 +1,137 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { CSSProperties, HTMLAttributes, ReactNode, MouseEvent as ReactMouseEvent, ComponentType } from 'react';
import type {
BaseEdge,
BezierPathOptions,
Position,
SmoothStepPathOptions,
DefaultEdgeOptionsBase,
HandleType,
Connection,
ConnectionLineType,
HandleElement,
ConnectionStatus,
} from '@reactflow/system';
import { Node } from '.';
export type EdgeLabelOptions = {
label?: string | ReactNode;
labelStyle?: CSSProperties;
labelShowBg?: boolean;
labelBgStyle?: CSSProperties;
labelBgPadding?: [number, number];
labelBgBorderRadius?: number;
};
export type DefaultEdge<EdgeData = any> = BaseEdge<EdgeData> & {
style?: CSSProperties;
className?: string;
sourceNode?: Node;
targetNode?: Node;
} & EdgeLabelOptions;
type SmoothStepEdgeType<T> = DefaultEdge<T> & {
type: 'smoothstep';
pathOptions?: SmoothStepPathOptions;
};
type BezierEdgeType<T> = DefaultEdge<T> & {
type: 'default';
pathOptions?: BezierPathOptions;
};
export type Edge<T = any> = DefaultEdge<T> | SmoothStepEdgeType<T> | BezierEdgeType<T>;
export type EdgeMouseHandler = (event: ReactMouseEvent, edge: Edge) => void;
export type WrapEdgeProps<T = any> = Omit<Edge<T>, 'sourceHandle' | 'targetHandle'> & {
onClick?: EdgeMouseHandler;
onEdgeDoubleClick?: EdgeMouseHandler;
sourceHandleId?: string | null;
targetHandleId?: string | null;
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
sourcePosition: Position;
targetPosition: Position;
elementsSelectable?: boolean;
onEdgeUpdate?: OnEdgeUpdateFunc;
onContextMenu?: EdgeMouseHandler;
onMouseEnter?: EdgeMouseHandler;
onMouseMove?: EdgeMouseHandler;
onMouseLeave?: EdgeMouseHandler;
edgeUpdaterRadius?: number;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void;
rfId?: string;
isFocusable: boolean;
pathOptions?: BezierPathOptions | SmoothStepPathOptions;
};
export type DefaultEdgeOptions = DefaultEdgeOptionsBase<Edge>;
export type EdgeTextProps = HTMLAttributes<SVGElement> &
EdgeLabelOptions & {
x: number;
y: number;
};
// props that get passed to a custom edge
export type EdgeProps<T = any> = Pick<
Edge<T>,
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'
> &
Pick<
WrapEdgeProps,
| 'sourceX'
| 'sourceY'
| 'targetX'
| 'targetY'
| 'sourcePosition'
| 'targetPosition'
| 'sourceHandleId'
| 'targetHandleId'
| 'interactionWidth'
> &
EdgeLabelOptions & {
markerStart?: string;
markerEnd?: string;
// @TODO: how can we get better types for pathOptions?
pathOptions?: any;
};
export type BaseEdgeProps = Pick<EdgeProps, 'style' | 'markerStart' | 'markerEnd' | 'interactionWidth'> &
EdgeLabelOptions & {
labelX?: number;
labelY?: number;
path: string;
};
export type SmoothStepEdgeProps<T = any> = EdgeProps<T> & {
pathOptions?: SmoothStepPathOptions;
};
export type BezierEdgeProps<T = any> = EdgeProps<T> & {
pathOptions?: BezierPathOptions;
};
export type OnEdgeUpdateFunc<T = any> = (oldEdge: Edge<T>, newConnection: Connection) => void;
export type ConnectionLineComponentProps = {
connectionLineStyle?: CSSProperties;
connectionLineType: ConnectionLineType;
fromNode?: Node;
fromHandle?: HandleElement;
fromX: number;
fromY: number;
toX: number;
toY: number;
fromPosition: Position;
toPosition: Position;
connectionStatus: ConnectionStatus | null;
};
export type ConnectionLineComponent = ComponentType<ConnectionLineComponentProps>;

View File

@@ -0,0 +1,68 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type {
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
ComponentType,
MemoExoticComponent,
} from 'react';
import {
FitViewParamsBase,
FitViewOptionsBase,
NodeProps,
OnConnectStartParams,
ZoomInOut,
ZoomTo,
SetViewport,
GetZoom,
GetViewport,
SetCenter,
FitBounds,
Project,
} from '@reactflow/system';
import type { NodeChange, EdgeChange, Node, WrapNodeProps, Edge, EdgeProps, WrapEdgeProps, ReactFlowInstance } from '.';
export type OnNodesChange = (changes: NodeChange[]) => void;
export type OnEdgesChange = (changes: EdgeChange[]) => void;
export type OnNodesDelete = (nodes: Node[]) => void;
export type OnEdgesDelete = (edges: Edge[]) => void;
export type NodeTypes = { [key: string]: ComponentType<NodeProps> };
export type NodeTypesWrapped = { [key: string]: MemoExoticComponent<ComponentType<WrapNodeProps>> };
export type EdgeTypes = { [key: string]: ComponentType<EdgeProps> };
export type EdgeTypesWrapped = { [key: string]: MemoExoticComponent<ComponentType<WrapEdgeProps>> };
export type UnselectNodesAndEdgesParams = {
nodes?: Node[];
edges?: Edge[];
};
export type OnSelectionChangeParams = {
nodes: Node[];
edges: Edge[];
};
export type OnSelectionChangeFunc = (params: OnSelectionChangeParams) => void;
export type OnConnectStart = (event: ReactMouseEvent | ReactTouchEvent, params: OnConnectStartParams) => void;
export type OnConnectEnd = (event: MouseEvent | TouchEvent) => void;
export type FitViewParams = FitViewParamsBase<Node>;
export type FitViewOptions = FitViewOptionsBase<Node>;
export type FitView = (fitViewOptions?: FitViewOptions) => boolean;
export type OnInit<NodeData = any, EdgeData = any> = (reactFlowInstance: ReactFlowInstance<NodeData, EdgeData>) => void;
export type ViewportHelperFunctions = {
zoomIn: ZoomInOut;
zoomOut: ZoomInOut;
zoomTo: ZoomTo;
getZoom: GetZoom;
setViewport: SetViewport;
getViewport: GetViewport;
fitView: FitView;
setCenter: SetCenter;
fitBounds: FitBounds;
project: Project;
viewportInitialized: boolean;
};

View File

@@ -0,0 +1,7 @@
export * from './nodes';
export * from './edges';
export * from './changes';
export * from './component-props';
export * from './general';
export * from './store';
export * from './instance';

View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-namespace */
import { ViewportHelperFunctions, Viewport, Node, Edge, Rect } from '.';
import type { Rect, Viewport } from '@reactflow/system';
import type { Node, Edge, ViewportHelperFunctions } from '.';
export type ReactFlowJsonObject<NodeData = any, EdgeData = any> = {
nodes: Node<NodeData>[];
@@ -12,6 +13,7 @@ export type DeleteElementsOptions = {
nodes?: (Partial<Node> & { id: Node['id'] })[];
edges?: (Partial<Edge> & { id: Edge['id'] })[];
};
export namespace Instance {
export type GetNodes<NodeData> = () => Node<NodeData>[];
export type SetNodes<NodeData> = (

View File

@@ -0,0 +1,46 @@
import type { CSSProperties, MouseEvent as ReactMouseEvent } from 'react';
import type { BaseNode } from '@reactflow/system';
export type Node<NodeData = any, NodeType extends string | undefined = string | undefined> = BaseNode<
NodeData,
NodeType
> & {
style?: CSSProperties;
className?: string;
resizing?: boolean;
};
export type NodeMouseHandler = (event: ReactMouseEvent, node: Node) => void;
export type NodeDragHandler = (event: ReactMouseEvent, node: Node, nodes: Node[]) => void;
export type SelectionDragHandler = (event: ReactMouseEvent, nodes: Node[]) => void;
export type WrapNodeProps<NodeData = any> = Pick<
Node<NodeData>,
'id' | 'data' | 'style' | 'className' | 'dragHandle' | 'sourcePosition' | 'targetPosition' | 'hidden' | 'ariaLabel'
> &
Required<Pick<Node<NodeData>, 'selected' | 'type' | 'zIndex'>> & {
isConnectable: boolean;
xPos: number;
yPos: number;
xPosOrigin: number;
yPosOrigin: number;
initialized: boolean;
isSelectable: boolean;
isDraggable: boolean;
isFocusable: boolean;
selectNodesOnDrag: boolean;
onClick?: NodeMouseHandler;
onDoubleClick?: NodeMouseHandler;
onMouseEnter?: NodeMouseHandler;
onMouseMove?: NodeMouseHandler;
onMouseLeave?: NodeMouseHandler;
onContextMenu?: NodeMouseHandler;
resizeObserver: ResizeObserver | null;
isParent: boolean;
noDragClassName: string;
noPanClassName: string;
rfId: string;
disableKeyboardA11y: boolean;
};
export type NodeInternals = Map<string, Node>;

View File

@@ -0,0 +1,149 @@
import {
ConnectionMode,
ConnectionStatus,
CoordinateExtent,
D3SelectionInstance,
D3ZoomInstance,
HandleType,
NodeDimensionUpdate,
NodeDragItem,
NodeOrigin,
OnConnect,
OnError,
OnViewportChange,
SelectionRect,
SnapGrid,
StartHandle,
Transform,
XYPosition,
} from '@reactflow/system';
import type {
NodeDragHandler,
Edge,
Node,
NodeChange,
OnNodesChange,
OnEdgesChange,
NodeInternals,
OnConnectStart,
OnConnectEnd,
SelectionDragHandler,
DefaultEdgeOptions,
FitViewOptions,
OnNodesDelete,
OnEdgesDelete,
OnSelectionChangeFunc,
UnselectNodesAndEdgesParams,
} from '.';
export type ReactFlowStore = {
rfId: string;
width: number;
height: number;
transform: Transform;
nodeInternals: NodeInternals;
edges: Edge[];
onNodesChange: OnNodesChange | null;
onEdgesChange: OnEdgesChange | null;
hasDefaultNodes: boolean;
hasDefaultEdges: boolean;
domNode: HTMLDivElement | null;
paneDragging: boolean;
noPanClassName: string;
d3Zoom: D3ZoomInstance | null;
d3Selection: D3SelectionInstance | null;
d3ZoomHandler: ((this: Element, event: any, d: unknown) => void) | undefined;
minZoom: number;
maxZoom: number;
translateExtent: CoordinateExtent;
nodeExtent: CoordinateExtent;
nodeOrigin: NodeOrigin;
nodesSelectionActive: boolean;
userSelectionActive: boolean;
userSelectionRect: SelectionRect | null;
connectionNodeId: string | null;
connectionHandleId: string | null;
connectionHandleType: HandleType | null;
connectionPosition: XYPosition;
connectionStatus: ConnectionStatus | null;
connectionMode: ConnectionMode;
snapToGrid: boolean;
snapGrid: SnapGrid;
nodesDraggable: boolean;
nodesConnectable: boolean;
nodesFocusable: boolean;
edgesFocusable: boolean;
elementsSelectable: boolean;
elevateNodesOnSelect: boolean;
multiSelectionActive: boolean;
connectionStartHandle: StartHandle | null;
onNodeDragStart?: NodeDragHandler;
onNodeDrag?: NodeDragHandler;
onNodeDragStop?: NodeDragHandler;
onSelectionDragStart?: SelectionDragHandler;
onSelectionDrag?: SelectionDragHandler;
onSelectionDragStop?: SelectionDragHandler;
onConnect?: OnConnect;
onConnectStart?: OnConnectStart;
onConnectEnd?: OnConnectEnd;
onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd;
connectOnClick: boolean;
defaultEdgeOptions?: DefaultEdgeOptions;
fitViewOnInit: boolean;
fitViewOnInitDone: boolean;
fitViewOnInitOptions: FitViewOptions | undefined;
onNodesDelete?: OnNodesDelete;
onEdgesDelete?: OnEdgesDelete;
onError?: OnError;
// event handlers
onViewportChangeStart?: OnViewportChange;
onViewportChange?: OnViewportChange;
onViewportChangeEnd?: OnViewportChange;
onSelectionChange?: OnSelectionChangeFunc;
ariaLiveMessage: string;
autoPanOnConnect: boolean;
autoPanOnNodeDrag: boolean;
connectionRadius: number;
};
export type ReactFlowActions = {
setNodes: (nodes: Node[]) => void;
getNodes: () => Node[];
setEdges: (edges: Edge[]) => void;
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void;
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void;
updateNodePositions: (nodeDragItems: NodeDragItem[] | Node[], positionChanged: boolean, dragging: boolean) => void;
resetSelectedElements: () => void;
unselectNodesAndEdges: (params?: UnselectNodesAndEdgesParams) => void;
addSelectedNodes: (nodeIds: string[]) => void;
addSelectedEdges: (edgeIds: string[]) => void;
setMinZoom: (minZoom: number) => void;
setMaxZoom: (maxZoom: number) => void;
setTranslateExtent: (translateExtent: CoordinateExtent) => void;
setNodeExtent: (nodeExtent: CoordinateExtent) => void;
cancelConnection: () => void;
reset: () => void;
triggerNodeChanges: (changes: NodeChange[]) => void;
panBy: (delta: XYPosition) => void;
};
export type ReactFlowState = ReactFlowStore & ReactFlowActions;

View File

@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Node, Edge, EdgeChange, NodeChange } from '@reactflow/system';
import type { Node, Edge, EdgeChange, NodeChange } from '../types';
function handleParentExpand(res: any[], updateItem: any) {
const parent = res.find((e) => e.id === updateItem.parentNode);

View File

@@ -0,0 +1,18 @@
import {
isNodeBase,
isEdgeBase,
addEdgeBase,
getOutgoersBase,
getIncomersBase,
updateEdgeBase,
getConnectedEdgesBase,
} from '@reactflow/utils';
import type { Edge, Node } from '../types';
export const isNode = isNodeBase<Node, Edge>;
export const isEdge = isEdgeBase<Node, Edge>;
export const getOutgoers = getOutgoersBase<Node, Edge>;
export const getIncomers = getIncomersBase<Node, Edge>;
export const addEdge = addEdgeBase<Edge>;
export const updateEdge = updateEdgeBase<Edge>;
export const getConnectedEdges = getConnectedEdgesBase<Node, Edge>;

View File

@@ -0,0 +1,2 @@
export * from './changes';
export * from './general';

View File

@@ -1,7 +1,7 @@
import { get, type Writable } from 'svelte/store';
import { drag as d3Drag, type D3DragEvent, type SubjectPosition } from 'd3-drag';
import { select } from 'd3-selection';
import type { XYPosition, CoordinateExtent, Transform, Node as RFNode } from '@reactflow/system';
import type { XYPosition, CoordinateExtent, Transform } from '@reactflow/system';
import { getDragItems, hasSelector, calcNextPosition } from './utils';
import type { Node } from '$lib/types';
@@ -62,7 +62,7 @@ export default function drag(
dragItems = dragItems.map((n) => {
const nextPosition = { x: x - n.distance.x, y: y - n.distance.y };
const updatedPos = calcNextPosition(n, nextPosition, get(nodes) as RFNode[]);
const updatedPos = calcNextPosition(n, nextPosition, get(nodes));
// we want to make sure that we only fire a change event when there is a changes
hasChange =
@@ -89,7 +89,7 @@ export default function drag(
const pointerPos = getPointerPosition(event);
console.log(pointerPos);
lastPos = pointerPos;
dragItems = getDragItems(get(nodes) as RFNode[], pointerPos, nodeId);
dragItems = getDragItems(get(nodes), pointerPos, nodeId);
})
.on('drag', (event: UseDragEvent) => {
const pointerPos = getPointerPosition(event);

View File

@@ -1,13 +1,7 @@
import type {
CoordinateExtent,
Node,
NodeDragItem,
NodeInternals,
NodeOrigin,
XYPosition
} from '@reactflow/system';
import type { CoordinateExtent, NodeDragItem, NodeOrigin, XYPosition } from '@reactflow/system';
import { clampPosition, isNumeric } from '@reactflow/utils';
import { clampPosition, isNumeric } from '../../../utils';
import type { Node } from '$lib/types';
export function isParentSelected(node: Node, nodes: Node[]): boolean {
if (!node.parentNode) {
@@ -122,31 +116,3 @@ export function calcNextPosition(
positionAbsolute
};
}
// returns two params:
// 1. the dragged node (or the first of the list, if we are dragging a node selection)
// 2. array of selected nodes (for multi selections)
export function getEventHandlerParams({
nodeId,
dragItems,
nodeInternals
}: {
nodeId?: string;
dragItems: NodeDragItem[];
nodeInternals: NodeInternals;
}): [Node, Node[]] {
const extentedDragItems: Node[] = dragItems.map((n) => {
const node = nodeInternals.get(n.id)!;
return {
...node,
position: n.position,
positionAbsolute: n.positionAbsolute
};
});
return [
nodeId ? extentedDragItems.find((n) => n.id === nodeId)! : extentedDragItems[0],
extentedDragItems
];
}

View File

@@ -1,8 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Writable } from 'svelte/store';
import { select } from 'd3-selection';
import { zoom as d3Zoom, zoomIdentity } from 'd3-zoom';
import type { D3ZoomEvent } from 'd3-zoom';
import { zoom as d3Zoom, zoomIdentity, type D3ZoomEvent } from 'd3-zoom';
import type { D3SelectionInstance, D3ZoomInstance, Transform } from '@reactflow/system';
const isWrappedWithClass = (event: any, className: string | undefined) =>

View File

@@ -1,3 +1,4 @@
import { get, type Writable } from 'svelte/store';
import {
getHostForElement,
calcAutoPan,
@@ -10,7 +11,6 @@ import type {
HandleType,
Connection,
ConnectionMode,
Node,
XYPosition,
Transform
} from '@reactflow/system';
@@ -25,8 +25,7 @@ import {
type ConnectionHandle,
type ValidConnectionFunc
} from './utils';
import { get, type Writable } from 'svelte/store';
import type { ConnectionData } from '$lib/types';
import type { ConnectionData, Node } from '$lib/types';
export function handlePointerDown({
event,

View File

@@ -9,9 +9,9 @@
type $$Props = HandleProps;
export let id: $$Props['id'] = undefined;
export let type: $$Props['type'] = 'source';
export let position: $$Props['position'] = Position.Top;
export let id: $$Props['id'] = undefined;
export let isConnectable: $$Props['isConnectable'] = true;
export let isValidConnection: $$Props['isValidConnection'] = (_: Connection) => true;
let className: string | null = null;

View File

@@ -1,7 +1,9 @@
import { internalsSymbol, ConnectionMode, type ConnectionStatus } from '@reactflow/system';
import type { Connection, HandleType, XYPosition, Node, NodeHandleBounds } from '@reactflow/system';
import type { Connection, HandleType, XYPosition, NodeHandleBounds } from '@reactflow/system';
import { getEventPosition } from '@reactflow/utils';
import type { Node } from '$lib/types';
export type ConnectionHandle = {
id: string | null;
type: HandleType;

View File

@@ -1,13 +1,13 @@
<script lang="ts">
import type { BaseEdgeProps } from '$lib/types';
import EdgeLabelRenderer from '$lib/components/EdgeLabelRenderer/index.svelte';
import type { BaseEdgeProps } from '$lib/types';
type $$Props = BaseEdgeProps;
export let path: $$Props['path'];
export let label: $$Props['label'];
export let labelX: $$Props['labelX'];
export let labelY: $$Props['labelY'];
export let path: $$Props['path'] = '';
export let label: $$Props['label'] = undefined;
export let labelX: $$Props['labelX'] = undefined;
export let labelY: $$Props['labelY'] = undefined;
export let interactionWidth: $$Props['interactionWidth'] = 20;
</script>

View File

@@ -4,9 +4,9 @@
import { useStore } from '$lib/store';
import BezierEdge from '$lib/components/edges/StraightEdge.svelte';
import type { EdgeProps, WrapEdgeProps } from '$lib/types';
import type { EdgeProps, EdgeLayouted } from '$lib/types';
type $$Props = WrapEdgeProps;
type $$Props = EdgeLayouted;
export let id: $$Props['id'];
export let type: $$Props['type'] = 'default';
@@ -16,6 +16,8 @@
export let sourceY: $$Props['sourceY'] = 0;
export let targetX: $$Props['targetX'] = 0;
export let targetY: $$Props['targetY'] = 0;
export let sourceHandleId: $$Props['sourceHandleId'] = undefined;
export let targetHandleId: $$Props['targetHandleId'] = undefined;
export let sourcePosition: $$Props['sourcePosition'] = Position.Bottom;
export let targetPosition: $$Props['targetPosition'] = Position.Top;
export let animated: $$Props['animated'] = false;

View File

@@ -30,8 +30,11 @@
<script lang="ts">
import { useStore } from '$lib/store';
import { SelectionMode, type Node, type Edge } from '@reactflow/system';
import { getConnectedEdges, getEventPosition, getNodesInside } from '@reactflow/utils';
import { SelectionMode } from '@reactflow/system';
import { getEventPosition, getNodesInside } from '@reactflow/utils';
import { getConnectedEdges} from '$lib/utils';
import type { Node, Edge } from '$lib/types';
const {
nodes,
@@ -107,8 +110,8 @@
height: Math.abs(mousePos.y - startY)
};
selectedNodes = getNodesInside(
new Map($nodes.map((node) => [node.id, node])),
selectedNodes = getNodesInside<Node>(
$nodes,
nextUserSelectRect,
$transform,
selectionMode === SelectionMode.Partial,

View File

@@ -1,5 +1,6 @@
<script lang="ts">
import { setContext, onMount } from 'svelte';
import { ConnectionLineType } from '@reactflow/system';
import cc from 'classcat';
import { key, createStore } from '$lib/store';
@@ -23,7 +24,7 @@
export let nodeTypes: $$Props['nodeTypes'] = undefined;
export let selectionKey: $$Props['selectionKey'] = undefined;
export let deleteKey: $$Props['deleteKey'] = undefined;
export let connectionLineType: $$Props['connectionLineType'] = undefined;
export let connectionLineType: $$Props['connectionLineType'] = ConnectionLineType.Bezier;
let className: $$Props['class'] = undefined;
export { className as class };
@@ -51,27 +52,6 @@
});
});
// $: {
// const updatableProps = {
// defaultEdgeOptions,
// connectionMode,
// snapToGrid,
// snapGrid,
// nodesDraggable,
// connectOnClick,
// fitViewOnInit: fitView,
// fitViewOnInitOptions: fitViewOptions,
// };
// Object.keys(updatableProps).forEach((key) => {
// store.update((state) => ({
// ...state,
// [key]: valuesToUpdate[key],
// }));
// });
// }
$: {
store.setNodes(nodes);
}

View File

@@ -3,6 +3,8 @@ export { Controls, ControlButton } from '$lib/plugins/Controls';
export { Background, BackgroundVariant } from '$lib/plugins/Background';
export { Minimap } from '$lib/plugins/Minimap';
export { default as Panel } from '$lib/container/Panel/index.svelte';
export * from '$lib/types';
export * from '$lib/utils';
export default SvelteFlow;

View File

@@ -1,8 +1,8 @@
import { derived } from 'svelte/store';
import { getBezierPath, getSmoothStepPath, getStraightPath } from '@reactflow/edge-utils';
import { ConnectionLineType, ConnectionMode, Position } from '@reactflow/system';
import { ConnectionLineType, ConnectionMode, Position, internalsSymbol } from '@reactflow/system';
import type { SvelteFlowStoreState } from './types';
import { derived } from 'svelte/store';
const oppositePosition = {
[Position.Left]: Position.Right,
@@ -20,21 +20,21 @@ export function getConnectionPath(store: SvelteFlowStoreState) {
store.nodes,
store.transform
],
([$connection, $connectionLineType, $connectionMode, $nodes, $transform]) => {
if (!$connection.nodeId) {
([connection, connectionLineType, connectionMode, nodes, transform]) => {
if (!connection.nodeId) {
return null;
}
const fromNode = $nodes.find((n) => n.id === $connection.nodeId);
const fromNode = nodes.find((n) => n.id === connection.nodeId);
const fromHandleBounds = fromNode?.[internalsSymbol]?.handleBounds;
const handleBoundsStrict = fromHandleBounds?.[$connection.handleType || 'source'] || [];
const handleBoundsStrict = fromHandleBounds?.[connection.handleType || 'source'] || [];
const handleBoundsLoose = handleBoundsStrict
? handleBoundsStrict
: fromHandleBounds?.[$connection.handleType === 'source' ? 'target' : 'source']!;
: fromHandleBounds?.[connection.handleType === 'source' ? 'target' : 'source']!;
const handleBounds =
$connectionMode === ConnectionMode.Strict ? handleBoundsStrict : handleBoundsLoose;
const fromHandle = $connection.handleId
? handleBounds.find((d) => d.id === $connection.handleId)
connectionMode === ConnectionMode.Strict ? handleBoundsStrict : handleBoundsLoose;
const fromHandle = connection.handleId
? handleBounds.find((d) => d.id === connection.handleId)
: handleBounds[0];
const fromHandleX = fromHandle
? fromHandle.x + fromHandle.width / 2
@@ -49,22 +49,22 @@ export function getConnectionPath(store: SvelteFlowStoreState) {
sourceX: fromX,
sourceY: fromY,
sourcePosition: fromPosition,
targetX: (($connection.position?.x ?? 0) - $transform[0]) / $transform[2],
targetY: (($connection.position?.y ?? 0) - $transform[1]) / $transform[2],
targetX: ((connection.position?.x ?? 0) - transform[0]) / transform[2],
targetY: ((connection.position?.y ?? 0) - transform[1]) / transform[2],
targetPosition: toPosition
};
let path = '';
if ($connectionLineType === ConnectionLineType.Bezier) {
if (connectionLineType === ConnectionLineType.Bezier) {
// we assume the destination position is opposite to the source position
[path] = getBezierPath(pathParams);
} else if ($connectionLineType === ConnectionLineType.Step) {
} else if (connectionLineType === ConnectionLineType.Step) {
[path] = getSmoothStepPath({
...pathParams,
borderRadius: 0
});
} else if ($connectionLineType === ConnectionLineType.SmoothStep) {
} else if (connectionLineType === ConnectionLineType.SmoothStep) {
[path] = getSmoothStepPath(pathParams);
} else {
[path] = getStraightPath(pathParams);

View File

@@ -2,7 +2,7 @@ import { derived } from 'svelte/store';
import { Position } from '@reactflow/system';
import { getEdgePositions, getHandle, getNodeData } from '$lib/container/EdgeRenderer/utils';
import type { WrapEdgeProps } from '$lib/types';
import type { EdgeLayouted } from '$lib/types';
import type { SvelteFlowStoreState } from './types';
export function getEdgesLayouted(store: SvelteFlowStoreState) {
@@ -56,6 +56,6 @@ export function getEdgesLayouted(store: SvelteFlowStoreState) {
targetHandleId
};
})
.filter((e) => e !== null) as WrapEdgeProps[];
.filter((e) => e !== null) as EdgeLayouted[];
});
}

View File

@@ -1,5 +1,6 @@
import { getContext } from 'svelte';
import { get } from 'svelte/store';
import { zoomIdentity } from 'd3-zoom';
import {
type Transform,
type NodeDragItem,
@@ -7,23 +8,14 @@ import {
internalsSymbol,
type NodeOrigin,
type ViewportHelperFunctionOptions,
type Node as RFNode,
type Connection,
type XYPosition,
type CoordinateExtent
} from '@reactflow/system';
import {
fitView as fitViewUtil,
getConnectedEdges,
getD3Transition,
getDimensions,
addEdge as addEdgeUtil
} from '@reactflow/utils';
import { zoomIdentity } from 'd3-zoom';
import { fitView as fitViewUtil, getD3Transition, getDimensions } from '@reactflow/utils';
import { getHandleBounds } from '../../utils';
import { getHandleBounds, getConnectedEdges, addEdge as addEdgeUtil } from '$lib/utils';
import type { EdgeTypes, NodeTypes, Node, Edge, ConnectionData } from '$lib/types';
import { getEdgesLayouted } from './edges-layouted';
import { getConnectionPath } from './connection-path';
import { initConnectionData, initialStoreState } from './initial-store';
@@ -170,7 +162,7 @@ export function createStore({
return fitViewUtil(
{
nodes: get(store.nodes) as RFNode[],
nodes: get(store.nodes),
width: get(store.width),
height: get(store.height),
minZoom: 0.2,
@@ -227,7 +219,7 @@ export function createStore({
const initialHitEdges = deletableEdges.filter((e) => edgeIds.includes(e.id));
if (nodesToRemove || initialHitEdges) {
const connectedEdges = getConnectedEdges(nodesToRemove as RFNode[], deletableEdges);
const connectedEdges = getConnectedEdges(nodesToRemove, deletableEdges);
const edgesToRemove = [...initialHitEdges, ...connectedEdges];
const edgeIdsToRemove = edgesToRemove.reduce<string[]>((res, edge) => {
if (!res.includes(edge.id)) {

View File

@@ -5,15 +5,15 @@ import {
type D3SelectionInstance,
ConnectionMode,
ConnectionLineType,
type SelectionRect,
type Transform,
type NodeOrigin,
type Rect
type NodeOrigin
} from '@reactflow/system';
import DefaultNode from '$lib/components/nodes/DefaultNode.svelte';
import InputNode from '$lib/components/nodes/InputNode.svelte';
import OutputNode from '$lib/components/nodes/OutputNode.svelte';
import type { Node, Edge, ConnectionData, NodeTypes, EdgeTypes } from '$lib/types';
import type { Node, Edge, ConnectionData, NodeTypes, EdgeTypes, EdgeLayouted } from '$lib/types';
import BezierEdge from '$lib/components/edges/BezierEdge.svelte';
import StraightEdge from '$lib/components/edges/StraightEdge.svelte';
import SmoothStepEdge from '$lib/components/edges/SmoothStepEdge.svelte';
@@ -29,7 +29,7 @@ export const initConnectionData = {
export const initialStoreState = {
nodes: writable<Node[]>([]),
edges: writable<Edge[]>([]),
edgesLayouted: readable<Edge[]>([]),
edgesLayouted: readable<EdgeLayouted[]>([]),
height: writable<number>(500),
width: writable<number>(500),
nodeOrigin: writable<NodeOrigin>([0.5, 0.5]),
@@ -39,7 +39,7 @@ export const initialStoreState = {
}),
id: writable<string | null>(null),
dragging: writable<boolean>(false),
selectionRect: writable<(Rect & { startX: number; startY: number }) | null>(null),
selectionRect: writable<SelectionRect | null>(null),
selectionKeyPressed: writable<boolean>(false),
multiselectionKeyPressed: writable<boolean>(false),
deleteKeyPressed: writable<boolean>(false),

View File

@@ -6,7 +6,7 @@ import type {
NodeDragItem
} from '@reactflow/system';
import { initialStoreState } from './initial-store';
import type { initialStoreState } from './initial-store';
import type { Node, Edge, ConnectionData } from '$lib/types';
export type SvelteFlowStoreActions = {

View File

@@ -1,4 +1,66 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { SvelteComponentTyped } from 'svelte';
import type { EdgeProps } from '$lib/types';
import type {
BaseEdge,
BezierPathOptions,
Position,
SmoothStepPathOptions
} from '@reactflow/system';
import type { Node } from '$lib/types';
export type DefaultEdge<EdgeData = any> = BaseEdge<EdgeData> & {
label?: string;
style?: string;
class?: string;
sourceNode?: Node;
targetNode?: Node;
};
type SmoothStepEdgeType<T> = DefaultEdge<T> & {
type: 'smoothstep';
pathOptions?: SmoothStepPathOptions;
};
type BezierEdgeType<T> = DefaultEdge<T> & {
type: 'default';
pathOptions?: BezierPathOptions;
};
export type Edge<T = any> = DefaultEdge<T> | SmoothStepEdgeType<T> | BezierEdgeType<T>;
export type EdgeLayouted = Omit<Edge, 'sourceHandle' | 'targetHandle'> & {
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
sourcePosition: Position;
targetPosition: Position;
sourceHandleId?: string;
targetHandleId?: string;
};
export type EdgeProps = Pick<
EdgeLayouted,
| 'id'
| 'source'
| 'target'
| 'sourceX'
| 'sourceY'
| 'targetX'
| 'targetY'
| 'sourcePosition'
| 'targetPosition'
| 'animated'
| 'selected'
| 'label'
| 'interactionWidth'
>;
export type BaseEdgeProps = Pick<EdgeProps, 'interactionWidth' | 'label'> & {
path: string;
labelX?: number;
labelY?: number;
};
export type EdgeTypes = Record<string, typeof SvelteComponentTyped<EdgeProps>>;

View File

@@ -1,6 +1,7 @@
import type { Node, NodeTypes } from './nodes';
import type { ShortcutModifierDefinition } from '@svelte-put/shortcut';
import type { ConnectionLineType, Edge, HandleType, XYPosition } from '@reactflow/system';
import type { ConnectionLineType, HandleType, XYPosition } from '@reactflow/system';
import type { Node, NodeTypes, Edge } from '.';
export type KeyModifier = ShortcutModifierDefinition;
export type KeyDefinitionObject = { key: string; modifier?: KeyModifier };

View File

@@ -1,12 +1,3 @@
export type {
Position,
XYPosition,
Edge,
BaseEdgeProps,
WrapEdgeProps,
EdgeProps
} from '@reactflow/system';
export * from './nodes';
export * from './edges';
export * from './general';

View File

@@ -1,33 +1,17 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { SvelteComponentTyped } from 'svelte';
import type { internalsSymbol, NodeHandleBounds, Position, XYPosition } from '@reactflow/system';
import type { BaseNode } from '@reactflow/system';
// @todo: currently the helper function only like Node from '@reactflow/core'
// we need a base node type or helpes that accept Node like types
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Node<NodeData = any> = {
id: string;
type: string;
data: NodeData;
position: XYPosition;
sourcePosition?: Position;
targetPosition?: Position;
positionAbsolute?: XYPosition;
width?: number;
height?: number;
selected?: boolean;
export type Node<
NodeData = any,
NodeType extends string | undefined = string | undefined
> = BaseNode<NodeData, NodeType> & {
class?: string;
style?: string;
deletable?: boolean;
// not supported yet
parentNode?: string;
// only used internally
[internalsSymbol]?: {
z?: number;
handleBounds?: NodeHandleBounds;
isParent?: boolean;
};
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any

View File

@@ -0,0 +1,47 @@
import type { HandleElement, Position } from '@reactflow/system';
import {
isNodeBase,
isEdgeBase,
addEdgeBase,
getOutgoersBase,
getIncomersBase,
updateEdgeBase,
getConnectedEdgesBase,
getDimensions
} from '@reactflow/utils';
import type { Edge, Node } from '$lib/types';
export const isNode = isNodeBase<Node, Edge>;
export const isEdge = isEdgeBase<Node, Edge>;
export const getOutgoers = getOutgoersBase<Node, Edge>;
export const getIncomers = getIncomersBase<Node, Edge>;
export const addEdge = addEdgeBase<Edge>;
export const updateEdge = updateEdgeBase<Edge>;
export const getConnectedEdges = getConnectedEdgesBase<Node, Edge>;
export const getHandleBounds = (
selector: string,
nodeElement: HTMLDivElement,
zoom: number
): HandleElement[] | null => {
const handles = nodeElement.querySelectorAll(selector);
if (!handles || !handles.length) {
return null;
}
const handlesArray = Array.from(handles) as HTMLDivElement[];
const nodeBounds = nodeElement.getBoundingClientRect();
return handlesArray.map((handle): HandleElement => {
const handleBounds = handle.getBoundingClientRect();
return {
id: handle.getAttribute('data-handleid'),
position: handle.getAttribute('data-handlepos') as unknown as Position,
x: (handleBounds.left - nodeBounds.left) / zoom,
y: (handleBounds.top - nodeBounds.top) / zoom,
...getDimensions(handle)
};
});
};

View File

@@ -1,97 +0,0 @@
import {
type CoordinateExtent,
type Dimensions,
type XYPosition,
type Node,
type XYZPosition,
type HandleElement,
internalsSymbol,
Position
} from '@reactflow/system';
export const clamp = (val: number, min = 0, max = 1): number => Math.min(Math.max(val, min), max);
export const clampPosition = (position: XYPosition = { x: 0, y: 0 }, extent: CoordinateExtent) => ({
x: clamp(position.x, extent[0][0], extent[1][0]),
y: clamp(position.y, extent[0][1], extent[1][1])
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isNumeric = (n: any): n is number => !isNaN(n) && isFinite(n);
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
width: node.offsetWidth,
height: node.offsetHeight
});
type ParentNodes = Record<string, boolean>;
function calculateXYZPosition(node: Node, nodes: Node[], result: XYZPosition): XYZPosition {
if (!node.parentNode) {
return result;
}
const parentNode = nodes.find((n) => n.id === node.parentNode)!;
const parentNodePosition = parentNode.positionAbsolute!;
return calculateXYZPosition(parentNode, nodes, {
x: (result.x ?? 0) + parentNodePosition.x,
y: (result.y ?? 0) + parentNodePosition.y,
z:
(parentNode[internalsSymbol]?.z ?? 0) > (result.z ?? 0)
? parentNode[internalsSymbol]?.z ?? 0
: result.z ?? 0
});
}
export function updateAbsoluteNodePositions(nodes: Node[], parentNodes?: ParentNodes) {
nodes.forEach((node) => {
if (node.parentNode) {
throw new Error(`Parent node ${node.parentNode} not found`);
}
if (node.parentNode || parentNodes?.[node.id]) {
const { x, y, z } = calculateXYZPosition(node, nodes, {
...node.position,
z: node[internalsSymbol]?.z ?? 0
});
node.positionAbsolute = {
x,
y
};
node[internalsSymbol]!.z = z;
if (parentNodes?.[node.id]) {
node[internalsSymbol]!.isParent = true;
}
}
});
}
export const getHandleBounds = (
selector: string,
nodeElement: HTMLDivElement,
zoom: number
): HandleElement[] | null => {
const handles = nodeElement.querySelectorAll(selector);
if (!handles || !handles.length) {
return null;
}
const handlesArray = Array.from(handles) as HTMLDivElement[];
const nodeBounds = nodeElement.getBoundingClientRect();
return handlesArray.map((handle): HandleElement => {
const handleBounds = handle.getBoundingClientRect();
return {
id: handle.getAttribute('data-handleid'),
position: handle.getAttribute('data-handlepos') as unknown as Position,
x: (handleBounds.left - nodeBounds.left) / zoom,
y: (handleBounds.top - nodeBounds.top) / zoom,
...getDimensions(handle)
};
});
};

View File

@@ -4,11 +4,13 @@
"description": "Core system of React Flow.",
"keywords": [
"react",
"svelte",
"node-based UI",
"graph",
"diagram",
"workflow",
"react-flow"
"react-flow",
"svelte-flow"
],
"files": [
"dist"
@@ -41,18 +43,11 @@
"@types/d3-selection": "^3.0.3",
"@types/d3-zoom": "^3.0.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
},
"devDependencies": {
"@reactflow/eslint-config": "workspace:*",
"@reactflow/rollup-config": "workspace:*",
"@reactflow/tsconfig": "workspace:*",
"@types/node": "^18.7.16",
"@types/react": ">=17",
"@types/react-dom": ">=17",
"react": "^18.2.0",
"typescript": "^4.9.4"
},
"rollup": {

View File

@@ -1,4 +1,4 @@
import { Edge, HandleElement } from './types';
import { BaseEdge, HandleElement } from './types';
export const errorMessages = {
'001': () =>
@@ -11,7 +11,7 @@ export const errorMessages = {
'006': () => "Can't create edge. An edge needs a source and a target.",
'007': (id: string) => `The old edge with id=${id} does not exist.`,
'009': (type: string) => `Marker type "${type}" doesn't exist.`,
'008': (sourceHandle: HandleElement | null, edge: Edge) =>
'008': (sourceHandle: HandleElement | null, edge: BaseEdge) =>
`Couldn't create edge for ${!sourceHandle ? 'source' : 'target'} handle id: "${
!sourceHandle ? edge.sourceHandle : edge.targetHandle
}", edge id: ${edge.id}.`,

View File

@@ -1,34 +1,15 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { CSSProperties, ComponentType, HTMLAttributes, ReactNode, MouseEvent as ReactMouseEvent } from 'react';
import { ConnectionStatus, Position } from '.';
import type { Connection, HandleElement, HandleType, Node } from '.';
type EdgeLabelOptions = {
label?: string | ReactNode;
labelStyle?: CSSProperties;
labelShowBg?: boolean;
labelBgStyle?: CSSProperties;
labelBgPadding?: [number, number];
labelBgBorderRadius?: number;
};
// interface for the user edge items
type DefaultEdge<T = any> = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type BaseEdge<EdgeData = any> = {
id: string;
type?: string;
source: string;
target: string;
sourceHandle?: string | null;
targetHandle?: string | null;
style?: CSSProperties;
animated?: boolean;
hidden?: boolean;
deletable?: boolean;
data?: T;
className?: string;
sourceNode?: Node;
targetNode?: Node;
data?: EdgeData;
selected?: boolean;
markerStart?: EdgeMarkerType;
markerEnd?: EdgeMarkerType;
@@ -36,106 +17,22 @@ type DefaultEdge<T = any> = {
ariaLabel?: string;
interactionWidth?: number;
focusable?: boolean;
} & EdgeLabelOptions;
};
export type SmoothStepPathOptions = {
offset?: number;
borderRadius?: number;
};
type SmoothStepEdgeType<T> = DefaultEdge<T> & {
type: 'smoothstep';
pathOptions?: SmoothStepPathOptions;
};
export type BezierPathOptions = {
curvature?: number;
};
type BezierEdgeType<T> = DefaultEdge<T> & {
type: 'default';
pathOptions?: BezierPathOptions;
};
export type Edge<T = any> = DefaultEdge<T> | SmoothStepEdgeType<T> | BezierEdgeType<T>;
export type DefaultEdgeOptions = Omit<
Edge,
export type DefaultEdgeOptionsBase<EdgeType extends BaseEdge> = Omit<
EdgeType,
'id' | 'source' | 'target' | 'sourceHandle' | 'targetHandle' | 'sourceNode' | 'targetNode'
>;
export type EdgeMouseHandler = (event: ReactMouseEvent, edge: Edge) => void;
export type WrapEdgeProps<T = any> = Omit<Edge<T>, 'sourceHandle' | 'targetHandle'> & {
onClick?: EdgeMouseHandler;
onEdgeDoubleClick?: EdgeMouseHandler;
sourceHandleId?: string | null;
targetHandleId?: string | null;
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
sourcePosition: Position;
targetPosition: Position;
elementsSelectable?: boolean;
onEdgeUpdate?: OnEdgeUpdateFunc;
onContextMenu?: EdgeMouseHandler;
onMouseEnter?: EdgeMouseHandler;
onMouseMove?: EdgeMouseHandler;
onMouseLeave?: EdgeMouseHandler;
edgeUpdaterRadius?: number;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void;
rfId?: string;
isFocusable: boolean;
pathOptions?: BezierPathOptions | SmoothStepPathOptions;
};
// props that get passed to a custom edge
export type EdgeProps<T = any> = Pick<
Edge<T>,
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'
> &
Pick<
WrapEdgeProps,
| 'sourceX'
| 'sourceY'
| 'targetX'
| 'targetY'
| 'sourcePosition'
| 'targetPosition'
| 'sourceHandleId'
| 'targetHandleId'
| 'interactionWidth'
> &
EdgeLabelOptions & {
markerStart?: string;
markerEnd?: string;
// @TODO: how can we get better types for pathOptions?
pathOptions?: any;
};
export type BaseEdgeProps = Pick<EdgeProps, 'style' | 'markerStart' | 'markerEnd' | 'interactionWidth'> &
EdgeLabelOptions & {
labelX?: number;
labelY?: number;
path: string;
};
export type SmoothStepEdgeProps<T = any> = EdgeProps<T> & {
pathOptions?: SmoothStepPathOptions;
};
export type BezierEdgeProps<T = any> = EdgeProps<T> & {
pathOptions?: BezierPathOptions;
};
export type EdgeTextProps = HTMLAttributes<SVGElement> &
EdgeLabelOptions & {
x: number;
y: number;
};
export enum ConnectionLineType {
Bezier = 'default',
Straight = 'straight',
@@ -144,24 +41,6 @@ export enum ConnectionLineType {
SimpleBezier = 'simplebezier',
}
export type ConnectionLineComponentProps = {
connectionLineStyle?: CSSProperties;
connectionLineType: ConnectionLineType;
fromNode?: Node;
fromHandle?: HandleElement;
fromX: number;
fromY: number;
toX: number;
toY: number;
fromPosition: Position;
toPosition: Position;
connectionStatus: ConnectionStatus | null;
};
export type ConnectionLineComponent = ComponentType<ConnectionLineComponentProps>;
export type OnEdgeUpdateFunc<T = any> = (oldEdge: Edge<T>, newConnection: Connection) => void;
export type EdgeMarker = {
type: MarkerType;
color?: string;

View File

@@ -1,45 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type {
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
ComponentType,
MemoExoticComponent,
} from 'react';
import type { D3DragEvent, Selection as D3Selection, SubjectPosition, ZoomBehavior } from 'd3';
import type { XYPosition, Rect, Transform, CoordinateExtent } from './utils';
import type { NodeChange, EdgeChange } from './changes';
import type {
Node,
NodeInternals,
NodeDimensionUpdate,
NodeProps,
WrapNodeProps,
NodeDragItem,
NodeDragHandler,
SelectionDragHandler,
NodeOrigin,
} from './nodes';
import type { Edge, EdgeProps, WrapEdgeProps } from './edges';
import type { HandleType, StartHandle } from './handles';
import type { DefaultEdgeOptions } from '.';
import type { ReactFlowInstance } from './instance';
export type NodeTypes = { [key: string]: ComponentType<NodeProps> };
export type NodeTypesWrapped = { [key: string]: MemoExoticComponent<ComponentType<WrapNodeProps>> };
export type EdgeTypes = { [key: string]: ComponentType<EdgeProps> };
export type EdgeTypesWrapped = { [key: string]: MemoExoticComponent<ComponentType<WrapEdgeProps>> };
export type FitView = (fitViewOptions?: FitViewOptions) => boolean;
import type { XYPosition, Rect } from './utils';
import type { BaseNode, NodeOrigin } from './nodes';
import type { HandleType } from './handles';
export type Project = (position: XYPosition) => XYPosition;
export type OnNodesChange = (changes: NodeChange[]) => void;
export type OnEdgesChange = (changes: EdgeChange[]) => void;
export type OnNodesDelete = (nodes: Node[]) => void;
export type OnEdgesDelete = (edges: Edge[]) => void;
export type OnMove = (event: MouseEvent | TouchEvent, viewport: Viewport) => void;
export type OnMoveStart = OnMove;
export type OnMoveEnd = OnMove;
@@ -52,8 +19,6 @@ export type SetViewport = (viewport: Viewport, options?: ViewportHelperFunctionO
export type SetCenter = (x: number, y: number, options?: SetCenterOptions) => void;
export type FitBounds = (bounds: Rect, options?: FitBoundsOptions) => void;
export type OnInit<NodeData = any, EdgeData = any> = (reactFlowInstance: ReactFlowInstance<NodeData, EdgeData>) => void;
export interface Connection {
source: string | null;
target: string | null;
@@ -70,8 +35,8 @@ export enum ConnectionMode {
export type OnConnect = (connection: Connection) => void;
export type FitViewParams = {
nodes: Node[];
export type FitViewParamsBase<NodeType extends BaseNode> = {
nodes: NodeType[];
width: number;
height: number;
nodeOrigin: NodeOrigin;
@@ -81,13 +46,13 @@ export type FitViewParams = {
maxZoom: number;
};
export type FitViewOptions = {
export type FitViewOptionsBase<NodeType extends BaseNode> = {
padding?: number;
includeHiddenNodes?: boolean;
minZoom?: number;
maxZoom?: number;
duration?: number;
nodes?: (Partial<Node> & { id: Node['id'] })[];
nodes?: (Partial<NodeType> & { id: NodeType['id'] })[];
};
export type OnConnectStartParams = {
@@ -96,9 +61,6 @@ export type OnConnectStartParams = {
handleType: HandleType | null;
};
export type OnConnectStart = (event: ReactMouseEvent | ReactTouchEvent, params: OnConnectStartParams) => void;
export type OnConnectEnd = (event: MouseEvent | TouchEvent) => void;
export type Viewport = {
x: number;
y: number;
@@ -127,150 +89,13 @@ export type FitBoundsOptions = ViewportHelperFunctionOptions & {
padding?: number;
};
export type UnselectNodesAndEdgesParams = {
nodes?: Node[];
edges?: Edge[];
};
export type OnViewportChange = (viewport: Viewport) => void;
export type ViewportHelperFunctions = {
zoomIn: ZoomInOut;
zoomOut: ZoomInOut;
zoomTo: ZoomTo;
getZoom: GetZoom;
setViewport: SetViewport;
getViewport: GetViewport;
fitView: FitView;
setCenter: SetCenter;
fitBounds: FitBounds;
project: Project;
viewportInitialized: boolean;
};
export type D3ZoomInstance = ZoomBehavior<Element, unknown>;
export type D3SelectionInstance = D3Selection<Element, unknown, null, undefined>;
export type ReactFlowStore = {
rfId: string;
width: number;
height: number;
transform: Transform;
nodeInternals: NodeInternals;
edges: Edge[];
onNodesChange: OnNodesChange | null;
onEdgesChange: OnEdgesChange | null;
hasDefaultNodes: boolean;
hasDefaultEdges: boolean;
domNode: HTMLDivElement | null;
paneDragging: boolean;
noPanClassName: string;
d3Zoom: D3ZoomInstance | null;
d3Selection: D3SelectionInstance | null;
d3ZoomHandler: ((this: Element, event: any, d: unknown) => void) | undefined;
minZoom: number;
maxZoom: number;
translateExtent: CoordinateExtent;
nodeExtent: CoordinateExtent;
nodeOrigin: NodeOrigin;
nodesSelectionActive: boolean;
userSelectionActive: boolean;
userSelectionRect: SelectionRect | null;
connectionNodeId: string | null;
connectionHandleId: string | null;
connectionHandleType: HandleType | null;
connectionPosition: XYPosition;
connectionStatus: ConnectionStatus | null;
connectionMode: ConnectionMode;
snapToGrid: boolean;
snapGrid: SnapGrid;
nodesDraggable: boolean;
nodesConnectable: boolean;
nodesFocusable: boolean;
edgesFocusable: boolean;
elementsSelectable: boolean;
elevateNodesOnSelect: boolean;
multiSelectionActive: boolean;
connectionStartHandle: StartHandle | null;
onNodeDragStart?: NodeDragHandler;
onNodeDrag?: NodeDragHandler;
onNodeDragStop?: NodeDragHandler;
onSelectionDragStart?: SelectionDragHandler;
onSelectionDrag?: SelectionDragHandler;
onSelectionDragStop?: SelectionDragHandler;
onConnect?: OnConnect;
onConnectStart?: OnConnectStart;
onConnectEnd?: OnConnectEnd;
onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd;
connectOnClick: boolean;
defaultEdgeOptions?: DefaultEdgeOptions;
fitViewOnInit: boolean;
fitViewOnInitDone: boolean;
fitViewOnInitOptions: FitViewOptions | undefined;
onNodesDelete?: OnNodesDelete;
onEdgesDelete?: OnEdgesDelete;
onError?: OnError;
// event handlers
onViewportChangeStart?: OnViewportChange;
onViewportChange?: OnViewportChange;
onViewportChangeEnd?: OnViewportChange;
onSelectionChange?: OnSelectionChangeFunc;
ariaLiveMessage: string;
autoPanOnConnect: boolean;
autoPanOnNodeDrag: boolean;
connectionRadius: number;
};
export type ReactFlowActions = {
setNodes: (nodes: Node[]) => void;
getNodes: () => Node[];
setEdges: (edges: Edge[]) => void;
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void;
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void;
updateNodePositions: (nodeDragItems: NodeDragItem[] | Node[], positionChanged: boolean, dragging: boolean) => void;
resetSelectedElements: () => void;
unselectNodesAndEdges: (params?: UnselectNodesAndEdgesParams) => void;
addSelectedNodes: (nodeIds: string[]) => void;
addSelectedEdges: (edgeIds: string[]) => void;
setMinZoom: (minZoom: number) => void;
setMaxZoom: (maxZoom: number) => void;
setTranslateExtent: (translateExtent: CoordinateExtent) => void;
setNodeExtent: (nodeExtent: CoordinateExtent) => void;
cancelConnection: () => void;
reset: () => void;
triggerNodeChanges: (changes: NodeChange[]) => void;
panBy: (delta: XYPosition) => void;
};
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
export type UpdateNodeInternals = (nodeId: string) => void;
export type OnSelectionChangeParams = {
nodes: Node[];
edges: Edge[];
};
export type OnSelectionChangeFunc = (params: OnSelectionChangeParams) => void;
export type PanelPosition = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
export type ProOptions = {

View File

@@ -2,22 +2,23 @@ import type { XYPosition, Position, Dimensions, OnConnect, Connection } from '.'
export type HandleType = 'source' | 'target';
export interface HandleElement extends XYPosition, Dimensions {
id?: string | null;
position: Position;
}
export type HandleElement = XYPosition &
Dimensions & {
id?: string | null;
position: Position;
};
export interface StartHandle {
export type StartHandle = {
nodeId: string;
type: HandleType;
handleId?: string | null;
}
};
export interface HandleProps {
export type HandleProps = {
type: HandleType;
position: Position;
isConnectable?: boolean;
onConnect?: OnConnect;
isValidConnection?: (connection: Connection) => boolean;
id?: string;
}
};

View File

@@ -2,7 +2,4 @@ export * from './general';
export * from './nodes';
export * from './edges';
export * from './handles';
export * from './changes';
export * from './utils';
export * from './instance';
export * from './component-props';

View File

@@ -1,17 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { CSSProperties, MouseEvent as ReactMouseEvent } from 'react';
import { internalsSymbol } from '../';
import type { XYPosition, Position, CoordinateExtent, HandleElement } from '.';
// interface for the user node items
export type Node<T = any, U extends string | undefined = string | undefined> = {
// this is stuff that all nodes share independent of the framework
export type BaseNode<T = any, U extends string | undefined = string | undefined> = {
id: string;
position: XYPosition;
data: T;
type?: U;
style?: CSSProperties;
className?: string;
sourcePosition?: Position;
targetPosition?: Position;
hidden?: boolean;
@@ -31,7 +27,6 @@ export type Node<T = any, U extends string | undefined = string | undefined> = {
positionAbsolute?: XYPosition;
ariaLabel?: string;
focusable?: boolean;
resizing?: boolean;
// only used internally
[internalsSymbol]?: {
@@ -41,44 +36,17 @@ export type Node<T = any, U extends string | undefined = string | undefined> = {
};
};
export type NodeMouseHandler = (event: ReactMouseEvent, node: Node) => void;
export type NodeDragHandler = (event: ReactMouseEvent, node: Node, nodes: Node[]) => void;
export type SelectionDragHandler = (event: ReactMouseEvent, nodes: Node[]) => void;
export type WrapNodeProps<T = any> = Pick<
Node<T>,
'id' | 'data' | 'style' | 'className' | 'dragHandle' | 'sourcePosition' | 'targetPosition' | 'hidden' | 'ariaLabel'
> &
Required<Pick<Node<T>, 'selected' | 'type' | 'zIndex'>> & {
isConnectable: boolean;
xPos: number;
yPos: number;
xPosOrigin: number;
yPosOrigin: number;
initialized: boolean;
isSelectable: boolean;
isDraggable: boolean;
isFocusable: boolean;
selectNodesOnDrag: boolean;
onClick?: NodeMouseHandler;
onDoubleClick?: NodeMouseHandler;
onMouseEnter?: NodeMouseHandler;
onMouseMove?: NodeMouseHandler;
onMouseLeave?: NodeMouseHandler;
onContextMenu?: NodeMouseHandler;
resizeObserver: ResizeObserver | null;
isParent: boolean;
noDragClassName: string;
noPanClassName: string;
rfId: string;
disableKeyboardA11y: boolean;
};
// props that get passed to a custom node
export type NodeProps<T = any> = Pick<
WrapNodeProps<T>,
'id' | 'data' | 'dragHandle' | 'type' | 'selected' | 'isConnectable' | 'xPos' | 'yPos' | 'zIndex'
> & {
export type NodeProps<T = any> = {
id: BaseNode['id'];
data: T;
dragHandle: BaseNode['dragHandle'];
type: BaseNode['type'];
selected: BaseNode['selected'];
isConnectable: BaseNode['connectable'];
zIndex: BaseNode['zIndex'];
xPos: number;
yPos: number;
dragging: boolean;
targetPosition?: Position;
sourcePosition?: Position;
@@ -95,8 +63,6 @@ export type NodeDimensionUpdate = {
forceUpdate?: boolean;
};
export type NodeInternals = Map<string, Node>;
export type NodeBounds = XYPosition & {
width: number | null;
height: number | null;

View File

@@ -5,24 +5,24 @@ export enum Position {
Bottom = 'bottom',
}
export interface XYPosition {
export type XYPosition = {
x: number;
y: number;
}
};
export type XYZPosition = XYPosition & { z: number };
export interface Dimensions {
export type Dimensions = {
width: number;
height: number;
}
};
export interface Rect extends Dimensions, XYPosition {}
export type Rect = Dimensions & XYPosition;
export interface Box extends XYPosition {
export type Box = XYPosition & {
x2: number;
y2: number;
}
};
export type Transform = [number, number, number];

View File

@@ -5,27 +5,32 @@ import { zoomIdentity } from 'd3-zoom';
import { boxToRect, clamp, devWarn, getBoundsOfBoxes, getOverlappingArea, rectToBox } from './utils';
import {
errorMessages,
type Node,
type Edge,
type Connection,
type EdgeMarkerType,
type Transform,
type XYPosition,
type Rect,
type NodeInternals,
type NodeOrigin,
FitViewParams,
FitViewOptions,
BaseNode,
BaseEdge,
FitViewParamsBase,
FitViewOptionsBase,
} from '@reactflow/system';
export const isEdge = (element: Node | Connection | Edge): element is Edge =>
'id' in element && 'source' in element && 'target' in element;
export const isEdgeBase = <NodeType extends BaseNode = BaseNode, EdgeType extends BaseEdge = BaseEdge>(
element: NodeType | Connection | EdgeType
): element is EdgeType => 'id' in element && 'source' in element && 'target' in element;
export const isNode = (element: Node | Connection | Edge): element is Node =>
'id' in element && !('source' in element) && !('target' in element);
export const isNodeBase = <NodeType extends BaseNode = BaseNode, EdgeType extends BaseEdge = BaseEdge>(
element: NodeType | Connection | EdgeType
): element is NodeType => 'id' in element && !('source' in element) && !('target' in element);
export const getOutgoers = <T = any, U extends T = T>(node: Node<U>, nodes: Node<T>[], edges: Edge[]): Node<T>[] => {
if (!isNode(node)) {
export const getOutgoersBase = <NodeType extends BaseNode = BaseNode, EdgeType extends BaseEdge = BaseEdge>(
node: NodeType,
nodes: NodeType[],
edges: EdgeType[]
): NodeType[] => {
if (!isNodeBase(node)) {
return [];
}
@@ -33,8 +38,12 @@ export const getOutgoers = <T = any, U extends T = T>(node: Node<U>, nodes: Node
return nodes.filter((n) => outgoerIds.includes(n.id));
};
export const getIncomers = <T = any, U extends T = T>(node: Node<U>, nodes: Node<T>[], edges: Edge[]): Node<T>[] => {
if (!isNode(node)) {
export const getIncomersBase = <NodeType extends BaseNode = BaseNode, EdgeType extends BaseEdge = BaseEdge>(
node: NodeType,
nodes: NodeType[],
edges: EdgeType[]
): NodeType[] => {
if (!isNodeBase(node)) {
return [];
}
@@ -42,7 +51,7 @@ export const getIncomers = <T = any, U extends T = T>(node: Node<U>, nodes: Node
return nodes.filter((n) => incomersIds.includes(n.id));
};
const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection): string =>
const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection | BaseEdge): string =>
`reactflow__edge-${source}${sourceHandle || ''}-${target}${targetHandle || ''}`;
export const getMarkerId = (marker: EdgeMarkerType | undefined, rfId?: string): string => {
@@ -62,7 +71,7 @@ export const getMarkerId = (marker: EdgeMarkerType | undefined, rfId?: string):
.join('&')}`;
};
const connectionExists = (edge: Edge, edges: Edge[]) => {
const connectionExists = (edge: BaseEdge, edges: BaseEdge[]) => {
return edges.some(
(el) =>
el.source === edge.source &&
@@ -72,21 +81,24 @@ const connectionExists = (edge: Edge, edges: Edge[]) => {
);
};
export const addEdge = (edgeParams: Edge | Connection, edges: Edge[]): Edge[] => {
export const addEdgeBase = <EdgeType extends BaseEdge>(
edgeParams: EdgeType | Connection,
edges: EdgeType[]
): EdgeType[] => {
if (!edgeParams.source || !edgeParams.target) {
devWarn('006', errorMessages['006']());
return edges;
}
let edge: Edge;
if (isEdge(edgeParams)) {
let edge: EdgeType;
if (isEdgeBase(edgeParams)) {
edge = { ...edgeParams };
} else {
edge = {
...edgeParams,
id: getEdgeId(edgeParams),
} as Edge;
} as EdgeType;
}
if (connectionExists(edge, edges)) {
@@ -96,14 +108,18 @@ export const addEdge = (edgeParams: Edge | Connection, edges: Edge[]): Edge[] =>
return edges.concat(edge);
};
export const updateEdge = (oldEdge: Edge, newConnection: Connection, edges: Edge[]): Edge[] => {
export const updateEdgeBase = <EdgeType extends BaseEdge>(
oldEdge: EdgeType,
newConnection: Connection,
edges: EdgeType[]
): EdgeType[] => {
if (!newConnection.source || !newConnection.target) {
devWarn('006', errorMessages['006']());
return edges;
}
const foundEdge = edges.find((e) => e.id === oldEdge.id) as Edge;
const foundEdge = edges.find((e) => e.id === oldEdge.id) as EdgeType;
if (!foundEdge) {
devWarn('007', errorMessages['007'](oldEdge.id));
@@ -119,7 +135,7 @@ export const updateEdge = (oldEdge: Edge, newConnection: Connection, edges: Edge
target: newConnection.target,
sourceHandle: newConnection.sourceHandle,
targetHandle: newConnection.targetHandle,
} as Edge;
} as EdgeType;
return edges.filter((e) => e.id !== oldEdge.id).concat(edge);
};
@@ -153,7 +169,7 @@ export const rendererPointToPoint = ({ x, y }: XYPosition, [tx, ty, tScale]: Tra
};
export const getNodePositionWithOrigin = (
node: Node | undefined,
node: BaseNode | undefined,
nodeOrigin: NodeOrigin = [0, 0]
): XYPosition & { positionAbsolute: XYPosition } => {
if (!node) {
@@ -186,7 +202,7 @@ export const getNodePositionWithOrigin = (
};
};
export const getRectOfNodes = (nodes: Node[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
export const getRectOfNodes = (nodes: BaseNode[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
if (nodes.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 };
}
@@ -210,15 +226,15 @@ export const getRectOfNodes = (nodes: Node[], nodeOrigin: NodeOrigin = [0, 0]):
return boxToRect(box);
};
export const getNodesInside = (
nodeInternals: NodeInternals,
export const getNodesInside = <NodeType extends BaseNode>(
nodes: NodeType[],
rect: Rect,
[tx, ty, tScale]: Transform = [0, 0, 1],
partially = false,
// set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute
excludeNonSelectableNodes = false,
nodeOrigin: NodeOrigin = [0, 0]
): Node[] => {
): NodeType[] => {
const paneRect = {
x: (rect.x - tx) / tScale,
y: (rect.y - ty) / tScale,
@@ -226,13 +242,11 @@ export const getNodesInside = (
height: rect.height / tScale,
};
const visibleNodes: Node[] = [];
nodeInternals.forEach((node) => {
const visibleNodes = nodes.reduce<NodeType[]>((res, node) => {
const { width, height, selectable = true, hidden = false } = node;
if ((excludeNonSelectableNodes && !selectable) || hidden) {
return false;
return res;
}
const { positionAbsolute } = getNodePositionWithOrigin(node, nodeOrigin);
@@ -252,14 +266,19 @@ export const getNodesInside = (
const isVisible = notInitialized || partiallyVisible || overlappingArea >= area;
if (isVisible || node.dragging) {
visibleNodes.push(node);
res.push(node);
}
});
return res;
}, []);
return visibleNodes;
};
export const getConnectedEdges = (nodes: Node[], edges: Edge[]): Edge[] => {
export const getConnectedEdgesBase = <NodeType extends BaseNode = BaseNode, EdgeType extends BaseEdge = BaseEdge>(
nodes: NodeType[],
edges: EdgeType[]
): EdgeType[] => {
const nodeIds = nodes.map((node) => node.id);
return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target));
@@ -289,15 +308,15 @@ export const getD3Transition = (selection: D3Selection<Element, unknown, null, u
return selection.transition().duration(duration);
};
export function fitView(
{ nodes, width, height, d3Zoom, d3Selection, nodeOrigin, minZoom, maxZoom }: FitViewParams,
options: FitViewOptions = {}
export function fitView<Params extends FitViewParamsBase<BaseNode>, Options extends FitViewOptionsBase<BaseNode>>(
{ nodes, width, height, d3Zoom, d3Selection, nodeOrigin, minZoom, maxZoom }: Params,
options?: Options
) {
const filteredNodes = nodes.filter((n) => {
const isVisible = options.includeHiddenNodes ? n.width && n.height : !n.hidden;
const isVisible = options?.includeHiddenNodes ? n.width && n.height : !n.hidden;
if (options.nodes?.length) {
return isVisible && options.nodes.some((optionNode) => optionNode.id === n.id);
if (options?.nodes?.length) {
return isVisible && options?.nodes.some((optionNode) => optionNode.id === n.id);
}
return isVisible;
@@ -312,14 +331,14 @@ export function fitView(
bounds,
width,
height,
options.minZoom ?? minZoom,
options.maxZoom ?? maxZoom,
options.padding ?? 0.1
options?.minZoom ?? minZoom,
options?.maxZoom ?? maxZoom,
options?.padding ?? 0.1
);
const nextTransform = zoomIdentity.translate(x, y).scale(zoom);
if (typeof options.duration === 'number' && options.duration > 0) {
if (typeof options?.duration === 'number' && options.duration > 0) {
d3Zoom.transform(getD3Transition(d3Selection, options.duration), nextTransform);
} else {
d3Zoom.transform(d3Selection, nextTransform);

View File

@@ -3,7 +3,7 @@ import type {
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
} from 'react';
import type { Dimensions, Node, XYPosition, CoordinateExtent, Box, Rect } from '@reactflow/system';
import type { Dimensions, XYPosition, CoordinateExtent, Box, Rect, BaseNode } from '@reactflow/system';
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
width: node.offsetWidth,
@@ -60,7 +60,7 @@ export const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({
height: y2 - y,
});
export const nodeToRect = (node: Node): Rect => ({
export const nodeToRect = (node: BaseNode): Rect => ({
...(node.positionAbsolute || { x: 0, y: 0 }),
width: node.width || 0,
height: node.height || 0,
@@ -125,3 +125,8 @@ export const getEventPosition = (
y: evtY - (bounds?.top ?? 0),
};
};
export const infiniteExtent: CoordinateExtent = [
[Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY],
[Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY],
];