feat: sortVertices

This commit is contained in:
IlyaDoronin 2023-10-27 17:10:08 +03:00
parent f4a3dbcece
commit 882263fe1d

@ -48,6 +48,45 @@ const getCurrentIndent = (
return [currentIndent, bottomIndent]; return [currentIndent, bottomIndent];
}; };
const sortVertices = (
elements: ElementDefinition[],
vertices: Vertex[]
): ElementDefinition[] => {
const sortedVertices: ElementDefinition[] = [];
elements.forEach((element) => {
const currentVertex = vertices.find(({ id }) => element.data.id === id);
if (!currentVertex || (currentVertex?.edges?.length || 0) < 2) {
sortedVertices.push(element);
return;
}
const firstChildId = currentVertex.edges?.at(0);
const lastChildId = currentVertex.edges?.at(-1);
const firstChild = elements.find(({ data }) => data.id === firstChildId);
const lastChild = elements.find(({ data }) => data.id === lastChildId);
if (!firstChild?.position || !lastChild?.position) {
sortedVertices.push(element);
return;
}
const parentVertexTopIndent =
firstChild.position.y +
(lastChild.position.y - firstChild.position.y) / 2;
sortedVertices.push({
...element,
position: { x: element.position?.x || 0, y: parentVertexTopIndent },
});
});
return sortedVertices;
};
export const createGraphElements = ( export const createGraphElements = (
vertices: Vertex[] vertices: Vertex[]
): ElementDefinition[] => { ): ElementDefinition[] => {
@ -95,5 +134,7 @@ export const createGraphElements = (
}); });
}); });
return [...elements, ...bridges]; const sortedElements = sortVertices(elements, vertices);
return [...sortedElements, ...bridges];
}; };