Merge pull request #3966 from xyflow/next

React Flow 12.0.0-next.10 & Svelte Flow 0.0.37
This commit is contained in:
Moritz Klack
2024-02-29 20:03:33 +01:00
committed by GitHub
96 changed files with 1478 additions and 838 deletions
@@ -81,6 +81,8 @@ const initialNodes: Node[] = [
id: '4',
data: { label: 'Node 4' },
position: { x: 400, y: 200 },
width: 200,
height: 50,
type: 'custom',
},
];
@@ -0,0 +1,21 @@
import { memo, useState } from 'react';
import { Handle, Position } from '@xyflow/react';
function CustomNode() {
const [text, setText] = useState('this is a pretty long text');
return (
<>
<Handle type="target" position={Position.Top} />
<div style={{ background: '#eee', padding: 10 }}>
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<div>text: {text}</div>
</div>
</div>
<Handle type="source" position={Position.Bottom} />
</>
);
}
export default memo(CustomNode);
@@ -0,0 +1,69 @@
import { useCallback } from 'react';
import {
ReactFlow,
addEdge,
useEdgesState,
useNodesState,
Background,
Controls,
type Connection,
type Edge,
type Node,
} from '@xyflow/react';
import CustomNode from './CustomNode';
import '@xyflow/react/dist/style.css';
const initialNodes: Node[] = [
{
id: '1',
data: {},
position: { x: 0, y: 0 },
initialWidth: 200,
initialHeight: 50,
type: 'custom',
},
{
id: '2',
data: {},
position: { x: 0, y: 200 },
width: 200,
initialHeight: 50,
type: 'custom',
},
];
const initialEdges: Edge[] = [{ id: 'e1-2', source: '1', target: '2' }];
const nodeTypes = {
custom: CustomNode,
};
function Flow() {
const [nodes, , onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect = useCallback((params: Connection | Edge) => setEdges((eds) => addEdge(params, eds)), [setEdges]);
return (
<div style={{ width: 700, height: 400 }}>
<ReactFlow
nodes={nodes}
onNodesChange={onNodesChange}
edges={edges}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
nodeTypes={nodeTypes}
fitView
width={700}
height={400}
debug
>
<Background />
<Controls />
</ReactFlow>
</div>
);
}
export default Flow;
@@ -0,0 +1,25 @@
<script lang="ts">
import { Handle, Position, type NodeProps } from '@xyflow/svelte';
type $$Props = NodeProps;
let text = 'some default text';
</script>
<Handle type="target" position={Position.Left} />
<div class="custom">
<div>
text: {text}
</div>
<input type="text" bind:value={text} />
</div>
<Handle type="source" position={Position.Right} />
<style>
.custom {
background-color: white;
padding: 10px;
border: 1px solid #777;
border-radius: 20px;
}
</style>
@@ -0,0 +1,39 @@
<script lang="ts">
import { writable } from 'svelte/store';
import { SvelteFlow, Controls, Background, BackgroundVariant, type Node, type Edge } from '@xyflow/svelte';
import '@xyflow/svelte/dist/style.css';
import CustomNode from './CustomNode.svelte';
const nodes = writable<Node[]>([
{
id: '1',
position: { x: 0, y: 0 },
data: {},
initialWidth: 100,
initialHeight: 40,
type: 'input-node',
},
{
id: '2',
position: { x: 0, y: 150 },
data: {},
initialWidth: 100,
initialHeight: 40,
type: 'input-node',
},
]);
const edges = writable<Edge[]>([{ id: '1-2', source: '1', target: '2' }]);
const nodeTypes = {
'input-node': CustomNode,
};
</script>
<div style="height: 400px; width: 700px;">
<SvelteFlow {nodes} {edges} {nodeTypes} fitView width={700} height={400}>
<Controls />
<Background variant={BackgroundVariant.Dots} />
</SvelteFlow>
</div>
+20 -4
View File
@@ -1,6 +1,8 @@
---
import ReactFlowApp from '../components/ReactFlowExample'
import SvelteFlowApp from '../components/SvelteFlowExample/index.svelte'
import ReactFlowApp from '../components/ReactFlowExample';
import ReactFlowInitialApp from '../components/ReactFlowInitialExample';
import SvelteFlowApp from '../components/SvelteFlowExample/index.svelte';
import SvelteFlowInitialApp from '../components/SvelteFlowInitialExample/index.svelte';
---
<html lang="en">
@@ -18,10 +20,24 @@ import SvelteFlowApp from '../components/SvelteFlowExample/index.svelte'
</style>
</head>
<body>
<h2>React Flow</h2>
<p>no client hydration</p>
<ReactFlowApp />
<p>client hydration on load (client:load)</p>
<ReactFlowApp client:load />
<p>client hydration on load (client:load) and initialWidth / initialHeight</p>
<ReactFlowInitialApp client:load />
<h2>Svelte Flow</h2>
<SvelteFlowApp />
<h2>React Flow</h2>
<ReactFlowApp />
<p>client hydration on load (client:load)</p>
<SvelteFlowApp client:load />
<p>client hydration on load (client:load) and initialWidth / initialHeight</p>
<SvelteFlowInitialApp client:load />
</body>
</html>
+6
View File
@@ -49,6 +49,7 @@ import UseConnection from '../examples/UseConnection';
import UseNodesInitialized from '../examples/UseNodesInit';
import UseNodesData from '../examples/UseNodesData';
import UseHandleConnections from '../examples/UseHandleConnections';
import AddNodeOnEdgeDrop from '../examples/AddNodeOnEdgeDrop';
export interface IRoute {
name: string;
@@ -57,6 +58,11 @@ export interface IRoute {
}
const routes: IRoute[] = [
{
name: 'Add Node on edge Drop',
path: 'add-node-edge-drop',
component: AddNodeOnEdgeDrop,
},
{
name: 'Basic',
path: 'basic',
@@ -0,0 +1,99 @@
import { useCallback, useRef } from 'react';
import {
ReactFlow,
useNodesState,
useEdgesState,
addEdge,
useReactFlow,
ReactFlowProvider,
OnConnect,
OnConnectStart,
OnConnectEnd,
Node,
Edge,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
const initialNodes: Node[] = [
{
id: '0',
type: 'input',
data: { label: 'Node' },
position: { x: 0, y: 50 },
},
];
const initialEdges: Edge[] = [];
let id = 1;
const getId = () => `${id++}`;
const AddNodeOnEdgeDrop = () => {
const reactFlowWrapper = useRef(null);
const connectingNodeId = useRef<string | null>(null);
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const { screenToFlowPosition } = useReactFlow();
const onConnect: OnConnect = useCallback((params) => {
// reset the start node on connections
connectingNodeId.current = null;
setEdges((eds) => addEdge(params, eds));
}, []);
const onConnectStart: OnConnectStart = useCallback((_, { nodeId }) => {
connectingNodeId.current = nodeId;
}, []);
const onConnectEnd: OnConnectEnd = useCallback(
(event) => {
if (!connectingNodeId.current) return;
const targetIsPane = (event.target as HTMLDivElement)?.classList.contains('react-flow__pane');
if (targetIsPane && 'clientX' in event && 'clientY' in event) {
// we need to remove the wrapper bounds, in order to get the correct position
const id = getId();
const newNode: Node = {
id,
position: screenToFlowPosition({
x: event.clientX,
y: event.clientY,
}),
data: { label: `Node ${id}` },
origin: [0.5, 0.0],
};
const newEdge: Edge = {
id,
source: connectingNodeId.current,
target: id,
};
setNodes((nds) => nds.concat(newNode));
setEdges((eds) => eds.concat(newEdge));
}
},
[screenToFlowPosition]
);
return (
<div className="wrapper" ref={reactFlowWrapper} style={{ height: '100%' }}>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onConnectStart={onConnectStart}
onConnectEnd={onConnectEnd}
fitView
/>
</div>
);
};
export default () => (
<ReactFlowProvider>
<AddNodeOnEdgeDrop />
</ReactFlowProvider>
);
+9 -2
View File
@@ -13,10 +13,13 @@ import {
OnNodeDrag,
} from '@xyflow/react';
const onNodeDrag: OnNodeDrag = (_, node) => console.log('drag', node);
const onNodeDragStop = (_: MouseEvent, node: Node) => console.log('drag stop', node);
const onNodeDrag: OnNodeDrag = (_, node: Node, nodes: Node[]) => console.log('drag', node, nodes);
const onNodeDragStart = (_: MouseEvent, node: Node, nodes: Node[]) => console.log('drag start', node, nodes);
const onNodeDragStop = (_: MouseEvent, node: Node, nodes: Node[]) => console.log('drag stop', node, nodes);
const onNodeClick = (_: MouseEvent, node: Node) => console.log('click', node);
const printSelectionEvent = (name: string) => (_: MouseEvent, nodes: Node[]) => console.log(name, nodes);
const initialNodes: Node[] = [
{
id: '1',
@@ -113,7 +116,11 @@ const BasicFlow = () => {
defaultEdges={initialEdges}
onNodeClick={onNodeClick}
onNodeDragStop={onNodeDragStop}
onNodeDragStart={onNodeDragStart}
onNodeDrag={onNodeDrag}
onSelectionDragStart={printSelectionEvent('selection drag start')}
onSelectionDrag={printSelectionEvent('selection drag')}
onSelectionDragStop={printSelectionEvent('selection drag stop')}
className="react-flow-basic-example"
minZoom={0.2}
maxZoom={4}
@@ -9,13 +9,14 @@ import {
SnapGrid,
useEdgesState,
Background,
Edge,
OnNodeDrag,
OnInit,
applyNodeChanges,
OnNodesChange,
OnConnect,
OnBeforeDelete,
BuiltInNode,
BuiltInEdge,
} from '@xyflow/react';
import ColorSelectorNode from './ColorSelectorNode';
@@ -24,9 +25,10 @@ export type ColorSelectorNode = Node<
{ color: string; onChange: (event: ChangeEvent<HTMLInputElement>) => void },
'selectorNode'
>;
export type MyNode = Node | ColorSelectorNode;
export type MyNode = BuiltInNode | ColorSelectorNode;
export type MyEdge = BuiltInEdge;
const onInit: OnInit<MyNode> = (reactFlowInstance) => {
const onInit: OnInit<MyNode, MyEdge> = (reactFlowInstance) => {
console.log('flow loaded:', reactFlowInstance);
};
@@ -44,7 +46,7 @@ const nodeTypes = {
const CustomNodeFlow = () => {
const [nodes, setNodes] = useState<MyNode[]>([]);
const onNodesChange: OnNodesChange = useCallback(
const onNodesChange: OnNodesChange<MyNode> = useCallback(
(changes) =>
setNodes((nds) => {
const nextNodes = applyNodeChanges(changes, nds);
@@ -53,7 +55,7 @@ const CustomNodeFlow = () => {
[setNodes]
);
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
const [edges, setEdges, onEdgesChange] = useEdgesState<MyEdge>([]);
const [bgColor, setBgColor] = useState<string>(initBgColor);
@@ -61,7 +63,7 @@ const CustomNodeFlow = () => {
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
setNodes((nds) =>
nds.map((node) => {
if (node.id !== '2') {
if (node.id !== '2' || node.type !== 'selectorNode') {
return node;
}
@@ -143,7 +145,7 @@ const CustomNodeFlow = () => {
[setEdges]
);
const onBeforeDelete: OnBeforeDelete<MyNode> = useCallback(async (params) => true, []);
const onBeforeDelete: OnBeforeDelete<MyNode, MyEdge> = useCallback(async (params) => true, []);
return (
<ReactFlow
@@ -164,7 +166,7 @@ const CustomNodeFlow = () => {
maxZoom={2}
onBeforeDelete={onBeforeDelete}
>
<MiniMap
<MiniMap<MyNode>
nodeStrokeColor={(n: MyNode): string => {
if (n.type === 'input') return '#0041d0';
if (n.type === 'selectorNode') return bgColor;
@@ -14,7 +14,7 @@ const initialNodes: Node[] = [
dragHandle: '.custom-drag-handle',
style: { border: '1px solid #ddd', padding: '20px 40px' },
position: { x: 200, y: 200 },
data: null,
data: {},
},
];
@@ -50,7 +50,9 @@ const initialNodes: Node[] = [
maxHeight: 200,
},
position: { x: 0, y: 60 },
style: { ...nodeStyle, width: 100, height: 80 },
width: 100,
height: 80,
style: { ...nodeStyle },
},
{
id: '1b',
@@ -64,9 +66,9 @@ const initialNodes: Node[] = [
maxHeight: 400,
},
position: { x: 250, y: 0 },
width: 174,
height: 123,
style: {
width: 174,
height: 123,
...nodeStyle,
},
},
@@ -75,7 +77,9 @@ const initialNodes: Node[] = [
type: 'customResizer',
data: { label: 'custom resize icon' },
position: { x: 0, y: 200 },
style: { width: 100, height: 60, ...nodeStyle },
width: 100,
height: 60,
style: { ...nodeStyle },
},
{
id: '3',
@@ -94,7 +98,8 @@ const initialNodes: Node[] = [
keepAspectRatio: true,
},
position: { x: 400, y: 200 },
style: { ...nodeStyle, height: 50 },
height: 50,
style: { ...nodeStyle },
},
{
id: '4',
@@ -121,7 +126,9 @@ const initialNodes: Node[] = [
type: 'defaultResizer',
data: { label: 'Parent', keepAspectRatio: true },
position: { x: 700, y: 0 },
style: { ...nodeStyle, width: 300, height: 400 },
width: 300,
height: 400,
style: { ...nodeStyle },
},
{
id: '5a',
@@ -132,7 +139,9 @@ const initialNodes: Node[] = [
position: { x: 50, y: 50 },
parentNode: '5',
extent: 'parent',
style: { ...nodeStyle, width: 50, height: 100 },
width: 50,
height: 100,
style: { ...nodeStyle },
},
{
id: '5b',
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import { ReactFlow, Node, Edge, useNodesState, useEdgesState, Position, Connection, addEdge } from '@xyflow/react';
import styles from './touch-device.module.css';
import './touch-device.css';
const initialNodes: Node[] = [
{
@@ -42,7 +42,7 @@ const TouchDeviceFlow = () => {
onConnectEnd={onConnectEnd}
onClickConnectStart={onClickConnectStart}
onClickConnectEnd={onClickConnectEnd}
className={styles.flow}
className="touch-flow"
/>
);
};
@@ -0,0 +1,27 @@
.react-flow.touch-flow .react-flow__handle {
width: 20px;
height: 20px;
border-radius: 3px;
background-color: #9f7aea;
}
.touch-flow .react-flow__handle-right {
--translate: translate(50%, -50%);
}
.touch-flow .react-flow__handle-left {
--translate: translate(-50%, -50%);
}
@keyframes bounce {
0% {
transform: var(--translate) scale(1);
}
50% {
transform: var(--translate) scale(1.1);
}
}
.react-flow.touch-flow .react-flow__handle.clickconnecting {
animation: bounce 1600ms infinite ease-in;
}
@@ -1,19 +0,0 @@
.flow :global .react-flow__handle {
width: 20px;
height: 20px;
border-radius: 3px;
background-color: #9f7aea;
}
.flow :global .react-flow__handle.connecting {
animation: bounce 1600ms infinite ease-out;
}
@keyframes bounce {
0% {
transform: translate(0, -50%) scale(1);
}
50% {
transform: translate(0, -50%) scale(1.1);
}
}
@@ -1,20 +1,18 @@
import { memo } from 'react';
import { Handle, Position, useHandleConnections, useNodesData } from '@xyflow/react';
import { isTextNode, type MyNode } from '.';
function ResultNode() {
const connections = useHandleConnections({
type: 'target',
});
const nodesData = useNodesData(connections.map((connection) => connection.source));
const nodesData = useNodesData<MyNode>(connections.map((connection) => connection.source));
const textNodes = nodesData.filter(isTextNode);
return (
<div style={{ background: '#eee', color: '#222', padding: 10, fontSize: 12, borderRadius: 10 }}>
<Handle type="target" position={Position.Left} />
<div>
incoming texts:{' '}
{nodesData?.filter((nodeData) => nodeData.text !== undefined).map(({ text }, i) => <div key={i}>{text}</div>) ||
'none'}
</div>
<div>incoming texts: {textNodes.map(({ data }, i) => <div key={i}>{data.text}</div>) || 'none'}</div>
</div>
);
}
@@ -1,16 +1,18 @@
import { memo, useEffect } from 'react';
import { Position, NodeProps, useReactFlow, Handle, useHandleConnections, useNodesData } from '@xyflow/react';
import { isTextNode, type TextNode, type MyNode } from '.';
function UppercaseNode({ id }: NodeProps) {
const { updateNodeData } = useReactFlow();
const connections = useHandleConnections({
type: 'target',
});
const nodeData = useNodesData(connections[0]?.source);
const nodesData = useNodesData<MyNode>(connections[0]?.source);
const textNode = isTextNode(nodesData) ? nodesData : null;
useEffect(() => {
updateNodeData(id, { text: nodeData?.text.toUpperCase() });
}, [nodeData]);
updateNodeData(id, { text: textNode?.data.text.toUpperCase() });
}, [textNode]);
return (
<div style={{ background: '#eee', color: '#222', padding: 10, fontSize: 12, borderRadius: 10 }}>
@@ -17,8 +17,12 @@ import UppercaseNode from './UppercaseNode';
export type TextNode = Node<{ text: string }, 'text'>;
export type ResultNode = Node<{}, 'result'>;
export type UppercaseNode = Node<{}, 'uppercase'>;
export type MyNode = Node | TextNode | ResultNode | UppercaseNode;
export type UppercaseNode = Node<{ text: string }, 'uppercase'>;
export type MyNode = TextNode | ResultNode | UppercaseNode;
export function isTextNode(node: any): node is TextNode {
return node.type === 'text';
}
const nodeTypes = {
text: TextNode,
@@ -38,7 +42,7 @@ const initNodes: MyNode[] = [
{
id: '1a',
type: 'uppercase',
data: {},
data: { text: '' },
position: { x: 100, y: 0 },
},
{
@@ -24,10 +24,14 @@
background: #fff;
}
.validationflow :global .connecting {
.validationflow :global .connectingto {
background: #ff6060;
}
.validationflow :global .react-flow__node-custominput .connectingfrom {
background: #55dd99;
}
.validationflow :global .valid {
background: #55dd99;
}
@@ -23,7 +23,8 @@
'usenodesdata',
'usesvelteflow',
'useupdatenodeinternals',
'validation'
'validation',
'reset'
];
const onChange = (event: Event) => {
@@ -111,9 +111,10 @@
{
id: '5a',
type: 'defaultResizer',
data: { label: 'Child' },
data: { label: 'Child with extent parent' },
position: { x: 50, y: 50 },
parentNode: '5',
extent: 'parent',
style: nodeStyle
},
{
@@ -137,6 +138,7 @@
maxZoom={5}
snapGrid={snapToGrid ? [10, 10] : undefined}
fitView
nodeOrigin={[0.5, 0.5]}
>
<Controls />
<Panel position="bottom-right">
@@ -0,0 +1,43 @@
<script lang="ts">
import { writable } from 'svelte/store';
import {
SvelteFlow,
Controls,
Background,
MiniMap,
type Node,
type Edge,
type NodeTypes
} from '@xyflow/svelte';
import '@xyflow/svelte/dist/style.css';
const nodes = writable<Node[]>([]);
const edges = writable<Edge[]>([]);
const resetNodesArray = () => {
const node1: Node = {
id: 'c1',
data: { label: '1' },
position: { x: 0, y: 0 }
};
const node2: Node = {
id: 'c2',
data: { label: '2' },
position: { x: 100, y: 0 }
};
$nodes = [node1, node2];
};
</script>
<button on:click={resetNodesArray}> Reset </button>
<div style:height="100vh">
<SvelteFlow {nodes} {edges} fitView>
<Controls />
<Background />
<MiniMap />
</SvelteFlow>
</div>
@@ -1,3 +1,17 @@
<script context="module" lang="ts">
import type { Node } from '@xyflow/svelte';
type TextNodeType = Node<{ text: string }, 'text'>;
type UppercaseNodeType = Node<{ text: string }, 'uppercase'>;
type ResultNodeType = Node<{}, 'result'>;
export function isTextNode(node: any): node is TextNodeType {
return node.type === 'text';
}
export type MyNode = TextNodeType | UppercaseNodeType | ResultNodeType;
</script>
<script lang="ts">
import { writable } from 'svelte/store';
import {
@@ -6,7 +20,6 @@
Background,
BackgroundVariant,
MiniMap,
type Node,
type NodeTypes,
type Edge
} from '@xyflow/svelte';
@@ -22,7 +35,7 @@
result: ResultNode
};
const nodes = writable<Node[]>([
const nodes = writable<MyNode[]>([
{
id: '1',
type: 'text',
@@ -34,7 +47,9 @@
{
id: '1a',
type: 'uppercase',
data: {},
data: {
text: ''
},
position: { x: 100, y: 0 }
},
{
@@ -6,6 +6,7 @@
useNodesData,
type NodeProps
} from '@xyflow/svelte';
import { isTextNode, type MyNode } from './+page.svelte';
type $$Props = NodeProps;
@@ -16,15 +17,16 @@
type: 'target'
});
$: nodeData = useNodesData($connections.map((connection) => connection.source));
$: nodeData = useNodesData<MyNode>($connections.map((connection) => connection.source));
$: textNodes = $nodeData.filter(isTextNode);
</script>
<div class="custom">
<Handle type="target" position={Position.Left} />
<div>incoming texts:</div>
{#each $nodeData as data}
<div>{data.text}</div>
{#each textNodes as textNode}
<div>{textNode.data.text}</div>
{/each}
</div>
@@ -7,6 +7,7 @@
useSvelteFlow,
type NodeProps
} from '@xyflow/svelte';
import { isTextNode, type MyNode } from './+page.svelte';
type $$Props = NodeProps;
@@ -18,10 +19,11 @@
type: 'target'
});
$: nodeData = useNodesData($connections[0]?.source);
$: nodeData = useNodesData<MyNode>($connections[0]?.source);
$: textNode = isTextNode($nodeData) ? $nodeData : null;
$: {
updateNodeData(id, { text: $nodeData?.text?.toUpperCase() || '' });
updateNodeData(id, { text: textNode?.data.text.toUpperCase() || '' });
}
</script>
@@ -1,7 +1,11 @@
.svelte-flow__handle.connecting {
.svelte-flow__handle.connectingto {
background: #ff6060;
}
.svelte-flow__handle.connectingfrom {
background: #55dd99;
}
.svelte-flow__handle.valid {
background: #55dd99;
}
+15
View File
@@ -1,5 +1,20 @@
# @xyflow/react
## 12.0.0-next.10
## ⚠️ Breaking changes
- `useNodesData` not only returns data objects but also the type and the id of the node
- status class names for Handle components are slightly different. It's now "connectingfrom" and "connectingto" instead of "connecting"
## Patch changes
- better cursor defaults for the pane, nodes and edges
- `disableKeyboardA11y` now also disables Enter and Escape for selecting/deselecting nodes and edges
- fix bug where users couldn't drag a node after toggle nodes `hidden` attribute
- add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr
- fix `NodeResizer` when used in combination with `nodeOrigin`
## 12.0.0-next.9
### Patch changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@xyflow/react",
"version": "12.0.0-next.9",
"version": "12.0.0-next.10",
"description": "React Flow - A highly customizable React library for building node-based editors and interactive flow charts.",
"keywords": [
"react",
@@ -7,7 +7,7 @@ import { getNodesBounds, getBoundsOfRects, XYMinimap, type Rect, type XYMinimapI
import { useStore, useStoreApi } from '../../hooks/useStore';
import { Panel } from '../../components/Panel';
import type { ReactFlowState } from '../../types';
import type { ReactFlowState, Node } from '../../types';
import MiniMapNodes from './MiniMapNodes';
import type { MiniMapProps } from './types';
@@ -38,7 +38,7 @@ const selector = (s: ReactFlowState) => {
const ARIA_LABEL_KEY = 'react-flow__minimap-desc';
function MiniMapComponent({
function MiniMapComponent<NodeType extends Node = Node>({
style,
className,
nodeStrokeColor,
@@ -62,8 +62,8 @@ function MiniMapComponent({
inversePan,
zoomStep = 10,
offsetScale = 5,
}: MiniMapProps) {
const store = useStoreApi();
}: MiniMapProps<NodeType>) {
const store = useStoreApi<NodeType>();
const svg = useRef<SVGSVGElement>(null);
const { boundingRect, viewBB, rfId, panZoom, translateExtent, flowWidth, flowHeight } = useStore(selector, shallow);
const elementWidth = (style?.width as number) ?? defaultWidth;
@@ -155,7 +155,7 @@ function MiniMapComponent({
onClick={onSvgClick}
>
{ariaLabel && <title id={labelledBy}>{ariaLabel}</title>}
<MiniMapNodes
<MiniMapNodes<NodeType>
onClick={onSvgNodeClick}
nodeColor={nodeColor}
nodeStrokeColor={nodeStrokeColor}
@@ -178,4 +178,4 @@ function MiniMapComponent({
MiniMapComponent.displayName = 'MiniMap';
export const MiniMap = memo(MiniMapComponent);
export const MiniMap = memo(MiniMapComponent) as typeof MiniMapComponent;
@@ -1,21 +1,22 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ComponentType, memo } from 'react';
import { NodeOrigin, getNodePositionWithOrigin } from '@xyflow/system';
import { NodeOrigin, getNodeDimensions, getNodePositionWithOrigin, nodeHasDimensions } from '@xyflow/system';
import { shallow } from 'zustand/shallow';
import { useStore } from '../../hooks/useStore';
import { MiniMapNode } from './MiniMapNode';
import type { ReactFlowState } from '../../types';
import type { ReactFlowState, Node } from '../../types';
import type { MiniMapNodes as MiniMapNodesProps, GetMiniMapNodeAttribute, MiniMapNodeProps } from './types';
declare const window: any;
const selector = (s: ReactFlowState) => s.nodeOrigin;
const selectorNodeIds = (s: ReactFlowState) => s.nodes.map((node) => node.id);
const getAttrFunction = (func: any): GetMiniMapNodeAttribute => (func instanceof Function ? func : () => func);
const getAttrFunction = <NodeType extends Node>(func: any): GetMiniMapNodeAttribute<NodeType> =>
func instanceof Function ? func : () => func;
function MiniMapNodes({
function MiniMapNodes<NodeType extends Node>({
nodeStrokeColor,
nodeColor,
nodeClassName = '',
@@ -25,12 +26,12 @@ function MiniMapNodes({
// a component properly.
nodeComponent: NodeComponent = MiniMapNode,
onClick,
}: MiniMapNodesProps) {
}: MiniMapNodesProps<NodeType>) {
const nodeIds = useStore(selectorNodeIds, shallow);
const nodeOrigin = useStore(selector);
const nodeColorFunc = getAttrFunction(nodeColor);
const nodeStrokeColorFunc = getAttrFunction(nodeStrokeColor);
const nodeClassNameFunc = getAttrFunction(nodeClassName);
const nodeColorFunc = getAttrFunction<NodeType>(nodeColor);
const nodeStrokeColorFunc = getAttrFunction<NodeType>(nodeStrokeColor);
const nodeClassNameFunc = getAttrFunction<NodeType>(nodeClassName);
const shapeRendering = typeof window === 'undefined' || !!window.chrome ? 'crispEdges' : 'geometricPrecision';
@@ -42,7 +43,7 @@ function MiniMapNodes({
// minimize the cost of updates when individual nodes change.
//
// For more details, see a similar commit in `NodeRenderer/index.tsx`.
<NodeComponentWrapper
<NodeComponentWrapper<NodeType>
key={nodeId}
id={nodeId}
nodeOrigin={nodeOrigin}
@@ -60,7 +61,7 @@ function MiniMapNodes({
);
}
const NodeComponentWrapper = memo(function NodeComponentWrapper({
function NodeComponentWrapperInner<NodeType extends Node>({
id,
nodeOrigin,
nodeColorFunc,
@@ -74,9 +75,9 @@ const NodeComponentWrapper = memo(function NodeComponentWrapper({
}: {
id: string;
nodeOrigin: NodeOrigin;
nodeColorFunc: GetMiniMapNodeAttribute;
nodeStrokeColorFunc: GetMiniMapNodeAttribute;
nodeClassNameFunc: GetMiniMapNodeAttribute;
nodeColorFunc: GetMiniMapNodeAttribute<NodeType>;
nodeStrokeColorFunc: GetMiniMapNodeAttribute<NodeType>;
nodeClassNameFunc: GetMiniMapNodeAttribute<NodeType>;
nodeBorderRadius: number;
nodeStrokeWidth?: number;
NodeComponent: ComponentType<MiniMapNodeProps>;
@@ -84,7 +85,7 @@ const NodeComponentWrapper = memo(function NodeComponentWrapper({
shapeRendering: string;
}) {
const { node, x, y } = useStore((s) => {
const node = s.nodeLookup.get(id);
const node = s.nodeLookup.get(id) as NodeType;
const { x, y } = getNodePositionWithOrigin(node, node?.origin || nodeOrigin).positionAbsolute;
return {
@@ -93,16 +94,19 @@ const NodeComponentWrapper = memo(function NodeComponentWrapper({
y,
};
}, shallow);
if (!node || node.hidden || !(node.computed?.width || node.width) || !(node.computed?.height || node.height)) {
if (!node || node.hidden || !nodeHasDimensions(node)) {
return null;
}
const { width, height } = getNodeDimensions(node);
return (
<NodeComponent
x={x}
y={y}
width={node.computed?.width ?? node.width ?? 0}
height={node.computed?.height ?? node.height ?? 0}
width={width}
height={height}
style={node.style}
selected={!!node.selected}
className={nodeClassNameFunc(node)}
@@ -115,6 +119,8 @@ const NodeComponentWrapper = memo(function NodeComponentWrapper({
id={node.id}
/>
);
});
}
export default memo(MiniMapNodes);
const NodeComponentWrapper = memo(NodeComponentWrapperInner) as typeof NodeComponentWrapperInner;
export default memo(MiniMapNodes) as typeof MiniMapNodes;
@@ -50,12 +50,13 @@ function ResizeControl({
domNode: resizeControlRef.current,
nodeId: id,
getStoreItems: () => {
const { nodeLookup, transform, snapGrid, snapToGrid } = store.getState();
const { nodeLookup, transform, snapGrid, snapToGrid, nodeOrigin } = store.getState();
return {
nodeLookup,
transform,
snapGrid,
snapToGrid,
nodeOrigin,
};
},
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
@@ -5,20 +5,20 @@ import { EdgeAnchor } from '../Edges/EdgeAnchor';
import type { EdgeWrapperProps, Edge } from '../../types/edges';
import { useStoreApi } from '../../hooks/useStore';
type EdgeUpdateAnchorsProps = {
edge: Edge;
type EdgeUpdateAnchorsProps<EdgeType extends Edge = Edge> = {
edge: EdgeType;
isUpdatable: boolean | 'source' | 'target';
edgeUpdaterRadius: EdgeWrapperProps['edgeUpdaterRadius'];
sourceHandleId: Edge['sourceHandle'];
targetHandleId: Edge['targetHandle'];
onEdgeUpdate: EdgeWrapperProps['onEdgeUpdate'];
onEdgeUpdateStart: EdgeWrapperProps['onEdgeUpdateStart'];
onEdgeUpdateEnd: EdgeWrapperProps['onEdgeUpdateEnd'];
onEdgeUpdate: EdgeWrapperProps<EdgeType>['onEdgeUpdate'];
onEdgeUpdateStart: EdgeWrapperProps<EdgeType>['onEdgeUpdateStart'];
onEdgeUpdateEnd: EdgeWrapperProps<EdgeType>['onEdgeUpdateEnd'];
setUpdateHover: (hover: boolean) => void;
setUpdating: (updating: boolean) => void;
} & EdgePosition;
export function EdgeUpdateAnchors({
export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
isUpdatable,
edgeUpdaterRadius,
edge,
@@ -35,7 +35,7 @@ export function EdgeUpdateAnchors({
onEdgeUpdateEnd,
setUpdating,
setUpdateHover,
}: EdgeUpdateAnchorsProps) {
}: EdgeUpdateAnchorsProps<EdgeType>) {
const store = useStoreApi();
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 { builtinEdgeTypes, nullPosition } from './utils';
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,
edgesFocusable,
edgesUpdatable,
@@ -34,8 +34,9 @@ export function EdgeWrapper({
edgeTypes,
noPanClassName,
onError,
}: EdgeWrapperProps): JSX.Element | null {
let edge = useStore((s) => s.edgeLookup.get(id)!);
disableKeyboardA11y,
}: EdgeWrapperProps<EdgeType>): JSX.Element | null {
let edge = useStore((s) => s.edgeLookup.get(id)!) as EdgeType;
const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
edge = defaultEdgeOptions ? { ...defaultEdgeOptions, ...edge } : edge;
@@ -160,7 +161,7 @@ export function EdgeWrapper({
: undefined;
const onKeyDown = (event: KeyboardEvent) => {
if (elementSelectionKeys.includes(event.key) && isSelectable) {
if (!disableKeyboardA11y && elementSelectionKeys.includes(event.key) && isSelectable) {
const { unselectNodesAndEdges, addSelectedEdges } = store.getState();
const unselect = event.key === 'Escape';
@@ -236,7 +237,7 @@ export function EdgeWrapper({
/>
)}
{isUpdatable && (
<EdgeUpdateAnchors
<EdgeUpdateAnchors<EdgeType>
edge={edge}
isUpdatable={isUpdatable}
edgeUpdaterRadius={edgeUpdaterRadius}
+27 -7
View File
@@ -16,6 +16,7 @@ import {
type HandleProps,
type Connection,
type HandleType,
ConnectionMode,
} from '@xyflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore';
@@ -36,14 +37,24 @@ const connectingSelector =
connectionStartHandle: startHandle,
connectionEndHandle: endHandle,
connectionClickStartHandle: clickHandle,
connectionMode,
connectionStatus,
} = state;
const connectingTo = endHandle?.nodeId === nodeId && endHandle?.handleId === handleId && endHandle?.type === type;
return {
connecting:
(startHandle?.nodeId === nodeId && startHandle?.handleId === handleId && startHandle?.type === type) ||
(endHandle?.nodeId === nodeId && endHandle?.handleId === handleId && endHandle?.type === type),
connectingFrom:
startHandle?.nodeId === nodeId && startHandle?.handleId === handleId && startHandle?.type === type,
connectingTo,
clickConnecting:
clickHandle?.nodeId === nodeId && clickHandle?.handleId === handleId && clickHandle?.type === type,
isPossibleEndHandle:
connectionMode === ConnectionMode.Strict
? startHandle?.type !== type
: nodeId !== startHandle?.nodeId || handleId !== startHandle?.handleId,
connectionInProcess: !!startHandle,
valid: connectingTo && connectionStatus === 'valid',
};
};
@@ -71,7 +82,10 @@ const HandleComponent = forwardRef<HTMLDivElement, HandleComponentProps>(
const store = useStoreApi();
const nodeId = useNodeId();
const { connectOnClick, noPanClassName, rfId } = useStore(selector, shallow);
const { connecting, clickConnecting } = useStore(connectingSelector(nodeId, handleId, type), shallow);
const { connectingFrom, connectingTo, clickConnecting, isPossibleEndHandle, connectionInProcess, valid } = useStore(
connectingSelector(nodeId, handleId, type),
shallow
);
if (!nodeId) {
store.getState().onError?.('010', errorMessages['error010']());
@@ -201,10 +215,16 @@ const HandleComponent = forwardRef<HTMLDivElement, HandleComponentProps>(
connectable: isConnectable,
connectablestart: isConnectableStart,
connectableend: isConnectableEnd,
connecting: clickConnecting,
// this class is used to style the handle when the user is connecting
clickconnecting: clickConnecting,
connectingfrom: connectingFrom,
connectingto: connectingTo,
valid,
// shows where you can start a connection from
// and where you can end it while connecting
connectionindicator:
isConnectable && ((isConnectableStart && !connecting) || (isConnectableEnd && connecting)),
isConnectable &&
(!connectionInProcess || isPossibleEndHandle) &&
(connectionInProcess ? isConnectableEnd : isConnectableStart),
},
])}
onMouseDown={onPointerDown}
@@ -5,9 +5,11 @@ import {
clampPosition,
elementSelectionKeys,
errorMessages,
getNodeDimensions,
getPositionWithOrigin,
internalsSymbol,
isInputDOMNode,
nodeHasDimensions,
} from '@xyflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore';
@@ -16,10 +18,10 @@ import { ARIA_NODE_DESC_KEY } from '../A11yDescriptions';
import { useDrag } from '../../hooks/useDrag';
import { useMoveSelectedNodes } from '../../hooks/useMoveSelectedNodes';
import { handleNodeClick } from '../Nodes/utils';
import { arrowKeyDiffs, builtinNodeTypes } from './utils';
import type { NodeWrapperProps } from '../../types';
import { arrowKeyDiffs, builtinNodeTypes, getNodeInlineStyleDimensions } from './utils';
import type { Node, NodeWrapperProps } from '../../types';
export function NodeWrapper({
export function NodeWrapper<NodeType extends Node>({
id,
onClick,
onMouseEnter,
@@ -40,9 +42,9 @@ export function NodeWrapper({
nodeExtent,
nodeOrigin,
onError,
}: NodeWrapperProps) {
}: NodeWrapperProps<NodeType>) {
const { node, positionAbsoluteX, positionAbsoluteY, zIndex, isParent } = useStore((s) => {
const node = s.nodeLookup.get(id)!;
const node = s.nodeLookup.get(id)! as NodeType;
const positionAbsolute = nodeExtent
? clampPosition(node.computed?.positionAbsolute, nodeExtent)
@@ -79,11 +81,9 @@ export function NodeWrapper({
const prevTargetPosition = useRef(node.targetPosition);
const prevType = useRef(nodeType);
const width = node.width ?? undefined;
const height = node.height ?? undefined;
const computedWidth = node.computed?.width;
const computedHeight = node.computed?.height;
const initialized = (!!computedWidth && !!computedHeight) || (!!width && !!height);
const nodeDimensions = getNodeDimensions(node);
const inlineDimensions = getNodeInlineStyleDimensions(node);
const initialized = nodeHasDimensions(node);
const hasHandleBounds = !!node[internalsSymbol]?.handleBounds;
const moveSelectedNodes = useMoveSelectedNodes();
@@ -143,8 +143,7 @@ export function NodeWrapper({
const positionAbsoluteOrigin = getPositionWithOrigin({
x: positionAbsoluteX,
y: positionAbsoluteY,
width: computedWidth ?? width ?? 0,
height: computedHeight ?? height ?? 0,
...nodeDimensions,
origin: node.origin || nodeOrigin,
});
const hasPointerEvents = isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave;
@@ -174,7 +173,7 @@ export function NodeWrapper({
};
const onKeyDown = (event: KeyboardEvent) => {
if (isInputDOMNode(event.nativeEvent)) {
if (isInputDOMNode(event.nativeEvent) || disableKeyboardA11y) {
return;
}
@@ -187,12 +186,7 @@ export function NodeWrapper({
unselect,
nodeRef,
});
} else if (
!disableKeyboardA11y &&
isDraggable &&
node.selected &&
Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)
) {
} else if (isDraggable && node.selected && Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
store.setState({
ariaLiveMessage: `Moved selected node ${event.key
.replace('Arrow', '')
@@ -220,6 +214,7 @@ export function NodeWrapper({
selected: node.selected,
selectable: isSelectable,
parent: isParent,
draggable: isDraggable,
dragging,
},
])}
@@ -230,8 +225,7 @@ export function NodeWrapper({
pointerEvents: hasPointerEvents ? 'all' : 'none',
visibility: initialized ? 'visible' : 'hidden',
...node.style,
width: width ?? node.style?.width,
height: height ?? node.style?.height,
...inlineDimensions,
}}
data-id={id}
data-testid={`rf__node-${id}`}
@@ -252,8 +246,6 @@ export function NodeWrapper({
id={id}
data={node.data}
type={nodeType}
width={computedWidth}
height={computedHeight}
positionAbsoluteX={positionAbsoluteX}
positionAbsoluteY={positionAbsoluteY}
selected={node.selected}
@@ -263,6 +255,7 @@ export function NodeWrapper({
dragging={dragging}
dragHandle={node.dragHandle}
zIndex={zIndex}
{...nodeDimensions}
/>
</Provider>
</div>
@@ -5,7 +5,7 @@ import { InputNode } from '../Nodes/InputNode';
import { DefaultNode } from '../Nodes/DefaultNode';
import { GroupNode } from '../Nodes/GroupNode';
import { OutputNode } from '../Nodes/OutputNode';
import type { NodeTypes } from '../../types';
import type { Node, NodeTypes } from '../../types';
export const arrowKeyDiffs: Record<string, XYPosition> = {
ArrowUp: { x: 0, y: -1 },
@@ -20,3 +20,22 @@ export const builtinNodeTypes: NodeTypes = {
output: OutputNode as ComponentType<NodeProps>,
group: GroupNode as ComponentType<NodeProps>,
};
export function getNodeInlineStyleDimensions<NodeType extends Node = Node>(
node: NodeType
): {
width: number | string | undefined;
height: number | string | undefined;
} {
if (!node.computed) {
return {
width: node.width ?? node.initialWidth ?? node.style?.width,
height: node.height ?? node.initialHeight ?? node.style?.height,
};
}
return {
width: node.width ?? node.style?.width,
height: node.height ?? node.style?.height,
};
}
@@ -2,7 +2,6 @@
* The nodes selection rectangle gets displayed when a user
* made a selection with on or several nodes
*/
import { useRef, useEffect, type MouseEvent, type KeyboardEvent } from 'react';
import cc from 'classcat';
import { shallow } from 'zustand/shallow';
@@ -14,8 +13,8 @@ import { useMoveSelectedNodes } from '../../hooks/useMoveSelectedNodes';
import { arrowKeyDiffs } from '../NodeWrapper/utils';
import type { Node, ReactFlowState } from '../../types';
export type NodesSelectionProps = {
onSelectionContextMenu?: (event: MouseEvent, nodes: Node[]) => void;
export type NodesSelectionProps<NodeType> = {
onSelectionContextMenu?: (event: MouseEvent, nodes: NodeType[]) => void;
noPanClassName?: string;
disableKeyboardA11y: boolean;
};
@@ -32,8 +31,12 @@ const selector = (s: ReactFlowState) => {
};
};
export function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }: NodesSelectionProps) {
const store = useStoreApi();
export function NodesSelection<NodeType extends Node>({
onSelectionContextMenu,
noPanClassName,
disableKeyboardA11y,
}: NodesSelectionProps<NodeType>) {
const store = useStoreApi<NodeType>();
const { width, height, transformString, userSelectionActive } = useStore(selector, shallow);
const moveSelectedNodes = useMoveSelectedNodes();
@@ -65,10 +65,16 @@ const reactFlowFieldsToTrack = [
'selectNodesOnDrag',
'nodeDragThreshold',
'onBeforeDelete',
'debug',
] as const;
type ReactFlowFieldsToTrack = (typeof reactFlowFieldsToTrack)[number];
type StoreUpdaterProps = Pick<ReactFlowProps, ReactFlowFieldsToTrack> & { rfId: string };
type StoreUpdaterProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> = Pick<
ReactFlowProps<NodeType, EdgeType>,
ReactFlowFieldsToTrack
> & {
rfId: string;
};
// rfId doesn't exist in ReactFlowProps, but it's one of the fields we want to update
const fieldsToTrack = [...reactFlowFieldsToTrack, 'rfId'] as const;
@@ -97,7 +103,9 @@ const initPrevValues = {
rfId: '1',
};
export function StoreUpdater(props: StoreUpdaterProps) {
export function StoreUpdater<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
props: StoreUpdaterProps<NodeType, EdgeType>
) {
const {
setNodes,
setEdges,
@@ -108,7 +116,7 @@ export function StoreUpdater(props: StoreUpdaterProps) {
reset,
setDefaultNodesAndEdges,
} = useStore(selector, shallow);
const store = useStoreApi();
const store = useStoreApi<NodeType, EdgeType>();
useEffect(() => {
setDefaultNodesAndEdges(props.defaultNodes, props.defaultEdges);
@@ -120,7 +128,7 @@ export function StoreUpdater(props: StoreUpdaterProps) {
};
}, []);
const previousFields = useRef<Partial<StoreUpdaterProps>>(initPrevValues);
const previousFields = useRef<Partial<StoreUpdaterProps<NodeType, EdgeType>>>(initPrevValues);
useEffect(
() => {
@@ -6,10 +6,10 @@ import { useVisibleEdgeIds } from '../../hooks/useVisibleEdgeIds';
import MarkerDefinitions from './MarkerDefinitions';
import { GraphViewProps } from '../GraphView';
import { EdgeWrapper } from '../../components/EdgeWrapper';
import type { ReactFlowState } from '../../types';
import type { Edge, ReactFlowState, Node } from '../../types';
type EdgeRendererProps = Pick<
GraphViewProps,
type EdgeRendererProps<EdgeType extends Edge = Edge> = Pick<
GraphViewProps<Node, EdgeType>,
| 'onEdgeClick'
| 'onEdgeDoubleClick'
| 'defaultMarkerColor'
@@ -40,7 +40,7 @@ const selector = (s: ReactFlowState) => ({
onError: s.onError,
});
function EdgeRendererComponent({
function EdgeRendererComponent<EdgeType extends Edge = Edge>({
defaultMarkerColor,
onlyRenderVisibleElements,
rfId,
@@ -56,7 +56,8 @@ function EdgeRendererComponent({
onEdgeDoubleClick,
onEdgeUpdateStart,
onEdgeUpdateEnd,
}: EdgeRendererProps) {
disableKeyboardA11y,
}: EdgeRendererProps<EdgeType>) {
const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
const edgeIds = useVisibleEdgeIds(onlyRenderVisibleElements);
@@ -66,7 +67,7 @@ function EdgeRendererComponent({
{edgeIds.map((id) => {
return (
<EdgeWrapper
<EdgeWrapper<EdgeType>
key={id}
id={id}
edgesFocusable={edgesFocusable}
@@ -86,6 +87,7 @@ function EdgeRendererComponent({
rfId={rfId}
onError={onError}
edgeTypes={edgeTypes}
disableKeyboardA11y={disableKeyboardA11y}
/>
);
})}
@@ -95,4 +97,4 @@ function EdgeRendererComponent({
EdgeRendererComponent.displayName = 'EdgeRenderer';
export const EdgeRenderer = memo(EdgeRendererComponent);
export const EdgeRenderer = memo(EdgeRendererComponent) as typeof EdgeRendererComponent;
@@ -7,10 +7,10 @@ import { GraphViewProps } from '../GraphView';
import { ZoomPane } from '../ZoomPane';
import { Pane } from '../Pane';
import { NodesSelection } from '../../components/NodesSelection';
import type { ReactFlowState } from '../../types';
import type { ReactFlowState, Node } from '../../types';
export type FlowRendererProps = Omit<
GraphViewProps,
export type FlowRendererProps<NodeType extends Node = Node> = Omit<
GraphViewProps<NodeType>,
| 'snapToGrid'
| 'nodeTypes'
| 'edgeTypes'
@@ -32,7 +32,7 @@ const selector = (s: ReactFlowState) => {
return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive };
};
const FlowRendererComponent = ({
function FlowRendererComponent<NodeType extends Node = Node>({
children,
onPaneClick,
onPaneMouseEnter,
@@ -68,7 +68,7 @@ const FlowRendererComponent = ({
disableKeyboardA11y,
onViewportChange,
isControlledViewport,
}: FlowRendererProps) => {
}: FlowRendererProps<NodeType>) {
const { nodesSelectionActive, userSelectionActive } = useStore(selector);
const selectionKeyPressed = useKeyPress(selectionKeyCode);
const panActivationKeyPressed = useKeyPress(panActivationKeyCode);
@@ -125,8 +125,8 @@ const FlowRendererComponent = ({
</Pane>
</ZoomPane>
);
};
}
FlowRendererComponent.displayName = 'FlowRenderer';
export const FlowRenderer = memo(FlowRendererComponent);
export const FlowRenderer = memo(FlowRendererComponent) as typeof FlowRendererComponent;
@@ -8,15 +8,15 @@ import { useOnInitHandler } from '../../hooks/useOnInitHandler';
import { useViewportSync } from '../../hooks/useViewportSync';
import { ConnectionLineWrapper } from '../../components/ConnectionLine';
import { useNodeOrEdgeTypesWarning } from './useNodeOrEdgeTypesWarning';
import type { ReactFlowProps } from '../../types';
import type { Edge, Node, ReactFlowProps } from '../../types';
export type GraphViewProps = Omit<
ReactFlowProps,
export type GraphViewProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> = Omit<
ReactFlowProps<NodeType, EdgeType>,
'onSelectionChange' | 'nodes' | 'edges' | 'onMove' | 'onMoveStart' | 'onMoveEnd' | 'elevateEdgesOnSelect'
> &
Required<
Pick<
ReactFlowProps,
ReactFlowProps<NodeType, EdgeType>,
| 'selectionKeyCode'
| 'deleteKeyCode'
| 'multiSelectionKeyCode'
@@ -37,7 +37,7 @@ export type GraphViewProps = Omit<
rfId: string;
};
function GraphViewComponent({
function GraphViewComponent<NodeType extends Node = Node, EdgeType extends Edge = Edge>({
nodeTypes,
edgeTypes,
onInit,
@@ -101,7 +101,7 @@ function GraphViewComponent({
rfId,
viewport,
onViewportChange,
}: GraphViewProps) {
}: GraphViewProps<NodeType, EdgeType>) {
useNodeOrEdgeTypesWarning(nodeTypes);
useNodeOrEdgeTypesWarning(edgeTypes);
@@ -109,7 +109,7 @@ function GraphViewComponent({
useViewportSync(viewport);
return (
<FlowRenderer
<FlowRenderer<NodeType>
onPaneClick={onPaneClick}
onPaneMouseEnter={onPaneMouseEnter}
onPaneMouseMove={onPaneMouseMove}
@@ -147,7 +147,7 @@ function GraphViewComponent({
isControlledViewport={!!viewport}
>
<Viewport>
<EdgeRenderer
<EdgeRenderer<EdgeType>
edgeTypes={edgeTypes}
onEdgeClick={onEdgeClick}
onEdgeDoubleClick={onEdgeDoubleClick}
@@ -173,7 +173,7 @@ function GraphViewComponent({
/>
<div className="react-flow__edgelabel-renderer" />
<div className="react-flow__viewport-portal" />
<NodeRenderer
<NodeRenderer<NodeType>
nodeTypes={nodeTypes}
onNodeClick={onNodeClick}
onNodeDoubleClick={onNodeDoubleClick}
@@ -196,4 +196,4 @@ function GraphViewComponent({
GraphViewComponent.displayName = 'GraphView';
export const GraphView = memo(GraphViewComponent);
export const GraphView = memo(GraphViewComponent) as typeof GraphViewComponent;
@@ -7,10 +7,10 @@ import { containerStyle } from '../../styles/utils';
import { GraphViewProps } from '../GraphView';
import { useResizeObserver } from './useResizeObserver';
import { NodeWrapper } from '../../components/NodeWrapper';
import type { ReactFlowState } from '../../types';
import type { Node, ReactFlowState } from '../../types';
export type NodeRendererProps = Pick<
GraphViewProps,
export type NodeRendererProps<NodeType extends Node> = Pick<
GraphViewProps<NodeType>,
| 'onNodeClick'
| 'onNodeDoubleClick'
| 'onNodeMouseEnter'
@@ -35,7 +35,7 @@ const selector = (s: ReactFlowState) => ({
onError: s.onError,
});
const NodeRendererComponent = (props: NodeRendererProps) => {
function NodeRendererComponent<NodeType extends Node>(props: NodeRendererProps<NodeType>) {
const { nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, onError } = useStore(selector, shallow);
const nodeIds = useVisibleNodeIds(props.onlyRenderVisibleElements);
const resizeObserver = useResizeObserver();
@@ -67,7 +67,7 @@ const NodeRendererComponent = (props: NodeRendererProps) => {
// moved into `NodeComponentWrapper`. This ensures they are
// memorized so if `NodeRenderer` *has* to rerender, it only
// needs to regenerate the list of nodes, nothing else.
<NodeWrapper
<NodeWrapper<NodeType>
key={nodeId}
id={nodeId}
nodeTypes={props.nodeTypes}
@@ -94,8 +94,8 @@ const NodeRendererComponent = (props: NodeRendererProps) => {
})}
</div>
);
};
}
NodeRendererComponent.displayName = 'NodeRenderer';
export const NodeRenderer = memo(NodeRendererComponent);
export const NodeRenderer = memo(NodeRendererComponent) as typeof NodeRendererComponent;
+1 -1
View File
@@ -220,7 +220,7 @@ export function Pane({
return (
<div
className={cc(['react-flow__pane', { dragging, selection: isSelecting }])}
className={cc(['react-flow__pane', { draggable: panOnDrag, dragging, selection: isSelecting }])}
onClick={hasActiveSelection ? undefined : wrapHandler(onClick, container)}
onContextMenu={wrapHandler(onContextMenu, container)}
onWheel={wrapHandler(onWheel, container)}
+262 -272
View File
@@ -1,4 +1,4 @@
import { forwardRef, type CSSProperties } from 'react';
import { ForwardedRef, forwardRef, type CSSProperties } from 'react';
import cc from 'classcat';
import { ConnectionLineType, PanOnScrollMode, SelectionMode, infiniteExtent, isMacOs } from '@xyflow/system';
@@ -9,7 +9,7 @@ import { StoreUpdater } from '../../components/StoreUpdater';
import { useColorModeClass } from '../../hooks/useColorModeClass';
import { GraphView } from '../GraphView';
import { Wrapper } from './Wrapper';
import type { ReactFlowProps, ReactFlowRefType } from '../../types';
import type { Edge, Node, ReactFlowProps, ReactFlowRefType } from '../../types';
import { defaultViewport as initViewport, defaultNodeOrigin } from './init-values';
const wrapperStyle: CSSProperties = {
@@ -20,280 +20,270 @@ const wrapperStyle: CSSProperties = {
zIndex: 0,
};
const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
(
{
nodes,
edges,
defaultNodes,
defaultEdges,
className,
nodeTypes,
edgeTypes,
onNodeClick,
onEdgeClick,
onInit,
onMove,
onMoveStart,
onMoveEnd,
onConnect,
onConnectStart,
onConnectEnd,
onClickConnectStart,
onClickConnectEnd,
onNodeMouseEnter,
onNodeMouseMove,
onNodeMouseLeave,
onNodeContextMenu,
onNodeDoubleClick,
onNodeDragStart,
onNodeDrag,
onNodeDragStop,
onNodesDelete,
onEdgesDelete,
onDelete,
onSelectionChange,
onSelectionDragStart,
onSelectionDrag,
onSelectionDragStop,
onSelectionContextMenu,
onSelectionStart,
onSelectionEnd,
onBeforeDelete,
connectionMode,
connectionLineType = ConnectionLineType.Bezier,
connectionLineStyle,
connectionLineComponent,
connectionLineContainerStyle,
deleteKeyCode = 'Backspace',
selectionKeyCode = 'Shift',
selectionOnDrag = false,
selectionMode = SelectionMode.Full,
panActivationKeyCode = 'Space',
multiSelectionKeyCode = isMacOs() ? 'Meta' : 'Control',
zoomActivationKeyCode = isMacOs() ? 'Meta' : 'Control',
snapToGrid,
snapGrid,
onlyRenderVisibleElements = false,
selectNodesOnDrag,
nodesDraggable,
nodesConnectable,
nodesFocusable,
nodeOrigin = defaultNodeOrigin,
edgesFocusable,
edgesUpdatable,
elementsSelectable = true,
defaultViewport = initViewport,
minZoom = 0.5,
maxZoom = 2,
translateExtent = infiniteExtent,
preventScrolling = true,
nodeExtent,
defaultMarkerColor = '#b1b1b7',
zoomOnScroll = true,
zoomOnPinch = true,
panOnScroll = false,
panOnScrollSpeed = 0.5,
panOnScrollMode = PanOnScrollMode.Free,
zoomOnDoubleClick = true,
panOnDrag = true,
onPaneClick,
onPaneMouseEnter,
onPaneMouseMove,
onPaneMouseLeave,
onPaneScroll,
onPaneContextMenu,
children,
onEdgeUpdate,
onEdgeContextMenu,
onEdgeDoubleClick,
onEdgeMouseEnter,
onEdgeMouseMove,
onEdgeMouseLeave,
onEdgeUpdateStart,
onEdgeUpdateEnd,
edgeUpdaterRadius = 10,
onNodesChange,
onEdgesChange,
noDragClassName = 'nodrag',
noWheelClassName = 'nowheel',
noPanClassName = 'nopan',
fitView,
fitViewOptions,
connectOnClick,
attributionPosition,
proOptions,
defaultEdgeOptions,
elevateNodesOnSelect,
elevateEdgesOnSelect,
disableKeyboardA11y = false,
autoPanOnConnect,
autoPanOnNodeDrag,
connectionRadius,
isValidConnection,
onError,
style,
id,
nodeDragThreshold,
viewport,
onViewportChange,
width,
height,
colorMode = 'light',
...rest
},
ref
) => {
const rfId = id || '1';
const colorModeClassName = useColorModeClass(colorMode);
function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
{
nodes,
edges,
defaultNodes,
defaultEdges,
className,
nodeTypes,
edgeTypes,
onNodeClick,
onEdgeClick,
onInit,
onMove,
onMoveStart,
onMoveEnd,
onConnect,
onConnectStart,
onConnectEnd,
onClickConnectStart,
onClickConnectEnd,
onNodeMouseEnter,
onNodeMouseMove,
onNodeMouseLeave,
onNodeContextMenu,
onNodeDoubleClick,
onNodeDragStart,
onNodeDrag,
onNodeDragStop,
onNodesDelete,
onEdgesDelete,
onDelete,
onSelectionChange,
onSelectionDragStart,
onSelectionDrag,
onSelectionDragStop,
onSelectionContextMenu,
onSelectionStart,
onSelectionEnd,
onBeforeDelete,
connectionMode,
connectionLineType = ConnectionLineType.Bezier,
connectionLineStyle,
connectionLineComponent,
connectionLineContainerStyle,
deleteKeyCode = 'Backspace',
selectionKeyCode = 'Shift',
selectionOnDrag = false,
selectionMode = SelectionMode.Full,
panActivationKeyCode = 'Space',
multiSelectionKeyCode = isMacOs() ? 'Meta' : 'Control',
zoomActivationKeyCode = isMacOs() ? 'Meta' : 'Control',
snapToGrid,
snapGrid,
onlyRenderVisibleElements = false,
selectNodesOnDrag,
nodesDraggable,
nodesConnectable,
nodesFocusable,
nodeOrigin = defaultNodeOrigin,
edgesFocusable,
edgesUpdatable,
elementsSelectable = true,
defaultViewport = initViewport,
minZoom = 0.5,
maxZoom = 2,
translateExtent = infiniteExtent,
preventScrolling = true,
nodeExtent,
defaultMarkerColor = '#b1b1b7',
zoomOnScroll = true,
zoomOnPinch = true,
panOnScroll = false,
panOnScrollSpeed = 0.5,
panOnScrollMode = PanOnScrollMode.Free,
zoomOnDoubleClick = true,
panOnDrag = true,
onPaneClick,
onPaneMouseEnter,
onPaneMouseMove,
onPaneMouseLeave,
onPaneScroll,
onPaneContextMenu,
children,
onEdgeUpdate,
onEdgeContextMenu,
onEdgeDoubleClick,
onEdgeMouseEnter,
onEdgeMouseMove,
onEdgeMouseLeave,
onEdgeUpdateStart,
onEdgeUpdateEnd,
edgeUpdaterRadius = 10,
onNodesChange,
onEdgesChange,
noDragClassName = 'nodrag',
noWheelClassName = 'nowheel',
noPanClassName = 'nopan',
fitView,
fitViewOptions,
connectOnClick,
attributionPosition,
proOptions,
defaultEdgeOptions,
elevateNodesOnSelect,
elevateEdgesOnSelect,
disableKeyboardA11y = false,
autoPanOnConnect,
autoPanOnNodeDrag,
connectionRadius,
isValidConnection,
onError,
style,
id,
nodeDragThreshold,
viewport,
onViewportChange,
width,
height,
colorMode = 'light',
debug,
...rest
}: ReactFlowProps<NodeType, EdgeType>,
ref: ForwardedRef<ReactFlowRefType>
) {
const rfId = id || '1';
const colorModeClassName = useColorModeClass(colorMode);
return (
<div
{...rest}
style={{ ...style, ...wrapperStyle }}
ref={ref}
className={cc(['react-flow', className, colorModeClassName])}
data-testid="rf__wrapper"
id={id}
>
<Wrapper
return (
<div
{...rest}
style={{ ...style, ...wrapperStyle }}
ref={ref}
className={cc(['react-flow', className, colorModeClassName])}
data-testid="rf__wrapper"
id={id}
>
<Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}>
<GraphView<NodeType, EdgeType>
onInit={onInit}
onNodeClick={onNodeClick}
onEdgeClick={onEdgeClick}
onNodeMouseEnter={onNodeMouseEnter}
onNodeMouseMove={onNodeMouseMove}
onNodeMouseLeave={onNodeMouseLeave}
onNodeContextMenu={onNodeContextMenu}
onNodeDoubleClick={onNodeDoubleClick}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
connectionLineType={connectionLineType}
connectionLineStyle={connectionLineStyle}
connectionLineComponent={connectionLineComponent}
connectionLineContainerStyle={connectionLineContainerStyle}
selectionKeyCode={selectionKeyCode}
selectionOnDrag={selectionOnDrag}
selectionMode={selectionMode}
deleteKeyCode={deleteKeyCode}
multiSelectionKeyCode={multiSelectionKeyCode}
panActivationKeyCode={panActivationKeyCode}
zoomActivationKeyCode={zoomActivationKeyCode}
onlyRenderVisibleElements={onlyRenderVisibleElements}
defaultViewport={defaultViewport}
translateExtent={translateExtent}
minZoom={minZoom}
maxZoom={maxZoom}
preventScrolling={preventScrolling}
zoomOnScroll={zoomOnScroll}
zoomOnPinch={zoomOnPinch}
zoomOnDoubleClick={zoomOnDoubleClick}
panOnScroll={panOnScroll}
panOnScrollSpeed={panOnScrollSpeed}
panOnScrollMode={panOnScrollMode}
panOnDrag={panOnDrag}
onPaneClick={onPaneClick}
onPaneMouseEnter={onPaneMouseEnter}
onPaneMouseMove={onPaneMouseMove}
onPaneMouseLeave={onPaneMouseLeave}
onPaneScroll={onPaneScroll}
onPaneContextMenu={onPaneContextMenu}
onSelectionContextMenu={onSelectionContextMenu}
onSelectionStart={onSelectionStart}
onSelectionEnd={onSelectionEnd}
onEdgeUpdate={onEdgeUpdate}
onEdgeContextMenu={onEdgeContextMenu}
onEdgeDoubleClick={onEdgeDoubleClick}
onEdgeMouseEnter={onEdgeMouseEnter}
onEdgeMouseMove={onEdgeMouseMove}
onEdgeMouseLeave={onEdgeMouseLeave}
onEdgeUpdateStart={onEdgeUpdateStart}
onEdgeUpdateEnd={onEdgeUpdateEnd}
edgeUpdaterRadius={edgeUpdaterRadius}
defaultMarkerColor={defaultMarkerColor}
noDragClassName={noDragClassName}
noWheelClassName={noWheelClassName}
noPanClassName={noPanClassName}
rfId={rfId}
disableKeyboardA11y={disableKeyboardA11y}
nodeOrigin={nodeOrigin}
nodeExtent={nodeExtent}
viewport={viewport}
onViewportChange={onViewportChange}
/>
<StoreUpdater<NodeType, EdgeType>
nodes={nodes}
edges={edges}
defaultNodes={defaultNodes}
defaultEdges={defaultEdges}
width={width}
height={height}
onConnect={onConnect}
onConnectStart={onConnectStart}
onConnectEnd={onConnectEnd}
onClickConnectStart={onClickConnectStart}
onClickConnectEnd={onClickConnectEnd}
nodesDraggable={nodesDraggable}
nodesConnectable={nodesConnectable}
nodesFocusable={nodesFocusable}
edgesFocusable={edgesFocusable}
edgesUpdatable={edgesUpdatable}
elementsSelectable={elementsSelectable}
elevateNodesOnSelect={elevateNodesOnSelect}
elevateEdgesOnSelect={elevateEdgesOnSelect}
minZoom={minZoom}
maxZoom={maxZoom}
nodeExtent={nodeExtent}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
snapToGrid={snapToGrid}
snapGrid={snapGrid}
connectionMode={connectionMode}
translateExtent={translateExtent}
connectOnClick={connectOnClick}
defaultEdgeOptions={defaultEdgeOptions}
fitView={fitView}
>
<GraphView
onInit={onInit}
onNodeClick={onNodeClick}
onEdgeClick={onEdgeClick}
onNodeMouseEnter={onNodeMouseEnter}
onNodeMouseMove={onNodeMouseMove}
onNodeMouseLeave={onNodeMouseLeave}
onNodeContextMenu={onNodeContextMenu}
onNodeDoubleClick={onNodeDoubleClick}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
connectionLineType={connectionLineType}
connectionLineStyle={connectionLineStyle}
connectionLineComponent={connectionLineComponent}
connectionLineContainerStyle={connectionLineContainerStyle}
selectionKeyCode={selectionKeyCode}
selectionOnDrag={selectionOnDrag}
selectionMode={selectionMode}
deleteKeyCode={deleteKeyCode}
multiSelectionKeyCode={multiSelectionKeyCode}
panActivationKeyCode={panActivationKeyCode}
zoomActivationKeyCode={zoomActivationKeyCode}
onlyRenderVisibleElements={onlyRenderVisibleElements}
defaultViewport={defaultViewport}
translateExtent={translateExtent}
minZoom={minZoom}
maxZoom={maxZoom}
preventScrolling={preventScrolling}
zoomOnScroll={zoomOnScroll}
zoomOnPinch={zoomOnPinch}
zoomOnDoubleClick={zoomOnDoubleClick}
panOnScroll={panOnScroll}
panOnScrollSpeed={panOnScrollSpeed}
panOnScrollMode={panOnScrollMode}
panOnDrag={panOnDrag}
onPaneClick={onPaneClick}
onPaneMouseEnter={onPaneMouseEnter}
onPaneMouseMove={onPaneMouseMove}
onPaneMouseLeave={onPaneMouseLeave}
onPaneScroll={onPaneScroll}
onPaneContextMenu={onPaneContextMenu}
onSelectionContextMenu={onSelectionContextMenu}
onSelectionStart={onSelectionStart}
onSelectionEnd={onSelectionEnd}
onEdgeUpdate={onEdgeUpdate}
onEdgeContextMenu={onEdgeContextMenu}
onEdgeDoubleClick={onEdgeDoubleClick}
onEdgeMouseEnter={onEdgeMouseEnter}
onEdgeMouseMove={onEdgeMouseMove}
onEdgeMouseLeave={onEdgeMouseLeave}
onEdgeUpdateStart={onEdgeUpdateStart}
onEdgeUpdateEnd={onEdgeUpdateEnd}
edgeUpdaterRadius={edgeUpdaterRadius}
defaultMarkerColor={defaultMarkerColor}
noDragClassName={noDragClassName}
noWheelClassName={noWheelClassName}
noPanClassName={noPanClassName}
rfId={rfId}
disableKeyboardA11y={disableKeyboardA11y}
nodeOrigin={nodeOrigin}
nodeExtent={nodeExtent}
viewport={viewport}
onViewportChange={onViewportChange}
/>
<StoreUpdater
nodes={nodes}
edges={edges}
defaultNodes={defaultNodes}
defaultEdges={defaultEdges}
onConnect={onConnect}
onConnectStart={onConnectStart}
onConnectEnd={onConnectEnd}
onClickConnectStart={onClickConnectStart}
onClickConnectEnd={onClickConnectEnd}
nodesDraggable={nodesDraggable}
nodesConnectable={nodesConnectable}
nodesFocusable={nodesFocusable}
edgesFocusable={edgesFocusable}
edgesUpdatable={edgesUpdatable}
elementsSelectable={elementsSelectable}
elevateNodesOnSelect={elevateNodesOnSelect}
elevateEdgesOnSelect={elevateEdgesOnSelect}
minZoom={minZoom}
maxZoom={maxZoom}
nodeExtent={nodeExtent}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
snapToGrid={snapToGrid}
snapGrid={snapGrid}
connectionMode={connectionMode}
translateExtent={translateExtent}
connectOnClick={connectOnClick}
defaultEdgeOptions={defaultEdgeOptions}
fitView={fitView}
fitViewOptions={fitViewOptions}
onNodesDelete={onNodesDelete}
onEdgesDelete={onEdgesDelete}
onDelete={onDelete}
onNodeDragStart={onNodeDragStart}
onNodeDrag={onNodeDrag}
onNodeDragStop={onNodeDragStop}
onSelectionDrag={onSelectionDrag}
onSelectionDragStart={onSelectionDragStart}
onSelectionDragStop={onSelectionDragStop}
onMove={onMove}
onMoveStart={onMoveStart}
onMoveEnd={onMoveEnd}
noPanClassName={noPanClassName}
nodeOrigin={nodeOrigin}
rfId={rfId}
autoPanOnConnect={autoPanOnConnect}
autoPanOnNodeDrag={autoPanOnNodeDrag}
onError={onError}
connectionRadius={connectionRadius}
isValidConnection={isValidConnection}
selectNodesOnDrag={selectNodesOnDrag}
nodeDragThreshold={nodeDragThreshold}
onBeforeDelete={onBeforeDelete}
/>
<SelectionListener onSelectionChange={onSelectionChange} />
{children}
<Attribution proOptions={proOptions} position={attributionPosition} />
<A11yDescriptions rfId={rfId} disableKeyboardA11y={disableKeyboardA11y} />
</Wrapper>
</div>
);
}
);
fitViewOptions={fitViewOptions}
onNodesDelete={onNodesDelete}
onEdgesDelete={onEdgesDelete}
onDelete={onDelete}
onNodeDragStart={onNodeDragStart}
onNodeDrag={onNodeDrag}
onNodeDragStop={onNodeDragStop}
onSelectionDrag={onSelectionDrag}
onSelectionDragStart={onSelectionDragStart}
onSelectionDragStop={onSelectionDragStop}
onMove={onMove}
onMoveStart={onMoveStart}
onMoveEnd={onMoveEnd}
noPanClassName={noPanClassName}
nodeOrigin={nodeOrigin}
rfId={rfId}
autoPanOnConnect={autoPanOnConnect}
autoPanOnNodeDrag={autoPanOnNodeDrag}
onError={onError}
connectionRadius={connectionRadius}
isValidConnection={isValidConnection}
selectNodesOnDrag={selectNodesOnDrag}
nodeDragThreshold={nodeDragThreshold}
onBeforeDelete={onBeforeDelete}
debug={debug}
/>
<SelectionListener onSelectionChange={onSelectionChange} />
{children}
<Attribution proOptions={proOptions} position={attributionPosition} />
<A11yDescriptions rfId={rfId} disableKeyboardA11y={disableKeyboardA11y} />
</Wrapper>
</div>
);
}
ReactFlow.displayName = 'ReactFlow';
export default ReactFlow;
export default forwardRef(ReactFlow) as typeof ReactFlow;
+18 -21
View File
@@ -31,35 +31,32 @@ export function useDrag({
const xyDrag = useRef<XYDragInstance>();
useEffect(() => {
if (nodeRef?.current) {
xyDrag.current = XYDrag({
domNode: nodeRef.current,
getStoreItems: () => store.getState(),
onNodeMouseDown: (id: string) => {
handleNodeClick({
id,
store,
nodeRef,
});
},
onDragStart: () => {
setDragging(true);
},
onDragStop: () => {
setDragging(false);
},
});
}
xyDrag.current = XYDrag({
getStoreItems: () => store.getState(),
onNodeMouseDown: (id: string) => {
handleNodeClick({
id,
store,
nodeRef,
});
},
onDragStart: () => {
setDragging(true);
},
onDragStop: () => {
setDragging(false);
},
});
}, []);
useEffect(() => {
if (disabled) {
xyDrag.current?.destroy();
} else {
} else if (nodeRef.current) {
xyDrag.current?.update({
noDragClassName,
handleSelector,
domNode: nodeRef.current as Element,
domNode: nodeRef.current,
isSelectable,
nodeId,
});
+2 -2
View File
@@ -11,8 +11,8 @@ const edgesSelector = (state: ReactFlowState) => state.edges;
* @public
* @returns An array of edges
*/
export function useEdges<EdgeData>(): Edge<EdgeData>[] {
const edges = useStore(edgesSelector, shallow);
export function useEdges<EdgeType extends Edge = Edge>(): EdgeType[] {
const edges = useStore(edgesSelector, shallow) as EdgeType[];
return edges;
}
@@ -0,0 +1,4 @@
import { useEffect, useLayoutEffect } from 'react';
// we need this hook to prevent a warning when using react-flow in SSR
export const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
+21 -16
View File
@@ -4,40 +4,45 @@ import { shallow } from 'zustand/shallow';
import { useStore } from '../hooks/useStore';
import type { Node } from '../types';
export interface NodeDataReturn<NodeType extends Node> {
id: string;
type: NodeType['type'];
data: NodeType['data'];
}
/**
* Hook for receiving data of one or multiple nodes
*
* @public
* @param nodeId - The id (or ids) of the node to get the data from
* @param guard - Optional guard function to narrow down the node type
* @returns An array od data objects
* @returns An object (or array of object) with {id, type, data} representing each node
*/
export function useNodesData<NodeType extends Node = Node>(nodeId: string): NodeType['data'] | null;
export function useNodesData<NodeType extends Node = Node>(nodeIds: string[]): NodeType['data'][];
export function useNodesData<NodeType extends Node = Node>(
nodeIds: string[],
guard: (node: Node) => node is NodeType
): NodeType['data'][];
nodeId: string
): Pick<NodeType, 'id' | 'type' | 'data'> | null;
export function useNodesData<NodeType extends Node = Node>(nodeIds: string[]): Pick<NodeType, 'id' | 'type' | 'data'>[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useNodesData(nodeIds: any): any {
const nodesData = useStore(
useCallback(
(s) => {
if (!Array.isArray(nodeIds)) {
return s.nodeLookup.get(nodeIds)?.data || null;
}
const data = [];
const isArrayOfIds = Array.isArray(nodeIds);
const _nodeIds = isArrayOfIds ? nodeIds : [nodeIds];
for (const nodeId of nodeIds) {
const nodeData = s.nodeLookup.get(nodeId)?.data;
if (nodeData) {
data.push(nodeData);
for (const nodeId of _nodeIds) {
const node = s.nodeLookup.get(nodeId);
if (node) {
data.push({
id: node.id,
type: node.type,
data: node.data,
});
}
}
return data;
return isArrayOfIds ? data : data[0] ?? null;
},
[nodeIds]
),
@@ -1,7 +1,7 @@
import { useState, useCallback, type Dispatch, type SetStateAction } from 'react';
import { applyNodeChanges, applyEdgeChanges } from '../utils/changes';
import type { Node, NodeChange, Edge, EdgeChange } from '../types';
import type { Node, Edge, OnNodesChange, OnEdgesChange } from '../types';
/**
* Hook for managing the state of nodes - should only be used for prototyping / simple use cases.
@@ -10,12 +10,12 @@ import type { Node, NodeChange, Edge, EdgeChange } from '../types';
* @param initialNodes
* @returns an array [nodes, setNodes, onNodesChange]
*/
export function useNodesState<NodeType extends Node = Node>(
export function useNodesState<NodeType extends Node>(
initialNodes: NodeType[]
): [NodeType[], Dispatch<SetStateAction<NodeType[]>>, (changes: NodeChange<NodeType>[]) => void] {
): [NodeType[], Dispatch<SetStateAction<NodeType[]>>, OnNodesChange<NodeType>] {
const [nodes, setNodes] = useState(initialNodes);
const onNodesChange = useCallback(
(changes: NodeChange<NodeType>[]) => setNodes((nds) => applyNodeChanges(changes, nds)),
const onNodesChange: OnNodesChange<NodeType> = useCallback(
(changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
[]
);
@@ -31,10 +31,10 @@ export function useNodesState<NodeType extends Node = Node>(
*/
export function useEdgesState<EdgeType extends Edge = Edge>(
initialEdges: EdgeType[]
): [EdgeType[], Dispatch<SetStateAction<EdgeType[]>>, (changes: EdgeChange<EdgeType>[]) => void] {
): [EdgeType[], Dispatch<SetStateAction<EdgeType[]>>, OnEdgesChange<EdgeType>] {
const [edges, setEdges] = useState(initialEdges);
const onEdgesChange = useCallback(
(changes: EdgeChange<EdgeType>[]) => setEdges((eds) => applyEdgeChanges(changes, eds)),
const onEdgesChange: OnEdgesChange<EdgeType> = useCallback(
(changes) => setEdges((eds) => applyEdgeChanges(changes, eds)),
[]
);
+5 -3
View File
@@ -1,15 +1,17 @@
import { useEffect, useRef } from 'react';
import { useReactFlow } from './useReactFlow';
import type { OnInit } from '../types';
import type { OnInit, Node, Edge } from '../types';
/**
* Hook for calling onInit handler.
*
* @internal
*/
export function useOnInitHandler(onInit: OnInit | undefined) {
const rfInstance = useReactFlow();
export function useOnInitHandler<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onInit: OnInit<NodeType, EdgeType> | undefined
) {
const rfInstance = useReactFlow<NodeType, EdgeType>();
const isInitialized = useRef<boolean>(false);
useEffect(() => {
+3 -2
View File
@@ -1,10 +1,11 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { getElementsToRemove, getOverlappingArea, isRectObject, nodeToRect, type Rect } from '@xyflow/system';
import useViewportHelper from './useViewportHelper';
import { useStoreApi } from './useStore';
import type { ReactFlowInstance, Instance, Node, Edge } from '../types';
import { getElementsDiffChanges, isNode } from '../utils';
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';
/**
* Hook for accessing the ReactFlow instance.
@@ -54,7 +55,7 @@ export function useReactFlow<NodeType extends Node = Node, EdgeType extends Edge
// Layout effects are guaranteed to run before the next render which means we
// shouldn't run into any issues with stale state or weird issues that come from
// rendering things one frame later than expected (we used to use `setTimeout`).
useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
// Because we need to flip the state back to false after flushing, this should
// trigger the hook again (!). If the hook is being run again we know that any
// updates should have been processed by now and we can safely clear the queue
+13 -9
View File
@@ -1,15 +1,13 @@
import { useContext, useMemo } from 'react';
import { useStoreWithEqualityFn as useZustandStore } from 'zustand/traditional';
import type { StoreApi } from 'zustand';
import { UseBoundStoreWithEqualityFn, useStoreWithEqualityFn as useZustandStore } from 'zustand/traditional';
import { errorMessages } from '@xyflow/system';
import StoreContext from '../contexts/RFStoreContext';
import type { ReactFlowState } from '../types';
import type { Edge, Node, ReactFlowState } from '../types';
import { StoreApi } from 'zustand';
const zustandErrorMessage = errorMessages['error001']();
type ExtractState = StoreApi<ReactFlowState> extends { getState: () => infer T } ? T : never;
/**
* Hook for accessing the internal store. Should only be used in rare cases.
*
@@ -17,8 +15,12 @@ type ExtractState = StoreApi<ReactFlowState> extends { getState: () => infer T }
* @param selector
* @param equalityFn
* @returns The selected state slice
*
* @example
* const nodes = useStore((state: ReactFlowState<MyNodeType>) => state.nodes);
*
*/
function useStore<StateSlice = ExtractState>(
function useStore<StateSlice = unknown>(
selector: (state: ReactFlowState) => StateSlice,
equalityFn?: (a: StateSlice, b: StateSlice) => boolean
) {
@@ -31,8 +33,10 @@ function useStore<StateSlice = ExtractState>(
return useZustandStore(store, selector, equalityFn);
}
const useStoreApi = () => {
const store = useContext(StoreContext);
function useStoreApi<NodeType extends Node = Node, EdgeType extends Edge = Edge>() {
const store = useContext(StoreContext) as UseBoundStoreWithEqualityFn<
StoreApi<ReactFlowState<NodeType, EdgeType>>
> | null;
if (store === null) {
throw new Error(zustandErrorMessage);
@@ -47,6 +51,6 @@ const useStoreApi = () => {
}),
[store]
);
};
}
export { useStore, useStoreApi };
-1
View File
@@ -53,7 +53,6 @@ export {
type OnConnectStart,
type OnConnect,
type OnConnectEnd,
type IsValidConnection,
type Viewport,
type SnapGrid,
PanOnScrollMode,
+16 -6
View File
@@ -89,6 +89,7 @@ const createRFStore = ({
fitViewOnInitOptions,
domNode,
nodeOrigin,
debug,
} = get();
const changes: NodeDimensionChange[] = [];
@@ -130,6 +131,9 @@ const createRFStore = ({
set({ nodes: nextNodes, fitViewDone: nextFitViewDone });
if (changes?.length > 0) {
if (debug) {
console.log('React Flow: trigger node changes', changes);
}
onNodesChange?.(changes);
}
},
@@ -149,7 +153,7 @@ const createRFStore = ({
get().triggerNodeChanges(changes);
},
triggerNodeChanges: (changes) => {
const { onNodesChange, setNodes, nodes, hasDefaultNodes } = get();
const { onNodesChange, setNodes, nodes, hasDefaultNodes, debug } = get();
if (changes?.length) {
if (hasDefaultNodes) {
@@ -157,11 +161,15 @@ const createRFStore = ({
setNodes(updatedNodes);
}
if (debug) {
console.log('React Flow: trigger node changes', changes);
}
onNodesChange?.(changes);
}
},
triggerEdgeChanges: (changes) => {
const { onEdgesChange, setEdges, edges, hasDefaultEdges } = get();
const { onEdgesChange, setEdges, edges, hasDefaultEdges, debug } = get();
if (changes?.length) {
if (hasDefaultEdges) {
@@ -169,6 +177,10 @@ const createRFStore = ({
setEdges(updatedEdges);
}
if (debug) {
console.log('React Flow: trigger edge changes', changes);
}
onEdgesChange?.(changes);
}
},
@@ -291,13 +303,11 @@ const createRFStore = ({
connectionEndHandle: null,
}),
updateConnection: (params) => {
const { connectionStatus, connectionStartHandle, connectionEndHandle, connectionPosition } = get();
const { connectionPosition } = get();
const currentConnection = {
...params,
connectionPosition: params.connectionPosition ?? connectionPosition,
connectionStatus: params.connectionStatus ?? connectionStatus,
connectionStartHandle: params.connectionStartHandle ?? connectionStartHandle,
connectionEndHandle: params.connectionEndHandle ?? connectionEndHandle,
};
set(currentConnection);
+4 -1
View File
@@ -43,7 +43,9 @@ const getInitialState = ({
let transform: Transform = [0, 0, 1];
if (fitView && width && height) {
const nodesWithDimensions = nextNodes.filter((node) => node.width && node.height);
const nodesWithDimensions = nextNodes.filter(
(node) => (node.width || node.initialWidth) && (node.height || node.initialHeight)
);
// @todo users nodeOrigin should be used here
const bounds = getNodesBounds(nodesWithDimensions, { nodeOrigin: [0, 0] });
const { x, y, zoom } = getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
@@ -113,6 +115,7 @@ const getInitialState = ({
onSelectionChangeHandlers: [],
lib: 'react',
debug: false,
};
};
-1
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { XYPosition, Dimensions } from '@xyflow/system';
import type { Node, Edge } from '.';
+41 -35
View File
@@ -18,7 +18,6 @@ import type {
HandleType,
SelectionMode,
OnError,
IsValidConnection,
ColorMode,
SnapGrid,
} from '@xyflow/system';
@@ -44,13 +43,15 @@ import type {
EdgeMouseHandler,
OnNodeDrag,
OnBeforeDelete,
IsValidConnection,
} from '.';
/**
* ReactFlow component props.
* @public
*/
export interface ReactFlowProps 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.
* @example
* const nodes = [
@@ -62,7 +63,7 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
* }
* ];
*/
nodes?: Node[];
nodes?: NodeType[];
/** An array of edges to render in a controlled flow.
* @example
* const edges = [
@@ -73,11 +74,11 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
* }
* ];
*/
edges?: Edge[];
edges?: EdgeType[];
/** The initial nodes to render in an uncontrolled flow. */
defaultNodes?: Node[];
defaultNodes?: NodeType[];
/** 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.
*
* Properties on a new edge will override these defaults if they exist.
@@ -99,38 +100,38 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
*/
defaultEdgeOptions?: DefaultEdgeOptions;
/** This event handler is called when a user clicks on a node */
onNodeClick?: NodeMouseHandler;
onNodeClick?: NodeMouseHandler<NodeType>;
/** This event handler is called when a user double clicks on a node */
onNodeDoubleClick?: NodeMouseHandler;
onNodeDoubleClick?: NodeMouseHandler<NodeType>;
/** This event handler is called when mouse of a user enters a node */
onNodeMouseEnter?: NodeMouseHandler;
onNodeMouseEnter?: NodeMouseHandler<NodeType>;
/** This event handler is called when mouse of a user moves over a node */
onNodeMouseMove?: NodeMouseHandler;
onNodeMouseMove?: NodeMouseHandler<NodeType>;
/** This event handler is called when mouse of a user leaves a node */
onNodeMouseLeave?: NodeMouseHandler;
onNodeMouseLeave?: NodeMouseHandler<NodeType>;
/** This event handler is called when a user right clicks on a node */
onNodeContextMenu?: NodeMouseHandler;
onNodeContextMenu?: NodeMouseHandler<NodeType>;
/** This event handler is called when a user starts to drag a node */
onNodeDragStart?: OnNodeDrag;
onNodeDragStart?: OnNodeDrag<NodeType>;
/** This event handler is called when a user drags a node */
onNodeDrag?: OnNodeDrag;
onNodeDrag?: OnNodeDrag<NodeType>;
/** This event handler is called when a user stops dragging a node */
onNodeDragStop?: OnNodeDrag;
onNodeDragStop?: OnNodeDrag<NodeType>;
/** 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 */
onEdgeContextMenu?: EdgeMouseHandler;
onEdgeContextMenu?: EdgeMouseHandler<EdgeType>;
/** 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 */
onEdgeMouseMove?: EdgeMouseHandler;
onEdgeMouseMove?: EdgeMouseHandler<EdgeType>;
/** 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 */
onEdgeDoubleClick?: EdgeMouseHandler;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdate?: OnEdgeUpdateFunc;
onEdgeDoubleClick?: EdgeMouseHandler<EdgeType>;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdate?: OnEdgeUpdateFunc<EdgeType>;
/** This event handler is called when a Node is updated
* @example // Use NodesState hook to create edges and get onNodesChange handler
* import ReactFlow, { useNodesState } from '@xyflow/react';
@@ -147,7 +148,7 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
*
* return (<ReactFlow onNodeChange={onNodeChange} {...rest} />)
*/
onNodesChange?: OnNodesChange;
onNodesChange?: OnNodesChange<NodeType>;
/** This event handler is called when a Edge is updated
* @example // Use EdgesState hook to create edges and get onEdgesChange handler
* import ReactFlow, { useEdgesState } from '@xyflow/react';
@@ -164,22 +165,22 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
*
* return (<ReactFlow onEdgesChange={onEdgesChange} {...rest} />)
*/
onEdgesChange?: OnEdgesChange;
onEdgesChange?: OnEdgesChange<EdgeType>;
/** This event handler gets called when a Node is deleted */
onNodesDelete?: OnNodesDelete;
onNodesDelete?: OnNodesDelete<NodeType>;
/** 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 */
onDelete?: OnDelete;
onDelete?: OnDelete<NodeType, EdgeType>;
/** 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 */
onSelectionDrag?: SelectionDragHandler;
onSelectionDrag?: SelectionDragHandler<NodeType>;
/** This event handler gets called when a user stops dragging a selection box */
onSelectionDragStop?: SelectionDragHandler;
onSelectionDragStop?: SelectionDragHandler<NodeType>;
onSelectionStart?: (event: ReactMouseEvent) => void;
onSelectionEnd?: (event: ReactMouseEvent) => void;
onSelectionContextMenu?: (event: ReactMouseEvent, nodes: Node[]) => void;
onSelectionContextMenu?: (event: ReactMouseEvent, nodes: NodeType[]) => void;
/** When a connection line is completed and two nodes are connected by the user, this event fires with the new connection.
*
* You can use the addEdge utility to convert the connection to a complete edge.
@@ -201,7 +202,7 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
onClickConnectStart?: OnConnectStart;
onClickConnectEnd?: OnConnectEnd;
/** This event handler gets called when a flow has finished initializing */
onInit?: OnInit;
onInit?: OnInit<NodeType, EdgeType>;
/** This event handler is called while the user is either panning or zooming the viewport. */
onMove?: OnMove;
/** This event handler gets called when a user starts to pan or zoom the viewport */
@@ -223,7 +224,7 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
/** This event handler gets called when mouse leaves the pane */
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. */
onBeforeDelete?: OnBeforeDelete;
onBeforeDelete?: OnBeforeDelete<NodeType, EdgeType>;
/** Custom node types to be available in a flow.
*
* React Flow matches a node's type to a component in the nodeTypes object.
@@ -502,6 +503,11 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
* @example 'system' | 'light' | 'dark'
*/
colorMode?: ColorMode;
/** If set true, some debug information will be logged to the console like which events are fired.
*
* @default undefined
*/
debug?: boolean;
}
export type ReactFlowRefType = HTMLDivElement;
+32 -28
View File
@@ -30,7 +30,14 @@ export type EdgeLabelOptions = {
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 & {
style?: CSSProperties;
className?: string;
@@ -38,48 +45,45 @@ export type DefaultEdge<EdgeData = any> = EdgeBase<EdgeData> &
focusable?: boolean;
};
type SmoothStepEdgeType<T> = DefaultEdge<T> & {
type: 'smoothstep';
type SmoothStepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
EdgeData,
'smoothstep'
> & {
pathOptions?: SmoothStepPathOptions;
};
type BezierEdgeType<T> = DefaultEdge<T> & {
type: 'default';
type BezierEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<EdgeData, 'default'> & {
pathOptions?: BezierPathOptions;
};
type StepEdgeType<T> = DefaultEdge<T> & {
type: 'step';
type StepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<EdgeData, 'step'> & {
pathOptions?: StepPathOptions;
};
/**
* 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 BuiltInEdge = SmoothStepEdge | BezierEdge | StepEdge;
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;
edgesFocusable: boolean;
edgesUpdatable: boolean;
elementsSelectable: boolean;
noPanClassName: string;
onClick?: EdgeMouseHandler;
onDoubleClick?: EdgeMouseHandler;
onEdgeUpdate?: OnEdgeUpdateFunc;
onContextMenu?: EdgeMouseHandler;
onMouseEnter?: EdgeMouseHandler;
onMouseMove?: EdgeMouseHandler;
onMouseLeave?: EdgeMouseHandler;
onClick?: EdgeMouseHandler<EdgeType>;
onDoubleClick?: EdgeMouseHandler<EdgeType>;
onEdgeUpdate?: OnEdgeUpdateFunc<EdgeType>;
onContextMenu?: EdgeMouseHandler<EdgeType>;
onMouseEnter?: EdgeMouseHandler<EdgeType>;
onMouseMove?: EdgeMouseHandler<EdgeType>;
onMouseLeave?: EdgeMouseHandler<EdgeType>;
edgeUpdaterRadius?: number;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: Edge, handleType: HandleType) => void;
onEdgeUpdateStart?: (event: ReactMouseEvent, edge: EdgeType, handleType: HandleType) => void;
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent, edge: EdgeType, handleType: HandleType) => void;
rfId?: string;
edgeTypes?: EdgeTypes;
onError?: OnError;
disableKeyboardA11y?: boolean;
};
export type DefaultEdgeOptions = DefaultEdgeOptionsBase<Edge>;
@@ -94,10 +98,10 @@ export type EdgeTextProps = HTMLAttributes<SVGElement> &
* Custom edge component props
* @public
*/
export type EdgeProps<T = any> = Pick<
Edge<T>,
'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'
> &
export type EdgeProps<
EdgeData extends Record<string, unknown> = Record<string, unknown>,
EdgeType extends string | undefined = string | undefined
> = Pick<Edge<EdgeData, EdgeType>, 'id' | 'animated' | 'data' | 'style' | 'selected' | 'source' | 'target'> &
EdgePosition &
EdgeLabelOptions & {
sourceHandleId?: string | null;
@@ -185,7 +189,7 @@ export type StraightEdgeProps = Omit<EdgeComponentProps, 'sourcePosition' | 'tar
*/
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 = {
connectionLineStyle?: CSSProperties;
+8 -3
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
FitViewParamsBase,
FitViewOptionsBase,
@@ -12,6 +11,7 @@ import {
XYPosition,
NodeProps,
OnBeforeDeleteBase,
Connection,
} from '@xyflow/system';
import type { NodeChange, EdgeChange, Node, Edge, ReactFlowInstance, EdgeProps } from '.';
@@ -21,8 +21,11 @@ export type OnNodesChange<NodeType extends Node = Node> = (changes: NodeChange<N
export type OnEdgesChange<EdgeType extends Edge = Edge> = (changes: EdgeChange<EdgeType>[]) => void;
export type OnNodesDelete<NodeType extends Node = Node> = (nodes: NodeType[]) => void;
export type OnEdgesDelete = (edges: Edge[]) => void;
export type OnDelete = (params: { nodes: Node[]; edges: Edge[] }) => void;
export type OnEdgesDelete<EdgeType extends Edge = Edge> = (edges: EdgeType[]) => 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 EdgeTypes = { [key: string]: ComponentType<EdgeProps> };
@@ -139,3 +142,5 @@ export type OnBeforeDelete<NodeType extends Node = Node, EdgeType extends Edge =
NodeType,
EdgeType
>;
export type IsValidConnection<EdgeType extends Edge = Edge> = (edge: EdgeType | Connection) => boolean;
-1
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-namespace */
import type { Rect, Viewport } from '@xyflow/system';
import type { Node, Edge, ViewportHelperFunctions } from '.';
+13 -12
View File
@@ -7,11 +7,10 @@ import { NodeTypes } from './general';
* The node data structure that gets used for the nodes prop.
* @public
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Node<NodeData = any, NodeType extends string | undefined = string | undefined> = NodeBase<
NodeData,
NodeType
> & {
export type Node<
NodeData extends Record<string, unknown> = Record<string, unknown>,
NodeType extends string | undefined = string | undefined
> = NodeBase<NodeData, NodeType> & {
style?: CSSProperties;
className?: string;
resizing?: boolean;
@@ -26,18 +25,18 @@ export type OnNodeDrag<NodeType extends Node = Node> = (
nodes: NodeType[]
) => void;
export type NodeWrapperProps = {
export type NodeWrapperProps<NodeType extends Node> = {
id: string;
nodesConnectable: boolean;
elementsSelectable: boolean;
nodesDraggable: boolean;
nodesFocusable: boolean;
onClick?: NodeMouseHandler;
onDoubleClick?: NodeMouseHandler;
onMouseEnter?: NodeMouseHandler;
onMouseMove?: NodeMouseHandler;
onMouseLeave?: NodeMouseHandler;
onContextMenu?: NodeMouseHandler;
onClick?: NodeMouseHandler<NodeType>;
onDoubleClick?: NodeMouseHandler<NodeType>;
onMouseEnter?: NodeMouseHandler<NodeType>;
onMouseMove?: NodeMouseHandler<NodeType>;
onMouseLeave?: NodeMouseHandler<NodeType>;
onContextMenu?: NodeMouseHandler<NodeType>;
resizeObserver: ResizeObserver | null;
noDragClassName: string;
noPanClassName: string;
@@ -48,3 +47,5 @@ export type NodeWrapperProps = {
nodeOrigin: NodeOrigin;
onError?: OnError;
};
export type BuiltInNode = Node<{ label: string }, 'input' | 'output' | 'default'>;
+27 -22
View File
@@ -21,7 +21,6 @@ import {
type OnMoveStart,
type OnMove,
type OnMoveEnd,
type IsValidConnection,
type UpdateConnection,
type EdgeLookup,
type ConnectionLookup,
@@ -43,21 +42,22 @@ import type {
OnDelete,
OnNodeDrag,
OnBeforeDelete,
IsValidConnection,
EdgeChange,
} from '.';
export type ReactFlowStore = {
export type ReactFlowStore<NodeType extends Node = Node, EdgeType extends Edge = Edge> = {
rfId: string;
width: number;
height: number;
transform: Transform;
nodes: Node[];
nodeLookup: NodeLookup<Node>;
nodes: NodeType[];
nodeLookup: NodeLookup<NodeType>;
edges: Edge[];
edgeLookup: EdgeLookup<Edge>;
edgeLookup: EdgeLookup<EdgeType>;
connectionLookup: ConnectionLookup;
onNodesChange: OnNodesChange | null;
onEdgesChange: OnEdgesChange | null;
onNodesChange: OnNodesChange<NodeType> | null;
onEdgesChange: OnEdgesChange<EdgeType> | null;
hasDefaultNodes: boolean;
hasDefaultEdges: boolean;
domNode: HTMLDivElement | null;
@@ -99,9 +99,9 @@ export type ReactFlowStore = {
connectionEndHandle: ConnectingHandle | null;
connectionClickStartHandle: ConnectingHandle | null;
onNodeDragStart?: OnNodeDrag;
onNodeDrag?: OnNodeDrag;
onNodeDragStop?: OnNodeDrag;
onNodeDragStart?: OnNodeDrag<NodeType>;
onNodeDrag?: OnNodeDrag<NodeType>;
onNodeDragStop?: OnNodeDrag<NodeType>;
onSelectionDragStart?: OnSelectionDrag;
onSelectionDrag?: OnSelectionDrag;
@@ -125,8 +125,8 @@ export type ReactFlowStore = {
fitViewDone: boolean;
fitViewOnInitOptions: FitViewOptions | undefined;
onNodesDelete?: OnNodesDelete;
onEdgesDelete?: OnEdgesDelete;
onNodesDelete?: OnNodesDelete<NodeType>;
onEdgesDelete?: OnEdgesDelete<EdgeType>;
onDelete?: OnDelete;
onError?: OnError;
@@ -134,7 +134,7 @@ export type ReactFlowStore = {
onViewportChangeStart?: OnViewportChange;
onViewportChange?: OnViewportChange;
onViewportChangeEnd?: OnViewportChange;
onBeforeDelete?: OnBeforeDelete;
onBeforeDelete?: OnBeforeDelete<NodeType, EdgeType>;
onSelectionChangeHandlers: OnSelectionChangeFunc[];
@@ -143,14 +143,16 @@ export type ReactFlowStore = {
autoPanOnNodeDrag: boolean;
connectionRadius: number;
isValidConnection?: IsValidConnection;
isValidConnection?: IsValidConnection<EdgeType>;
lib: string;
debug: boolean;
};
export type ReactFlowActions = {
setNodes: (nodes: Node[]) => void;
setEdges: (edges: Edge[]) => void;
export type ReactFlowActions<NodeType extends Node, EdgeType extends Edge> = {
setNodes: (nodes: NodeType[]) => void;
setEdges: (edges: EdgeType[]) => void;
setDefaultNodesAndEdges: (nodes?: NodeType[], edges?: EdgeType[]) => void;
updateNodeDimensions: (updates: Map<string, NodeDimensionUpdate>) => void;
updateNodePositions: UpdateNodePositions;
resetSelectedElements: () => void;
@@ -164,11 +166,14 @@ export type ReactFlowActions = {
cancelConnection: () => void;
updateConnection: UpdateConnection;
reset: () => void;
triggerNodeChanges: (changes: NodeChange[] | null) => void;
triggerEdgeChanges: (changes: EdgeChange[] | null) => void;
triggerNodeChanges: (changes: NodeChange<NodeType>[]) => void;
triggerEdgeChanges: (changes: EdgeChange<EdgeType>[]) => void;
panBy: PanBy;
fitView: (nodes: Node[], options?: FitViewOptions) => boolean;
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void;
fitView: (nodes: NodeType[], options?: FitViewOptions) => boolean;
};
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
export type ReactFlowState<NodeType extends Node = Node, EdgeType extends Edge = Edge> = ReactFlowStore<
NodeType,
EdgeType
> &
ReactFlowActions<NodeType, EdgeType>;
+14
View File
@@ -1,5 +1,19 @@
# @xyflow/svelte
## 0.0.37
## ⚠️ Breaking changes
- `useNodesData` not only returns data objects but also the type and the id of the node
- status class names for Handle components are slightly different. It's now "connectingfrom" and "connectingto" instead of "connecting"
## Patch changes
- better cursor defaults for the pane, nodes and edges
- add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr
- always re-measure nodes when new nodes get passed
- fix `NodeResizer` when used in combination with `nodeOrigin`
## 0.0.36
## Patch changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@xyflow/svelte",
"version": "0.0.36",
"version": "0.0.37",
"description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.",
"keywords": [
"svelte",
@@ -19,7 +19,6 @@ export type UseDragParams = {
export default function drag(domNode: Element, params: UseDragParams) {
const { store, onDrag, onDragStart, onDragStop, onNodeMouseDown } = params;
const dragInstance = XYDrag({
domNode,
onDrag,
onDragStart,
onDragStop,
@@ -22,6 +22,7 @@
export let animated: $$Props['animated'] = false;
export let selected: $$Props['selected'] = false;
export let selectable: $$Props['selectable'] = undefined;
export let hidden: $$Props['hidden'] = false;
export let label: $$Props['label'] = undefined;
export let labelStyle: $$Props['labelStyle'] = undefined;
@@ -44,7 +45,7 @@
setContext('svelteflow__edge_id', id);
const { edgeLookup, edgeTypes, flowId } = useStore();
const { edgeLookup, edgeTypes, flowId, elementsSelectable } = useStore();
const dispatch = createEventDispatcher<{
edgeclick: { edge: Edge; event: MouseEvent | TouchEvent };
edgecontextmenu: { edge: Edge; event: MouseEvent };
@@ -53,6 +54,7 @@
$: edgeComponent = $edgeTypes[type!] || BezierEdgeInternal;
$: markerStartUrl = markerStart ? `url(#${getMarkerId(markerStart, $flowId)})` : undefined;
$: markerEndUrl = markerEnd ? `url(#${getMarkerId(markerEnd, $flowId)})` : undefined;
$: isSelectable = selectable || ($elementsSelectable && typeof selectable === 'undefined');
const handleEdgeSelect = useHandleEdgeSelect();
@@ -82,6 +84,7 @@
class={cc(['svelte-flow__edge', className])}
class:animated
class:selected
class:selectable={isSelectable}
data-id={id}
on:click={onClick}
on:contextmenu={onContextMenu}
@@ -56,7 +56,8 @@
onconnect: onConnectAction,
onconnectstart: onConnectStartAction,
onconnectend: onConnectEndAction,
flowId
flowId,
connection
} = store;
function onPointerDown(event: MouseEvent | TouchEvent) {
@@ -123,6 +124,16 @@
prevConnections = connections ?? new Map();
}
$: connectingFrom =
$connection.startHandle?.nodeId === nodeId &&
$connection.startHandle?.type === type &&
$connection.startHandle?.handleId === handleId;
$: connectingTo =
$connection.endHandle?.nodeId === nodeId &&
$connection.endHandle?.type === type &&
$connection.endHandle?.handleId === handleId;
$: valid = connectingTo && $connection.status === 'valid';
// @todo implement connectablestart, connectableend
</script>
@@ -141,6 +152,11 @@ The Handle component is the part of a node that can be used to connect nodes.
'nodrag',
'nopan',
position,
{
valid,
connectingto: connectingTo,
connectingfrom: connectingFrom
},
className
])}
class:source={!isTarget}
@@ -1,7 +1,13 @@
<svelte:options immutable />
<script lang="ts">
import { createEventDispatcher, setContext, SvelteComponent, type ComponentType } from 'svelte';
import {
createEventDispatcher,
setContext,
SvelteComponent,
type ComponentType,
onDestroy
} from 'svelte';
import { get, writable } from 'svelte/store';
import cc from 'classcat';
import { errorMessages, Position, type NodeProps } from '@xyflow/system';
@@ -11,6 +17,7 @@
import DefaultNode from '$lib/components/nodes/DefaultNode.svelte';
import type { NodeWrapperProps } from './types';
import type { Node } from '$lib/types';
import { getNodeInlineStyleDimensions } from './utils';
interface $$Props extends NodeWrapperProps {}
@@ -34,6 +41,10 @@
export let sourcePosition: NodeWrapperProps['sourcePosition'] = undefined;
export let targetPosition: NodeWrapperProps['targetPosition'] = undefined;
export let zIndex: NodeWrapperProps['zIndex'];
export let computedWidth: NodeWrapperProps['computedWidth'] = undefined;
export let computedHeight: NodeWrapperProps['computedHeight'] = undefined;
export let initialWidth: NodeWrapperProps['initialWidth'] = undefined;
export let initialHeight: NodeWrapperProps['initialHeight'] = undefined;
export let width: NodeWrapperProps['width'] = undefined;
export let height: NodeWrapperProps['height'] = undefined;
export let dragHandle: NodeWrapperProps['dragHandle'] = undefined;
@@ -77,6 +88,15 @@
let prevSourcePosition: Position | undefined = undefined;
let prevTargetPosition: Position | undefined = undefined;
$: inlineStyleDimensions = getNodeInlineStyleDimensions({
width,
height,
initialWidth,
initialHeight,
computedWidth,
computedHeight
});
$: {
connectableStore.set(!!connectable);
}
@@ -115,15 +135,22 @@
setContext('svelteflow__node_connectable', connectableStore);
$: {
// hiding the noder removes html element is removed from the dom
if (nodeRef) {
resizeObserver?.observe(nodeRef);
prevNodeRef = nodeRef;
} else if (prevNodeRef) {
resizeObserver?.unobserve(prevNodeRef);
if (!prevNodeRef) {
resizeObserver?.observe(nodeRef);
prevNodeRef = nodeRef;
} else if (prevNodeRef !== nodeRef || (!computedWidth && !computedHeight)) {
resizeObserver?.unobserve(prevNodeRef);
resizeObserver?.observe(nodeRef);
prevNodeRef = nodeRef;
}
}
}
onDestroy(() => {
resizeObserver?.unobserve(nodeRef);
});
function onSelectNodeHandler(event: MouseEvent | TouchEvent) {
if (selectable && (!get(selectNodesOnDrag) || !draggable || get(nodeDragThreshold) > 0)) {
// this handler gets called by XYDrag on drag start when selectNodesOnDrag=true
@@ -170,9 +197,7 @@
style:z-index={zIndex}
style:transform="translate({positionOriginX}px, {positionOriginY}px)"
style:visibility={initialized ? 'visible' : 'hidden'}
style="{style ?? ''}; {!width ? '' : `width:${width}px;`} {!height
? ''
: `height:${height}px;`}"
style="{style ?? ''};{inlineStyleDimensions.width}{inlineStyleDimensions.height}"
on:click={onSelectNodeHandler}
on:mouseenter={(event) => dispatch('nodemouseenter', { node, event })}
on:mouseleave={(event) => dispatch('nodemouseleave', { node, event })}
@@ -16,9 +16,13 @@ export type NodeWrapperProps = Pick<
| 'targetPosition'
| 'dragHandle'
| 'hidden'
| 'width'
| 'height'
| 'initialWidth'
| 'initialHeight'
> & {
width?: number;
height?: number;
computedWidth?: number;
computedHeight?: number;
type: string;
positionX: number;
positionY: number;
@@ -0,0 +1,33 @@
export function getNodeInlineStyleDimensions({
width,
height,
initialWidth,
initialHeight,
computedWidth,
computedHeight
}: {
width?: number;
height?: number;
initialWidth?: number;
initialHeight?: number;
computedWidth?: number;
computedHeight?: number;
}): {
width: string | undefined;
height: string | undefined;
} {
if (computedWidth === undefined && computedHeight === undefined) {
const styleWidth = width ?? initialWidth;
const styleHeight = height ?? initialHeight;
return {
width: styleWidth ? `width:${styleWidth}px;` : '',
height: styleHeight ? `height:${styleHeight}px;` : ''
};
}
return {
width: width ? `width:${width}px;` : '',
height: height ? `height:${height}px;` : ''
};
}
@@ -33,6 +33,7 @@
style={edge.style}
animated={edge.animated}
selected={edge.selected}
selectable={edge.selectable}
hidden={edge.hidden}
label={edge.label}
labelStyle={edge.labelStyle}
@@ -1,6 +1,11 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import { internalsSymbol, getPositionWithOrigin } from '@xyflow/system';
import {
internalsSymbol,
getPositionWithOrigin,
getNodeDimensions,
nodeHasDimensions
} from '@xyflow/system';
import { NodeWrapper } from '$lib/components/NodeWrapper';
import { useStore } from '$lib/store';
@@ -39,11 +44,11 @@
<div class="svelte-flow__nodes">
{#each $visibleNodes as node (node.id)}
{@const nodeDimesions = getNodeDimensions(node)}
{@const posOrigin = getPositionWithOrigin({
x: node.computed?.positionAbsolute?.x ?? 0,
y: node.computed?.positionAbsolute?.y ?? 0,
width: node.computed?.width ?? node.width ?? 0,
height: node.computed?.height ?? node.height ?? 0,
...nodeDimesions,
origin: node.origin
})}
<NodeWrapper
@@ -74,10 +79,13 @@
dragging={node.dragging}
zIndex={node[internalsSymbol]?.z ?? 0}
dragHandle={node.dragHandle}
width={node.width ?? undefined}
height={node.height ?? undefined}
initialized={(!!node.computed?.width && !!node.computed?.height) ||
(!!node.width && !!node.height)}
initialized={nodeHasDimensions(node)}
width={node.width}
height={node.height}
initialWidth={node.initialWidth}
initialHeight={node.initialHeight}
computedWidth={node.computed?.width}
computedHeight={node.computed?.height}
{resizeObserver}
on:nodeclick
on:nodemouseenter
@@ -202,6 +202,7 @@
<div
bind:this={container}
class="svelte-flow__pane"
class:draggable={panOnDrag}
class:dragging={$dragging}
class:selection={isSelecting}
on:click={hasActiveSelection ? undefined : wrapHandler(onClick, container)}
@@ -10,7 +10,6 @@ import type {
OnMoveEnd,
CoordinateExtent,
PanOnScrollMode,
IsValidConnection,
OnError,
ConnectionMode,
PanelPosition,
@@ -31,7 +30,8 @@ import type {
FitViewOptions,
OnDelete,
OnEdgeCreate,
OnBeforeDelete
OnBeforeDelete,
IsValidConnection
} from '$lib/types';
import type { Writable } from 'svelte/store';
+18 -31
View File
@@ -3,17 +3,13 @@ import { derived, type Readable } from 'svelte/store';
import type { Node } from '$lib/types';
import { useStore } from '$lib/store';
function areNodesDataEqual(a: Node['data'][] | null, b: Node['data'][] | null) {
if ((!a && !b) || (!a?.length && !b?.length)) {
true;
}
if (!a || !b || a.length !== b.length) {
function areNodesDataEqual(a: any[], b: any[]) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
if (a[i].data !== b[i].data) {
return false;
}
}
@@ -26,47 +22,38 @@ function areNodesDataEqual(a: Node['data'][] | null, b: Node['data'][] | null) {
*
* @public
* @param nodeId - The id (or ids) of the node to get the data from
* @param guard - Optional guard function to narrow down the node type
* @returns A readable store with an array of data objects
*/
export function useNodesData<NodeType extends Node = Node>(
nodeId: string
): Readable<NodeType['data'] | null>;
): Readable<Pick<NodeType, 'id' | 'data' | 'type'> | null>;
export function useNodesData<NodeType extends Node = Node>(
nodeIds: string[]
): Readable<NodeType['data'][]>;
export function useNodesData<NodeType extends Node = Node>(
nodeIds: string[],
guard: (node: Node) => node is NodeType
): Readable<NodeType['data'][]>;
): Readable<Pick<NodeType, 'id' | 'data' | 'type'>[]>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useNodesData(nodeIds: any): any {
const { nodes, nodeLookup } = useStore();
let prevNodesData: (Node['data'] | null)[] | null = null;
let prevNodesData: any = [];
return derived([nodes, nodeLookup], ([, nodeLookup], set) => {
let nextNodesData: (Node['data'] | null)[] | null = null;
const nodeIdArray = Array.isArray(nodeIds);
const nextNodesData = [];
const isArrayOfIds = Array.isArray(nodeIds);
const _nodeIds = isArrayOfIds ? nodeIds : [nodeIds];
if (!nodeIdArray) {
nextNodesData = [nodeLookup.get(nodeIds)?.data || null];
} else {
const data = [];
for (const nodeId of nodeIds) {
const nodeData = nodeLookup.get(nodeId)?.data;
if (nodeData) {
data.push(nodeData);
}
for (const nodeId of _nodeIds) {
const node = nodeLookup.get(nodeId);
if (node) {
nextNodesData.push({
id: node.id,
type: node.type,
data: node.data
});
}
nextNodesData = data;
}
if (!areNodesDataEqual(nextNodesData, prevNodesData)) {
prevNodesData = nextNodesData;
set(nodeIdArray ? nextNodesData : nextNodesData[0]);
set(isArrayOfIds ? nextNodesData : nextNodesData[0] ?? null);
}
});
}
+1 -2
View File
@@ -45,7 +45,7 @@ export type {
DefaultEdgeOptions
} from '$lib/types/edges';
export type { HandleComponentProps, FitViewOptions } from '$lib/types/general';
export type { Node, NodeTypes, DefaultNodeOptions } from '$lib/types/nodes';
export type { Node, NodeTypes, DefaultNodeOptions, BuiltInNode } from '$lib/types/nodes';
export type { SvelteFlowStore } from '$lib/store/types';
// system types
@@ -66,7 +66,6 @@ export {
type OnConnectStart,
type OnConnect,
type OnConnectEnd,
type IsValidConnection,
type Viewport,
type SnapGrid,
PanOnScrollMode,
@@ -7,7 +7,13 @@
<script lang="ts">
import cc from 'classcat';
import { getBoundsOfRects, getNodePositionWithOrigin, getNodesBounds } from '@xyflow/system';
import {
getBoundsOfRects,
getNodeDimensions,
getNodePositionWithOrigin,
getNodesBounds,
nodeHasDimensions
} from '@xyflow/system';
import { useStore } from '$lib/store';
import { Panel } from '$lib/container/Panel';
@@ -116,13 +122,13 @@
{#if ariaLabel}<title id={labelledBy}>{ariaLabel}</title>{/if}
{#each $nodes as node (node.id)}
{#if (node.computed?.width || node?.width) && (node.computed?.height || node.height)}
{#if nodeHasDimensions(node)}
{@const pos = getNodePositionWithOrigin(node).positionAbsolute}
{@const nodeDimesions = getNodeDimensions(node)}
<MinimapNode
x={pos.x}
y={pos.y}
width={node.computed?.width ?? node.width ?? 0}
height={node.computed?.height ?? node.height ?? 0}
{...nodeDimesions}
selected={node.selected}
color={nodeColorFunc?.(node)}
borderRadius={nodeBorderRadius}
@@ -35,7 +35,7 @@
let className: $$Props['class'] = '';
export { className as class };
const { nodeLookup, snapGrid, viewport, nodes } = useStore();
const { nodeLookup, snapGrid, viewport, nodes, nodeOrigin } = useStore();
const contextNodeId = getContext<string>('svelteflow__node_id');
$: id = typeof nodeId === 'string' ? nodeId : contextNodeId;
@@ -64,7 +64,8 @@
nodeLookup: $nodeLookup,
transform: [$viewport.x, $viewport.y, $viewport.zoom],
snapGrid: $snapGrid ?? undefined,
snapToGrid: !!$snapGrid
snapToGrid: !!$snapGrid,
nodeOrigin: $nodeOrigin
};
},
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
-2
View File
@@ -1,7 +1,6 @@
import { getContext, setContext } from 'svelte';
import { derived, get, writable } from 'svelte/store';
import {
internalsSymbol,
createMarkerIds,
fitView as fitViewUtil,
getElementsToRemove,
@@ -15,7 +14,6 @@ import {
type XYPosition,
type CoordinateExtent,
type UpdateConnection,
type NodeDragItem,
errorMessages
} from '@xyflow/system';
@@ -14,7 +14,6 @@ import {
type MarkerProps,
type PanZoomInstance,
type CoordinateExtent,
type IsValidConnection,
type NodeOrigin,
type OnError,
type Viewport,
@@ -47,7 +46,8 @@ import type {
FitViewOptions,
OnDelete,
OnEdgeCreate,
OnBeforeDelete
OnBeforeDelete,
IsValidConnection
} from '$lib/types';
import { createNodesStore, createEdgesStore } from './utils';
import { initConnectionProps, type ConnectionProps } from './derived-connection-props';
@@ -79,7 +79,7 @@ export const getInitialStore = ({
height?: number;
fitView?: boolean;
}) => {
const nodeLookup = new Map();
const nodeLookup: NodeLookup = new Map();
const nextNodes = adoptUserProvidedNodes(nodes, nodeLookup, {
nodeOrigin: [0, 0],
elevateNodesOnSelect: false
@@ -91,7 +91,9 @@ export const getInitialStore = ({
let viewport: Viewport = { x: 0, y: 0, zoom: 1 };
if (fitView && width && height) {
const nodesWithDimensions = nextNodes.filter((node) => node.width && node.height);
const nodesWithDimensions = nextNodes.filter(
(node) => (node.width && node.height) || (node.initialWidth && node.initialHeight)
);
// @todo users nodeOrigin should be used here
const bounds = getNodesBounds(nodesWithDimensions, { nodeOrigin: [0, 0] });
viewport = getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
@@ -101,7 +103,7 @@ export const getInitialStore = ({
flowId: writable<string | null>(null),
nodes: createNodesStore(nextNodes, nodeLookup),
nodeLookup: readable<NodeLookup<Node>>(nodeLookup),
edgeLookup: readable<EdgeLookup>(edgeLookup),
edgeLookup: readable<EdgeLookup<Edge>>(edgeLookup),
visibleNodes: readable<Node[]>([]),
edges: createEdgesStore(edges, connectionLookup, edgeLookup),
visibleEdges: readable<EdgeLayouted[]>([]),
+24 -17
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { SvelteComponent, ComponentType } from 'svelte';
import type {
EdgeBase,
@@ -11,41 +10,49 @@ import type {
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;
labelStyle?: string;
style?: string;
class?: string;
};
type SmoothStepEdgeType<T> = DefaultEdge<T> & {
type: 'smoothstep';
type SmoothStepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
EdgeData,
'smoothstep'
> & {
pathOptions?: SmoothStepPathOptions;
};
type BezierEdgeType<T> = DefaultEdge<T> & {
type: 'default';
type BezierEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
EdgeData,
'default'
> & {
pathOptions?: BezierPathOptions;
};
type StepEdgeType<T> = DefaultEdge<T> & {
type: 'step';
type StepEdge<EdgeData extends Record<string, unknown> = Record<string, unknown>> = Edge<
EdgeData,
'step'
> & {
pathOptions?: StepPathOptions;
};
/**
* 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>;
export type BuiltInEdge = SmoothStepEdge | BezierEdge | StepEdge;
/**
* 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 & {
markerStart?: string;
markerEnd?: string;
+4
View File
@@ -57,3 +57,7 @@ export type OnBeforeDelete<
NodeType extends Node = Node,
EdgeType extends Edge = Edge
> = OnBeforeDeleteBase<NodeType, EdgeType>;
export type IsValidConnection<EdgeType extends Edge = Edge> = (
edge: EdgeType | Connection
) => boolean;
+3 -2
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { ComponentType, SvelteComponent } from 'svelte';
import type { NodeBase, NodeProps } from '@xyflow/system';
@@ -7,7 +6,7 @@ import type { NodeBase, NodeProps } from '@xyflow/system';
* @public
*/
export type Node<
NodeData = any,
NodeData extends Record<string, unknown> = Record<string, unknown>,
NodeType extends string | undefined = string | undefined
> = NodeBase<NodeData, NodeType> & {
class?: string;
@@ -17,3 +16,5 @@ export type Node<
export type NodeTypes = Record<string, ComponentType<SvelteComponent<NodeProps>>>;
export type DefaultNodeOptions = Partial<Omit<Node, 'id'>>;
export type BuiltInNode = Node<{ label: string }, 'input' | 'output' | 'default'>;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@xyflow/system",
"version": "0.0.17",
"version": "0.0.18",
"description": "xyflow core system that powers React Flow and Svelte Flow.",
"keywords": [
"node-based UI",
+21 -8
View File
@@ -66,14 +66,17 @@
.xy-flow__pane {
z-index: 1;
cursor: grab;
&.selection {
cursor: pointer;
}
&.dragging {
cursor: grabbing;
&.draggable {
cursor: grab;
&.dragging {
cursor: grabbing;
}
}
}
@@ -120,7 +123,10 @@
.xy-flow__edge {
pointer-events: visibleStroke;
cursor: pointer;
&.selectable {
cursor: pointer;
}
&.animated path {
stroke-dasharray: 5;
@@ -183,16 +189,19 @@ svg.xy-flow__connectionline {
pointer-events: all;
transform-origin: 0 0;
box-sizing: border-box;
cursor: grab;
cursor: default;
&.dragging {
cursor: grabbing;
&.selectable {
cursor: pointer;
}
/* only used in Svelte Flow, should we remove it here? */
&.draggable {
cursor: grab;
pointer-events: all;
&.dragging {
cursor: grabbing;
}
}
}
@@ -214,6 +223,10 @@ svg.xy-flow__connectionline {
min-width: 5px;
min-height: 5px;
&.connectingfrom {
pointer-events: all;
}
&.connectionindicator {
pointer-events: all;
cursor: crosshair;
+5 -3
View File
@@ -1,11 +1,13 @@
import { Position } from './utils';
// 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 */
id: string;
/** Type of an edge defined in edgeTypes */
type?: string;
type?: EdgeType;
/** Id of source node */
source: string;
/** Id of target node */
+16 -13
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { internalsSymbol } from '../constants';
import type { XYPosition, Position, CoordinateExtent, HandleElement } from '.';
import { Optional } from '../utils/types';
@@ -6,10 +5,13 @@ import { Optional } from '../utils/types';
/**
* Framework independent node data structure.
*
* @typeParam T - type of the node data
* @typeParam U - type of the node
* @typeParam NodeData - type of the node data
* @typeParam NodeType - 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 */
id: string;
/** Position of a node on the pane
@@ -17,9 +19,9 @@ export type NodeBase<T = any, U extends string | undefined = string | undefined>
*/
position: XYPosition;
/** Arbitrary data passed to a node */
data: T;
data: NodeData;
/** Type of node defined in nodeTypes */
type?: U;
type?: NodeType;
/** Only relevant for default, source, target nodeType. controls source position
* @example 'right', 'left', 'top', 'bottom'
*/
@@ -37,8 +39,10 @@ export type NodeBase<T = any, U extends string | undefined = string | undefined>
connectable?: boolean;
deletable?: boolean;
dragHandle?: string;
width?: number | null;
height?: number | null;
width?: number;
height?: number;
initialWidth?: number;
initialHeight?: number;
/** Parent node id, used for creating sub-flows */
parentNode?: string;
zIndex?: number;
@@ -70,21 +74,20 @@ export type NodeBase<T = any, U extends string | undefined = string | undefined>
/** Holds a reference to the original node object provided by the user
* (which may lack some fields, like `computed` or `[internalSymbol]`. Used
* as an optimization to avoid certain operations. */
userProvidedNode: NodeBase<T, U>;
userProvidedNode: NodeBase<NodeData, NodeType>;
};
};
// props that get passed to a custom node
/**
* The node data structure that gets used for the nodes prop.
*
* @public
* @param id - The id of the node.
*/
export type NodeProps<T = any> = {
/** Id of the node */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type NodeProps<NodeData = any> = {
id: NodeBase['id'];
data: T;
data: NodeData;
dragHandle: NodeBase['dragHandle'];
type: NodeBase['type'];
selected: NodeBase['selected'];
+8 -5
View File
@@ -4,6 +4,7 @@ import { NodeBase, NodeHandle } from '../../types/nodes';
import { Position } from '../../types/utils';
import { errorMessages, internalsSymbol } from '../../constants';
import { HandleElement } from '../../types';
import { getNodeDimensions } from '../general';
export type GetEdgePositionParams = {
id: string;
@@ -16,7 +17,10 @@ export type GetEdgePositionParams = {
};
function isNodeInitialized(node: NodeBase): boolean {
return !!(node?.[internalsSymbol]?.handleBounds || node?.handles?.length) && !!(node?.computed?.width || node?.width);
return (
!!(node?.[internalsSymbol]?.handleBounds || node?.handles?.length) &&
!!(node?.computed?.width || node?.width || node?.initialWidth)
);
}
export function getEdgePosition(params: GetEdgePositionParams): EdgePosition | null {
@@ -75,8 +79,8 @@ function toHandleBounds(handles?: NodeHandle[]) {
const target = [];
for (const handle of handles) {
handle.width = handle.width || 1;
handle.height = handle.height || 1;
handle.width = handle.width ?? 1;
handle.height = handle.height ?? 1;
if (handle.type === 'source') {
source.push(handle as HandleElement);
@@ -94,8 +98,7 @@ function toHandleBounds(handles?: NodeHandle[]) {
function getHandlePosition(position: Position, node: NodeBase, handle: HandleElement | null = null): number[] {
const x = (handle?.x ?? 0) + (node.computed?.positionAbsolute?.x ?? 0);
const y = (handle?.y ?? 0) + (node.computed?.positionAbsolute?.y ?? 0);
const width = handle?.width || (node?.computed?.width ?? node?.width ?? 0);
const height = handle?.height || (node?.computed?.height ?? node?.height ?? 0);
const { width, height } = handle ?? getNodeDimensions(node);
switch (position) {
case Position.Top:
@@ -81,8 +81,8 @@ function getPoints({
// opposite handle positions, default case
if (sourceDir[dirAccessor] * targetDir[dirAccessor] === -1) {
centerX = center.x || defaultCenterX;
centerY = center.y || defaultCenterY;
centerX = center.x ?? defaultCenterX;
centerY = center.y ?? defaultCenterY;
// --->
// |
// >---
+16
View File
@@ -202,3 +202,19 @@ export const isMacOs = () => typeof navigator !== 'undefined' && navigator?.user
export function isCoordinateExtent(extent?: CoordinateExtent | 'parent'): extent is CoordinateExtent {
return extent !== undefined && extent !== 'parent';
}
export function getNodeDimensions<NodeType extends NodeBase = NodeBase>(
node: NodeType
): { width: number; height: number } {
return {
width: node.computed?.width ?? node.width ?? node.initialWidth ?? 0,
height: node.computed?.height ?? node.height ?? node.initialHeight ?? 0,
};
}
export function nodeHasDimensions<NodeType extends NodeBase = NodeBase>(node: NodeType): boolean {
return (
(node.computed?.width ?? node.width ?? node.initialWidth) !== undefined &&
(node.computed?.height ?? node.height ?? node.initialHeight) !== undefined
);
}
+7 -6
View File
@@ -9,6 +9,7 @@ import {
pointToRendererPoint,
getViewportForBounds,
isCoordinateExtent,
getNodeDimensions,
} from './general';
import {
type Transform,
@@ -116,8 +117,9 @@ export const getNodePositionWithOrigin = (
};
}
const offsetX = (node.computed?.width ?? node.width ?? 0) * nodeOrigin[0];
const offsetY = (node.computed?.height ?? node.height ?? 0) * nodeOrigin[1];
const { width, height } = getNodeDimensions(node);
const offsetX = width * nodeOrigin[0];
const offsetY = height * nodeOrigin[1];
const position: XYPosition = {
x: node.position.x - offsetX,
@@ -164,8 +166,7 @@ export const getNodesBounds = (
currBox,
rectToBox({
...nodePos[params.useRelativePosition ? 'position' : 'positionAbsolute'],
width: node.computed?.width ?? node.width ?? 0,
height: node.computed?.height ?? node.height ?? 0,
...getNodeDimensions(node),
})
);
},
@@ -192,8 +193,8 @@ export const getNodesInside = <NodeType extends NodeBase>(
const visibleNodes = nodes.reduce<NodeType[]>((res, node) => {
const { computed, selectable = true, hidden = false } = node;
const width = computed?.width ?? node.width ?? null;
const height = computed?.height ?? node.height ?? null;
const width = computed?.width ?? node.width ?? node.initialWidth ?? null;
const height = computed?.height ?? node.height ?? node.initialHeight ?? null;
if ((excludeNonSelectableNodes && !selectable) || hidden) {
return res;
+33 -22
View File
@@ -1,5 +1,5 @@
import { drag } from 'd3-drag';
import { select } from 'd3-selection';
import { select, type Selection } from 'd3-selection';
import {
calcAutoPan,
@@ -58,7 +58,6 @@ type StoreItems<OnNodeDrag> = {
};
export type XYDragParams<OnNodeDrag> = {
domNode: Element;
getStoreItems: () => StoreItems<OnNodeDrag>;
onDragStart?: OnDrag;
onDrag?: OnDrag;
@@ -81,7 +80,6 @@ export type DragUpdateParams = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => void | undefined>({
domNode,
onNodeMouseDown,
getStoreItems,
onDragStart,
@@ -93,15 +91,14 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
let dragItems: NodeDragItem[] = [];
let autoPanStarted = false;
let mousePosition: XYPosition = { x: 0, y: 0 };
let dragEvent: MouseEvent | null = null;
let containerBounds: DOMRect | null = null;
let dragStarted = false;
const d3Selection = select(domNode);
let d3Selection: Selection<Element, unknown, null, undefined> | null = null;
// public functions
function update({ noDragClassName, handleSelector, domNode, isSelectable, nodeId }: DragUpdateParams) {
function updateNodes({ x, y }: XYPosition) {
d3Selection = select(domNode);
function updateNodes({ x, y }: XYPosition, dragEvent: MouseEvent | null) {
const {
nodeLookup,
nodeExtent,
@@ -171,16 +168,21 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
}
updateNodePositions(dragItems, true);
const onNodeOrSelectionDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag);
if (dragEvent && (onDrag || onNodeOrSelectionDrag)) {
if (dragEvent && (onDrag || onNodeDrag || (!nodeId && onSelectionDrag))) {
const [currentNode, currentNodes] = getEventHandlerParams({
nodeId,
dragItems,
nodeLookup,
});
onDrag?.(dragEvent as MouseEvent, dragItems, currentNode, currentNodes);
onNodeOrSelectionDrag?.(dragEvent as MouseEvent, currentNode, currentNodes);
onDrag?.(dragEvent, dragItems, currentNode, currentNodes);
onNodeDrag?.(dragEvent, currentNode, currentNodes);
if (!nodeId) {
const _onSelectionDrag = wrapSelectionDragFunc(onSelectionDrag);
_onSelectionDrag(dragEvent, currentNode, currentNodes);
}
}
}
@@ -198,7 +200,7 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
lastPos.y = (lastPos.y ?? 0) - yMovement / transform[2];
if (panBy({ x: xMovement, y: yMovement })) {
updateNodes(lastPos as XYPosition);
updateNodes(lastPos as XYPosition, null);
}
}
autoPanId = requestAnimationFrame(autoPan);
@@ -236,16 +238,20 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
lastPos = pointerPos;
dragItems = getDragItems(nodes, nodesDraggable, pointerPos, nodeId);
const onNodeOrSelectionDragStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
if (dragItems.length > 0 && (onDragStart || onNodeOrSelectionDragStart)) {
if (dragItems.length > 0 && (onDragStart || onNodeDragStart || (!nodeId && onSelectionDragStart))) {
const [currentNode, currentNodes] = getEventHandlerParams({
nodeId,
dragItems,
nodeLookup,
});
onDragStart?.(event.sourceEvent as MouseEvent, dragItems, currentNode, currentNodes);
onNodeOrSelectionDragStart?.(event.sourceEvent as MouseEvent, currentNode, currentNodes);
onNodeDragStart?.(event.sourceEvent as MouseEvent, currentNode, currentNodes);
if (!nodeId) {
const _onSelectionDragStart = wrapSelectionDragFunc(onSelectionDragStart);
_onSelectionDragStart(event.sourceEvent as MouseEvent, currentNode, currentNodes);
}
}
}
@@ -283,10 +289,10 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
// skip events without movement
if ((lastPos.x !== pointerPos.xSnapped || lastPos.y !== pointerPos.ySnapped) && dragItems && dragStarted) {
dragEvent = event.sourceEvent as MouseEvent;
// dragEvent = event.sourceEvent as MouseEvent;
mousePosition = getEventPosition(event.sourceEvent, containerBounds!);
updateNodes(pointerPos);
updateNodes(pointerPos, event.sourceEvent as MouseEvent);
}
})
.on('end', (event: UseDragEvent) => {
@@ -300,18 +306,23 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
if (dragItems.length > 0) {
const { nodeLookup, updateNodePositions, onNodeDragStop, onSelectionDragStop } = getStoreItems();
const onNodeOrSelectionDragStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
updateNodePositions(dragItems, false);
if (onDragStop || onNodeOrSelectionDragStop) {
if (onDragStop || onNodeDragStop || (!nodeId && onSelectionDragStop)) {
const [currentNode, currentNodes] = getEventHandlerParams({
nodeId,
dragItems,
nodeLookup,
});
onDragStop?.(event.sourceEvent as MouseEvent, dragItems, currentNode, currentNodes);
onNodeOrSelectionDragStop?.(event.sourceEvent as MouseEvent, currentNode, currentNodes);
onNodeDragStop?.(event.sourceEvent as MouseEvent, currentNode, currentNodes);
if (!nodeId) {
const _onSelectionDragStop = wrapSelectionDragFunc(onSelectionDragStop);
_onSelectionDragStop(event.sourceEvent as MouseEvent, currentNode, currentNodes);
}
}
}
})
@@ -329,7 +340,7 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
}
function destroy() {
d3Selection.on('.drag', null);
d3Selection?.on('.drag', null);
}
return {
+1 -15
View File
@@ -15,7 +15,7 @@ import {
type ConnectionHandle,
} from '../types';
import { getClosestHandle, getConnectionStatus, getHandleLookup, getHandleType, resetRecentHandle } from './utils';
import { getClosestHandle, getConnectionStatus, getHandleLookup, getHandleType } from './utils';
export type OnPointerDownParams = {
autoPanOnConnect: boolean;
@@ -107,7 +107,6 @@ function onPointerDown(
return;
}
let prevActiveHandle: Element;
let connectionPosition = getEventPosition(event, containerBounds);
let autoPanStarted = false;
let connection: Connection | null = null;
@@ -194,18 +193,6 @@ function onPointerDown(
connectionStatus: getConnectionStatus(!!closestHandle, isValid),
connectionEndHandle: result.endHandle,
});
if (!closestHandle && !isValid && !handleDomNode) {
return resetRecentHandle(prevActiveHandle, lib);
}
if (connection?.source !== connection?.target && handleDomNode) {
resetRecentHandle(prevActiveHandle, lib);
prevActiveHandle = handleDomNode;
handleDomNode.classList.add('connecting', `${lib}-flow__handle-connecting`);
handleDomNode.classList.toggle('valid', isValid);
handleDomNode.classList.toggle(`${lib}-flow__handle-valid`, isValid);
}
}
function onPointerUp(event: MouseEvent | TouchEvent) {
@@ -221,7 +208,6 @@ function onPointerDown(
onEdgeUpdateEnd?.(event);
}
resetRecentHandle(prevActiveHandle, lib);
cancelConnection();
cancelAnimationFrame(autoPanId);
autoPanStarted = false;
+2 -6
View File
@@ -38,7 +38,7 @@ export function getClosestHandle(
let closestHandles: ConnectionHandle[] = [];
let minDistance = Infinity;
handles.forEach((handle) => {
for (const handle of handles) {
const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2));
if (distance <= connectionRadius) {
if (distance < minDistance) {
@@ -49,7 +49,7 @@ export function getClosestHandle(
}
minDistance = distance;
}
});
}
if (!closestHandles.length) {
return null;
@@ -101,10 +101,6 @@ export function getHandleType(
return null;
}
export function resetRecentHandle(handleDomNode: Element, lib: string): void {
handleDomNode?.classList.remove('valid', 'connecting', `${lib}-flow__handle-valid`, `${lib}-flow__handle-connecting`);
}
export function getConnectionStatus(isInsideConnectionRadius: boolean, isHandleValid: boolean) {
let connectionStatus = null;
+39 -34
View File
@@ -3,7 +3,7 @@ import { select } from 'd3-selection';
import { getControlDirection, getDimensionsAfterResize, getResizeDirection } from './utils';
import { getPointerPosition } from '../utils';
import type { CoordinateExtent, NodeBase, NodeLookup, Transform, XYPosition } from '../types';
import type { CoordinateExtent, NodeBase, NodeLookup, NodeOrigin, Transform, XYPosition } from '../types';
import type { OnResize, OnResizeEnd, OnResizeStart, ResizeDragEvent, ShouldResize, ControlPosition } from './types';
const initPrevValues = { width: 0, height: 0, x: 0, y: 0 };
@@ -42,6 +42,7 @@ type XYResizerParams = {
transform: Transform;
snapGrid?: [number, number];
snapToGrid: boolean;
nodeOrigin: NodeOrigin;
};
onChange: (changes: XYResizerChange, childChanges: XYResizerChildChange[]) => void;
onEnd?: () => void;
@@ -74,13 +75,17 @@ function nodeToParentExtent(node: NodeBase): CoordinateExtent {
];
}
function nodeToChildExtent(child: NodeBase, parent: NodeBase): CoordinateExtent {
function nodeToChildExtent(child: NodeBase, parent: NodeBase, nodeOrigin: NodeOrigin): CoordinateExtent {
const x = parent.position.x + child.position.x;
const y = parent.position.y + child.position.y;
const width = child.computed!.width! ?? 0;
const height = child.computed!.height! ?? 0;
const originOffsetX = nodeOrigin[0] * width;
const originOffsetY = nodeOrigin[1] * height;
return [
[parent.position.x + child.position.x, parent.position.y + child.position.y],
[
parent.position.x + child.position.x + child.computed!.width!,
parent.position.y + child.position.y + child.computed!.height!,
],
[x - originOffsetX, y - originOffsetY],
[x + width - originOffsetX, y + height - originOffsetY],
];
}
@@ -109,7 +114,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
const dragHandler = drag<HTMLDivElement, unknown>()
.on('start', (event: ResizeDragEvent) => {
const { nodeLookup, transform, snapGrid, snapToGrid } = getStoreItems();
const { nodeLookup, transform, snapGrid, snapToGrid, nodeOrigin } = getStoreItems();
node = nodeLookup.get(nodeId);
if (node) {
@@ -151,7 +156,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
});
if (child.extent === 'parent' || child.expandParent) {
const extent = nodeToChildExtent(child, node!);
const extent = nodeToChildExtent(child, node!, child.origin ?? nodeOrigin);
if (childExtent) {
childExtent = [
@@ -169,14 +174,14 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
}
})
.on('drag', (event: ResizeDragEvent) => {
const { transform, snapGrid, snapToGrid } = getStoreItems();
const { transform, snapGrid, snapToGrid, nodeOrigin: storeNodeOrigin } = getStoreItems();
const pointerPosition = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
const childChanges: XYResizerChildChange[] = [];
if (node) {
const change = { ...initChange };
const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues;
const change = { ...initChange };
const nodeOrigin = node.origin ?? storeNodeOrigin;
const { width, height, x, y } = getDimensionsAfterResize(
startValues,
@@ -184,6 +189,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
pointerPosition,
boundaries,
keepAspectRatio,
nodeOrigin,
parentExtent,
childExtent
);
@@ -191,40 +197,39 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
const isWidthChange = width !== prevWidth;
const isHeightChange = height !== prevHeight;
if (controlDirection.affectsX || controlDirection.affectsY) {
const isXPosChange = x !== prevX && isWidthChange;
const isYPosChange = y !== prevY && isHeightChange;
const isXPosChange = x !== prevX && isWidthChange;
const isYPosChange = y !== prevY && isHeightChange;
if (isXPosChange || isYPosChange) {
change.isXPosChange = isXPosChange;
change.isYPosChange = isYPosChange;
change.x = isXPosChange ? x : prevX;
change.y = isYPosChange ? y : prevY;
if (isXPosChange || isYPosChange || nodeOrigin[0] === 1 || nodeOrigin[1] == 1) {
change.isXPosChange = isXPosChange;
change.isYPosChange = isYPosChange;
change.x = isXPosChange ? x : prevX;
change.y = isYPosChange ? y : prevY;
prevValues.x = change.x;
prevValues.y = change.y;
prevValues.x = change.x;
prevValues.y = change.y;
// Fix expandParent when resizing from top/left
if (parentNode && node.expandParent) {
if (change.x < 0) {
prevValues.x = 0;
startValues.x = startValues.x - change.x;
}
// Fix expandParent when resizing from top/left
if (parentNode && node.expandParent) {
if (change.x < 0) {
prevValues.x = 0;
startValues.x = startValues.x - change.x;
}
if (change.y < 0) {
prevValues.y = 0;
startValues.y = startValues.y - change.y;
}
if (change.y < 0) {
prevValues.y = 0;
startValues.y = startValues.y - change.y;
}
}
if (childNodes.length > 0) {
const xChange = x - prevX;
const yChange = y - prevY;
for (const childNode of childNodes) {
childNode.position = {
x: childNode.position.x - xChange,
y: childNode.position.y - yChange,
x: childNode.position.x - xChange + nodeOrigin[0] * (width - prevWidth),
y: childNode.position.y - yChange + nodeOrigin[1] * (height - prevHeight),
};
childChanges.push(childNode);
}
+25 -12
View File
@@ -1,4 +1,4 @@
import { CoordinateExtent } from '../types';
import { CoordinateExtent, NodeOrigin } from '../types';
import { getPointerPosition } from '../utils';
import { ControlPosition } from './types';
@@ -94,7 +94,7 @@ function xor(a: boolean, b: boolean) {
/**
* Calculates new width & height and x & y of node after resize based on pointer position
* @description - Buckle up, this is a chunky one! If you want to determine the new dimensions of a node after a resize,
* @description - Buckle up, this is a chunky one... If you want to determine the new dimensions of a node after a resize,
* you have to account for all possible restrictions: min/max width/height of the node, the maximum extent the node is allowed
* to move in (in this case: resize into) determined by the parent node, the minimal extent determined by child nodes
* with expandParent or extent: 'parent' set and oh yeah, these things also have to work with keepAspectRatio!
@@ -102,6 +102,8 @@ function xor(a: boolean, b: boolean) {
* strongest restriction. Because the resize affects x, y and width, height and width, height of a opposing side with keepAspectRatio,
* the resize amount is always kept in distX & distY amount (the distance in mouse movement)
* Instead of clamping each value, we first calculate the biggest 'clamp' (for the lack of a better name) and then apply it to all values.
* To complicate things nodeOrigin has to be taken into account as well. This is done by offsetting the nodes as if their origin is [0, 0],
* then calculating the restrictions as usual
* @param startValues - starting values of resize
* @param controlDirection - dimensions affected by the resize
* @param pointerPosition - the current pointer position corrected for snapping
@@ -115,6 +117,7 @@ export function getDimensionsAfterResize(
pointerPosition: ReturnType<typeof getPointerPosition>,
boundaries: { minWidth: number; maxWidth: number; minHeight: number; maxHeight: number },
keepAspectRatio: boolean,
nodeOrigin: NodeOrigin,
extent?: CoordinateExtent,
childExtent?: CoordinateExtent
) {
@@ -132,6 +135,9 @@ export function getDimensionsAfterResize(
const newWidth = startWidth + (affectsX ? -distX : distX);
const newHeight = startHeight + (affectsY ? -distY : distY);
const originOffsetX = -nodeOrigin[0] * startWidth;
const originOffsetY = -nodeOrigin[1] * startHeight;
// Check if maxWidth, minWWidth, maxHeight, minHeight are restricting the resize
let clampX = getSizeClamp(newWidth, minWidth, maxWidth);
let clampY = getSizeClamp(newHeight, minHeight, maxHeight);
@@ -141,15 +147,15 @@ export function getDimensionsAfterResize(
let xExtentClamp = 0;
let yExtentClamp = 0;
if (affectsX && distX < 0) {
xExtentClamp = getLowerExtentClamp(startX + distX, extent[0][0]);
xExtentClamp = getLowerExtentClamp(startX + distX + originOffsetX, extent[0][0]);
} else if (!affectsX && distX > 0) {
xExtentClamp = getUpperExtentClamp(startX + newWidth, extent[1][0]);
xExtentClamp = getUpperExtentClamp(startX + newWidth + originOffsetX, extent[1][0]);
}
if (affectsY && distY < 0) {
yExtentClamp = getLowerExtentClamp(startY + distY, extent[0][1]);
yExtentClamp = getLowerExtentClamp(startY + distY + originOffsetY, extent[0][1]);
} else if (!affectsY && distY > 0) {
yExtentClamp = getUpperExtentClamp(startY + newHeight, extent[1][1]);
yExtentClamp = getUpperExtentClamp(startY + newHeight + originOffsetY, extent[1][1]);
}
clampX = Math.max(clampX, xExtentClamp);
@@ -187,10 +193,12 @@ export function getDimensionsAfterResize(
if (extent) {
let aspectExtentClamp = 0;
if ((!affectsX && !affectsY) || (affectsX && !affectsY && isDiagonal)) {
aspectExtentClamp = getUpperExtentClamp(startY + newWidth / aspectRatio, extent[1][1]) * aspectRatio;
aspectExtentClamp =
getUpperExtentClamp(startY + originOffsetY + newWidth / aspectRatio, extent[1][1]) * aspectRatio;
} else {
aspectExtentClamp =
getLowerExtentClamp(startY + (affectsX ? distX : -distX) / aspectRatio, extent[0][1]) * aspectRatio;
getLowerExtentClamp(startY + originOffsetY + (affectsX ? distX : -distX) / aspectRatio, extent[0][1]) *
aspectRatio;
}
clampX = Math.max(clampX, aspectExtentClamp);
}
@@ -216,10 +224,12 @@ export function getDimensionsAfterResize(
if (extent) {
let aspectExtentClamp = 0;
if ((!affectsX && !affectsY) || (affectsY && !affectsX && isDiagonal)) {
aspectExtentClamp = getUpperExtentClamp(startX + newHeight * aspectRatio, extent[1][0]) / aspectRatio;
aspectExtentClamp =
getUpperExtentClamp(startX + newHeight * aspectRatio + originOffsetX, extent[1][0]) / aspectRatio;
} else {
aspectExtentClamp =
getLowerExtentClamp(startX + (affectsY ? distY : -distY) * aspectRatio, extent[0][0]) / aspectRatio;
getLowerExtentClamp(startX + (affectsY ? distY : -distY) * aspectRatio + originOffsetX, extent[0][0]) /
aspectRatio;
}
clampY = Math.max(clampY, aspectExtentClamp);
}
@@ -258,10 +268,13 @@ export function getDimensionsAfterResize(
}
}
const x = affectsX ? startX + distX : startX;
const y = affectsY ? startY + distY : startY;
return {
width: startWidth + (affectsX ? -distX : distX),
height: startHeight + (affectsY ? -distY : distY),
x: affectsX ? startX + distX : startX,
y: affectsY ? startY + distY : startY,
x: nodeOrigin[0] * distX * (!affectsX ? 1 : -1) + x,
y: nodeOrigin[1] * distY * (!affectsY ? 1 : -1) + y,
};
}