refactor(types): use same structure for nodes and edges

This commit is contained in:
moklick
2024-02-17 15:45:10 +01:00
parent 776f6ce0b7
commit ad7403cc75
24 changed files with 176 additions and 147 deletions
@@ -5,20 +5,20 @@ import { EdgeAnchor } from '../Edges/EdgeAnchor';
import type { EdgeWrapperProps, Edge } from '../../types/edges'; import type { EdgeWrapperProps, Edge } from '../../types/edges';
import { useStoreApi } from '../../hooks/useStore'; import { useStoreApi } from '../../hooks/useStore';
type EdgeUpdateAnchorsProps = { type EdgeUpdateAnchorsProps<EdgeType extends Edge = Edge> = {
edge: Edge; edge: EdgeType;
isUpdatable: boolean | 'source' | 'target'; isUpdatable: boolean | 'source' | 'target';
edgeUpdaterRadius: EdgeWrapperProps['edgeUpdaterRadius']; edgeUpdaterRadius: EdgeWrapperProps['edgeUpdaterRadius'];
sourceHandleId: Edge['sourceHandle']; sourceHandleId: Edge['sourceHandle'];
targetHandleId: Edge['targetHandle']; targetHandleId: Edge['targetHandle'];
onEdgeUpdate: EdgeWrapperProps['onEdgeUpdate']; onEdgeUpdate: EdgeWrapperProps<EdgeType>['onEdgeUpdate'];
onEdgeUpdateStart: EdgeWrapperProps['onEdgeUpdateStart']; onEdgeUpdateStart: EdgeWrapperProps<EdgeType>['onEdgeUpdateStart'];
onEdgeUpdateEnd: EdgeWrapperProps['onEdgeUpdateEnd']; onEdgeUpdateEnd: EdgeWrapperProps<EdgeType>['onEdgeUpdateEnd'];
setUpdateHover: (hover: boolean) => void; setUpdateHover: (hover: boolean) => void;
setUpdating: (updating: boolean) => void; setUpdating: (updating: boolean) => void;
} & EdgePosition; } & EdgePosition;
export function EdgeUpdateAnchors({ export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
isUpdatable, isUpdatable,
edgeUpdaterRadius, edgeUpdaterRadius,
edge, edge,
@@ -35,7 +35,7 @@ export function EdgeUpdateAnchors({
onEdgeUpdateEnd, onEdgeUpdateEnd,
setUpdating, setUpdating,
setUpdateHover, setUpdateHover,
}: EdgeUpdateAnchorsProps) { }: EdgeUpdateAnchorsProps<EdgeType>) {
const store = useStoreApi(); const store = useStoreApi();
const handleEdgeUpdater = (event: React.MouseEvent<SVGGElement, MouseEvent>, isSourceHandle: boolean) => { const handleEdgeUpdater = (event: React.MouseEvent<SVGGElement, MouseEvent>, isSourceHandle: boolean) => {
@@ -13,9 +13,9 @@ import { useStoreApi, useStore } from '../../hooks/useStore';
import { ARIA_EDGE_DESC_KEY } from '../A11yDescriptions'; import { ARIA_EDGE_DESC_KEY } from '../A11yDescriptions';
import { builtinEdgeTypes, nullPosition } from './utils'; import { builtinEdgeTypes, nullPosition } from './utils';
import { EdgeUpdateAnchors } from './EdgeUpdateAnchors'; import { EdgeUpdateAnchors } from './EdgeUpdateAnchors';
import type { EdgeWrapperProps } from '../../types'; import type { Edge, EdgeWrapperProps } from '../../types';
export function EdgeWrapper({ export function EdgeWrapper<EdgeType extends Edge = Edge>({
id, id,
edgesFocusable, edgesFocusable,
edgesUpdatable, edgesUpdatable,
@@ -34,8 +34,8 @@ export function EdgeWrapper({
edgeTypes, edgeTypes,
noPanClassName, noPanClassName,
onError, onError,
}: EdgeWrapperProps): JSX.Element | null { }: EdgeWrapperProps<EdgeType>): JSX.Element | null {
let edge = useStore((s) => s.edgeLookup.get(id)!); let edge = useStore((s) => s.edgeLookup.get(id)!) as EdgeType;
const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions); const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
edge = defaultEdgeOptions ? { ...defaultEdgeOptions, ...edge } : edge; edge = defaultEdgeOptions ? { ...defaultEdgeOptions, ...edge } : edge;
@@ -236,7 +236,7 @@ export function EdgeWrapper({
/> />
)} )}
{isUpdatable && ( {isUpdatable && (
<EdgeUpdateAnchors <EdgeUpdateAnchors<EdgeType>
edge={edge} edge={edge}
isUpdatable={isUpdatable} isUpdatable={isUpdatable}
edgeUpdaterRadius={edgeUpdaterRadius} edgeUpdaterRadius={edgeUpdaterRadius}
@@ -68,7 +68,10 @@ const reactFlowFieldsToTrack = [
] as const; ] as const;
type ReactFlowFieldsToTrack = (typeof reactFlowFieldsToTrack)[number]; type ReactFlowFieldsToTrack = (typeof reactFlowFieldsToTrack)[number];
type StoreUpdaterProps<NodeType extends Node = Node> = Pick<ReactFlowProps<NodeType>, ReactFlowFieldsToTrack> & { type StoreUpdaterProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> = Pick<
ReactFlowProps<NodeType, EdgeType>,
ReactFlowFieldsToTrack
> & {
rfId: string; rfId: string;
}; };
@@ -86,7 +89,9 @@ const selector = (s: ReactFlowState) => ({
reset: s.reset, reset: s.reset,
}); });
export function StoreUpdater<NodeType extends Node = Node>(props: StoreUpdaterProps<NodeType>) { export function StoreUpdater<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
props: StoreUpdaterProps<NodeType, EdgeType>
) {
const { const {
setNodes, setNodes,
setEdges, setEdges,
@@ -108,7 +113,7 @@ export function StoreUpdater<NodeType extends Node = Node>(props: StoreUpdaterPr
}; };
}, []); }, []);
const previousFields = useRef<Partial<StoreUpdaterProps<NodeType>>>({ const previousFields = useRef<Partial<StoreUpdaterProps<NodeType, EdgeType>>>({
// these are values that are also passed directly to other components // these are values that are also passed directly to other components
// than the StoreUpdater. We can reduce the number of setStore calls // than the StoreUpdater. We can reduce the number of setStore calls
// by setting the same values here as prev fields. // by setting the same values here as prev fields.
@@ -6,10 +6,10 @@ import { useVisibleEdgeIds } from '../../hooks/useVisibleEdgeIds';
import MarkerDefinitions from './MarkerDefinitions'; import MarkerDefinitions from './MarkerDefinitions';
import { GraphViewProps } from '../GraphView'; import { GraphViewProps } from '../GraphView';
import { EdgeWrapper } from '../../components/EdgeWrapper'; import { EdgeWrapper } from '../../components/EdgeWrapper';
import type { ReactFlowState } from '../../types'; import type { Edge, ReactFlowState, Node } from '../../types';
type EdgeRendererProps = Pick< type EdgeRendererProps<EdgeType extends Edge = Edge> = Pick<
GraphViewProps, GraphViewProps<Node, EdgeType>,
| 'onEdgeClick' | 'onEdgeClick'
| 'onEdgeDoubleClick' | 'onEdgeDoubleClick'
| 'defaultMarkerColor' | 'defaultMarkerColor'
@@ -40,7 +40,7 @@ const selector = (s: ReactFlowState) => ({
onError: s.onError, onError: s.onError,
}); });
function EdgeRendererComponent({ function EdgeRendererComponent<EdgeType extends Edge = Edge>({
defaultMarkerColor, defaultMarkerColor,
onlyRenderVisibleElements, onlyRenderVisibleElements,
rfId, rfId,
@@ -56,7 +56,7 @@ function EdgeRendererComponent({
onEdgeDoubleClick, onEdgeDoubleClick,
onEdgeUpdateStart, onEdgeUpdateStart,
onEdgeUpdateEnd, onEdgeUpdateEnd,
}: EdgeRendererProps) { }: EdgeRendererProps<EdgeType>) {
const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow); const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
const edgeIds = useVisibleEdgeIds(onlyRenderVisibleElements); const edgeIds = useVisibleEdgeIds(onlyRenderVisibleElements);
@@ -66,7 +66,7 @@ function EdgeRendererComponent({
{edgeIds.map((id) => { {edgeIds.map((id) => {
return ( return (
<EdgeWrapper <EdgeWrapper<EdgeType>
key={id} key={id}
id={id} id={id}
edgesFocusable={edgesFocusable} edgesFocusable={edgesFocusable}
@@ -95,4 +95,4 @@ function EdgeRendererComponent({
EdgeRendererComponent.displayName = 'EdgeRenderer'; EdgeRendererComponent.displayName = 'EdgeRenderer';
export const EdgeRenderer = memo(EdgeRendererComponent); export const EdgeRenderer = memo(EdgeRendererComponent) as typeof EdgeRendererComponent;
@@ -9,7 +9,7 @@ import { Pane } from '../Pane';
import { NodesSelection } from '../../components/NodesSelection'; import { NodesSelection } from '../../components/NodesSelection';
import type { ReactFlowState, Node } from '../../types'; import type { ReactFlowState, Node } from '../../types';
export type FlowRendererProps<NodeType extends Node> = Omit< export type FlowRendererProps<NodeType extends Node = Node> = Omit<
GraphViewProps<NodeType>, GraphViewProps<NodeType>,
| 'snapToGrid' | 'snapToGrid'
| 'nodeTypes' | 'nodeTypes'
@@ -32,7 +32,7 @@ const selector = (s: ReactFlowState) => {
return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive }; return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive };
}; };
function FlowRendererComponent<NodeType extends Node>({ function FlowRendererComponent<NodeType extends Node = Node>({
children, children,
onPaneClick, onPaneClick,
onPaneMouseEnter, onPaneMouseEnter,
@@ -8,15 +8,15 @@ import { useOnInitHandler } from '../../hooks/useOnInitHandler';
import { useViewportSync } from '../../hooks/useViewportSync'; import { useViewportSync } from '../../hooks/useViewportSync';
import { ConnectionLineWrapper } from '../../components/ConnectionLine'; import { ConnectionLineWrapper } from '../../components/ConnectionLine';
import { useNodeOrEdgeTypesWarning } from './useNodeOrEdgeTypesWarning'; import { useNodeOrEdgeTypesWarning } from './useNodeOrEdgeTypesWarning';
import type { Node, ReactFlowProps } from '../../types'; import type { Edge, Node, ReactFlowProps } from '../../types';
export type GraphViewProps<NodeType extends Node = Node> = Omit< export type GraphViewProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> = Omit<
ReactFlowProps<NodeType>, ReactFlowProps<NodeType, EdgeType>,
'onSelectionChange' | 'nodes' | 'edges' | 'onMove' | 'onMoveStart' | 'onMoveEnd' | 'elevateEdgesOnSelect' 'onSelectionChange' | 'nodes' | 'edges' | 'onMove' | 'onMoveStart' | 'onMoveEnd' | 'elevateEdgesOnSelect'
> & > &
Required< Required<
Pick< Pick<
ReactFlowProps<NodeType>, ReactFlowProps<NodeType, EdgeType>,
| 'selectionKeyCode' | 'selectionKeyCode'
| 'deleteKeyCode' | 'deleteKeyCode'
| 'multiSelectionKeyCode' | 'multiSelectionKeyCode'
@@ -38,7 +38,7 @@ export type GraphViewProps<NodeType extends Node = Node> = Omit<
rfId: string; rfId: string;
}; };
function GraphViewComponent<NodeType extends Node = Node>({ function GraphViewComponent<NodeType extends Node = Node, EdgeType extends Edge = Edge>({
nodeTypes, nodeTypes,
edgeTypes, edgeTypes,
onInit, onInit,
@@ -102,7 +102,7 @@ function GraphViewComponent<NodeType extends Node = Node>({
rfId, rfId,
viewport, viewport,
onViewportChange, onViewportChange,
}: GraphViewProps<NodeType>) { }: GraphViewProps<NodeType, EdgeType>) {
useNodeOrEdgeTypesWarning(nodeTypes); useNodeOrEdgeTypesWarning(nodeTypes);
useNodeOrEdgeTypesWarning(edgeTypes); useNodeOrEdgeTypesWarning(edgeTypes);
@@ -148,7 +148,7 @@ function GraphViewComponent<NodeType extends Node = Node>({
isControlledViewport={!!viewport} isControlledViewport={!!viewport}
> >
<Viewport> <Viewport>
<EdgeRenderer <EdgeRenderer<EdgeType>
edgeTypes={edgeTypes} edgeTypes={edgeTypes}
onEdgeClick={onEdgeClick} onEdgeClick={onEdgeClick}
onEdgeDoubleClick={onEdgeDoubleClick} onEdgeDoubleClick={onEdgeDoubleClick}
@@ -17,7 +17,7 @@ import { StoreUpdater } from '../../components/StoreUpdater';
import { useColorModeClass } from '../../hooks/useColorModeClass'; import { useColorModeClass } from '../../hooks/useColorModeClass';
import { GraphView } from '../GraphView'; import { GraphView } from '../GraphView';
import { Wrapper } from './Wrapper'; import { Wrapper } from './Wrapper';
import type { ReactFlowProps, ReactFlowRefType, Node } from '../../types'; import type { ReactFlowProps, ReactFlowRefType, Node, Edge } from '../../types';
export const initNodeOrigin: NodeOrigin = [0, 0]; export const initNodeOrigin: NodeOrigin = [0, 0];
const initDefaultViewport: Viewport = { x: 0, y: 0, zoom: 1 }; const initDefaultViewport: Viewport = { x: 0, y: 0, zoom: 1 };
@@ -30,13 +30,7 @@ const wrapperStyle: CSSProperties = {
zIndex: 0, zIndex: 0,
}; };
declare module 'react' { function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
function forwardRef<T, P = Record<string, never>>(
render: (props: P, ref: React.Ref<T>) => React.ReactNode | null
): (props: P & React.RefAttributes<T>) => React.ReactNode | null;
}
function ReactFlow<NodeType extends Node = Node>(
{ {
nodes, nodes,
edges, edges,
@@ -156,7 +150,7 @@ function ReactFlow<NodeType extends Node = Node>(
height, height,
colorMode = 'light', colorMode = 'light',
...rest ...rest
}: ReactFlowProps<NodeType>, }: ReactFlowProps<NodeType, EdgeType>,
ref: ForwardedRef<ReactFlowRefType> ref: ForwardedRef<ReactFlowRefType>
) { ) {
const rfId = id || '1'; const rfId = id || '1';
@@ -172,7 +166,7 @@ function ReactFlow<NodeType extends Node = Node>(
id={id} id={id}
> >
<Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}> <Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}>
<GraphView<NodeType> <GraphView<NodeType, EdgeType>
onInit={onInit} onInit={onInit}
onNodeClick={onNodeClick} onNodeClick={onNodeClick}
onEdgeClick={onEdgeClick} onEdgeClick={onEdgeClick}
@@ -300,6 +294,4 @@ function ReactFlow<NodeType extends Node = Node>(
); );
} }
export default forwardRef(ReactFlow) as <T extends Node = Node>( export default forwardRef(ReactFlow) as typeof ReactFlow;
props: ReactFlowProps<T> & { ref?: React.ForwardedRef<HTMLUListElement> }
) => ReturnType<typeof ReactFlow>;
+2 -2
View File
@@ -11,8 +11,8 @@ const edgesSelector = (state: ReactFlowState) => state.edges;
* @public * @public
* @returns An array of edges * @returns An array of edges
*/ */
export function useEdges<EdgeData>(): Edge<EdgeData>[] { export function useEdges<EdgeType extends Edge = Edge>(): EdgeType[] {
const edges = useStore(edgesSelector, shallow); const edges = useStore(edgesSelector, shallow) as EdgeType[];
return edges; return edges;
} }
+5 -3
View File
@@ -1,15 +1,17 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { useReactFlow } from './useReactFlow'; import { useReactFlow } from './useReactFlow';
import type { OnInit, Node } from '../types'; import type { OnInit, Node, Edge } from '../types';
/** /**
* Hook for calling onInit handler. * Hook for calling onInit handler.
* *
* @internal * @internal
*/ */
export function useOnInitHandler<NodeType extends Node = Node>(onInit: OnInit<NodeType> | undefined) { export function useOnInitHandler<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
const rfInstance = useReactFlow<NodeType>(); onInit: OnInit<NodeType, EdgeType> | undefined
) {
const rfInstance = useReactFlow<NodeType, EdgeType>();
const isInitialized = useRef<boolean>(false); const isInitialized = useRef<boolean>(false);
useEffect(() => { useEffect(() => {
-1
View File
@@ -53,7 +53,6 @@ export {
type OnConnectStart, type OnConnectStart,
type OnConnect, type OnConnect,
type OnConnectEnd, type OnConnectEnd,
type IsValidConnection,
type Viewport, type Viewport,
type SnapGrid, type SnapGrid,
PanOnScrollMode, PanOnScrollMode,
+22 -21
View File
@@ -18,7 +18,6 @@ import type {
HandleType, HandleType,
SelectionMode, SelectionMode,
OnError, OnError,
IsValidConnection,
ColorMode, ColorMode,
SnapGrid, SnapGrid,
} from '@xyflow/system'; } from '@xyflow/system';
@@ -44,13 +43,15 @@ import type {
EdgeMouseHandler, EdgeMouseHandler,
OnNodeDrag, OnNodeDrag,
OnBeforeDelete, OnBeforeDelete,
IsValidConnection,
} from '.'; } from '.';
/** /**
* ReactFlow component props. * ReactFlow component props.
* @public * @public
*/ */
export interface ReactFlowProps<NodeType extends Node = Node> extends Omit<HTMLAttributes<HTMLDivElement>, 'onError'> { export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends Edge = Edge>
extends Omit<HTMLAttributes<HTMLDivElement>, 'onError'> {
/** An array of nodes to render in a controlled flow. /** An array of nodes to render in a controlled flow.
* @example * @example
* const nodes = [ * const nodes = [
@@ -73,11 +74,11 @@ export interface ReactFlowProps<NodeType extends Node = Node> extends Omit<HTMLA
* } * }
* ]; * ];
*/ */
edges?: Edge[]; edges?: EdgeType[];
/** The initial nodes to render in an uncontrolled flow. */ /** The initial nodes to render in an uncontrolled flow. */
defaultNodes?: NodeType[]; defaultNodes?: NodeType[];
/** The initial edges to render in an uncontrolled flow. */ /** The initial edges to render in an uncontrolled flow. */
defaultEdges?: Edge[]; defaultEdges?: EdgeType[];
/** Defaults to be applied to all new edges that are added to the flow. /** Defaults to be applied to all new edges that are added to the flow.
* *
* Properties on a new edge will override these defaults if they exist. * Properties on a new edge will override these defaults if they exist.
@@ -117,20 +118,20 @@ export interface ReactFlowProps<NodeType extends Node = Node> extends Omit<HTMLA
/** This event handler is called when a user stops dragging a node */ /** This event handler is called when a user stops dragging a node */
onNodeDragStop?: OnNodeDrag<NodeType>; onNodeDragStop?: OnNodeDrag<NodeType>;
/** This event handler is called when a user clicks on an edge */ /** This event handler is called when a user clicks on an edge */
onEdgeClick?: (event: ReactMouseEvent, edge: Edge) => void; onEdgeClick?: (event: ReactMouseEvent, edge: EdgeType) => void;
/** This event handler is called when a user right clicks on an edge */ /** This event handler is called when a user right clicks on an edge */
onEdgeContextMenu?: EdgeMouseHandler; onEdgeContextMenu?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when mouse of a user enters an edge */ /** This event handler is called when mouse of a user enters an edge */
onEdgeMouseEnter?: EdgeMouseHandler; onEdgeMouseEnter?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when mouse of a user moves over an edge */ /** This event handler is called when mouse of a user moves over an edge */
onEdgeMouseMove?: EdgeMouseHandler; onEdgeMouseMove?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when mouse of a user leaves an edge */ /** This event handler is called when mouse of a user leaves an edge */
onEdgeMouseLeave?: EdgeMouseHandler; onEdgeMouseLeave?: EdgeMouseHandler<EdgeType>;
/** This event handler is called when a user double clicks on an edge */ /** This event handler is called when a user double clicks on an edge */
onEdgeDoubleClick?: EdgeMouseHandler; onEdgeDoubleClick?: EdgeMouseHandler<EdgeType>;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void; onEdgeUpdateStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void; onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdate?: OnEdgeUpdateFunc; onEdgeUpdate?: OnEdgeUpdateFunc<EdgeType>;
/** This event handler is called when a Node is updated /** This event handler is called when a Node is updated
* @example // Use NodesState hook to create edges and get onNodesChange handler * @example // Use NodesState hook to create edges and get onNodesChange handler
* import ReactFlow, { useNodesState } from '@xyflow/react'; * import ReactFlow, { useNodesState } from '@xyflow/react';
@@ -164,19 +165,19 @@ export interface ReactFlowProps<NodeType extends Node = Node> extends Omit<HTMLA
* *
* return (<ReactFlow onEdgesChange={onEdgesChange} {...rest} />) * return (<ReactFlow onEdgesChange={onEdgesChange} {...rest} />)
*/ */
onEdgesChange?: OnEdgesChange; onEdgesChange?: OnEdgesChange<EdgeType>;
/** This event handler gets called when a Node is deleted */ /** This event handler gets called when a Node is deleted */
onNodesDelete?: OnNodesDelete<NodeType>; onNodesDelete?: OnNodesDelete<NodeType>;
/** This event handler gets called when a Edge is deleted */ /** This event handler gets called when a Edge is deleted */
onEdgesDelete?: OnEdgesDelete; onEdgesDelete?: OnEdgesDelete<EdgeType>;
/** This event handler gets called when a Node or Edge is deleted */ /** This event handler gets called when a Node or Edge is deleted */
onDelete?: OnDelete; onDelete?: OnDelete<NodeType, EdgeType>;
/** This event handler gets called when a user starts to drag a selection box */ /** This event handler gets called when a user starts to drag a selection box */
onSelectionDragStart?: SelectionDragHandler; onSelectionDragStart?: SelectionDragHandler<NodeType>;
/** This event handler gets called when a user drags a selection box */ /** This event handler gets called when a user drags a selection box */
onSelectionDrag?: SelectionDragHandler; onSelectionDrag?: SelectionDragHandler<NodeType>;
/** This event handler gets called when a user stops dragging a selection box */ /** This event handler gets called when a user stops dragging a selection box */
onSelectionDragStop?: SelectionDragHandler; onSelectionDragStop?: SelectionDragHandler<NodeType>;
onSelectionStart?: (event: ReactMouseEvent) => void; onSelectionStart?: (event: ReactMouseEvent) => void;
onSelectionEnd?: (event: ReactMouseEvent) => void; onSelectionEnd?: (event: ReactMouseEvent) => void;
onSelectionContextMenu?: (event: ReactMouseEvent, nodes: NodeType[]) => void; onSelectionContextMenu?: (event: ReactMouseEvent, nodes: NodeType[]) => void;
@@ -201,7 +202,7 @@ export interface ReactFlowProps<NodeType extends Node = Node> extends Omit<HTMLA
onClickConnectStart?: OnConnectStart; onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd; onClickConnectEnd?: OnConnectEnd;
/** This event handler gets called when a flow has finished initializing */ /** This event handler gets called when a flow has finished initializing */
onInit?: OnInit<NodeType>; onInit?: OnInit<NodeType, EdgeType>;
/** This event handler is called while the user is either panning or zooming the viewport. */ /** This event handler is called while the user is either panning or zooming the viewport. */
onMove?: OnMove; onMove?: OnMove;
/** This event handler gets called when a user starts to pan or zoom the viewport */ /** This event handler gets called when a user starts to pan or zoom the viewport */
@@ -223,7 +224,7 @@ export interface ReactFlowProps<NodeType extends Node = Node> extends Omit<HTMLA
/** This event handler gets called when mouse leaves the pane */ /** This event handler gets called when mouse leaves the pane */
onPaneMouseLeave?: (event: ReactMouseEvent) => void; onPaneMouseLeave?: (event: ReactMouseEvent) => void;
/** This handler gets called before the user deletes nodes or edges and provides a way to abort the deletion by returning false. */ /** This handler gets called before the user deletes nodes or edges and provides a way to abort the deletion by returning false. */
onBeforeDelete?: OnBeforeDelete<NodeType>; onBeforeDelete?: OnBeforeDelete<NodeType, EdgeType>;
/** Custom node types to be available in a flow. /** Custom node types to be available in a flow.
* *
* React Flow matches a node's type to a component in the nodeTypes object. * React Flow matches a node's type to a component in the nodeTypes object.
+28 -25
View File
@@ -30,7 +30,14 @@ export type EdgeLabelOptions = {
export type EdgeUpdatable = boolean | HandleType; export type EdgeUpdatable = boolean | HandleType;
export type DefaultEdge<EdgeData = any> = EdgeBase<EdgeData> & /**
* The Edge type is mainly used for the `edges` that get passed to the ReactFlow component
* @public
*/
export type Edge<
EdgeData extends Record<string, unknown> = Record<string, unknown>,
EdgeType extends string | undefined = string | undefined
> = EdgeBase<EdgeData, EdgeType> &
EdgeLabelOptions & { EdgeLabelOptions & {
style?: CSSProperties; style?: CSSProperties;
className?: string; className?: string;
@@ -38,45 +45,41 @@ export type DefaultEdge<EdgeData = any> = EdgeBase<EdgeData> &
focusable?: boolean; focusable?: boolean;
}; };
type SmoothStepEdgeType<T> = DefaultEdge<T> & { type SmoothStepEdgeType<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<EdgeData> & {
type: 'smoothstep'; type: 'smoothstep';
pathOptions?: SmoothStepPathOptions; pathOptions?: SmoothStepPathOptions;
}; };
type BezierEdgeType<T> = DefaultEdge<T> & { type BezierEdgeType<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<EdgeData> & {
type: 'default'; type: 'default';
pathOptions?: BezierPathOptions; pathOptions?: BezierPathOptions;
}; };
type StepEdgeType<T> = DefaultEdge<T> & { type StepEdgeType<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<EdgeData> & {
type: 'step'; type: 'step';
pathOptions?: StepPathOptions; pathOptions?: StepPathOptions;
}; };
/** export type BuiltInEdge = SmoothStepEdgeType | BezierEdgeType | StepEdgeType;
* The Edge type is mainly used for the `edges` that get passed to the ReactFlow component
* @public
*/
export type Edge<T = any> = DefaultEdge<T> | SmoothStepEdgeType<T> | BezierEdgeType<T> | StepEdgeType<T>;
export type EdgeMouseHandler = (event: ReactMouseEvent, edge: Edge) => void; export type EdgeMouseHandler<EdgeType extends Edge = Edge> = (event: ReactMouseEvent, edge: EdgeType) => void;
export type EdgeWrapperProps = { export type EdgeWrapperProps<EdgeType extends Edge = Edge> = {
id: string; id: string;
edgesFocusable: boolean; edgesFocusable: boolean;
edgesUpdatable: boolean; edgesUpdatable: boolean;
elementsSelectable: boolean; elementsSelectable: boolean;
noPanClassName: string; noPanClassName: string;
onClick?: EdgeMouseHandler; onClick?: EdgeMouseHandler<EdgeType>;
onDoubleClick?: EdgeMouseHandler; onDoubleClick?: EdgeMouseHandler<EdgeType>;
onEdgeUpdate?: OnEdgeUpdateFunc; onEdgeUpdate?: OnEdgeUpdateFunc<EdgeType>;
onContextMenu?: EdgeMouseHandler; onContextMenu?: EdgeMouseHandler<EdgeType>;
onMouseEnter?: EdgeMouseHandler; onMouseEnter?: EdgeMouseHandler<EdgeType>;
onMouseMove?: EdgeMouseHandler; onMouseMove?: EdgeMouseHandler<EdgeType>;
onMouseLeave?: EdgeMouseHandler; onMouseLeave?: EdgeMouseHandler<EdgeType>;
edgeUpdaterRadius?: number; edgeUpdaterRadius?: number;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void; onEdgeUpdateStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void; onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
rfId?: string; rfId?: string;
edgeTypes?: EdgeTypes; edgeTypes?: EdgeTypes;
onError?: OnError; onError?: OnError;
@@ -94,10 +97,10 @@ export type EdgeTextProps = HTMLAttributes<SVGElement> &
* Custom edge component props * Custom edge component props
* @public * @public
*/ */
export type EdgeProps<T = any> = Pick< export type EdgeProps<
Edge<T>, EdgeData extends Record<string, unknown> = Record<string, unknown>,
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target' EdgeType extends string | undefined = string | undefined
> & > = Pick<Edge<EdgeData, EdgeType>, 'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'> &
EdgePosition & EdgePosition &
EdgeLabelOptions & { EdgeLabelOptions & {
sourceHandleId?: string | null; sourceHandleId?: string | null;
@@ -185,7 +188,7 @@ export type StraightEdgeProps = Omit<EdgeComponentProps, 'sourcePosition' | 'tar
*/ */
export type SimpleBezierEdgeProps = EdgeComponentProps; export type SimpleBezierEdgeProps = EdgeComponentProps;
export type OnEdgeUpdateFunc<T = any> = (oldEdge: Edge<T>, newConnection: Connection) => void; export type OnEdgeUpdateFunc<EdgeType extends Edge = Edge> = (oldEdge: EdgeType, newConnection: Connection) => void;
export type ConnectionLineComponentProps = { export type ConnectionLineComponentProps = {
connectionLineStyle?: CSSProperties; connectionLineStyle?: CSSProperties;
+8 -2
View File
@@ -12,6 +12,7 @@ import {
XYPosition, XYPosition,
NodeProps, NodeProps,
OnBeforeDeleteBase, OnBeforeDeleteBase,
Connection,
} from '@xyflow/system'; } from '@xyflow/system';
import type { NodeChange, EdgeChange, Node, Edge, ReactFlowInstance, EdgeProps } from '.'; import type { NodeChange, EdgeChange, Node, Edge, ReactFlowInstance, EdgeProps } from '.';
@@ -21,8 +22,11 @@ export type OnNodesChange<NodeType extends Node = Node> = (changes: NodeChange<N
export type OnEdgesChange<EdgeType extends Edge = Edge> = (changes: EdgeChange<EdgeType>[]) => void; export type OnEdgesChange<EdgeType extends Edge = Edge> = (changes: EdgeChange<EdgeType>[]) => void;
export type OnNodesDelete<NodeType extends Node = Node> = (nodes: NodeType[]) => void; export type OnNodesDelete<NodeType extends Node = Node> = (nodes: NodeType[]) => void;
export type OnEdgesDelete = (edges: Edge[]) => void; export type OnEdgesDelete<EdgeType extends Edge = Edge> = (edges: EdgeType[]) => void;
export type OnDelete = (params: { nodes: Node[]; edges: Edge[] }) => void; export type OnDelete<NodeType extends Node = Node, EdgeType extends Edge = Edge> = (params: {
nodes: NodeType[];
edges: EdgeType[];
}) => void;
export type NodeTypes = { [key: string]: ComponentType<NodeProps> }; export type NodeTypes = { [key: string]: ComponentType<NodeProps> };
export type EdgeTypes = { [key: string]: ComponentType<EdgeProps> }; export type EdgeTypes = { [key: string]: ComponentType<EdgeProps> };
@@ -139,3 +143,5 @@ export type OnBeforeDelete<NodeType extends Node = Node, EdgeType extends Edge =
NodeType, NodeType,
EdgeType EdgeType
>; >;
export type IsValidConnection<EdgeType extends Edge = Edge> = (edge: EdgeType | Connection) => boolean;
+4 -5
View File
@@ -7,11 +7,10 @@ import { NodeTypes } from './general';
* The node data structure that gets used for the nodes prop. * The node data structure that gets used for the nodes prop.
* @public * @public
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any export type Node<
export type Node<NodeData = any, NodeType extends string | undefined = string | undefined> = NodeBase< NodeData extends Record<string, unknown> = Record<string, unknown>,
NodeData, NodeType extends string | undefined = string | undefined
NodeType > = NodeBase<NodeData, NodeType> & {
> & {
style?: CSSProperties; style?: CSSProperties;
className?: string; className?: string;
resizing?: boolean; resizing?: boolean;
+16 -12
View File
@@ -21,7 +21,6 @@ import {
type OnMoveStart, type OnMoveStart,
type OnMove, type OnMove,
type OnMoveEnd, type OnMoveEnd,
type IsValidConnection,
type UpdateConnection, type UpdateConnection,
type EdgeLookup, type EdgeLookup,
type ConnectionLookup, type ConnectionLookup,
@@ -43,9 +42,10 @@ import type {
OnDelete, OnDelete,
OnNodeDrag, OnNodeDrag,
OnBeforeDelete, OnBeforeDelete,
IsValidConnection,
} from '.'; } from '.';
export type ReactFlowStore<NodeType extends Node = Node> = { export type ReactFlowStore<NodeType extends Node = Node, EdgeType extends Edge = Edge> = {
rfId: string; rfId: string;
width: number; width: number;
height: number; height: number;
@@ -53,10 +53,10 @@ export type ReactFlowStore<NodeType extends Node = Node> = {
nodes: NodeType[]; nodes: NodeType[];
nodeLookup: NodeLookup<NodeType>; nodeLookup: NodeLookup<NodeType>;
edges: Edge[]; edges: Edge[];
edgeLookup: EdgeLookup<Edge>; edgeLookup: EdgeLookup<EdgeType>;
connectionLookup: ConnectionLookup; connectionLookup: ConnectionLookup;
onNodesChange: OnNodesChange<NodeType> | null; onNodesChange: OnNodesChange<NodeType> | null;
onEdgesChange: OnEdgesChange | null; onEdgesChange: OnEdgesChange<EdgeType> | null;
hasDefaultNodes: boolean; hasDefaultNodes: boolean;
hasDefaultEdges: boolean; hasDefaultEdges: boolean;
domNode: HTMLDivElement | null; domNode: HTMLDivElement | null;
@@ -124,8 +124,8 @@ export type ReactFlowStore<NodeType extends Node = Node> = {
fitViewDone: boolean; fitViewDone: boolean;
fitViewOnInitOptions: FitViewOptions | undefined; fitViewOnInitOptions: FitViewOptions | undefined;
onNodesDelete?: OnNodesDelete; onNodesDelete?: OnNodesDelete<NodeType>;
onEdgesDelete?: OnEdgesDelete; onEdgesDelete?: OnEdgesDelete<EdgeType>;
onDelete?: OnDelete; onDelete?: OnDelete;
onError?: OnError; onError?: OnError;
@@ -133,7 +133,7 @@ export type ReactFlowStore<NodeType extends Node = Node> = {
onViewportChangeStart?: OnViewportChange; onViewportChangeStart?: OnViewportChange;
onViewportChange?: OnViewportChange; onViewportChange?: OnViewportChange;
onViewportChangeEnd?: OnViewportChange; onViewportChangeEnd?: OnViewportChange;
onBeforeDelete?: OnBeforeDelete; onBeforeDelete?: OnBeforeDelete<NodeType, EdgeType>;
onSelectionChangeHandlers: OnSelectionChangeFunc[]; onSelectionChangeHandlers: OnSelectionChangeFunc[];
@@ -142,15 +142,15 @@ export type ReactFlowStore<NodeType extends Node = Node> = {
autoPanOnNodeDrag: boolean; autoPanOnNodeDrag: boolean;
connectionRadius: number; connectionRadius: number;
isValidConnection?: IsValidConnection; isValidConnection?: IsValidConnection<EdgeType>;
lib: string; lib: string;
}; };
export type ReactFlowActions<NodeType extends Node> = { export type ReactFlowActions<NodeType extends Node, EdgeType extends Edge> = {
setNodes: (nodes: NodeType[]) => void; setNodes: (nodes: NodeType[]) => void;
setEdges: (edges: Edge[]) => void; setEdges: (edges: EdgeType[]) => void;
setDefaultNodesAndEdges: (nodes?: NodeType[], edges?: Edge[]) => void; setDefaultNodesAndEdges: (nodes?: NodeType[], edges?: EdgeType[]) => void;
updateNodeDimensions: (updates: Map<string, NodeDimensionUpdate>) => void; updateNodeDimensions: (updates: Map<string, NodeDimensionUpdate>) => void;
updateNodePositions: UpdateNodePositions; updateNodePositions: UpdateNodePositions;
resetSelectedElements: () => void; resetSelectedElements: () => void;
@@ -169,4 +169,8 @@ export type ReactFlowActions<NodeType extends Node> = {
fitView: (nodes: NodeType[], options?: FitViewOptions) => boolean; fitView: (nodes: NodeType[], options?: FitViewOptions) => boolean;
}; };
export type ReactFlowState<NodeType extends Node = Node> = ReactFlowStore<NodeType> & ReactFlowActions<NodeType>; export type ReactFlowState<NodeType extends Node = Node, EdgeType extends Edge = Edge> = ReactFlowStore<
NodeType,
EdgeType
> &
ReactFlowActions<NodeType, EdgeType>;
@@ -10,7 +10,6 @@ import type {
OnMoveEnd, OnMoveEnd,
CoordinateExtent, CoordinateExtent,
PanOnScrollMode, PanOnScrollMode,
IsValidConnection,
OnError, OnError,
ConnectionMode, ConnectionMode,
PanelPosition, PanelPosition,
@@ -18,8 +17,7 @@ import type {
ColorMode, ColorMode,
OnConnect, OnConnect,
OnConnectStart, OnConnectStart,
OnConnectEnd, OnConnectEnd
OnBeforeDelete
} from '@xyflow/system'; } from '@xyflow/system';
import type { import type {
@@ -31,7 +29,9 @@ import type {
DefaultEdgeOptions, DefaultEdgeOptions,
FitViewOptions, FitViewOptions,
OnDelete, OnDelete,
OnEdgeCreate OnEdgeCreate,
OnBeforeDelete,
IsValidConnection
} from '$lib/types'; } from '$lib/types';
import type { Writable } from 'svelte/store'; import type { Writable } from 'svelte/store';
@@ -3,7 +3,7 @@ import { derived, type Readable } from 'svelte/store';
import type { Node } from '$lib/types'; import type { Node } from '$lib/types';
import { useStore } from '$lib/store'; import { useStore } from '$lib/store';
function areNodesDataEqual(a: Node['data'][] | null, b: Node['data'][] | null) { function areNodesDataEqual(a: (Node['data'] | null)[] | null, b: (Node['data'] | null)[] | null) {
if ((!a && !b) || (!a?.length && !b?.length)) { if ((!a && !b) || (!a?.length && !b?.length)) {
true; true;
} }
-1
View File
@@ -66,7 +66,6 @@ export {
type OnConnectStart, type OnConnectStart,
type OnConnect, type OnConnect,
type OnConnectEnd, type OnConnectEnd,
type IsValidConnection,
type Viewport, type Viewport,
type SnapGrid, type SnapGrid,
PanOnScrollMode, PanOnScrollMode,
@@ -14,7 +14,6 @@ import {
type MarkerProps, type MarkerProps,
type PanZoomInstance, type PanZoomInstance,
type CoordinateExtent, type CoordinateExtent,
type IsValidConnection,
type NodeOrigin, type NodeOrigin,
type OnError, type OnError,
type Viewport, type Viewport,
@@ -47,7 +46,8 @@ import type {
FitViewOptions, FitViewOptions,
OnDelete, OnDelete,
OnEdgeCreate, OnEdgeCreate,
OnBeforeDelete OnBeforeDelete,
IsValidConnection
} from '$lib/types'; } from '$lib/types';
import { createNodesStore, createEdgesStore } from './utils'; import { createNodesStore, createEdgesStore } from './utils';
import { initConnectionProps, type ConnectionProps } from './derived-connection-props'; import { initConnectionProps, type ConnectionProps } from './derived-connection-props';
+24 -17
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { SvelteComponent, ComponentType } from 'svelte'; import type { SvelteComponent, ComponentType } from 'svelte';
import type { import type {
EdgeBase, EdgeBase,
@@ -11,41 +10,49 @@ import type {
import type { Node } from '$lib/types'; import type { Node } from '$lib/types';
export type DefaultEdge<EdgeData = any> = EdgeBase<EdgeData> & { /**
* The Edge type is mainly used for the `edges` that get passed to the SvelteFlow component.
*/
export type Edge<
EdgeData extends Record<string, unknown> = Record<string, unknown>,
EdgeType extends string | undefined = string | undefined
> = EdgeBase<EdgeData, EdgeType> & {
label?: string; label?: string;
labelStyle?: string; labelStyle?: string;
style?: string; style?: string;
class?: string; class?: string;
}; };
type SmoothStepEdgeType<T> = DefaultEdge<T> & { type SmoothStepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
type: 'smoothstep'; EdgeData,
'smoothstep'
> & {
pathOptions?: SmoothStepPathOptions; pathOptions?: SmoothStepPathOptions;
}; };
type BezierEdgeType<T> = DefaultEdge<T> & { type BezierEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
type: 'default'; EdgeData,
'default'
> & {
pathOptions?: BezierPathOptions; pathOptions?: BezierPathOptions;
}; };
type StepEdgeType<T> = DefaultEdge<T> & { type StepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
type: 'step'; EdgeData,
'step'
> & {
pathOptions?: StepPathOptions; pathOptions?: StepPathOptions;
}; };
/** export type BuiltInEdge = SmoothStepEdge | BezierEdge | StepEdge;
* The Edge type is mainly used for the `edges` that get passed to the SvelteFlow component.
*/
export type Edge<T = any> =
| DefaultEdge<T>
| SmoothStepEdgeType<T>
| BezierEdgeType<T>
| StepEdgeType<T>;
/** /**
* Custom edge component props. * Custom edge component props.
*/ */
export type EdgeProps<T = any> = Omit<Edge<T>, 'sourceHandle' | 'targetHandle' | 'type'> & export type EdgeProps<
EdgeData extends Record<string, unknown> = Record<string, unknown>,
EdgeType extends string | undefined = string | undefined
> = Omit<Edge<EdgeData, EdgeType>, 'sourceHandle' | 'targetHandle' | 'type'> &
EdgePosition & { EdgePosition & {
markerStart?: string; markerStart?: string;
markerEnd?: string; markerEnd?: string;
+4
View File
@@ -57,3 +57,7 @@ export type OnBeforeDelete<
NodeType extends Node = Node, NodeType extends Node = Node,
EdgeType extends Edge = Edge EdgeType extends Edge = Edge
> = OnBeforeDeleteBase<NodeType, EdgeType>; > = OnBeforeDeleteBase<NodeType, EdgeType>;
export type IsValidConnection<EdgeType extends Edge = Edge> = (
edge: EdgeType | Connection
) => boolean;
+3 -1
View File
@@ -7,7 +7,7 @@ import type { NodeBase, NodeProps } from '@xyflow/system';
* @public * @public
*/ */
export type Node< export type Node<
NodeData = any, NodeData extends Record<string, unknown> = Record<string, unknown>,
NodeType extends string | undefined = string | undefined NodeType extends string | undefined = string | undefined
> = NodeBase<NodeData, NodeType> & { > = NodeBase<NodeData, NodeType> & {
class?: string; class?: string;
@@ -17,3 +17,5 @@ export type Node<
export type NodeTypes = Record<string, ComponentType<SvelteComponent<NodeProps>>>; export type NodeTypes = Record<string, ComponentType<SvelteComponent<NodeProps>>>;
export type DefaultNodeOptions = Partial<Omit<Node, 'id'>>; export type DefaultNodeOptions = Partial<Omit<Node, 'id'>>;
export type BuiltInNode = Node<{ label: string }, 'input' | 'output' | 'default'>;
+5 -2
View File
@@ -1,11 +1,14 @@
import { Position } from './utils'; import { Position } from './utils';
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EdgeBase<EdgeData = any> = { export type EdgeBase<
EdgeData extends Record<string, unknown> = Record<string, unknown>,
EdgeType extends string | undefined = string | undefined
> = {
/** Unique id of an edge */ /** Unique id of an edge */
id: string; id: string;
/** Type of an edge defined in edgeTypes */ /** Type of an edge defined in edgeTypes */
type?: string; type?: EdgeType;
/** Id of source node */ /** Id of source node */
source: string; source: string;
/** Id of target node */ /** Id of target node */
+7 -4
View File
@@ -9,7 +9,10 @@ import { Optional } from '../utils/types';
* @typeParam T - type of the node data * @typeParam T - type of the node data
* @typeParam U - type of the node * @typeParam U - type of the node
*/ */
export type NodeBase<T = any, U extends string | undefined = string | undefined> = { export type NodeBase<
NodeData extends Record<string, unknown> = Record<string, unknown>,
NodeType extends string | undefined = string | undefined
> = {
/** Unique id of a node */ /** Unique id of a node */
id: string; id: string;
/** Position of a node on the pane /** Position of a node on the pane
@@ -17,9 +20,9 @@ export type NodeBase<T = any, U extends string | undefined = string | undefined>
*/ */
position: XYPosition; position: XYPosition;
/** Arbitrary data passed to a node */ /** Arbitrary data passed to a node */
data: T; data: NodeData;
/** Type of node defined in nodeTypes */ /** Type of node defined in nodeTypes */
type?: U; type?: NodeType;
/** Only relevant for default, source, target nodeType. controls source position /** Only relevant for default, source, target nodeType. controls source position
* @example 'right', 'left', 'top', 'bottom' * @example 'right', 'left', 'top', 'bottom'
*/ */
@@ -70,7 +73,7 @@ export type NodeBase<T = any, U extends string | undefined = string | undefined>
/** Holds a reference to the original node object provided by the user /** Holds a reference to the original node object provided by the user
* (which may lack some fields, like `computed` or `[internalSymbol]`. Used * (which may lack some fields, like `computed` or `[internalSymbol]`. Used
* as an optimization to avoid certain operations. */ * as an optimization to avoid certain operations. */
userProvidedNode: NodeBase<T, U>; userProvidedNode: NodeBase<NodeData, NodeType>;
}; };
}; };