Files
xyflow/src/container/EdgeRenderer/utils.ts
T

102 lines
2.7 KiB
TypeScript

import { ComponentType } from 'react';
import { BezierEdge, StepEdge, SmoothStepEdge, StraightEdge } from '../../components/Edges';
import wrapEdge from '../../components/Edges/wrapEdge';
import { EdgeTypesType, EdgeProps, Position, Node, XYPosition, ElementId, HandleElement } from '../../types';
export function createEdgeTypes(edgeTypes: EdgeTypesType): EdgeTypesType {
const standardTypes: EdgeTypesType = {
default: wrapEdge((edgeTypes.default || BezierEdge) as ComponentType<EdgeProps>),
straight: wrapEdge((edgeTypes.bezier || StraightEdge) as ComponentType<EdgeProps>),
step: wrapEdge((edgeTypes.step || StepEdge) as ComponentType<EdgeProps>),
smoothstep: wrapEdge((edgeTypes.step || SmoothStepEdge) as ComponentType<EdgeProps>),
};
const wrappedTypes = {} as EdgeTypesType;
const specialTypes: EdgeTypesType = Object.keys(edgeTypes)
.filter((k) => !['default', 'bezier'].includes(k))
.reduce((res, key) => {
res[key] = wrapEdge((edgeTypes[key] || BezierEdge) as ComponentType<EdgeProps>);
return res;
}, wrappedTypes);
return {
...standardTypes,
...specialTypes,
};
}
export function getHandlePosition(position: Position, node: Node, handle: any | null = null): XYPosition {
if (!handle) {
switch (position) {
case Position.Top:
return {
x: node.__rf.width / 2,
y: 0,
};
case Position.Right:
return {
x: node.__rf.width,
y: node.__rf.height / 2,
};
case Position.Bottom:
return {
x: node.__rf.width / 2,
y: node.__rf.height,
};
case Position.Left:
return {
x: 0,
y: node.__rf.height / 2,
};
}
}
switch (position) {
case Position.Top:
return {
x: handle.x + handle.width / 2,
y: handle.y,
};
case Position.Right:
return {
x: handle.x + handle.width,
y: handle.y + handle.height / 2,
};
case Position.Bottom:
return {
x: handle.x + handle.width / 2,
y: handle.y + handle.height,
};
case Position.Left:
return {
x: handle.x,
y: handle.y + handle.height / 2,
};
}
}
export function getHandle(bounds: HandleElement[], handleId: ElementId | null): HandleElement | null | undefined {
let handle = null;
if (!bounds) {
return null;
}
// there is no handleId when there are no multiple handles/ handles with ids
// so we just pick the first one
if (bounds.length === 1 || !handleId) {
handle = bounds[0];
} else if (handleId) {
handle = bounds.find((d) => d.id === handleId);
}
if (typeof handle === 'undefined') {
return null;
}
return handle;
}