feat(noderenderer): render nodes recursively

This commit is contained in:
Christopher Möller
2021-10-22 12:09:01 +02:00
parent c1d5c35a04
commit 8b95cd712f
2 changed files with 29 additions and 15 deletions

View File

@@ -32,7 +32,7 @@ const initialNodes: Node[] = [
},
{
id: '4a',
data: { label: 'Node 4a', isNested: true },
data: { label: 'Node 4a' },
position: { x: 400, y: 400 },
className: 'light',
parentNode: '4',
@@ -47,14 +47,14 @@ const initialNodes: Node[] = [
},
{
id: '4b1',
data: { label: 'Node 4b1', isNested: true },
data: { label: 'Node 4b1' },
position: { x: 450, y: 450 },
className: 'light',
parentNode: '4b',
},
{
id: '4b2',
data: { label: 'Node 4b2', isNested: true },
data: { label: 'Node 4b2' },
position: { x: 550, y: 550 },
className: 'light',
parentNode: '4b',
@@ -135,6 +135,7 @@ const BasicFlow = () => {
defaultZoom={1.5}
minZoom={0.2}
maxZoom={4}
onlyRenderVisibleElements={false}
>
<MiniMap />
<Controls />

View File

@@ -31,7 +31,7 @@ const selector = (s: ReactFlowState) => ({
});
interface NodesProps extends NodeRendererProps {
nodes?: Node[];
nodes: Node[];
isDraggable?: boolean;
resizeObserver: ResizeObserver | null;
scale: number;
@@ -41,10 +41,12 @@ interface NodesProps extends NodeRendererProps {
nodesConnectable: boolean;
elementsSelectable: boolean;
recursionDepth: number;
parentId?: string;
}
function Nodes({
nodes = [],
nodes,
parentId,
isDraggable,
resizeObserver,
scale,
@@ -56,7 +58,12 @@ function Nodes({
recursionDepth,
...props
}: NodesProps): any {
return nodes.map((node) => {
const rootNodes = useMemo(
() => (parentId ? nodes.filter((n) => n.parentNode === parentId) : nodes.filter((n) => !n.parentNode)),
[nodes, parentId]
);
return rootNodes.map((node) => {
const nodeType = node.type || 'default';
if (!props.nodeTypes[nodeType]) {
@@ -75,18 +82,11 @@ function Nodes({
node.height !== null &&
typeof node.width !== 'undefined' &&
typeof node.height !== 'undefined';
let childRect;
const childNodes = nodes.filter((n) => n.parentNode === node.id && !n.isHidden);
// if (childNodes.length) {
// console.log(node.id, childNodes, getRectOfNodes(childNodes));
// }
// console.log(childNodes);
if (childNodes.length) {
childRect = getRectOfNodes(childNodes);
const childRect = getRectOfNodes(childNodes);
node.position = node.isDragging
? node.position
: { x: Math.round(childRect.x) - 10, y: Math.round(childRect.y) - 10 };
@@ -130,10 +130,23 @@ function Nodes({
isDraggable={isNodeDraggable}
isSelectable={isSelectable}
isConnectable={isConnectable}
resizeObserver={resizeObserver}
resizeObserver={childNodes.length ? resizeObserver : null}
dragHandle={node.dragHandle}
zIndex={3 + recursionDepth}
/>
<MemoizedNodes
nodes={nodes}
parentId={node.id}
snapToGrid={snapToGrid}
snapGrid={snapGrid}
nodesDraggable={nodesDraggable}
nodesConnectable={nodesConnectable}
resizeObserver={resizeObserver}
elementsSelectable={elementsSelectable}
scale={scale}
recursionDepth={recursionDepth + 1}
{...props}
/>
</Fragment>
);
});