Merge pull request #3906 from xyflow/next
React Flow 12.0.0-next.9 & Svelte Flow 0.0.36
This commit is contained in:
@@ -28,6 +28,7 @@ import NodeTypesObjectChange from '../examples/NodeTypesObjectChange';
|
|||||||
import Overview from '../examples/Overview';
|
import Overview from '../examples/Overview';
|
||||||
import Provider from '../examples/Provider';
|
import Provider from '../examples/Provider';
|
||||||
import SaveRestore from '../examples/SaveRestore';
|
import SaveRestore from '../examples/SaveRestore';
|
||||||
|
import SetNodesBatching from '../examples/SetNodesBatching';
|
||||||
import Stress from '../examples/Stress';
|
import Stress from '../examples/Stress';
|
||||||
import Subflow from '../examples/Subflow';
|
import Subflow from '../examples/Subflow';
|
||||||
import SwitchFlow from '../examples/Switch';
|
import SwitchFlow from '../examples/Switch';
|
||||||
@@ -226,6 +227,11 @@ const routes: IRoute[] = [
|
|||||||
path: 'save-restore',
|
path: 'save-restore',
|
||||||
component: SaveRestore,
|
component: SaveRestore,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'SetNodes Batching',
|
||||||
|
path: 'setnodes-batching',
|
||||||
|
component: SetNodesBatching,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'Stress',
|
name: 'Stress',
|
||||||
path: 'stress',
|
path: 'stress',
|
||||||
|
|||||||
@@ -27,9 +27,9 @@ const buttonStyle: CSSProperties = {
|
|||||||
zIndex: 4,
|
zIndex: 4,
|
||||||
};
|
};
|
||||||
|
|
||||||
const CustomMiniMapNode = ({ x, y, width, height, color }: MiniMapNodeProps) => (
|
const CustomMiniMapNode = ({ x, y, width, height }: MiniMapNodeProps) => {
|
||||||
<circle cx={x} cy={y} r={Math.max(width, height) / 2} fill={color} />
|
return <circle cx={x} cy={y} r={Math.max(width, height) / 2} fill="#ffcc00" />;
|
||||||
);
|
};
|
||||||
|
|
||||||
const CustomMiniMapNodeFlow = () => {
|
const CustomMiniMapNodeFlow = () => {
|
||||||
const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
|
const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
|
||||||
|
|||||||
@@ -116,6 +116,42 @@ const initialNodes: Node[] = [
|
|||||||
position: { x: 250, y: 400 },
|
position: { x: 250, y: 400 },
|
||||||
style: { ...nodeStyle },
|
style: { ...nodeStyle },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: '5',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: { label: 'Parent', keepAspectRatio: true },
|
||||||
|
position: { x: 700, y: 0 },
|
||||||
|
style: { ...nodeStyle, width: 300, height: 400 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5a',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: {
|
||||||
|
label: 'Child with extent: parent',
|
||||||
|
},
|
||||||
|
position: { x: 50, y: 50 },
|
||||||
|
parentNode: '5',
|
||||||
|
extent: 'parent',
|
||||||
|
style: { ...nodeStyle, width: 50, height: 100 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5b',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: { label: 'Child with expandParent' },
|
||||||
|
position: { x: 150, y: 100 },
|
||||||
|
parentNode: '5',
|
||||||
|
expandParent: true,
|
||||||
|
style: { ...nodeStyle },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5c',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: { label: 'Child with expandParent & keepAspectRatio', keepAspectRatio: true },
|
||||||
|
position: { x: 25, y: 200 },
|
||||||
|
parentNode: '5',
|
||||||
|
expandParent: true,
|
||||||
|
style: { ...nodeStyle },
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const CustomNodeFlow = () => {
|
const CustomNodeFlow = () => {
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { useCallback } from 'react';
|
||||||
|
import {
|
||||||
|
ReactFlow,
|
||||||
|
MiniMap,
|
||||||
|
Background,
|
||||||
|
BackgroundVariant,
|
||||||
|
Controls,
|
||||||
|
ReactFlowProvider,
|
||||||
|
Node,
|
||||||
|
Edge,
|
||||||
|
useReactFlow,
|
||||||
|
Panel,
|
||||||
|
} from '@xyflow/react';
|
||||||
|
|
||||||
|
const a = { id: 'a', data: { label: 'A' }, position: { x: 250, y: 5 } };
|
||||||
|
const b = { id: 'b', data: { label: 'B' }, position: { x: 100, y: 100 } };
|
||||||
|
const c = { id: 'c', data: { label: 'C' }, position: { x: 400, y: 100 } };
|
||||||
|
|
||||||
|
const SetNotesBatchingFlow = () => {
|
||||||
|
const { setNodes, updateNode } = useReactFlow();
|
||||||
|
|
||||||
|
const triggerMultipleSetNodes = useCallback(() => {
|
||||||
|
setNodes([a]);
|
||||||
|
setNodes((nodes) => [...nodes, b]);
|
||||||
|
setNodes((nodes) => [...nodes, c]);
|
||||||
|
setNodes((nodes) =>
|
||||||
|
nodes.map((node) =>
|
||||||
|
node.id === 'a' ? { ...node, position: { x: node.position.x + 20, y: node.position.y + 20 } } : node
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const triggerMultipleUpdateNodes = useCallback(() => {
|
||||||
|
triggerMultipleSetNodes();
|
||||||
|
updateNode('a', (a) => ({ position: { x: a.position.x + 20, y: a.position.y + 20 } }));
|
||||||
|
updateNode('b', (b) => ({ position: { x: b.position.x + 20, y: b.position.y + 20 } }));
|
||||||
|
updateNode('c', (c) => ({ position: { x: c.position.x + 20, y: c.position.y + 20 } }));
|
||||||
|
updateNode('a', (a) => ({ data: { ...a.data, label: `A ${Date.now()}` } }));
|
||||||
|
updateNode('b', (b) => ({ data: { ...b.data, label: `B ${Date.now()}` } }));
|
||||||
|
updateNode('c', (c) => ({ data: { ...c.data, label: `C ${Date.now()}` } }));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ReactFlow
|
||||||
|
defaultNodes={[]}
|
||||||
|
defaultEdges={[]}
|
||||||
|
className="react-flow-basic-example"
|
||||||
|
minZoom={0.2}
|
||||||
|
maxZoom={4}
|
||||||
|
fitView
|
||||||
|
>
|
||||||
|
<Background variant={BackgroundVariant.Dots} />
|
||||||
|
<MiniMap />
|
||||||
|
<Controls />
|
||||||
|
|
||||||
|
<Panel position="top-right">
|
||||||
|
<button onClick={triggerMultipleSetNodes}>queue multiple setNodes calls</button>
|
||||||
|
<button onClick={triggerMultipleUpdateNodes}>queue multiple updateNode calls</button>
|
||||||
|
</Panel>
|
||||||
|
</ReactFlow>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
return (
|
||||||
|
<ReactFlowProvider>
|
||||||
|
<SetNotesBatchingFlow />
|
||||||
|
</ReactFlowProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -90,7 +90,7 @@ const initialNodes: Node[] = [
|
|||||||
data: { label: 'Node 5' },
|
data: { label: 'Node 5' },
|
||||||
position: { x: 650, y: 250 },
|
position: { x: 650, y: 250 },
|
||||||
className: 'light',
|
className: 'light',
|
||||||
style: { width: 400, height: 150 },
|
style: { width: 100, height: 100 },
|
||||||
zIndex: 1000,
|
zIndex: 1000,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -161,9 +161,12 @@ const Subflow = () => {
|
|||||||
setNodes((nds) => {
|
setNodes((nds) => {
|
||||||
return nds.map((n) => {
|
return nds.map((n) => {
|
||||||
if (!n.parentNode) {
|
if (!n.parentNode) {
|
||||||
n.position = {
|
return {
|
||||||
x: Math.random() * 400,
|
...n,
|
||||||
y: Math.random() * 400,
|
position: {
|
||||||
|
x: Math.random() * 400,
|
||||||
|
y: Math.random() * 400,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,8 +181,10 @@ const Subflow = () => {
|
|||||||
const toggleClassnames = () => {
|
const toggleClassnames = () => {
|
||||||
setNodes((nds) => {
|
setNodes((nds) => {
|
||||||
return nds.map((n) => {
|
return nds.map((n) => {
|
||||||
n.className = n.className === 'light' ? 'dark' : 'light';
|
return {
|
||||||
return n;
|
...n,
|
||||||
|
className: n.className === 'light' ? 'dark' : 'light',
|
||||||
|
};
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -187,8 +192,10 @@ const Subflow = () => {
|
|||||||
const toggleChildNodes = () => {
|
const toggleChildNodes = () => {
|
||||||
setNodes((nds) => {
|
setNodes((nds) => {
|
||||||
return nds.map((n) => {
|
return nds.map((n) => {
|
||||||
n.hidden = !!n.parentNode && !n.hidden;
|
return {
|
||||||
return n;
|
...n,
|
||||||
|
hidden: !!n.parentNode && !n.hidden,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -215,19 +222,12 @@ const Subflow = () => {
|
|||||||
<Background />
|
<Background />
|
||||||
|
|
||||||
<Panel position="top-right">
|
<Panel position="top-right">
|
||||||
<button onClick={resetTransform} style={{ marginRight: 5 }}>
|
<button onClick={resetTransform}>reset transform</button>
|
||||||
reset transform
|
<button onClick={updatePos}>change pos</button>
|
||||||
</button>
|
<button onClick={toggleClassnames}>toggle classnames</button>
|
||||||
<button onClick={updatePos} style={{ marginRight: 5 }}>
|
<button onClick={toggleChildNodes}>toggleChildNodes</button>
|
||||||
change pos
|
|
||||||
</button>
|
|
||||||
<button onClick={toggleClassnames} style={{ marginRight: 5 }}>
|
|
||||||
toggle classnames
|
|
||||||
</button>
|
|
||||||
<button style={{ marginRight: 5 }} onClick={toggleChildNodes}>
|
|
||||||
toggleChildNodes
|
|
||||||
</button>
|
|
||||||
<button onClick={logToObject}>toObject</button>
|
<button onClick={logToObject}>toObject</button>
|
||||||
|
<button onClick={() => setNodes(initialNodes)}>setNodes</button>
|
||||||
</Panel>
|
</Panel>
|
||||||
</ReactFlow>
|
</ReactFlow>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -14,8 +14,16 @@ function TextNode({ id, data }: NodeProps) {
|
|||||||
return (
|
return (
|
||||||
<div style={{ background: '#eee', color: '#222', padding: 10, fontSize: 12, borderRadius: 10 }}>
|
<div style={{ background: '#eee', color: '#222', padding: 10, fontSize: 12, borderRadius: 10 }}>
|
||||||
<div>node {id}</div>
|
<div>node {id}</div>
|
||||||
<div>
|
<div style={{ marginTop: 5 }}>
|
||||||
<input onChange={(evt) => updateText(evt.target.value)} value={text} />
|
<label style={{ fontSize: 12 }}>useState + updateNodeData</label>
|
||||||
|
<input onChange={(evt) => updateText(evt.target.value)} value={text} style={{ display: 'block' }} />
|
||||||
|
|
||||||
|
<label style={{ fontSize: 12 }}>updateNodeData</label>
|
||||||
|
<input
|
||||||
|
onChange={(evt) => updateNodeData(id, { text: evt.target.value })}
|
||||||
|
value={data.text}
|
||||||
|
style={{ display: 'block' }}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Handle type="source" position={Position.Right} />
|
<Handle type="source" position={Position.Right} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ const initNodes: MyNode[] = [
|
|||||||
data: {},
|
data: {},
|
||||||
position: { x: 100, y: 0 },
|
position: { x: 100, y: 0 },
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
id: '2',
|
id: '2',
|
||||||
type: 'text',
|
type: 'text',
|
||||||
|
|||||||
@@ -100,6 +100,29 @@
|
|||||||
data: { label: 'horizontal resizer with maxWidth', maxWidth: 300 },
|
data: { label: 'horizontal resizer with maxWidth', maxWidth: 300 },
|
||||||
position: { x: 250, y: 400 },
|
position: { x: 250, y: 400 },
|
||||||
style: nodeStyle
|
style: nodeStyle
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: { label: 'Parent' },
|
||||||
|
position: { x: 700, y: 0 },
|
||||||
|
style: nodeStyle + 'width: 300px; height: 300px'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5a',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: { label: 'Child' },
|
||||||
|
position: { x: 50, y: 50 },
|
||||||
|
parentNode: '5',
|
||||||
|
style: nodeStyle
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5b',
|
||||||
|
type: 'defaultResizer',
|
||||||
|
data: { label: 'Child' },
|
||||||
|
position: { x: 100, y: 100 },
|
||||||
|
parentNode: '5',
|
||||||
|
style: nodeStyle
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
# @xyflow/react
|
# @xyflow/react
|
||||||
|
|
||||||
|
## 12.0.0-next.9
|
||||||
|
|
||||||
|
### Patch changes
|
||||||
|
|
||||||
|
- a better `NodeResizer` that works with subflows. Child nodes do not move when parent node gets resized and parent extent is taken into account
|
||||||
|
- refactor `setNodes` batching
|
||||||
|
- re-measure nodes when necessary
|
||||||
|
- don't trigger drag start / end when node is not draggable
|
||||||
|
|
||||||
## 12.0.0-next.8
|
## 12.0.0-next.8
|
||||||
|
|
||||||
### Patch changes
|
### Patch changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@xyflow/react",
|
"name": "@xyflow/react",
|
||||||
"version": "12.0.0-next.7",
|
"version": "12.0.0-next.9",
|
||||||
"description": "React Flow - A highly customizable React library for building node-based editors and interactive flow charts.",
|
"description": "React Flow - A highly customizable React library for building node-based editors and interactive flow charts.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"react",
|
"react",
|
||||||
|
|||||||
@@ -49,9 +49,10 @@ function MiniMapComponent({
|
|||||||
// We need to rename the prop to be `CapitalCase` so that JSX will render it as
|
// We need to rename the prop to be `CapitalCase` so that JSX will render it as
|
||||||
// a component properly.
|
// a component properly.
|
||||||
nodeComponent,
|
nodeComponent,
|
||||||
|
bgColor,
|
||||||
maskColor,
|
maskColor,
|
||||||
maskStrokeColor = 'none',
|
maskStrokeColor,
|
||||||
maskStrokeWidth = 1,
|
maskStrokeWidth,
|
||||||
position = 'bottom-right',
|
position = 'bottom-right',
|
||||||
onClick,
|
onClick,
|
||||||
onNodeClick,
|
onNodeClick,
|
||||||
@@ -130,7 +131,11 @@ function MiniMapComponent({
|
|||||||
style={
|
style={
|
||||||
{
|
{
|
||||||
...style,
|
...style,
|
||||||
'--xy-minimap-mask-color-props': typeof maskColor === 'string' ? maskColor : undefined,
|
'--xy-minimap-background-color-props': typeof bgColor === 'string' ? bgColor : undefined,
|
||||||
|
'--xy-minimap-mask-background-color-props': typeof maskColor === 'string' ? maskColor : undefined,
|
||||||
|
'--xy-minimap-mask-stroke-color-props': typeof maskStrokeColor === 'string' ? maskStrokeColor : undefined,
|
||||||
|
'--xy-minimap-mask-stroke-width-props':
|
||||||
|
typeof maskStrokeWidth === 'number' ? maskStrokeWidth * viewScale : undefined,
|
||||||
'--xy-minimap-node-background-color-props': typeof nodeColor === 'string' ? nodeColor : undefined,
|
'--xy-minimap-node-background-color-props': typeof nodeColor === 'string' ? nodeColor : undefined,
|
||||||
'--xy-minimap-node-stroke-color-props': typeof nodeStrokeColor === 'string' ? nodeStrokeColor : undefined,
|
'--xy-minimap-node-stroke-color-props': typeof nodeStrokeColor === 'string' ? nodeStrokeColor : undefined,
|
||||||
'--xy-minimap-node-stroke-width-props': typeof nodeStrokeWidth === 'string' ? nodeStrokeWidth : undefined,
|
'--xy-minimap-node-stroke-width-props': typeof nodeStrokeWidth === 'string' ? nodeStrokeWidth : undefined,
|
||||||
@@ -143,6 +148,7 @@ function MiniMapComponent({
|
|||||||
width={elementWidth}
|
width={elementWidth}
|
||||||
height={elementHeight}
|
height={elementHeight}
|
||||||
viewBox={`${x} ${y} ${width} ${height}`}
|
viewBox={`${x} ${y} ${width} ${height}`}
|
||||||
|
className="react-flow__minimap-svg"
|
||||||
role="img"
|
role="img"
|
||||||
aria-labelledby={labelledBy}
|
aria-labelledby={labelledBy}
|
||||||
ref={svg}
|
ref={svg}
|
||||||
@@ -163,8 +169,6 @@ function MiniMapComponent({
|
|||||||
d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z
|
d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z
|
||||||
M${viewBB.x},${viewBB.y}h${viewBB.width}v${viewBB.height}h${-viewBB.width}z`}
|
M${viewBB.x},${viewBB.y}h${viewBB.width}v${viewBB.height}h${-viewBB.width}z`}
|
||||||
fillRule="evenodd"
|
fillRule="evenodd"
|
||||||
stroke={maskStrokeColor}
|
|
||||||
strokeWidth={maskStrokeWidth}
|
|
||||||
pointerEvents="none"
|
pointerEvents="none"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ export type MiniMapProps<NodeType extends Node = Node> = Omit<HTMLAttributes<SVG
|
|||||||
nodeStrokeWidth?: number;
|
nodeStrokeWidth?: number;
|
||||||
/** Component used to render nodes on minimap */
|
/** Component used to render nodes on minimap */
|
||||||
nodeComponent?: ComponentType<MiniMapNodeProps>;
|
nodeComponent?: ComponentType<MiniMapNodeProps>;
|
||||||
|
/** Background color of minimap */
|
||||||
|
bgColor?: string;
|
||||||
/** Color of mask representing viewport */
|
/** Color of mask representing viewport */
|
||||||
maskColor?: string;
|
maskColor?: string;
|
||||||
/** Stroke color of mask representing viewport */
|
/** Stroke color of mask representing viewport */
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import { useRef, useEffect, memo } from 'react';
|
import { useRef, useEffect, memo } from 'react';
|
||||||
import cc from 'classcat';
|
import cc from 'classcat';
|
||||||
import { XYResizer, ResizeControlVariant, type XYResizerInstance, type XYResizerChange } from '@xyflow/system';
|
import {
|
||||||
|
XYResizer,
|
||||||
|
ResizeControlVariant,
|
||||||
|
type XYResizerInstance,
|
||||||
|
type XYResizerChange,
|
||||||
|
XYResizerChildChange,
|
||||||
|
} from '@xyflow/system';
|
||||||
|
|
||||||
import { useStoreApi } from '../../hooks/useStore';
|
import { useStoreApi } from '../../hooks/useStore';
|
||||||
import { useNodeId } from '../../contexts/NodeIdContext';
|
import { useNodeId } from '../../contexts/NodeIdContext';
|
||||||
@@ -52,7 +58,7 @@ function ResizeControl({
|
|||||||
snapToGrid,
|
snapToGrid,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
onChange: (change: XYResizerChange) => {
|
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
|
||||||
const { triggerNodeChanges } = store.getState();
|
const { triggerNodeChanges } = store.getState();
|
||||||
|
|
||||||
const changes: NodeChange[] = [];
|
const changes: NodeChange[] = [];
|
||||||
@@ -83,6 +89,16 @@ function ResizeControl({
|
|||||||
|
|
||||||
changes.push(dimensionChange);
|
changes.push(dimensionChange);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const childChange of childChanges) {
|
||||||
|
const positionChange: NodePositionChange = {
|
||||||
|
...childChange,
|
||||||
|
type: 'position',
|
||||||
|
};
|
||||||
|
|
||||||
|
changes.push(positionChange);
|
||||||
|
}
|
||||||
|
|
||||||
triggerNodeChanges(changes);
|
triggerNodeChanges(changes);
|
||||||
},
|
},
|
||||||
onEnd: () => {
|
onEnd: () => {
|
||||||
|
|||||||
@@ -101,12 +101,12 @@ export function EdgeWrapper({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const markerStartUrl = useMemo(
|
const markerStartUrl = useMemo(
|
||||||
() => (edge.markerStart ? `url(#${getMarkerId(edge.markerStart, rfId)})` : undefined),
|
() => (edge.markerStart ? `url('#${getMarkerId(edge.markerStart, rfId)}')` : undefined),
|
||||||
[edge.markerStart, rfId]
|
[edge.markerStart, rfId]
|
||||||
);
|
);
|
||||||
|
|
||||||
const markerEndUrl = useMemo(
|
const markerEndUrl = useMemo(
|
||||||
() => (edge.markerEnd ? `url(#${getMarkerId(edge.markerEnd, rfId)})` : undefined),
|
() => (edge.markerEnd ? `url('#${getMarkerId(edge.markerEnd, rfId)}')` : undefined),
|
||||||
[edge.markerEnd, rfId]
|
[edge.markerEnd, rfId]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { useStore, useStoreApi } from '../../hooks/useStore';
|
|||||||
import { Provider } from '../../contexts/NodeIdContext';
|
import { Provider } from '../../contexts/NodeIdContext';
|
||||||
import { ARIA_NODE_DESC_KEY } from '../A11yDescriptions';
|
import { ARIA_NODE_DESC_KEY } from '../A11yDescriptions';
|
||||||
import { useDrag } from '../../hooks/useDrag';
|
import { useDrag } from '../../hooks/useDrag';
|
||||||
import { useUpdateNodePositions } from '../../hooks/useUpdateNodePositions';
|
import { useMoveSelectedNodes } from '../../hooks/useMoveSelectedNodes';
|
||||||
import { handleNodeClick } from '../Nodes/utils';
|
import { handleNodeClick } from '../Nodes/utils';
|
||||||
import { arrowKeyDiffs, builtinNodeTypes } from './utils';
|
import { arrowKeyDiffs, builtinNodeTypes } from './utils';
|
||||||
import type { NodeWrapperProps } from '../../types';
|
import type { NodeWrapperProps } from '../../types';
|
||||||
@@ -79,16 +79,33 @@ export function NodeWrapper({
|
|||||||
const prevTargetPosition = useRef(node.targetPosition);
|
const prevTargetPosition = useRef(node.targetPosition);
|
||||||
const prevType = useRef(nodeType);
|
const prevType = useRef(nodeType);
|
||||||
|
|
||||||
const updatePositions = useUpdateNodePositions();
|
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 hasHandleBounds = !!node[internalsSymbol]?.handleBounds;
|
||||||
|
|
||||||
|
const moveSelectedNodes = useMoveSelectedNodes();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (nodeRef.current) {
|
||||||
|
resizeObserver?.unobserve(nodeRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (nodeRef.current && !node.hidden) {
|
if (nodeRef.current && !node.hidden) {
|
||||||
const currNode = nodeRef.current;
|
const currNode = nodeRef.current;
|
||||||
resizeObserver?.observe(currNode);
|
|
||||||
|
|
||||||
return () => resizeObserver?.unobserve(currNode);
|
if (!initialized || !hasHandleBounds) {
|
||||||
|
resizeObserver?.unobserve(currNode);
|
||||||
|
resizeObserver?.observe(currNode);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [node.hidden]);
|
}, [node.hidden, initialized, hasHandleBounds]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// when the user programmatically changes the source or handle position, we re-initialize the node
|
// when the user programmatically changes the source or handle position, we re-initialize the node
|
||||||
@@ -123,11 +140,6 @@ export function NodeWrapper({
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const width = node.width ?? undefined;
|
|
||||||
const height = node.height ?? undefined;
|
|
||||||
const computedWidth = node.computed?.width;
|
|
||||||
const computedHeight = node.computed?.height;
|
|
||||||
|
|
||||||
const positionAbsoluteOrigin = getPositionWithOrigin({
|
const positionAbsoluteOrigin = getPositionWithOrigin({
|
||||||
x: positionAbsoluteX,
|
x: positionAbsoluteX,
|
||||||
y: positionAbsoluteY,
|
y: positionAbsoluteY,
|
||||||
@@ -135,7 +147,6 @@ export function NodeWrapper({
|
|||||||
height: computedHeight ?? height ?? 0,
|
height: computedHeight ?? height ?? 0,
|
||||||
origin: node.origin || nodeOrigin,
|
origin: node.origin || nodeOrigin,
|
||||||
});
|
});
|
||||||
const initialized = (!!computedWidth && !!computedHeight) || (!!width && !!height);
|
|
||||||
const hasPointerEvents = isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave;
|
const hasPointerEvents = isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave;
|
||||||
|
|
||||||
const onMouseEnterHandler = onMouseEnter ? (event: MouseEvent) => onMouseEnter(event, { ...node }) : undefined;
|
const onMouseEnterHandler = onMouseEnter ? (event: MouseEvent) => onMouseEnter(event, { ...node }) : undefined;
|
||||||
@@ -188,10 +199,9 @@ export function NodeWrapper({
|
|||||||
.toLowerCase()}. New position, x: ${~~positionAbsoluteX}, y: ${~~positionAbsoluteY}`,
|
.toLowerCase()}. New position, x: ${~~positionAbsoluteX}, y: ${~~positionAbsoluteY}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
updatePositions({
|
moveSelectedNodes({
|
||||||
x: arrowKeyDiffs[event.key].x,
|
direction: arrowKeyDiffs[event.key],
|
||||||
y: arrowKeyDiffs[event.key].y,
|
factor: event.shiftKey ? 4 : 1,
|
||||||
isShiftPressed: event.shiftKey,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { getNodesBounds } from '@xyflow/system';
|
|||||||
|
|
||||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||||
import { useDrag } from '../../hooks/useDrag';
|
import { useDrag } from '../../hooks/useDrag';
|
||||||
import { useUpdateNodePositions } from '../../hooks/useUpdateNodePositions';
|
import { useMoveSelectedNodes } from '../../hooks/useMoveSelectedNodes';
|
||||||
import { arrowKeyDiffs } from '../NodeWrapper/utils';
|
import { arrowKeyDiffs } from '../NodeWrapper/utils';
|
||||||
import type { Node, ReactFlowState } from '../../types';
|
import type { Node, ReactFlowState } from '../../types';
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ const selector = (s: ReactFlowState) => {
|
|||||||
export function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }: NodesSelectionProps) {
|
export function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }: NodesSelectionProps) {
|
||||||
const store = useStoreApi();
|
const store = useStoreApi();
|
||||||
const { width, height, transformString, userSelectionActive } = useStore(selector, shallow);
|
const { width, height, transformString, userSelectionActive } = useStore(selector, shallow);
|
||||||
const updatePositions = useUpdateNodePositions();
|
const moveSelectedNodes = useMoveSelectedNodes();
|
||||||
|
|
||||||
const nodeRef = useRef<HTMLDivElement>(null);
|
const nodeRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
@@ -64,10 +64,9 @@ export function NodesSelection({ onSelectionContextMenu, noPanClassName, disable
|
|||||||
|
|
||||||
const onKeyDown = (event: KeyboardEvent) => {
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
if (Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
|
if (Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
|
||||||
updatePositions({
|
moveSelectedNodes({
|
||||||
x: arrowKeyDiffs[event.key].x,
|
direction: arrowKeyDiffs[event.key],
|
||||||
y: arrowKeyDiffs[event.key].y,
|
factor: event.shiftKey ? 4 : 1,
|
||||||
isShiftPressed: event.shiftKey,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ export function ReactFlowProvider({
|
|||||||
children,
|
children,
|
||||||
initialNodes,
|
initialNodes,
|
||||||
initialEdges,
|
initialEdges,
|
||||||
|
defaultNodes,
|
||||||
|
defaultEdges,
|
||||||
initialWidth,
|
initialWidth,
|
||||||
initialHeight,
|
initialHeight,
|
||||||
fitView,
|
fitView,
|
||||||
@@ -17,16 +19,19 @@ export function ReactFlowProvider({
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
initialNodes?: Node[];
|
initialNodes?: Node[];
|
||||||
initialEdges?: Edge[];
|
initialEdges?: Edge[];
|
||||||
|
defaultNodes?: Node[];
|
||||||
|
defaultEdges?: Edge[];
|
||||||
initialWidth?: number;
|
initialWidth?: number;
|
||||||
initialHeight?: number;
|
initialHeight?: number;
|
||||||
fitView?: boolean;
|
fitView?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const storeRef = useRef<UseBoundStoreWithEqualityFn<StoreApi<ReactFlowState>> | null>(null);
|
const storeRef = useRef<UseBoundStoreWithEqualityFn<StoreApi<ReactFlowState>> | null>(null);
|
||||||
|
|
||||||
if (!storeRef.current) {
|
if (!storeRef.current) {
|
||||||
storeRef.current = createRFStore({
|
storeRef.current = createRFStore({
|
||||||
nodes: initialNodes,
|
nodes: initialNodes,
|
||||||
edges: initialEdges,
|
edges: initialEdges,
|
||||||
|
defaultNodes,
|
||||||
|
defaultEdges,
|
||||||
width: initialWidth,
|
width: initialWidth,
|
||||||
height: initialHeight,
|
height: initialHeight,
|
||||||
fitView,
|
fitView,
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { infiniteExtent, type CoordinateExtent } from '@xyflow/system';
|
|||||||
|
|
||||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||||
import type { Node, Edge, ReactFlowState, ReactFlowProps, FitViewOptions } from '../../types';
|
import type { Node, Edge, ReactFlowState, ReactFlowProps, FitViewOptions } from '../../types';
|
||||||
import { initNodeOrigin } from '../../container/ReactFlow';
|
import { defaultNodeOrigin } from '../../container/ReactFlow/init-values';
|
||||||
|
|
||||||
// these fields exist in the global store and we need to keep them up to date
|
// these fields exist in the global store and we need to keep them up to date
|
||||||
const reactFlowFieldsToTrack = [
|
const reactFlowFieldsToTrack = [
|
||||||
@@ -76,48 +76,51 @@ const fieldsToTrack = [...reactFlowFieldsToTrack, 'rfId'] as const;
|
|||||||
const selector = (s: ReactFlowState) => ({
|
const selector = (s: ReactFlowState) => ({
|
||||||
setNodes: s.setNodes,
|
setNodes: s.setNodes,
|
||||||
setEdges: s.setEdges,
|
setEdges: s.setEdges,
|
||||||
setDefaultNodesAndEdges: s.setDefaultNodesAndEdges,
|
|
||||||
setMinZoom: s.setMinZoom,
|
setMinZoom: s.setMinZoom,
|
||||||
setMaxZoom: s.setMaxZoom,
|
setMaxZoom: s.setMaxZoom,
|
||||||
setTranslateExtent: s.setTranslateExtent,
|
setTranslateExtent: s.setTranslateExtent,
|
||||||
setNodeExtent: s.setNodeExtent,
|
setNodeExtent: s.setNodeExtent,
|
||||||
reset: s.reset,
|
reset: s.reset,
|
||||||
|
setDefaultNodesAndEdges: s.setDefaultNodesAndEdges,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const initPrevValues = {
|
||||||
|
// these are values that are also passed directly to other components
|
||||||
|
// than the StoreUpdater. We can reduce the number of setStore calls
|
||||||
|
// by setting the same values here as prev fields.
|
||||||
|
translateExtent: infiniteExtent,
|
||||||
|
nodeOrigin: defaultNodeOrigin,
|
||||||
|
minZoom: 0.5,
|
||||||
|
maxZoom: 2,
|
||||||
|
elementsSelectable: true,
|
||||||
|
noPanClassName: 'nopan',
|
||||||
|
rfId: '1',
|
||||||
|
};
|
||||||
|
|
||||||
export function StoreUpdater(props: StoreUpdaterProps) {
|
export function StoreUpdater(props: StoreUpdaterProps) {
|
||||||
const {
|
const {
|
||||||
setNodes,
|
setNodes,
|
||||||
setEdges,
|
setEdges,
|
||||||
setDefaultNodesAndEdges,
|
|
||||||
setMinZoom,
|
setMinZoom,
|
||||||
setMaxZoom,
|
setMaxZoom,
|
||||||
setTranslateExtent,
|
setTranslateExtent,
|
||||||
setNodeExtent,
|
setNodeExtent,
|
||||||
reset,
|
reset,
|
||||||
|
setDefaultNodesAndEdges,
|
||||||
} = useStore(selector, shallow);
|
} = useStore(selector, shallow);
|
||||||
const store = useStoreApi();
|
const store = useStoreApi();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const edgesWithDefaults = props.defaultEdges?.map((e) => ({ ...e, ...props.defaultEdgeOptions }));
|
setDefaultNodesAndEdges(props.defaultNodes, props.defaultEdges);
|
||||||
setDefaultNodesAndEdges(props.defaultNodes, edgesWithDefaults);
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
// when we reset the store we also need to reset the previous fields
|
||||||
|
previousFields.current = initPrevValues;
|
||||||
reset();
|
reset();
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const previousFields = useRef<Partial<StoreUpdaterProps>>({
|
const previousFields = useRef<Partial<StoreUpdaterProps>>(initPrevValues);
|
||||||
// these are values that are also passed directly to other components
|
|
||||||
// than the StoreUpdater. We can reduce the number of setStore calls
|
|
||||||
// by setting the same values here as prev fields.
|
|
||||||
translateExtent: infiniteExtent,
|
|
||||||
nodeOrigin: initNodeOrigin,
|
|
||||||
minZoom: 0.5,
|
|
||||||
maxZoom: 2,
|
|
||||||
elementsSelectable: true,
|
|
||||||
noPanClassName: 'nopan',
|
|
||||||
rfId: '1',
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(
|
useEffect(
|
||||||
() => {
|
() => {
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ export type GraphViewProps = Omit<
|
|||||||
| 'maxZoom'
|
| 'maxZoom'
|
||||||
| 'defaultMarkerColor'
|
| 'defaultMarkerColor'
|
||||||
| 'noDragClassName'
|
| 'noDragClassName'
|
||||||
| 'noDragClassName'
|
|
||||||
| 'noWheelClassName'
|
| 'noWheelClassName'
|
||||||
| 'noPanClassName'
|
| 'noPanClassName'
|
||||||
| 'defaultViewport'
|
| 'defaultViewport'
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ export function Wrapper({
|
|||||||
children,
|
children,
|
||||||
nodes,
|
nodes,
|
||||||
edges,
|
edges,
|
||||||
|
defaultNodes,
|
||||||
|
defaultEdges,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
fitView,
|
fitView,
|
||||||
@@ -15,6 +17,8 @@ export function Wrapper({
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
nodes?: Node[];
|
nodes?: Node[];
|
||||||
edges?: Edge[];
|
edges?: Edge[];
|
||||||
|
defaultNodes?: Node[];
|
||||||
|
defaultEdges?: Edge[];
|
||||||
width?: number;
|
width?: number;
|
||||||
height?: number;
|
height?: number;
|
||||||
fitView?: boolean;
|
fitView?: boolean;
|
||||||
@@ -31,6 +35,8 @@ export function Wrapper({
|
|||||||
<ReactFlowProvider
|
<ReactFlowProvider
|
||||||
initialNodes={nodes}
|
initialNodes={nodes}
|
||||||
initialEdges={edges}
|
initialEdges={edges}
|
||||||
|
defaultNodes={defaultNodes}
|
||||||
|
defaultEdges={defaultEdges}
|
||||||
initialWidth={width}
|
initialWidth={width}
|
||||||
initialHeight={height}
|
initialHeight={height}
|
||||||
fitView={fitView}
|
fitView={fitView}
|
||||||
|
|||||||
@@ -1,14 +1,6 @@
|
|||||||
import { forwardRef, type CSSProperties } from 'react';
|
import { forwardRef, type CSSProperties } from 'react';
|
||||||
import cc from 'classcat';
|
import cc from 'classcat';
|
||||||
import {
|
import { ConnectionLineType, PanOnScrollMode, SelectionMode, infiniteExtent, isMacOs } from '@xyflow/system';
|
||||||
ConnectionLineType,
|
|
||||||
PanOnScrollMode,
|
|
||||||
SelectionMode,
|
|
||||||
infiniteExtent,
|
|
||||||
isMacOs,
|
|
||||||
type NodeOrigin,
|
|
||||||
type Viewport,
|
|
||||||
} from '@xyflow/system';
|
|
||||||
|
|
||||||
import { A11yDescriptions } from '../../components/A11yDescriptions';
|
import { A11yDescriptions } from '../../components/A11yDescriptions';
|
||||||
import { Attribution } from '../../components/Attribution';
|
import { Attribution } from '../../components/Attribution';
|
||||||
@@ -18,9 +10,7 @@ import { useColorModeClass } from '../../hooks/useColorModeClass';
|
|||||||
import { GraphView } from '../GraphView';
|
import { GraphView } from '../GraphView';
|
||||||
import { Wrapper } from './Wrapper';
|
import { Wrapper } from './Wrapper';
|
||||||
import type { ReactFlowProps, ReactFlowRefType } from '../../types';
|
import type { ReactFlowProps, ReactFlowRefType } from '../../types';
|
||||||
|
import { defaultViewport as initViewport, defaultNodeOrigin } from './init-values';
|
||||||
export const initNodeOrigin: NodeOrigin = [0, 0];
|
|
||||||
const initDefaultViewport: Viewport = { x: 0, y: 0, zoom: 1 };
|
|
||||||
|
|
||||||
const wrapperStyle: CSSProperties = {
|
const wrapperStyle: CSSProperties = {
|
||||||
width: '100%',
|
width: '100%',
|
||||||
@@ -89,11 +79,11 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
|||||||
nodesDraggable,
|
nodesDraggable,
|
||||||
nodesConnectable,
|
nodesConnectable,
|
||||||
nodesFocusable,
|
nodesFocusable,
|
||||||
nodeOrigin = initNodeOrigin,
|
nodeOrigin = defaultNodeOrigin,
|
||||||
edgesFocusable,
|
edgesFocusable,
|
||||||
edgesUpdatable,
|
edgesUpdatable,
|
||||||
elementsSelectable = true,
|
elementsSelectable = true,
|
||||||
defaultViewport = initDefaultViewport,
|
defaultViewport = initViewport,
|
||||||
minZoom = 0.5,
|
minZoom = 0.5,
|
||||||
maxZoom = 2,
|
maxZoom = 2,
|
||||||
translateExtent = infiniteExtent,
|
translateExtent = infiniteExtent,
|
||||||
@@ -166,7 +156,15 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
|||||||
data-testid="rf__wrapper"
|
data-testid="rf__wrapper"
|
||||||
id={id}
|
id={id}
|
||||||
>
|
>
|
||||||
<Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}>
|
<Wrapper
|
||||||
|
nodes={nodes}
|
||||||
|
edges={edges}
|
||||||
|
defaultNodes={defaultNodes}
|
||||||
|
defaultEdges={defaultEdges}
|
||||||
|
width={width}
|
||||||
|
height={height}
|
||||||
|
fitView={fitView}
|
||||||
|
>
|
||||||
<GraphView
|
<GraphView
|
||||||
onInit={onInit}
|
onInit={onInit}
|
||||||
onNodeClick={onNodeClick}
|
onNodeClick={onNodeClick}
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { type NodeOrigin, Viewport } from '@xyflow/system';
|
||||||
|
|
||||||
|
export const defaultNodeOrigin: NodeOrigin = [0, 0];
|
||||||
|
export const defaultViewport: Viewport = { x: 0, y: 0, zoom: 1 };
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
import { useEffect, useMemo, useRef } from 'react';
|
import { useEffect, useMemo, useRef } from 'react';
|
||||||
import { Connection, HandleType, areConnectionMapsEqual, handleConnectionChange } from '@xyflow/system';
|
import {
|
||||||
|
Connection,
|
||||||
|
HandleConnection,
|
||||||
|
HandleType,
|
||||||
|
areConnectionMapsEqual,
|
||||||
|
handleConnectionChange,
|
||||||
|
} from '@xyflow/system';
|
||||||
|
|
||||||
import { useStore } from './useStore';
|
import { useStore } from './useStore';
|
||||||
import { useNodeId } from '../contexts/NodeIdContext';
|
import { useNodeId } from '../contexts/NodeIdContext';
|
||||||
@@ -21,7 +27,7 @@ type useHandleConnectionsParams = {
|
|||||||
* @param param.id - the handle id (this is only needed if the node has multiple handles of the same type)
|
* @param param.id - the handle id (this is only needed if the node has multiple handles of the same type)
|
||||||
* @param param.onConnect - gets called when a connection is established
|
* @param param.onConnect - gets called when a connection is established
|
||||||
* @param param.onDisconnect - gets called when a connection is removed
|
* @param param.onDisconnect - gets called when a connection is removed
|
||||||
* @returns an array with connections
|
* @returns an array with handle connections
|
||||||
*/
|
*/
|
||||||
export function useHandleConnections({
|
export function useHandleConnections({
|
||||||
type,
|
type,
|
||||||
@@ -29,10 +35,11 @@ export function useHandleConnections({
|
|||||||
nodeId,
|
nodeId,
|
||||||
onConnect,
|
onConnect,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
}: useHandleConnectionsParams): Connection[] {
|
}: useHandleConnectionsParams): HandleConnection[] {
|
||||||
const _nodeId = useNodeId();
|
const _nodeId = useNodeId();
|
||||||
const prevConnections = useRef<Map<string, Connection> | null>(null);
|
const currentNodeId = nodeId ?? _nodeId;
|
||||||
const currentNodeId = nodeId || _nodeId;
|
|
||||||
|
const prevConnections = useRef<Map<string, HandleConnection> | null>(null);
|
||||||
|
|
||||||
const connections = useStore(
|
const connections = useStore(
|
||||||
(state) => state.connectionLookup.get(`${currentNodeId}-${type}-${id}`),
|
(state) => state.connectionLookup.get(`${currentNodeId}-${type}-${id}`),
|
||||||
|
|||||||
@@ -92,6 +92,12 @@ export function useKeyPress(
|
|||||||
} else {
|
} else {
|
||||||
pressedKeys.current.delete(event[keyOrCode]);
|
pressedKeys.current.delete(event[keyOrCode]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fix for Mac: when cmd key is pressed, keyup is not triggered for any other key, see: https://stackoverflow.com/questions/27380018/when-cmd-key-is-kept-pressed-keyup-is-not-triggered-for-any-other-key
|
||||||
|
if (event.key === 'Meta') {
|
||||||
|
pressedKeys.current.clear();
|
||||||
|
}
|
||||||
|
|
||||||
modifierPressed.current = false;
|
modifierPressed.current = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+11
-12
@@ -1,22 +1,22 @@
|
|||||||
import { useCallback } from 'react';
|
import { useCallback } from 'react';
|
||||||
import { calculateNodePosition, snapPosition } from '@xyflow/system';
|
import { calculateNodePosition, snapPosition, type XYPosition } from '@xyflow/system';
|
||||||
|
|
||||||
import { Node } from '../types';
|
import { Node } from '../types';
|
||||||
import { useStoreApi } from '../hooks/useStore';
|
import { useStoreApi } from './useStore';
|
||||||
|
|
||||||
const selectedAndDraggable = (nodesDraggable: boolean) => (n: Node) =>
|
const selectedAndDraggable = (nodesDraggable: boolean) => (n: Node) =>
|
||||||
n.selected && (n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'));
|
n.selected && (n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook for updating node positions.
|
* Hook for updating node positions by passing a direction and factor
|
||||||
*
|
*
|
||||||
* @internal
|
* @internal
|
||||||
* @returns function for updating node positions
|
* @returns function for updating node positions
|
||||||
*/
|
*/
|
||||||
export function useUpdateNodePositions() {
|
export function useMoveSelectedNodes() {
|
||||||
const store = useStoreApi();
|
const store = useStoreApi();
|
||||||
|
|
||||||
const updatePositions = useCallback((params: { x: number; y: number; isShiftPressed: boolean }) => {
|
const moveSelectedNodes = useCallback((params: { direction: XYPosition; factor: number }) => {
|
||||||
const {
|
const {
|
||||||
nodeExtent,
|
nodeExtent,
|
||||||
nodes,
|
nodes,
|
||||||
@@ -29,14 +29,13 @@ export function useUpdateNodePositions() {
|
|||||||
nodeOrigin,
|
nodeOrigin,
|
||||||
} = store.getState();
|
} = store.getState();
|
||||||
const selectedNodes = nodes.filter(selectedAndDraggable(nodesDraggable));
|
const selectedNodes = nodes.filter(selectedAndDraggable(nodesDraggable));
|
||||||
// by default a node moves 5px on each key press, or 20px if shift is pressed
|
// by default a node moves 5px on each key press
|
||||||
// if snap grid is enabled, we use that for the velocity.
|
// if snap grid is enabled, we use that for the velocity
|
||||||
const xVelo = snapToGrid ? snapGrid[0] : 5;
|
const xVelo = snapToGrid ? snapGrid[0] : 5;
|
||||||
const yVelo = snapToGrid ? snapGrid[1] : 5;
|
const yVelo = snapToGrid ? snapGrid[1] : 5;
|
||||||
const factor = params.isShiftPressed ? 4 : 1;
|
|
||||||
|
|
||||||
const xDiff = params.x * xVelo * factor;
|
const xDiff = params.direction.x * xVelo * params.factor;
|
||||||
const yDiff = params.y * yVelo * factor;
|
const yDiff = params.direction.y * yVelo * params.factor;
|
||||||
|
|
||||||
const nodeUpdates = selectedNodes.map((node) => {
|
const nodeUpdates = selectedNodes.map((node) => {
|
||||||
if (node.computed?.positionAbsolute) {
|
if (node.computed?.positionAbsolute) {
|
||||||
@@ -65,8 +64,8 @@ export function useUpdateNodePositions() {
|
|||||||
return node;
|
return node;
|
||||||
});
|
});
|
||||||
|
|
||||||
updateNodePositions(nodeUpdates, true, false);
|
updateNodePositions(nodeUpdates);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return updatePositions;
|
return moveSelectedNodes;
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,9 @@
|
|||||||
import { useCallback, useMemo, useRef } from 'react';
|
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { getElementsToRemove, getOverlappingArea, isRectObject, nodeToRect, type Rect } from '@xyflow/system';
|
import { getElementsToRemove, getOverlappingArea, isRectObject, nodeToRect, type Rect } from '@xyflow/system';
|
||||||
|
|
||||||
import useViewportHelper from './useViewportHelper';
|
import useViewportHelper from './useViewportHelper';
|
||||||
import { useStoreApi } from './useStore';
|
import { useStoreApi } from './useStore';
|
||||||
import type {
|
import type { ReactFlowInstance, Instance, Node, Edge } from '../types';
|
||||||
ReactFlowInstance,
|
|
||||||
Instance,
|
|
||||||
NodeAddChange,
|
|
||||||
EdgeAddChange,
|
|
||||||
Node,
|
|
||||||
Edge,
|
|
||||||
NodeChange,
|
|
||||||
EdgeChange,
|
|
||||||
} from '../types';
|
|
||||||
import { getElementsDiffChanges, isNode } from '../utils';
|
import { getElementsDiffChanges, isNode } from '../utils';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,82 +37,109 @@ export function useReactFlow<NodeType extends Node = Node, EdgeType extends Edge
|
|||||||
return edges.find((e) => e.id === id) as EdgeType;
|
return edges.find((e) => e.id === id) as EdgeType;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// this is used to handle multiple syncronous setNodes calls
|
type SetElementsQueue = {
|
||||||
const setNodesData = useRef<Node[]>();
|
nodes: (NodeType[] | ((nodes: NodeType[]) => NodeType[]))[];
|
||||||
const setNodesTimeout = useRef<ReturnType<typeof setTimeout>>();
|
edges: (EdgeType[] | ((edges: EdgeType[]) => EdgeType[]))[];
|
||||||
const setNodes = useCallback<Instance.SetNodes<NodeType>>((payload) => {
|
};
|
||||||
const { nodes = [], setNodes, hasDefaultNodes, onNodesChange, nodeLookup } = store.getState();
|
|
||||||
const nextNodes = typeof payload === 'function' ? payload((setNodesData.current as NodeType[]) || nodes) : payload;
|
|
||||||
|
|
||||||
setNodesData.current = nextNodes;
|
// A reference of all the batched updates to process before the next render. We
|
||||||
|
// want a mutable reference here so multiple synchronous calls to `setNodes` etc
|
||||||
|
// can be batched together.
|
||||||
|
const setElementsQueue = useRef<SetElementsQueue>({ nodes: [], edges: [] });
|
||||||
|
// Because we're using a ref above, we need some way to let React know when to
|
||||||
|
// actually process the queue. We flip this bit of state to `true` any time we
|
||||||
|
// mutate the queue and then flip it back to `false` after flushing the queue.
|
||||||
|
const [shouldFlushQueue, setShouldFlushQueue] = useState(false);
|
||||||
|
|
||||||
if (setNodesTimeout.current) {
|
// Layout effects are guaranteed to run before the next render which means we
|
||||||
clearTimeout(setNodesTimeout.current);
|
// 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(() => {
|
||||||
|
// 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
|
||||||
|
// and bail early.
|
||||||
|
if (!shouldFlushQueue) {
|
||||||
|
setElementsQueue.current = { nodes: [], edges: [] };
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// if there are multiple synchronous setNodes calls, we only want to call onNodesChange once
|
if (setElementsQueue.current.nodes.length) {
|
||||||
// for this, we use a timeout to wait for the last call and store updated nodes in setNodesData
|
const { nodes = [], setNodes, hasDefaultNodes, onNodesChange, nodeLookup } = store.getState();
|
||||||
// this is not perfect, but should work in most cases
|
|
||||||
setNodesTimeout.current = setTimeout(() => {
|
// This is essentially an `Array.reduce` in imperative clothing. Processing
|
||||||
if (hasDefaultNodes) {
|
// this queue is a relatively hot path so we'd like to avoid the overhead of
|
||||||
setNodes(nextNodes);
|
// array methods where we can.
|
||||||
} else if (onNodesChange) {
|
let next = nodes as NodeType[];
|
||||||
const changes: NodeChange[] = getElementsDiffChanges({ items: setNodesData.current, lookup: nodeLookup });
|
for (const payload of setElementsQueue.current.nodes) {
|
||||||
onNodesChange(changes);
|
next = typeof payload === 'function' ? payload(next) : payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
setNodesData.current = undefined;
|
if (hasDefaultNodes) {
|
||||||
}, 0);
|
setNodes(next);
|
||||||
|
} else if (onNodesChange) {
|
||||||
|
onNodesChange(
|
||||||
|
getElementsDiffChanges({
|
||||||
|
items: next,
|
||||||
|
lookup: nodeLookup,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setElementsQueue.current.nodes = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (setElementsQueue.current.edges.length) {
|
||||||
|
const { edges = [], setEdges, hasDefaultEdges, onEdgesChange, edgeLookup } = store.getState();
|
||||||
|
|
||||||
|
let next = edges as EdgeType[];
|
||||||
|
for (const payload of setElementsQueue.current.edges) {
|
||||||
|
next = typeof payload === 'function' ? payload(next) : payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasDefaultEdges) {
|
||||||
|
setEdges(next);
|
||||||
|
} else if (onEdgesChange) {
|
||||||
|
onEdgesChange(
|
||||||
|
getElementsDiffChanges({
|
||||||
|
items: next,
|
||||||
|
lookup: edgeLookup,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setElementsQueue.current.edges = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Beacuse we're using reactive state to trigger this effect, we need to flip
|
||||||
|
// it back to false.
|
||||||
|
setShouldFlushQueue(false);
|
||||||
|
}, [shouldFlushQueue]);
|
||||||
|
|
||||||
|
const setNodes = useCallback<Instance.SetNodes<NodeType>>((payload) => {
|
||||||
|
setElementsQueue.current.nodes.push(payload);
|
||||||
|
setShouldFlushQueue(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// this is used to handle multiple syncronous setEdges calls
|
|
||||||
const setEdgesData = useRef<Edge[]>();
|
|
||||||
const setEdgesTimeout = useRef<ReturnType<typeof setTimeout>>();
|
|
||||||
const setEdges = useCallback<Instance.SetEdges<EdgeType>>((payload) => {
|
const setEdges = useCallback<Instance.SetEdges<EdgeType>>((payload) => {
|
||||||
const { edges = [], setEdges, hasDefaultEdges, onEdgesChange, edgeLookup } = store.getState();
|
setElementsQueue.current.edges.push(payload);
|
||||||
const nextEdges = typeof payload === 'function' ? payload((setEdgesData.current as EdgeType[]) || edges) : payload;
|
setShouldFlushQueue(true);
|
||||||
|
|
||||||
setEdgesData.current = nextEdges;
|
|
||||||
|
|
||||||
if (setEdgesTimeout.current) {
|
|
||||||
clearTimeout(setEdgesTimeout.current);
|
|
||||||
}
|
|
||||||
|
|
||||||
setEdgesTimeout.current = setTimeout(() => {
|
|
||||||
if (hasDefaultEdges) {
|
|
||||||
setEdges(nextEdges);
|
|
||||||
} else if (onEdgesChange) {
|
|
||||||
const changes: EdgeChange[] = getElementsDiffChanges({ items: nextEdges, lookup: edgeLookup });
|
|
||||||
onEdgesChange(changes);
|
|
||||||
}
|
|
||||||
|
|
||||||
setEdgesData.current = undefined;
|
|
||||||
}, 0);
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const addNodes = useCallback<Instance.AddNodes<NodeType>>((payload) => {
|
const addNodes = useCallback<Instance.AddNodes<NodeType>>((payload) => {
|
||||||
const nodes = Array.isArray(payload) ? payload : [payload];
|
const newNodes = Array.isArray(payload) ? payload : [payload];
|
||||||
const { nodes: currentNodes, hasDefaultNodes, onNodesChange, setNodes } = store.getState();
|
|
||||||
|
|
||||||
if (hasDefaultNodes) {
|
// Queueing a functional update means that we won't worry about other calls
|
||||||
const nextNodes = [...currentNodes, ...nodes];
|
// to `setNodes` that might happen elsewhere.
|
||||||
setNodes(nextNodes);
|
setElementsQueue.current.nodes.push((nodes) => [...nodes, ...newNodes]);
|
||||||
} else if (onNodesChange) {
|
setShouldFlushQueue(true);
|
||||||
const changes = nodes.map((node) => ({ item: node, type: 'add' } as NodeAddChange<NodeType>));
|
|
||||||
onNodesChange(changes);
|
|
||||||
}
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const addEdges = useCallback<Instance.AddEdges<EdgeType>>((payload) => {
|
const addEdges = useCallback<Instance.AddEdges<EdgeType>>((payload) => {
|
||||||
const nextEdges = Array.isArray(payload) ? payload : [payload];
|
const newEdges = Array.isArray(payload) ? payload : [payload];
|
||||||
const { edges = [], setEdges, hasDefaultEdges, onEdgesChange } = store.getState();
|
|
||||||
|
|
||||||
if (hasDefaultEdges) {
|
setElementsQueue.current.edges.push((edges) => [...edges, ...newEdges]);
|
||||||
setEdges([...edges, ...nextEdges]);
|
setShouldFlushQueue(true);
|
||||||
} else if (onEdgesChange) {
|
|
||||||
const changes = nextEdges.map((edge) => ({ item: edge, type: 'add' } as EdgeAddChange<EdgeType>));
|
|
||||||
onEdgesChange(changes);
|
|
||||||
}
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const toObject = useCallback<Instance.ToObject<NodeType, EdgeType>>(() => {
|
const toObject = useCallback<Instance.ToObject<NodeType, EdgeType>>(() => {
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ import {
|
|||||||
updateConnectionLookup,
|
updateConnectionLookup,
|
||||||
} from '@xyflow/system';
|
} from '@xyflow/system';
|
||||||
|
|
||||||
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
|
import { applyEdgeChanges, applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
|
||||||
import { updateNodesAndEdgesSelections } from './utils';
|
|
||||||
import getInitialState from './initialState';
|
import getInitialState from './initialState';
|
||||||
import type {
|
import type {
|
||||||
ReactFlowState,
|
ReactFlowState,
|
||||||
@@ -28,19 +27,23 @@ import type {
|
|||||||
const createRFStore = ({
|
const createRFStore = ({
|
||||||
nodes,
|
nodes,
|
||||||
edges,
|
edges,
|
||||||
|
defaultNodes,
|
||||||
|
defaultEdges,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
fitView,
|
fitView,
|
||||||
}: {
|
}: {
|
||||||
nodes?: Node[];
|
nodes?: Node[];
|
||||||
edges?: Edge[];
|
edges?: Edge[];
|
||||||
|
defaultNodes?: Node[];
|
||||||
|
defaultEdges?: Edge[];
|
||||||
width?: number;
|
width?: number;
|
||||||
height?: number;
|
height?: number;
|
||||||
fitView?: boolean;
|
fitView?: boolean;
|
||||||
}) =>
|
}) =>
|
||||||
createWithEqualityFn<ReactFlowState>(
|
createWithEqualityFn<ReactFlowState>(
|
||||||
(set, get) => ({
|
(set, get) => ({
|
||||||
...getInitialState({ nodes, edges, width, height, fitView }),
|
...getInitialState({ nodes, edges, width, height, fitView, defaultNodes, defaultEdges }),
|
||||||
setNodes: (nodes: Node[]) => {
|
setNodes: (nodes: Node[]) => {
|
||||||
const { nodeLookup, nodeOrigin, elevateNodesOnSelect } = get();
|
const { nodeLookup, nodeOrigin, elevateNodesOnSelect } = get();
|
||||||
// setNodes() is called exclusively in response to user actions:
|
// setNodes() is called exclusively in response to user actions:
|
||||||
@@ -49,7 +52,6 @@ const createRFStore = ({
|
|||||||
//
|
//
|
||||||
// When this happens, we take the note objects passed by the user and extend them with fields
|
// When this happens, we take the note objects passed by the user and extend them with fields
|
||||||
// relevant for internal React Flow operations.
|
// relevant for internal React Flow operations.
|
||||||
// TODO: consider updating the types to reflect the distinction between user-provided nodes and internal nodes.
|
|
||||||
const nodesWithInternalData = adoptUserProvidedNodes(nodes, nodeLookup, { nodeOrigin, elevateNodesOnSelect });
|
const nodesWithInternalData = adoptUserProvidedNodes(nodes, nodeLookup, { nodeOrigin, elevateNodesOnSelect });
|
||||||
|
|
||||||
set({ nodes: nodesWithInternalData });
|
set({ nodes: nodesWithInternalData });
|
||||||
@@ -61,37 +63,17 @@ const createRFStore = ({
|
|||||||
|
|
||||||
set({ edges });
|
set({ edges });
|
||||||
},
|
},
|
||||||
// when the user works with an uncontrolled flow,
|
|
||||||
// we set a flag `hasDefaultNodes` / `hasDefaultEdges`
|
|
||||||
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => {
|
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => {
|
||||||
const hasDefaultNodes = typeof nodes !== 'undefined';
|
if (nodes) {
|
||||||
const hasDefaultEdges = typeof edges !== 'undefined';
|
const { setNodes } = get();
|
||||||
|
setNodes(nodes);
|
||||||
const nextState: {
|
set({ hasDefaultNodes: true });
|
||||||
nodes?: Node[];
|
|
||||||
edges?: Edge[];
|
|
||||||
hasDefaultNodes: boolean;
|
|
||||||
hasDefaultEdges: boolean;
|
|
||||||
} = {
|
|
||||||
hasDefaultNodes,
|
|
||||||
hasDefaultEdges,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (hasDefaultNodes) {
|
|
||||||
const { nodeLookup, nodeOrigin, elevateNodesOnSelect } = get();
|
|
||||||
nextState.nodes = adoptUserProvidedNodes(nodes, nodeLookup, {
|
|
||||||
nodeOrigin,
|
|
||||||
elevateNodesOnSelect,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
if (hasDefaultEdges) {
|
if (edges) {
|
||||||
const { connectionLookup, edgeLookup } = get();
|
const { setEdges } = get();
|
||||||
updateConnectionLookup(connectionLookup, edgeLookup, edges);
|
setEdges(edges);
|
||||||
|
set({ hasDefaultEdges: true });
|
||||||
nextState.edges = edges;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
set(nextState);
|
|
||||||
},
|
},
|
||||||
// Every node gets registerd at a ResizeObserver. Whenever a node
|
// Every node gets registerd at a ResizeObserver. Whenever a node
|
||||||
// changes its dimensions, this function is called to measure the
|
// changes its dimensions, this function is called to measure the
|
||||||
@@ -151,99 +133,82 @@ const createRFStore = ({
|
|||||||
onNodesChange?.(changes);
|
onNodesChange?.(changes);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
updateNodePositions: (nodeDragItems, positionChanged = true, dragging = false) => {
|
updateNodePositions: (nodeDragItems, dragging = false) => {
|
||||||
const changes = nodeDragItems.map((node) => {
|
const changes = nodeDragItems.map((node) => {
|
||||||
const change: NodePositionChange = {
|
const change: NodePositionChange = {
|
||||||
id: node.id,
|
id: node.id,
|
||||||
type: 'position',
|
type: 'position',
|
||||||
|
position: node.position,
|
||||||
|
positionAbsolute: node.computed?.positionAbsolute,
|
||||||
dragging,
|
dragging,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (positionChanged) {
|
|
||||||
change.positionAbsolute = node.computed?.positionAbsolute;
|
|
||||||
change.position = node.position;
|
|
||||||
}
|
|
||||||
|
|
||||||
return change;
|
return change;
|
||||||
});
|
});
|
||||||
|
|
||||||
get().triggerNodeChanges(changes);
|
get().triggerNodeChanges(changes);
|
||||||
},
|
},
|
||||||
|
|
||||||
triggerNodeChanges: (changes) => {
|
triggerNodeChanges: (changes) => {
|
||||||
const { onNodesChange, nodeLookup, nodes, hasDefaultNodes, nodeOrigin, elevateNodesOnSelect } = get();
|
const { onNodesChange, setNodes, nodes, hasDefaultNodes } = get();
|
||||||
|
|
||||||
if (changes?.length) {
|
if (changes?.length) {
|
||||||
if (hasDefaultNodes) {
|
if (hasDefaultNodes) {
|
||||||
const updatedNodes = applyNodeChanges(changes, nodes);
|
const updatedNodes = applyNodeChanges(changes, nodes);
|
||||||
const nextNodes = adoptUserProvidedNodes(updatedNodes, nodeLookup, {
|
setNodes(updatedNodes);
|
||||||
nodeOrigin,
|
|
||||||
elevateNodesOnSelect,
|
|
||||||
});
|
|
||||||
set({ nodes: nextNodes });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onNodesChange?.(changes);
|
onNodesChange?.(changes);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
triggerEdgeChanges: (changes) => {
|
||||||
|
const { onEdgesChange, setEdges, edges, hasDefaultEdges } = get();
|
||||||
|
|
||||||
|
if (changes?.length) {
|
||||||
|
if (hasDefaultEdges) {
|
||||||
|
const updatedEdges = applyEdgeChanges(changes, edges);
|
||||||
|
setEdges(updatedEdges);
|
||||||
|
}
|
||||||
|
|
||||||
|
onEdgesChange?.(changes);
|
||||||
|
}
|
||||||
|
},
|
||||||
addSelectedNodes: (selectedNodeIds) => {
|
addSelectedNodes: (selectedNodeIds) => {
|
||||||
const { multiSelectionActive, edges, nodes } = get();
|
const { multiSelectionActive, edges, nodes, triggerNodeChanges, triggerEdgeChanges } = get();
|
||||||
let changedNodes: NodeSelectionChange[];
|
|
||||||
let changedEdges: EdgeSelectionChange[] | null = null;
|
|
||||||
|
|
||||||
if (multiSelectionActive) {
|
if (multiSelectionActive) {
|
||||||
changedNodes = selectedNodeIds.map((nodeId) => createSelectionChange(nodeId, true)) as NodeSelectionChange[];
|
const nodeChanges = selectedNodeIds.map((nodeId) => createSelectionChange(nodeId, true));
|
||||||
} else {
|
triggerNodeChanges(nodeChanges as NodeSelectionChange[]);
|
||||||
changedNodes = getSelectionChanges(nodes, new Set([...selectedNodeIds]), true);
|
return;
|
||||||
changedEdges = getSelectionChanges(edges);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
updateNodesAndEdgesSelections({
|
triggerNodeChanges(getSelectionChanges(nodes, new Set([...selectedNodeIds]), true));
|
||||||
changedNodes,
|
triggerEdgeChanges(getSelectionChanges(edges));
|
||||||
changedEdges,
|
|
||||||
get,
|
|
||||||
set,
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
addSelectedEdges: (selectedEdgeIds) => {
|
addSelectedEdges: (selectedEdgeIds) => {
|
||||||
const { multiSelectionActive, edges, nodes } = get();
|
const { multiSelectionActive, edges, nodes, triggerNodeChanges, triggerEdgeChanges } = get();
|
||||||
let changedEdges: EdgeSelectionChange[];
|
|
||||||
let changedNodes: NodeSelectionChange[] | null = null;
|
|
||||||
|
|
||||||
if (multiSelectionActive) {
|
if (multiSelectionActive) {
|
||||||
changedEdges = selectedEdgeIds.map((edgeId) => createSelectionChange(edgeId, true)) as EdgeSelectionChange[];
|
const changedEdges = selectedEdgeIds.map((edgeId) => createSelectionChange(edgeId, true));
|
||||||
} else {
|
triggerEdgeChanges(changedEdges as EdgeSelectionChange[]);
|
||||||
changedEdges = getSelectionChanges(edges, new Set([...selectedEdgeIds]));
|
return;
|
||||||
changedNodes = getSelectionChanges(nodes, new Set(), true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
updateNodesAndEdgesSelections({
|
triggerEdgeChanges(getSelectionChanges(edges, new Set([...selectedEdgeIds])));
|
||||||
changedNodes,
|
triggerNodeChanges(getSelectionChanges(nodes, new Set(), true));
|
||||||
changedEdges,
|
|
||||||
get,
|
|
||||||
set,
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
unselectNodesAndEdges: ({ nodes, edges }: UnselectNodesAndEdgesParams = {}) => {
|
unselectNodesAndEdges: ({ nodes, edges }: UnselectNodesAndEdgesParams = {}) => {
|
||||||
const { edges: storeEdges, nodes: storeNodes } = get();
|
const { edges: storeEdges, nodes: storeNodes, triggerNodeChanges, triggerEdgeChanges } = get();
|
||||||
const nodesToUnselect = nodes ? nodes : storeNodes;
|
const nodesToUnselect = nodes ? nodes : storeNodes;
|
||||||
const edgesToUnselect = edges ? edges : storeEdges;
|
const edgesToUnselect = edges ? edges : storeEdges;
|
||||||
|
|
||||||
const changedNodes = nodesToUnselect.map((n) => {
|
const nodeChanges = nodesToUnselect.map((n) => {
|
||||||
n.selected = false;
|
n.selected = false;
|
||||||
return createSelectionChange(n.id, false);
|
return createSelectionChange(n.id, false);
|
||||||
}) as NodeSelectionChange[];
|
|
||||||
const changedEdges = edgesToUnselect.map((edge) =>
|
|
||||||
createSelectionChange(edge.id, false)
|
|
||||||
) as EdgeSelectionChange[];
|
|
||||||
|
|
||||||
updateNodesAndEdgesSelections({
|
|
||||||
changedNodes,
|
|
||||||
changedEdges,
|
|
||||||
get,
|
|
||||||
set,
|
|
||||||
});
|
});
|
||||||
|
const edgeChanges = edgesToUnselect.map((edge) => createSelectionChange(edge.id, false));
|
||||||
|
|
||||||
|
triggerNodeChanges(nodeChanges as NodeSelectionChange[]);
|
||||||
|
triggerEdgeChanges(edgeChanges as EdgeSelectionChange[]);
|
||||||
},
|
},
|
||||||
setMinZoom: (minZoom) => {
|
setMinZoom: (minZoom) => {
|
||||||
const { panZoom, maxZoom } = get();
|
const { panZoom, maxZoom } = get();
|
||||||
@@ -263,21 +228,19 @@ const createRFStore = ({
|
|||||||
set({ translateExtent });
|
set({ translateExtent });
|
||||||
},
|
},
|
||||||
resetSelectedElements: () => {
|
resetSelectedElements: () => {
|
||||||
const { edges, nodes } = get();
|
const { edges, nodes, triggerNodeChanges, triggerEdgeChanges } = get();
|
||||||
|
|
||||||
const nodesToUnselect = nodes
|
const nodeChanges = nodes.reduce<NodeSelectionChange[]>(
|
||||||
.filter((e) => e.selected)
|
(res, node) => (node.selected ? [...res, createSelectionChange(node.id, false) as NodeSelectionChange] : res),
|
||||||
.map((n) => createSelectionChange(n.id, false)) as NodeSelectionChange[];
|
[]
|
||||||
const edgesToUnselect = edges
|
);
|
||||||
.filter((e) => e.selected)
|
const edgeChanges = edges.reduce<EdgeSelectionChange[]>(
|
||||||
.map((e) => createSelectionChange(e.id, false)) as EdgeSelectionChange[];
|
(res, edge) => (edge.selected ? [...res, createSelectionChange(edge.id, false) as EdgeSelectionChange] : res),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
updateNodesAndEdgesSelections({
|
triggerNodeChanges(nodeChanges);
|
||||||
changedNodes: nodesToUnselect,
|
triggerEdgeChanges(edgeChanges);
|
||||||
changedEdges: edgesToUnselect,
|
|
||||||
get,
|
|
||||||
set,
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
setNodeExtent: (nodeExtent) => {
|
setNodeExtent: (nodeExtent) => {
|
||||||
const { nodes } = get();
|
const { nodes } = get();
|
||||||
@@ -340,13 +303,7 @@ const createRFStore = ({
|
|||||||
set(currentConnection);
|
set(currentConnection);
|
||||||
},
|
},
|
||||||
|
|
||||||
reset: () => {
|
reset: () => set({ ...getInitialState() }),
|
||||||
// @todo: what should we do about this? Do we still need it?
|
|
||||||
// if you are on a SPA with multiple flows, we want to make sure that the store gets resetted
|
|
||||||
// when you switch pages. Does this reset solves this? Currently it always gets called. This
|
|
||||||
// leads to an emtpy nodes array at the beginning.
|
|
||||||
// set({ ...getInitialState() });
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
Object.is
|
Object.is
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -12,14 +12,18 @@ import {
|
|||||||
import type { Edge, Node, ReactFlowStore } from '../types';
|
import type { Edge, Node, ReactFlowStore } from '../types';
|
||||||
|
|
||||||
const getInitialState = ({
|
const getInitialState = ({
|
||||||
nodes = [],
|
nodes,
|
||||||
edges = [],
|
edges,
|
||||||
|
defaultNodes,
|
||||||
|
defaultEdges,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
fitView,
|
fitView,
|
||||||
}: {
|
}: {
|
||||||
nodes?: Node[];
|
nodes?: Node[];
|
||||||
edges?: Edge[];
|
edges?: Edge[];
|
||||||
|
defaultNodes?: Node[];
|
||||||
|
defaultEdges?: Edge[];
|
||||||
width?: number;
|
width?: number;
|
||||||
height?: number;
|
height?: number;
|
||||||
fitView?: boolean;
|
fitView?: boolean;
|
||||||
@@ -27,9 +31,11 @@ const getInitialState = ({
|
|||||||
const nodeLookup = new Map();
|
const nodeLookup = new Map();
|
||||||
const connectionLookup = new Map();
|
const connectionLookup = new Map();
|
||||||
const edgeLookup = new Map();
|
const edgeLookup = new Map();
|
||||||
|
const storeEdges = defaultEdges ?? edges ?? [];
|
||||||
|
const storeNodes = defaultNodes ?? nodes ?? [];
|
||||||
|
|
||||||
updateConnectionLookup(connectionLookup, edgeLookup, edges);
|
updateConnectionLookup(connectionLookup, edgeLookup, storeEdges);
|
||||||
const nextNodes = adoptUserProvidedNodes(nodes, nodeLookup, {
|
const nextNodes = adoptUserProvidedNodes(storeNodes, nodeLookup, {
|
||||||
nodeOrigin: [0, 0],
|
nodeOrigin: [0, 0],
|
||||||
elevateNodesOnSelect: false,
|
elevateNodesOnSelect: false,
|
||||||
});
|
});
|
||||||
@@ -51,13 +57,13 @@ const getInitialState = ({
|
|||||||
transform,
|
transform,
|
||||||
nodes: nextNodes,
|
nodes: nextNodes,
|
||||||
nodeLookup,
|
nodeLookup,
|
||||||
edges,
|
edges: storeEdges,
|
||||||
edgeLookup,
|
edgeLookup,
|
||||||
connectionLookup,
|
connectionLookup,
|
||||||
onNodesChange: null,
|
onNodesChange: null,
|
||||||
onEdgesChange: null,
|
onEdgesChange: null,
|
||||||
hasDefaultNodes: false,
|
hasDefaultNodes: defaultNodes !== undefined,
|
||||||
hasDefaultEdges: false,
|
hasDefaultEdges: defaultEdges !== undefined,
|
||||||
panZoom: null,
|
panZoom: null,
|
||||||
minZoom: 0.5,
|
minZoom: 0.5,
|
||||||
maxZoom: 2,
|
maxZoom: 2,
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
import type { StoreApi } from 'zustand';
|
|
||||||
import type { Edge, EdgeSelectionChange, Node, NodeSelectionChange, ReactFlowState } from '../types';
|
|
||||||
|
|
||||||
export function handleControlledSelectionChange<NodeOrEdge extends Node | Edge>(
|
|
||||||
changes: NodeSelectionChange[] | EdgeSelectionChange[],
|
|
||||||
items: NodeOrEdge[]
|
|
||||||
): NodeOrEdge[] {
|
|
||||||
return items.map((item) => {
|
|
||||||
const change = changes.find((change) => change.id === item.id);
|
|
||||||
|
|
||||||
if (change) {
|
|
||||||
item.selected = change.selected;
|
|
||||||
}
|
|
||||||
|
|
||||||
return item;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateNodesAndEdgesParams = {
|
|
||||||
changedNodes: NodeSelectionChange[] | null;
|
|
||||||
changedEdges: EdgeSelectionChange[] | null;
|
|
||||||
get: StoreApi<ReactFlowState>['getState'];
|
|
||||||
set: StoreApi<ReactFlowState>['setState'];
|
|
||||||
};
|
|
||||||
|
|
||||||
export function updateNodesAndEdgesSelections({ changedNodes, changedEdges, get, set }: UpdateNodesAndEdgesParams) {
|
|
||||||
const { nodes, edges, onNodesChange, onEdgesChange, hasDefaultNodes, hasDefaultEdges } = get();
|
|
||||||
|
|
||||||
if (changedNodes?.length) {
|
|
||||||
if (hasDefaultNodes) {
|
|
||||||
set({ nodes: handleControlledSelectionChange(changedNodes, nodes) });
|
|
||||||
}
|
|
||||||
|
|
||||||
onNodesChange?.(changedNodes);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (changedEdges?.length) {
|
|
||||||
if (hasDefaultEdges) {
|
|
||||||
set({ edges: handleControlledSelectionChange(changedEdges, edges) });
|
|
||||||
}
|
|
||||||
|
|
||||||
onEdgesChange?.(changedEdges);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -346,11 +346,11 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
|
|||||||
*/
|
*/
|
||||||
panOnDrag?: boolean | number[];
|
panOnDrag?: boolean | number[];
|
||||||
/** Minimum zoom level
|
/** Minimum zoom level
|
||||||
* @default 0.1
|
* @default 0.5
|
||||||
*/
|
*/
|
||||||
minZoom?: number;
|
minZoom?: number;
|
||||||
/** Maximum zoom level
|
/** Maximum zoom level
|
||||||
* @default 1
|
* @default 2
|
||||||
*/
|
*/
|
||||||
maxZoom?: number;
|
maxZoom?: number;
|
||||||
/** Controlled viewport to be used instead of internal one */
|
/** Controlled viewport to be used instead of internal one */
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ import type {
|
|||||||
OnDelete,
|
OnDelete,
|
||||||
OnNodeDrag,
|
OnNodeDrag,
|
||||||
OnBeforeDelete,
|
OnBeforeDelete,
|
||||||
|
EdgeChange,
|
||||||
} from '.';
|
} from '.';
|
||||||
|
|
||||||
export type ReactFlowStore = {
|
export type ReactFlowStore = {
|
||||||
@@ -150,7 +151,6 @@ export type ReactFlowStore = {
|
|||||||
export type ReactFlowActions = {
|
export type ReactFlowActions = {
|
||||||
setNodes: (nodes: Node[]) => void;
|
setNodes: (nodes: Node[]) => void;
|
||||||
setEdges: (edges: Edge[]) => void;
|
setEdges: (edges: Edge[]) => void;
|
||||||
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void;
|
|
||||||
updateNodeDimensions: (updates: Map<string, NodeDimensionUpdate>) => void;
|
updateNodeDimensions: (updates: Map<string, NodeDimensionUpdate>) => void;
|
||||||
updateNodePositions: UpdateNodePositions;
|
updateNodePositions: UpdateNodePositions;
|
||||||
resetSelectedElements: () => void;
|
resetSelectedElements: () => void;
|
||||||
@@ -164,9 +164,11 @@ export type ReactFlowActions = {
|
|||||||
cancelConnection: () => void;
|
cancelConnection: () => void;
|
||||||
updateConnection: UpdateConnection;
|
updateConnection: UpdateConnection;
|
||||||
reset: () => void;
|
reset: () => void;
|
||||||
triggerNodeChanges: (changes: NodeChange[]) => void;
|
triggerNodeChanges: (changes: NodeChange[] | null) => void;
|
||||||
|
triggerEdgeChanges: (changes: EdgeChange[] | null) => void;
|
||||||
panBy: PanBy;
|
panBy: PanBy;
|
||||||
fitView: (nodes: Node[], options?: FitViewOptions) => boolean;
|
fitView: (nodes: Node[], options?: FitViewOptions) => boolean;
|
||||||
|
setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
|
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
|
||||||
|
|||||||
@@ -219,11 +219,13 @@ export function applyEdgeChanges<EdgeType extends Edge = Edge>(
|
|||||||
return applyChanges(changes, edges) as EdgeType[];
|
return applyChanges(changes, edges) as EdgeType[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createSelectionChange = (id: string, selected: boolean): NodeSelectionChange | EdgeSelectionChange => ({
|
export function createSelectionChange(id: string, selected: boolean): NodeSelectionChange | EdgeSelectionChange {
|
||||||
id,
|
return {
|
||||||
type: 'select',
|
id,
|
||||||
selected,
|
type: 'select',
|
||||||
});
|
selected,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function getSelectionChanges(
|
export function getSelectionChanges(
|
||||||
items: any[],
|
items: any[],
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
# @xyflow/svelte
|
# @xyflow/svelte
|
||||||
|
|
||||||
|
## 0.0.36
|
||||||
|
|
||||||
|
## Patch changes
|
||||||
|
|
||||||
|
- a better NodeResizer (child nodes do not move when parent node gets resized)
|
||||||
|
- fix `on:panecontextmenu`
|
||||||
|
- add `role="button"` to `<EdgeLabel />` to prevent a11y warnings
|
||||||
|
- don't delete node when input is focused and user presses Backspace + Ctrl (or any other mod key)
|
||||||
|
- `useHandleConnections`: use context node id when no node id is passed
|
||||||
|
- don't trigger drag start / end when node is not draggable
|
||||||
|
|
||||||
## 0.0.35
|
## 0.0.35
|
||||||
|
|
||||||
## Minor changes
|
## Minor changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@xyflow/svelte",
|
"name": "@xyflow/svelte",
|
||||||
"version": "0.0.34",
|
"version": "0.0.36",
|
||||||
"description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.",
|
"description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"svelte",
|
"svelte",
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
class="svelte-flow__edge-label"
|
class="svelte-flow__edge-label"
|
||||||
style:transform="translate(-50%, -50%) translate({x}px,{y}px)"
|
style:transform="translate(-50%, -50%) translate({x}px,{y}px)"
|
||||||
style={'pointer-events: all;' + style}
|
style={'pointer-events: all;' + style}
|
||||||
|
role="button"
|
||||||
on:click={() => {
|
on:click={() => {
|
||||||
if (id) handleEdgeSelect(id);
|
if (id) handleEdgeSelect(id);
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
Position,
|
Position,
|
||||||
XYHandle,
|
XYHandle,
|
||||||
isMouseEvent,
|
isMouseEvent,
|
||||||
type Connection,
|
type HandleConnection,
|
||||||
areConnectionMapsEqual,
|
areConnectionMapsEqual,
|
||||||
handleConnectionChange
|
handleConnectionChange
|
||||||
} from '@xyflow/system';
|
} from '@xyflow/system';
|
||||||
@@ -103,8 +103,8 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let prevConnections: Map<string, Connection> | null = null;
|
let prevConnections: Map<string, HandleConnection> | null = null;
|
||||||
let connections: Map<string, Connection> | undefined;
|
let connections: Map<string, HandleConnection> | undefined;
|
||||||
|
|
||||||
$: if (onconnect || ondisconnect) {
|
$: if (onconnect || ondisconnect) {
|
||||||
// connectionLookup is not reactive, so we use edges to get notified about updates
|
// connectionLookup is not reactive, so we use edges to get notified about updates
|
||||||
|
|||||||
@@ -113,7 +113,15 @@
|
|||||||
{
|
{
|
||||||
...deleteKeyDefinition,
|
...deleteKeyDefinition,
|
||||||
enabled: deleteKeyDefinition.key !== null,
|
enabled: deleteKeyDefinition.key !== null,
|
||||||
callback: (detail) => !isInputDOMNode(detail.originalEvent) && deleteKeyPressed.set(true)
|
callback: (detail) => {
|
||||||
|
const isModifierKey =
|
||||||
|
detail.originalEvent.ctrlKey ||
|
||||||
|
detail.originalEvent.metaKey ||
|
||||||
|
detail.originalEvent.shiftKey;
|
||||||
|
if (!isModifierKey && !isInputDOMNode(detail.originalEvent)) {
|
||||||
|
deleteKeyPressed.set(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
type: 'keydown'
|
type: 'keydown'
|
||||||
|
|||||||
@@ -215,7 +215,12 @@
|
|||||||
panOnScroll={panOnScroll === undefined ? false : panOnScroll}
|
panOnScroll={panOnScroll === undefined ? false : panOnScroll}
|
||||||
panOnDrag={panOnDrag === undefined ? true : panOnDrag}
|
panOnDrag={panOnDrag === undefined ? true : panOnDrag}
|
||||||
>
|
>
|
||||||
<Pane on:paneclick panOnDrag={panOnDrag === undefined ? true : panOnDrag} {selectionOnDrag}>
|
<Pane
|
||||||
|
on:paneclick
|
||||||
|
on:panecontextmenu
|
||||||
|
panOnDrag={panOnDrag === undefined ? true : panOnDrag}
|
||||||
|
{selectionOnDrag}
|
||||||
|
>
|
||||||
<ViewportComponent>
|
<ViewportComponent>
|
||||||
<EdgeRenderer on:edgeclick on:edgecontextmenu {defaultEdgeOptions} />
|
<EdgeRenderer on:edgeclick on:edgecontextmenu {defaultEdgeOptions} />
|
||||||
<ConnectionLine
|
<ConnectionLine
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ import type {
|
|||||||
ColorMode,
|
ColorMode,
|
||||||
OnConnect,
|
OnConnect,
|
||||||
OnConnectStart,
|
OnConnectStart,
|
||||||
OnConnectEnd,
|
OnConnectEnd
|
||||||
OnBeforeDelete
|
|
||||||
} from '@xyflow/system';
|
} from '@xyflow/system';
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
@@ -31,7 +30,8 @@ import type {
|
|||||||
DefaultEdgeOptions,
|
DefaultEdgeOptions,
|
||||||
FitViewOptions,
|
FitViewOptions,
|
||||||
OnDelete,
|
OnDelete,
|
||||||
OnEdgeCreate
|
OnEdgeCreate,
|
||||||
|
OnBeforeDelete
|
||||||
} from '$lib/types';
|
} from '$lib/types';
|
||||||
import type { Writable } from 'svelte/store';
|
import type { Writable } from 'svelte/store';
|
||||||
|
|
||||||
@@ -135,11 +135,11 @@ export type SvelteFlowProps = DOMAttributes<HTMLDivElement> & {
|
|||||||
*/
|
*/
|
||||||
nodeDragThreshold?: number;
|
nodeDragThreshold?: number;
|
||||||
/** Minimum zoom level
|
/** Minimum zoom level
|
||||||
* @default 0.1
|
* @default 0.5
|
||||||
*/
|
*/
|
||||||
minZoom?: number;
|
minZoom?: number;
|
||||||
/** Maximum zoom level
|
/** Maximum zoom level
|
||||||
* @default 1
|
* @default 2
|
||||||
*/
|
*/
|
||||||
maxZoom?: number;
|
maxZoom?: number;
|
||||||
/** Sets the initial position and zoom of the viewport.
|
/** Sets the initial position and zoom of the viewport.
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
import { derived } from 'svelte/store';
|
import { derived } from 'svelte/store';
|
||||||
import { areConnectionMapsEqual, type Connection, type HandleType } from '@xyflow/system';
|
import { areConnectionMapsEqual, type HandleConnection, type HandleType } from '@xyflow/system';
|
||||||
|
|
||||||
import { useStore } from '$lib/store';
|
import { useStore } from '$lib/store';
|
||||||
|
import { getContext } from 'svelte';
|
||||||
|
|
||||||
export type useHandleConnectionsParams = {
|
export type useHandleConnectionsParams = {
|
||||||
nodeId: string;
|
|
||||||
type: HandleType;
|
type: HandleType;
|
||||||
|
nodeId?: string;
|
||||||
id?: string | null;
|
id?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const initialConnections: Connection[] = [];
|
const initialConnections: HandleConnection[] = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook to check if a <Handle /> is connected to another <Handle /> and get the connections.
|
* Hook to check if a <Handle /> is connected to another <Handle /> and get the connections.
|
||||||
@@ -20,14 +21,18 @@ const initialConnections: Connection[] = [];
|
|||||||
* @param param.id - the handle id (this is only needed if the node has multiple handles of the same type)
|
* @param param.id - the handle id (this is only needed if the node has multiple handles of the same type)
|
||||||
* @returns an array with connections
|
* @returns an array with connections
|
||||||
*/
|
*/
|
||||||
export function useHandleConnections({ nodeId, type, id = null }: useHandleConnectionsParams) {
|
export function useHandleConnections({ type, nodeId, id = null }: useHandleConnectionsParams) {
|
||||||
const { edges, connectionLookup } = useStore();
|
const { edges, connectionLookup } = useStore();
|
||||||
let prevConnections: Map<string, Connection> | undefined = undefined;
|
|
||||||
|
const _nodeId = getContext<string>('svelteflow__node_id');
|
||||||
|
const currentNodeId = nodeId ?? _nodeId;
|
||||||
|
|
||||||
|
let prevConnections: Map<string, HandleConnection> | undefined = undefined;
|
||||||
|
|
||||||
return derived(
|
return derived(
|
||||||
[edges, connectionLookup],
|
[edges, connectionLookup],
|
||||||
([, connectionLookup], set) => {
|
([, connectionLookup], set) => {
|
||||||
const nextConnections = connectionLookup.get(`${nodeId}-${type}-${id || null}`);
|
const nextConnections = connectionLookup.get(`${currentNodeId}-${type}-${id || null}`);
|
||||||
|
|
||||||
if (!areConnectionMapsEqual(nextConnections, prevConnections)) {
|
if (!areConnectionMapsEqual(nextConnections, prevConnections)) {
|
||||||
prevConnections = nextConnections;
|
prevConnections = nextConnections;
|
||||||
|
|||||||
@@ -83,7 +83,7 @@
|
|||||||
|
|
||||||
<Panel
|
<Panel
|
||||||
{position}
|
{position}
|
||||||
{style}
|
style={style + (bgColor ? `;--xy-minimap-background-color-props:${bgColor}` : '')}
|
||||||
class={cc(['svelte-flow__minimap', className])}
|
class={cc(['svelte-flow__minimap', className])}
|
||||||
data-testid="svelte-flow__minimap"
|
data-testid="svelte-flow__minimap"
|
||||||
>
|
>
|
||||||
@@ -92,12 +92,14 @@
|
|||||||
width={elementWidth}
|
width={elementWidth}
|
||||||
height={elementHeight}
|
height={elementHeight}
|
||||||
viewBox="{x} {y} {viewboxWidth} {viewboxHeight}"
|
viewBox="{x} {y} {viewboxWidth} {viewboxHeight}"
|
||||||
|
class="svelte-flow__minimap-svg"
|
||||||
role="img"
|
role="img"
|
||||||
aria-labelledby={labelledBy}
|
aria-labelledby={labelledBy}
|
||||||
style:--xy-minimap-background-color-props={bgColor}
|
style:--xy-minimap-mask-background-color-props={maskColor}
|
||||||
style:--xy-minimap-mask-color-props={maskColor}
|
|
||||||
style:--xy-minimap-mask-stroke-color-props={maskStrokeColor}
|
style:--xy-minimap-mask-stroke-color-props={maskStrokeColor}
|
||||||
style:--xy-minimap-mask-stroke-width-props={maskStrokeWidth}
|
style:--xy-minimap-mask-stroke-width-props={maskStrokeWidth
|
||||||
|
? maskStrokeWidth * viewScale
|
||||||
|
: undefined}
|
||||||
use:interactive={{
|
use:interactive={{
|
||||||
panZoom: $panZoom,
|
panZoom: $panZoom,
|
||||||
viewport,
|
viewport,
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
ResizeControlVariant,
|
ResizeControlVariant,
|
||||||
type ControlPosition,
|
type ControlPosition,
|
||||||
type XYResizerInstance,
|
type XYResizerInstance,
|
||||||
type XYResizerChange
|
type XYResizerChange,
|
||||||
|
type XYResizerChildChange
|
||||||
} from '@xyflow/system';
|
} from '@xyflow/system';
|
||||||
import type { ResizeControlProps } from './types';
|
import type { ResizeControlProps } from './types';
|
||||||
|
|
||||||
@@ -66,7 +67,7 @@
|
|||||||
snapToGrid: !!$snapGrid
|
snapToGrid: !!$snapGrid
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
onChange: (change: XYResizerChange) => {
|
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
|
||||||
const node = $nodeLookup.get(id);
|
const node = $nodeLookup.get(id);
|
||||||
if (node) {
|
if (node) {
|
||||||
node.height = change.isHeightChange ? change.height : node.height;
|
node.height = change.isHeightChange ? change.height : node.height;
|
||||||
@@ -76,6 +77,13 @@
|
|||||||
? { x: change.x, y: change.y }
|
? { x: change.x, y: change.y }
|
||||||
: node.position;
|
: node.position;
|
||||||
|
|
||||||
|
for (const childChange of childChanges) {
|
||||||
|
const childNode = $nodeLookup.get(childChange.id);
|
||||||
|
if (childNode) {
|
||||||
|
childNode.position = childChange.position;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$nodes = $nodes;
|
$nodes = $nodes;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,28 +64,22 @@ export function createStore({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updateNodePositions: UpdateNodePositions = (nodeDragItems, dragging = false) => {
|
const updateNodePositions: UpdateNodePositions = (nodeDragItems, dragging = false) => {
|
||||||
store.nodes.update((nds) => {
|
const nodeLookup = get(store.nodeLookup);
|
||||||
return nds.map((node) => {
|
|
||||||
const nodeDragItem = (nodeDragItems as Array<Node | NodeDragItem>).find(
|
|
||||||
(ndi) => ndi.id === node.id
|
|
||||||
);
|
|
||||||
|
|
||||||
if (nodeDragItem) {
|
nodeDragItems.forEach((nodeDragItem) => {
|
||||||
return {
|
const node = nodeLookup.get(nodeDragItem.id);
|
||||||
...node,
|
|
||||||
dragging,
|
|
||||||
position: nodeDragItem.position,
|
|
||||||
computed: {
|
|
||||||
...node.computed,
|
|
||||||
positionAbsolute: nodeDragItem.computed?.positionAbsolute
|
|
||||||
},
|
|
||||||
[internalsSymbol]: node[internalsSymbol]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return node;
|
if (node) {
|
||||||
});
|
node.position = nodeDragItem.position;
|
||||||
|
node.dragging = dragging;
|
||||||
|
node.computed = {
|
||||||
|
...node.computed,
|
||||||
|
positionAbsolute: nodeDragItem.computed?.positionAbsolute
|
||||||
|
};
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
store.nodes.set(get(store.nodes));
|
||||||
};
|
};
|
||||||
|
|
||||||
function updateNodeDimensions(updates: Map<string, NodeDimensionUpdate>) {
|
function updateNodeDimensions(updates: Map<string, NodeDimensionUpdate>) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@xyflow/system",
|
"name": "@xyflow/system",
|
||||||
"version": "0.0.15",
|
"version": "0.0.17",
|
||||||
"description": "xyflow core system that powers React Flow and Svelte Flow.",
|
"description": "xyflow core system that powers React Flow and Svelte Flow.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"node-based UI",
|
"node-based UI",
|
||||||
|
|||||||
@@ -12,6 +12,8 @@
|
|||||||
|
|
||||||
--xy-minimap-background-color-default: #fff;
|
--xy-minimap-background-color-default: #fff;
|
||||||
--xy-minimap-mask-background-color-default: rgb(240, 240, 240, 0.6);
|
--xy-minimap-mask-background-color-default: rgb(240, 240, 240, 0.6);
|
||||||
|
--xy-minimap-mask-stroke-color-default: transparent;
|
||||||
|
--xy-minimap-mask-stroke-width-default: 1;
|
||||||
--xy-minimap-node-background-color-default: #e2e2e2;
|
--xy-minimap-node-background-color-default: #e2e2e2;
|
||||||
--xy-minimap-node-stroke-color-default: transparent;
|
--xy-minimap-node-stroke-color-default: transparent;
|
||||||
--xy-minimap-node-stroke-width-default: 2;
|
--xy-minimap-node-stroke-width-default: 2;
|
||||||
@@ -34,6 +36,8 @@
|
|||||||
|
|
||||||
--xy-minimap-background-color-default: #141414;
|
--xy-minimap-background-color-default: #141414;
|
||||||
--xy-minimap-mask-background-color-default: rgb(60, 60, 60, 0.6);
|
--xy-minimap-mask-background-color-default: rgb(60, 60, 60, 0.6);
|
||||||
|
--xy-minimap-mask-stroke-color-default: transparent;
|
||||||
|
--xy-minimap-mask-stroke-width-default: 1;
|
||||||
--xy-minimap-node-background-color-default: #2b2b2b;
|
--xy-minimap-node-background-color-default: #2b2b2b;
|
||||||
--xy-minimap-node-stroke-color-default: transparent;
|
--xy-minimap-node-stroke-color-default: transparent;
|
||||||
--xy-minimap-node-stroke-width-default: 2;
|
--xy-minimap-node-stroke-width-default: 2;
|
||||||
@@ -310,13 +314,28 @@ svg.xy-flow__connectionline {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.xy-flow__minimap {
|
.xy-flow__minimap {
|
||||||
background: var(--xy-minimap-background-color, var(--xy-minimap-background-color-default));
|
background: var(
|
||||||
|
--xy-minimap-background-color-props,
|
||||||
|
var(--xy-minimap-background-color, var(--xy-minimap-background-color-default))
|
||||||
|
);
|
||||||
|
|
||||||
|
&-svg {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
&-mask {
|
&-mask {
|
||||||
fill: var(
|
fill: var(
|
||||||
--xy-minimap-mask-background-color-props,
|
--xy-minimap-mask-background-color-props,
|
||||||
var(--xy-minimap-mask-background-color, var(--xy-minimap-mask-background-color-default))
|
var(--xy-minimap-mask-background-color, var(--xy-minimap-mask-background-color-default))
|
||||||
);
|
);
|
||||||
|
stroke: var(
|
||||||
|
--xy-minimap-mask-stroke-color-props,
|
||||||
|
var(--xy-minimap-mask-stroke-color, var(--xy-minimap-mask-stroke-color-default))
|
||||||
|
);
|
||||||
|
stroke-width: var(
|
||||||
|
--xy-minimap-mask-stroke-width-props,
|
||||||
|
var(--xy-minimap-mask-stroke-width, var(--xy-minimap-mask-stroke-width-default))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
&-node {
|
&-node {
|
||||||
|
|||||||
@@ -28,6 +28,10 @@ export type Connection = {
|
|||||||
targetHandle: string | null;
|
targetHandle: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type HandleConnection = Connection & {
|
||||||
|
edgeId: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type ConnectionStatus = 'valid' | 'invalid';
|
export type ConnectionStatus = 'valid' | 'invalid';
|
||||||
|
|
||||||
export enum ConnectionMode {
|
export enum ConnectionMode {
|
||||||
@@ -123,11 +127,7 @@ export type SelectionRect = Rect & {
|
|||||||
|
|
||||||
export type OnError = (id: string, message: string) => void;
|
export type OnError = (id: string, message: string) => void;
|
||||||
|
|
||||||
export type UpdateNodePositions = (
|
export type UpdateNodePositions = (dragItems: NodeDragItem[] | NodeBase[], dragging?: boolean) => void;
|
||||||
dragItems: NodeDragItem[] | NodeBase[],
|
|
||||||
positionChanged?: boolean,
|
|
||||||
dragging?: boolean
|
|
||||||
) => void;
|
|
||||||
export type PanBy = (delta: XYPosition) => boolean;
|
export type PanBy = (delta: XYPosition) => boolean;
|
||||||
|
|
||||||
export type UpdateConnection = (params: {
|
export type UpdateConnection = (params: {
|
||||||
@@ -140,7 +140,7 @@ export type UpdateConnection = (params: {
|
|||||||
export type ColorModeClass = 'light' | 'dark';
|
export type ColorModeClass = 'light' | 'dark';
|
||||||
export type ColorMode = ColorModeClass | 'system';
|
export type ColorMode = ColorModeClass | 'system';
|
||||||
|
|
||||||
export type ConnectionLookup = Map<string, Map<string, Connection>>;
|
export type ConnectionLookup = Map<string, Map<string, HandleConnection>>;
|
||||||
|
|
||||||
export type OnBeforeDeleteBase<NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase> = ({
|
export type OnBeforeDeleteBase<NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase> = ({
|
||||||
nodes,
|
nodes,
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Connection } from '../types';
|
import { HandleConnection } from '../types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
export function areConnectionMapsEqual(a?: Map<string, Connection>, b?: Map<string, Connection>) {
|
export function areConnectionMapsEqual(a?: Map<string, HandleConnection>, b?: Map<string, HandleConnection>) {
|
||||||
if (!a && !b) {
|
if (!a && !b) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -31,15 +31,15 @@ export function areConnectionMapsEqual(a?: Map<string, Connection>, b?: Map<stri
|
|||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
export function handleConnectionChange(
|
export function handleConnectionChange(
|
||||||
a: Map<string, Connection>,
|
a: Map<string, HandleConnection>,
|
||||||
b: Map<string, Connection>,
|
b: Map<string, HandleConnection>,
|
||||||
cb?: (diff: Connection[]) => void
|
cb?: (diff: HandleConnection[]) => void
|
||||||
) {
|
) {
|
||||||
if (!cb) {
|
if (!cb) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const diff: Connection[] = [];
|
const diff: HandleConnection[] = [];
|
||||||
|
|
||||||
a.forEach((connection, key) => {
|
a.forEach((connection, key) => {
|
||||||
if (!b?.has(key)) {
|
if (!b?.has(key)) {
|
||||||
|
|||||||
@@ -37,11 +37,9 @@ export function isInputDOMNode(event: KeyboardEvent): boolean {
|
|||||||
// using composed path for handling shadow dom
|
// using composed path for handling shadow dom
|
||||||
const target = (event.composedPath?.()?.[0] || event.target) as HTMLElement;
|
const target = (event.composedPath?.()?.[0] || event.target) as HTMLElement;
|
||||||
const isInput = inputTags.includes(target?.nodeName) || target?.hasAttribute('contenteditable');
|
const isInput = inputTags.includes(target?.nodeName) || target?.hasAttribute('contenteditable');
|
||||||
// we want to be able to do a multi selection event if we are in an input field
|
|
||||||
const isModifierKey = event.ctrlKey || event.metaKey || event.shiftKey;
|
|
||||||
|
|
||||||
// when an input field is focused we don't want to trigger deletion or movement of nodes
|
// when an input field is focused we don't want to trigger deletion or movement of nodes
|
||||||
return (isInput && !isModifierKey) || !!target?.closest('.nokey');
|
return isInput || !!target?.closest('.nokey');
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => 'clientX' in event;
|
export const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => 'clientX' in event;
|
||||||
|
|||||||
@@ -94,8 +94,8 @@ export function adoptUserProvidedNodes<NodeType extends NodeBase>(
|
|||||||
...n,
|
...n,
|
||||||
computed: {
|
computed: {
|
||||||
positionAbsolute: n.position,
|
positionAbsolute: n.position,
|
||||||
width: n.computed?.width || currentStoreNode?.computed?.width,
|
width: n.computed?.width,
|
||||||
height: n.computed?.height || currentStoreNode?.computed?.height,
|
height: n.computed?.height,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const z = (isNumeric(n.zIndex) ? n.zIndex : 0) + (n.selected ? selectedNodeZ : 0);
|
const z = (isNumeric(n.zIndex) ? n.zIndex : 0) + (n.selected ? selectedNodeZ : 0);
|
||||||
@@ -260,7 +260,7 @@ export function updateConnectionLookup(connectionLookup: ConnectionLookup, edgeL
|
|||||||
|
|
||||||
const prevSource = connectionLookup.get(sourceKey) || new Map();
|
const prevSource = connectionLookup.get(sourceKey) || new Map();
|
||||||
const prevTarget = connectionLookup.get(targetKey) || new Map();
|
const prevTarget = connectionLookup.get(targetKey) || new Map();
|
||||||
const connection = { source, target, sourceHandle, targetHandle };
|
const connection = { edgeId: edge.id, source, target, sourceHandle, targetHandle };
|
||||||
|
|
||||||
edgeLookup.set(edge.id, edge);
|
edgeLookup.set(edge.id, edge);
|
||||||
connectionLookup.set(sourceKey, prevSource.set(`${target}-${targetHandle}`, connection));
|
connectionLookup.set(sourceKey, prevSource.set(`${target}-${targetHandle}`, connection));
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
updateNodePositions(dragItems, true, true);
|
updateNodePositions(dragItems, true);
|
||||||
const onNodeOrSelectionDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag);
|
const onNodeOrSelectionDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag);
|
||||||
|
|
||||||
if (dragEvent && (onDrag || onNodeOrSelectionDrag)) {
|
if (dragEvent && (onDrag || onNodeOrSelectionDrag)) {
|
||||||
@@ -238,7 +238,7 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
|
|||||||
|
|
||||||
const onNodeOrSelectionDragStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
|
const onNodeOrSelectionDragStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
|
||||||
|
|
||||||
if (dragItems && (onDragStart || onNodeOrSelectionDragStart)) {
|
if (dragItems.length > 0 && (onDragStart || onNodeOrSelectionDragStart)) {
|
||||||
const [currentNode, currentNodes] = getEventHandlerParams({
|
const [currentNode, currentNodes] = getEventHandlerParams({
|
||||||
nodeId,
|
nodeId,
|
||||||
dragItems,
|
dragItems,
|
||||||
@@ -298,11 +298,11 @@ export function XYDrag<OnNodeDrag extends (e: any, nodes: any, node: any) => voi
|
|||||||
dragStarted = false;
|
dragStarted = false;
|
||||||
cancelAnimationFrame(autoPanId);
|
cancelAnimationFrame(autoPanId);
|
||||||
|
|
||||||
if (dragItems) {
|
if (dragItems.length > 0) {
|
||||||
const { nodeLookup, updateNodePositions, onNodeDragStop, onSelectionDragStop } = getStoreItems();
|
const { nodeLookup, updateNodePositions, onNodeDragStop, onSelectionDragStop } = getStoreItems();
|
||||||
const onNodeOrSelectionDragStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
|
const onNodeOrSelectionDragStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
|
||||||
|
|
||||||
updateNodePositions(dragItems, false, false);
|
updateNodePositions(dragItems, false);
|
||||||
|
|
||||||
if (onDragStop || onNodeOrSelectionDragStop) {
|
if (onDragStop || onNodeOrSelectionDragStop) {
|
||||||
const [currentNode, currentNodes] = getEventHandlerParams({
|
const [currentNode, currentNodes] = getEventHandlerParams({
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { drag } from 'd3-drag';
|
import { drag } from 'd3-drag';
|
||||||
import { select } from 'd3-selection';
|
import { select } from 'd3-selection';
|
||||||
|
|
||||||
import { getControlDirection, getDimensionsAfterResize, getPositionAfterResize, getResizeDirection } from './utils';
|
import { getControlDirection, getDimensionsAfterResize, getResizeDirection } from './utils';
|
||||||
import { getPointerPosition } from '../utils';
|
import { getPointerPosition } from '../utils';
|
||||||
import type { NodeLookup, Transform } from '../types';
|
import type { CoordinateExtent, NodeBase, NodeLookup, Transform, XYPosition } from '../types';
|
||||||
import type { OnResize, OnResizeEnd, OnResizeStart, ResizeDragEvent, ShouldResize, ControlPosition } from './types';
|
import type { OnResize, OnResizeEnd, OnResizeStart, ResizeDragEvent, ShouldResize, ControlPosition } from './types';
|
||||||
|
|
||||||
const initPrevValues = { width: 0, height: 0, x: 0, y: 0 };
|
const initPrevValues = { width: 0, height: 0, x: 0, y: 0 };
|
||||||
@@ -28,6 +28,12 @@ const initChange = {
|
|||||||
|
|
||||||
export type XYResizerChange = typeof initChange;
|
export type XYResizerChange = typeof initChange;
|
||||||
|
|
||||||
|
export type XYResizerChildChange = {
|
||||||
|
id: string;
|
||||||
|
position: XYPosition;
|
||||||
|
extent?: 'parent' | CoordinateExtent;
|
||||||
|
};
|
||||||
|
|
||||||
type XYResizerParams = {
|
type XYResizerParams = {
|
||||||
domNode: HTMLDivElement;
|
domNode: HTMLDivElement;
|
||||||
nodeId: string;
|
nodeId: string;
|
||||||
@@ -37,7 +43,7 @@ type XYResizerParams = {
|
|||||||
snapGrid?: [number, number];
|
snapGrid?: [number, number];
|
||||||
snapToGrid: boolean;
|
snapToGrid: boolean;
|
||||||
};
|
};
|
||||||
onChange: (changes: XYResizerChange) => void;
|
onChange: (changes: XYResizerChange, childChanges: XYResizerChildChange[]) => void;
|
||||||
onEnd?: () => void;
|
onEnd?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,6 +67,23 @@ export type XYResizerInstance = {
|
|||||||
destroy: () => void;
|
destroy: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function nodeToParentExtent(node: NodeBase): CoordinateExtent {
|
||||||
|
return [
|
||||||
|
[0, 0],
|
||||||
|
[node.computed!.width!, node.computed!.height!],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeToChildExtent(child: NodeBase, parent: NodeBase): CoordinateExtent {
|
||||||
|
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!,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResizerParams): XYResizerInstance {
|
export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResizerParams): XYResizerInstance {
|
||||||
const selection = select(domNode);
|
const selection = select(domNode);
|
||||||
|
|
||||||
@@ -78,53 +101,97 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
|
|||||||
|
|
||||||
const controlDirection = getControlDirection(controlPosition);
|
const controlDirection = getControlDirection(controlPosition);
|
||||||
|
|
||||||
|
let node: NodeBase | undefined = undefined;
|
||||||
|
let childNodes: XYResizerChildChange[] = [];
|
||||||
|
let parentNode: NodeBase | undefined = undefined; // Needed to fix expandParent
|
||||||
|
let parentExtent: CoordinateExtent | undefined = undefined;
|
||||||
|
let childExtent: CoordinateExtent | undefined = undefined;
|
||||||
|
|
||||||
const dragHandler = drag<HTMLDivElement, unknown>()
|
const dragHandler = drag<HTMLDivElement, unknown>()
|
||||||
.on('start', (event: ResizeDragEvent) => {
|
.on('start', (event: ResizeDragEvent) => {
|
||||||
const { nodeLookup, transform, snapGrid, snapToGrid } = getStoreItems();
|
const { nodeLookup, transform, snapGrid, snapToGrid } = getStoreItems();
|
||||||
const node = nodeLookup.get(nodeId);
|
node = nodeLookup.get(nodeId);
|
||||||
const { xSnapped, ySnapped } = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
|
||||||
|
|
||||||
prevValues = {
|
if (node) {
|
||||||
width: node?.computed?.width ?? 0,
|
const { xSnapped, ySnapped } = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
||||||
height: node?.computed?.height ?? 0,
|
|
||||||
x: node?.position.x ?? 0,
|
|
||||||
y: node?.position.y ?? 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
startValues = {
|
prevValues = {
|
||||||
...prevValues,
|
width: node.computed?.width ?? 0,
|
||||||
pointerX: xSnapped,
|
height: node.computed?.height ?? 0,
|
||||||
pointerY: ySnapped,
|
x: node.position.x ?? 0,
|
||||||
aspectRatio: prevValues.width / prevValues.height,
|
y: node.position.y ?? 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
onResizeStart?.(event, { ...prevValues });
|
startValues = {
|
||||||
|
...prevValues,
|
||||||
|
pointerX: xSnapped,
|
||||||
|
pointerY: ySnapped,
|
||||||
|
aspectRatio: prevValues.width / prevValues.height,
|
||||||
|
};
|
||||||
|
|
||||||
|
parentNode = undefined;
|
||||||
|
if (node.extent === 'parent' || node.expandParent) {
|
||||||
|
parentNode = nodeLookup.get(node.parentNode!);
|
||||||
|
if (parentNode && node.extent === 'parent') {
|
||||||
|
parentExtent = nodeToParentExtent(parentNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect all child nodes to correct their relative positions when top/left changes
|
||||||
|
// Determine largest minimal extent the parent node is allowed to resize to
|
||||||
|
childNodes = [];
|
||||||
|
childExtent = undefined;
|
||||||
|
|
||||||
|
for (const [childId, child] of nodeLookup) {
|
||||||
|
if (child.parentNode === nodeId) {
|
||||||
|
childNodes.push({
|
||||||
|
id: childId,
|
||||||
|
position: { ...child.position },
|
||||||
|
extent: child.extent,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (child.extent === 'parent' || child.expandParent) {
|
||||||
|
const extent = nodeToChildExtent(child, node!);
|
||||||
|
|
||||||
|
if (childExtent) {
|
||||||
|
childExtent = [
|
||||||
|
[Math.min(extent[0][0], childExtent[0][0]), Math.min(extent[0][1], childExtent[0][1])],
|
||||||
|
[Math.max(extent[1][0], childExtent[1][0]), Math.max(extent[1][1], childExtent[1][1])],
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
childExtent = extent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onResizeStart?.(event, { ...prevValues });
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.on('drag', (event: ResizeDragEvent) => {
|
.on('drag', (event: ResizeDragEvent) => {
|
||||||
const { nodeLookup, transform, snapGrid, snapToGrid } = getStoreItems();
|
const { transform, snapGrid, snapToGrid } = getStoreItems();
|
||||||
const pointerPosition = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
const pointerPosition = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
||||||
const node = nodeLookup.get(nodeId);
|
const childChanges: XYResizerChildChange[] = [];
|
||||||
|
|
||||||
if (node) {
|
if (node) {
|
||||||
const change = { ...initChange };
|
const change = { ...initChange };
|
||||||
|
|
||||||
const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues;
|
const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues;
|
||||||
|
|
||||||
const { width, height } = getDimensionsAfterResize(
|
const { width, height, x, y } = getDimensionsAfterResize(
|
||||||
startValues,
|
startValues,
|
||||||
controlDirection,
|
controlDirection,
|
||||||
pointerPosition,
|
pointerPosition,
|
||||||
boundaries,
|
boundaries,
|
||||||
keepAspectRatio
|
keepAspectRatio,
|
||||||
|
parentExtent,
|
||||||
|
childExtent
|
||||||
);
|
);
|
||||||
|
|
||||||
const isWidthChange = width !== prevWidth;
|
const isWidthChange = width !== prevWidth;
|
||||||
const isHeightChange = height !== prevHeight;
|
const isHeightChange = height !== prevHeight;
|
||||||
|
|
||||||
if (controlDirection.affectsX || controlDirection.affectsY) {
|
if (controlDirection.affectsX || controlDirection.affectsY) {
|
||||||
const { x, y } = getPositionAfterResize(startValues, controlDirection, width, height);
|
|
||||||
|
|
||||||
// only transform the node if the width or height changes
|
|
||||||
const isXPosChange = x !== prevX && isWidthChange;
|
const isXPosChange = x !== prevX && isWidthChange;
|
||||||
const isYPosChange = y !== prevY && isHeightChange;
|
const isYPosChange = y !== prevY && isHeightChange;
|
||||||
|
|
||||||
@@ -136,6 +203,31 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
|
|||||||
|
|
||||||
prevValues.x = change.x;
|
prevValues.x = change.x;
|
||||||
prevValues.y = change.y;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
childChanges.push(childNode);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,8 +236,8 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
|
|||||||
change.isHeightChange = isHeightChange;
|
change.isHeightChange = isHeightChange;
|
||||||
change.width = width;
|
change.width = width;
|
||||||
change.height = height;
|
change.height = height;
|
||||||
prevValues.width = width;
|
prevValues.width = change.width;
|
||||||
prevValues.height = height;
|
prevValues.height = change.height;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!change.isXPosChange && !change.isYPosChange && !isWidthChange && !isHeightChange) {
|
if (!change.isXPosChange && !change.isYPosChange && !isWidthChange && !isHeightChange) {
|
||||||
@@ -170,7 +262,7 @@ export function XYResizer({ domNode, nodeId, getStoreItems, onChange }: XYResize
|
|||||||
}
|
}
|
||||||
|
|
||||||
onResize?.(event, nextValues);
|
onResize?.(event, nextValues);
|
||||||
onChange(change);
|
onChange(change, childChanges);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.on('end', (event: ResizeDragEvent) => {
|
.on('end', (event: ResizeDragEvent) => {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { clamp, getPointerPosition } from '../utils';
|
import { CoordinateExtent } from '../types';
|
||||||
|
import { getPointerPosition } from '../utils';
|
||||||
import { ControlPosition } from './types';
|
import { ControlPosition } from './types';
|
||||||
|
|
||||||
type GetResizeDirectionParams = {
|
type GetResizeDirectionParams = {
|
||||||
@@ -75,81 +76,192 @@ type StartValues = PrevValues & {
|
|||||||
aspectRatio: number;
|
aspectRatio: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function getLowerExtentClamp(lowerExtent: number, lowerBound: number) {
|
||||||
|
return Math.max(0, lowerBound - lowerExtent);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUpperExtentClamp(upperExtent: number, upperBound: number) {
|
||||||
|
return Math.max(0, upperExtent - upperBound);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSizeClamp(size: number, minSize: number, maxSize: number) {
|
||||||
|
return Math.max(0, minSize - size, size - maxSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
function xor(a: boolean, b: boolean) {
|
||||||
|
return a ? !b : b;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculates new width & height of node after resize based on pointer position
|
* 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,
|
||||||
|
* 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!
|
||||||
|
* The way this is done is by determining how much each of these restricting actually restricts the resize and then applying the
|
||||||
|
* 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.
|
||||||
* @param startValues - starting values of resize
|
* @param startValues - starting values of resize
|
||||||
* @param controlDirection - dimensions affected by the resize
|
* @param controlDirection - dimensions affected by the resize
|
||||||
* @param pointerPosition - the current pointer position corrected for snapping
|
* @param pointerPosition - the current pointer position corrected for snapping
|
||||||
* @param boundaries - minimum and maximum dimensions of the node
|
* @param boundaries - minimum and maximum dimensions of the node
|
||||||
* @param keepAspectRatio - prevent changes of asprect ratio
|
* @param keepAspectRatio - prevent changes of asprect ratio
|
||||||
* @returns width: new width of node, height: new height of node
|
* @returns x, y, width and height of the node after resize
|
||||||
*/
|
*/
|
||||||
export function getDimensionsAfterResize(
|
export function getDimensionsAfterResize(
|
||||||
startValues: StartValues,
|
startValues: StartValues,
|
||||||
controlDirection: ReturnType<typeof getControlDirection>,
|
controlDirection: ReturnType<typeof getControlDirection>,
|
||||||
pointerPosition: ReturnType<typeof getPointerPosition>,
|
pointerPosition: ReturnType<typeof getPointerPosition>,
|
||||||
boundaries: { minWidth: number; maxWidth: number; minHeight: number; maxHeight: number },
|
boundaries: { minWidth: number; maxWidth: number; minHeight: number; maxHeight: number },
|
||||||
keepAspectRatio: boolean
|
keepAspectRatio: boolean,
|
||||||
|
extent?: CoordinateExtent,
|
||||||
|
childExtent?: CoordinateExtent
|
||||||
) {
|
) {
|
||||||
const { isHorizontal, isVertical, affectsX, affectsY } = controlDirection;
|
let { affectsX, affectsY } = controlDirection;
|
||||||
|
const { isHorizontal, isVertical } = controlDirection;
|
||||||
|
const isDiagonal = isHorizontal && isVertical;
|
||||||
|
|
||||||
const { xSnapped, ySnapped } = pointerPosition;
|
const { xSnapped, ySnapped } = pointerPosition;
|
||||||
const { minWidth, maxWidth, minHeight, maxHeight } = boundaries;
|
const { minWidth, maxWidth, minHeight, maxHeight } = boundaries;
|
||||||
|
|
||||||
const { pointerX: startX, pointerY: startY, width: startWidth, height: startHeight, aspectRatio } = startValues;
|
const { x: startX, y: startY, width: startWidth, height: startHeight, aspectRatio } = startValues;
|
||||||
const distX = Math.floor(isHorizontal ? xSnapped - startX : 0);
|
let distX = Math.floor(isHorizontal ? xSnapped - startValues.pointerX : 0);
|
||||||
const distY = Math.floor(isVertical ? ySnapped - startY : 0);
|
let distY = Math.floor(isVertical ? ySnapped - startValues.pointerY : 0);
|
||||||
|
|
||||||
let width = clamp(startWidth + (affectsX ? -distX : distX), minWidth, maxWidth);
|
const newWidth = startWidth + (affectsX ? -distX : distX);
|
||||||
let height = clamp(startHeight + (affectsY ? -distY : distY), minHeight, maxHeight);
|
const newHeight = startHeight + (affectsY ? -distY : distY);
|
||||||
|
|
||||||
if (keepAspectRatio) {
|
// Check if maxWidth, minWWidth, maxHeight, minHeight are restricting the resize
|
||||||
const nextAspectRatio = width / height;
|
let clampX = getSizeClamp(newWidth, minWidth, maxWidth);
|
||||||
const isDiagonal = isHorizontal && isVertical;
|
let clampY = getSizeClamp(newHeight, minHeight, maxHeight);
|
||||||
const isOnlyHorizontal = isHorizontal && !isVertical;
|
|
||||||
const isOnlyVertical = isVertical && !isHorizontal;
|
|
||||||
|
|
||||||
width = (nextAspectRatio <= aspectRatio && isDiagonal) || isOnlyVertical ? height * aspectRatio : width;
|
// Check if extent is restricting the resize
|
||||||
height = (nextAspectRatio > aspectRatio && isDiagonal) || isOnlyHorizontal ? width / aspectRatio : height;
|
if (extent) {
|
||||||
|
let xExtentClamp = 0;
|
||||||
if (width >= maxWidth) {
|
let yExtentClamp = 0;
|
||||||
width = maxWidth;
|
if (affectsX && distX < 0) {
|
||||||
height = maxWidth / aspectRatio;
|
xExtentClamp = getLowerExtentClamp(startX + distX, extent[0][0]);
|
||||||
} else if (width <= minWidth) {
|
} else if (!affectsX && distX > 0) {
|
||||||
width = minWidth;
|
xExtentClamp = getUpperExtentClamp(startX + newWidth, extent[1][0]);
|
||||||
height = minWidth / aspectRatio;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (height >= maxHeight) {
|
if (affectsY && distY < 0) {
|
||||||
height = maxHeight;
|
yExtentClamp = getLowerExtentClamp(startY + distY, extent[0][1]);
|
||||||
width = maxHeight * aspectRatio;
|
} else if (!affectsY && distY > 0) {
|
||||||
} else if (height <= minHeight) {
|
yExtentClamp = getUpperExtentClamp(startY + newHeight, extent[1][1]);
|
||||||
height = minHeight;
|
}
|
||||||
width = minHeight * aspectRatio;
|
|
||||||
|
clampX = Math.max(clampX, xExtentClamp);
|
||||||
|
clampY = Math.max(clampY, yExtentClamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the child extent is restricting the resize
|
||||||
|
if (childExtent) {
|
||||||
|
let xExtentClamp = 0;
|
||||||
|
let yExtentClamp = 0;
|
||||||
|
if (affectsX && distX > 0) {
|
||||||
|
xExtentClamp = getUpperExtentClamp(startX + distX, childExtent[0][0]);
|
||||||
|
} else if (!affectsX && distX < 0) {
|
||||||
|
xExtentClamp = getLowerExtentClamp(startX + newWidth, childExtent[1][0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (affectsY && distY > 0) {
|
||||||
|
yExtentClamp = getUpperExtentClamp(startY + distY, childExtent[0][1]);
|
||||||
|
} else if (!affectsY && distY < 0) {
|
||||||
|
yExtentClamp = getLowerExtentClamp(startY + newHeight, childExtent[1][1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
clampX = Math.max(clampX, xExtentClamp);
|
||||||
|
clampY = Math.max(clampY, yExtentClamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the aspect ratio resizing of the other side is restricting the resize
|
||||||
|
if (keepAspectRatio) {
|
||||||
|
if (isHorizontal) {
|
||||||
|
// Check if the max dimensions might be restricting the resize
|
||||||
|
const aspectHeightClamp = getSizeClamp(newWidth / aspectRatio, minHeight, maxHeight) * aspectRatio;
|
||||||
|
clampX = Math.max(clampX, aspectHeightClamp);
|
||||||
|
|
||||||
|
// Check if the extent is restricting the resize
|
||||||
|
if (extent) {
|
||||||
|
let aspectExtentClamp = 0;
|
||||||
|
if ((!affectsX && !affectsY) || (affectsX && !affectsY && isDiagonal)) {
|
||||||
|
aspectExtentClamp = getUpperExtentClamp(startY + newWidth / aspectRatio, extent[1][1]) * aspectRatio;
|
||||||
|
} else {
|
||||||
|
aspectExtentClamp =
|
||||||
|
getLowerExtentClamp(startY + (affectsX ? distX : -distX) / aspectRatio, extent[0][1]) * aspectRatio;
|
||||||
|
}
|
||||||
|
clampX = Math.max(clampX, aspectExtentClamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the child extent is restricting the resize
|
||||||
|
if (childExtent) {
|
||||||
|
let aspectExtentClamp = 0;
|
||||||
|
if ((!affectsX && !affectsY) || (affectsX && !affectsY && isDiagonal)) {
|
||||||
|
aspectExtentClamp = getLowerExtentClamp(startY + newWidth / aspectRatio, childExtent[1][1]) * aspectRatio;
|
||||||
|
} else {
|
||||||
|
aspectExtentClamp =
|
||||||
|
getUpperExtentClamp(startY + (affectsX ? distX : -distX) / aspectRatio, childExtent[0][1]) * aspectRatio;
|
||||||
|
}
|
||||||
|
clampX = Math.max(clampX, aspectExtentClamp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do the same thing for vertical resizing
|
||||||
|
if (isVertical) {
|
||||||
|
const aspectWidthClamp = getSizeClamp(newHeight * aspectRatio, minWidth, maxWidth) / aspectRatio;
|
||||||
|
clampY = Math.max(clampY, aspectWidthClamp);
|
||||||
|
|
||||||
|
if (extent) {
|
||||||
|
let aspectExtentClamp = 0;
|
||||||
|
if ((!affectsX && !affectsY) || (affectsY && !affectsX && isDiagonal)) {
|
||||||
|
aspectExtentClamp = getUpperExtentClamp(startX + newHeight * aspectRatio, extent[1][0]) / aspectRatio;
|
||||||
|
} else {
|
||||||
|
aspectExtentClamp =
|
||||||
|
getLowerExtentClamp(startX + (affectsY ? distY : -distY) * aspectRatio, extent[0][0]) / aspectRatio;
|
||||||
|
}
|
||||||
|
clampY = Math.max(clampY, aspectExtentClamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (childExtent) {
|
||||||
|
let aspectExtentClamp = 0;
|
||||||
|
if ((!affectsX && !affectsY) || (affectsY && !affectsX && isDiagonal)) {
|
||||||
|
aspectExtentClamp = getLowerExtentClamp(startX + newHeight * aspectRatio, childExtent[1][0]) / aspectRatio;
|
||||||
|
} else {
|
||||||
|
aspectExtentClamp =
|
||||||
|
getUpperExtentClamp(startX + (affectsY ? distY : -distY) * aspectRatio, childExtent[0][0]) / aspectRatio;
|
||||||
|
}
|
||||||
|
clampY = Math.max(clampY, aspectExtentClamp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
distY = distY + (distY < 0 ? clampY : -clampY);
|
||||||
|
distX = distX + (distX < 0 ? clampX : -clampX);
|
||||||
|
|
||||||
|
if (keepAspectRatio) {
|
||||||
|
if (isDiagonal) {
|
||||||
|
if (newWidth > newHeight * aspectRatio) {
|
||||||
|
distY = (xor(affectsX, affectsY) ? -distX : distX) / aspectRatio;
|
||||||
|
} else {
|
||||||
|
distX = (xor(affectsX, affectsY) ? -distY : distY) * aspectRatio;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (isHorizontal) {
|
||||||
|
distY = distX / aspectRatio;
|
||||||
|
affectsY = affectsX;
|
||||||
|
} else {
|
||||||
|
distX = distY * aspectRatio;
|
||||||
|
affectsX = affectsY;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
width,
|
width: startWidth + (affectsX ? -distX : distX),
|
||||||
height,
|
height: startHeight + (affectsY ? -distY : distY),
|
||||||
};
|
x: affectsX ? startX + distX : startX,
|
||||||
}
|
y: affectsY ? startY + distY : startY,
|
||||||
|
|
||||||
/**
|
|
||||||
* Determines new x & y position of node after resize based on new width & height
|
|
||||||
* @param startValues - starting values of resize
|
|
||||||
* @param controlDirection - dimensions affected by the resize
|
|
||||||
* @param width - new width of node
|
|
||||||
* @param height - new height of node
|
|
||||||
* @returns x: new x position of node, y: new y position of node
|
|
||||||
*/
|
|
||||||
export function getPositionAfterResize(
|
|
||||||
startValues: StartValues,
|
|
||||||
controlDirection: ReturnType<typeof getControlDirection>,
|
|
||||||
width: number,
|
|
||||||
height: number
|
|
||||||
) {
|
|
||||||
return {
|
|
||||||
x: controlDirection.affectsX ? startValues.x - (width - startValues.width) : startValues.x,
|
|
||||||
y: controlDirection.affectsY ? startValues.y - (height - startValues.height) : startValues.y,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user