refactor(nodes): handle type changes #545

This commit is contained in:
moklick
2020-10-05 12:14:22 +02:00
parent 787f8e1e25
commit c4e4f76a2b
3 changed files with 64 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
import React, { useState } from 'react';
import ReactFlow, { addEdge } from 'react-flow-renderer';
const onLoad = (reactFlowInstance) => reactFlowInstance.fitView();
const initialElements = [
{
id: '1',
sourcePosition: 'right',
type: 'input',
data: { label: 'Input' },
position: { x: 0, y: 80 },
},
{
id: '2',
type: 'output',
sourcePosition: 'right',
targetPosition: 'left',
data: { label: 'A Node' },
position: { x: 250, y: 0 },
},
{ id: 'e1-2', source: '1', type: 'smoothstep', target: '2', animated: true },
];
const HorizontalFlow = () => {
const [elements, setElements] = useState(initialElements);
const onConnect = (params) => setElements((els) => addEdge(params, els));
const changeType = () => {
setElements((elms) =>
elms.map((el) => {
if (el.type === 'input') {
return el;
}
el.type = el.type === 'default' ? 'output' : 'default';
return { ...el };
})
);
};
return (
<ReactFlow elements={elements} onConnect={onConnect} onLoad={onLoad}>
<button onClick={changeType} style={{ position: 'absolute', right: 10, top: 30, zIndex: 4 }}>
change type
</button>
</ReactFlow>
);
};
export default HorizontalFlow;

View File

@@ -15,6 +15,7 @@ import Provider from './Provider';
import Hidden from './Hidden';
import EdgeTypes from './EdgeTypes';
import CustomConnectionLine from './CustomConnectionLine';
import NodeTypeChange from './NodeTypeChange';
import './index.css';
@@ -79,6 +80,10 @@ const routes = [
path: '/custom-connectionline',
component: CustomConnectionLine,
},
{
path: '/nodetype-change',
component: NodeTypeChange,
},
];
const navLinks = routes.filter((route) => route.label);

View File

@@ -44,6 +44,13 @@ const useElementUpdater = (propElements: Elements): void => {
if (typeof propElement.type !== 'undefined') {
elementProps.type = propElement.type;
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
if (isNode(existingElement) && propElement.type !== existingElement.type) {
existingElement.__rf.width = null;
existingElement.__rf.height = null;
}
}
if (isNode(existingElement)) {