-
Sivan Duijn authoredSivan Duijn authored
getClosestPill.ts 1.12 KiB
import { MultiGraph } from 'graphology';
/**
* Gets the closest node to id
* @param id
* @param nodes Graphology querybuilder MultiGraph object
* @param allowedNodeTypes An array of the node types which are included in the search
* @param maxDistance The maximum distance
* @returns the closest node if within range
*/
export function GetClosestPill(
id: string,
nodes: MultiGraph,
allowedNodeTypes: string[],
maxDistance = 150
): string | undefined {
const { x, y, w, h } = nodes.getNodeAttributes(id);
const center: { x: number; y: number } = { x: x + w / 2, y: y + h / 2 };
let minDist = maxDistance * maxDistance;
let closestNode: string | undefined = undefined;
nodes.forEachNode((node, { x, y, w, h, type }) => {
if (allowedNodeTypes.includes(type)) {
const nodeCenter: { x: number; y: number } = {
x: x + w / 2,
y: y + h / 2,
};
const dx = center.x - nodeCenter.x;
const dy = center.y - nodeCenter.y;
const dist = dx * dx + dy * dy;
if (dist < minDist) {
minDist = dist;
closestNode = node;
}
}
});
return closestNode;
}