Skip to content

Commit

Permalink
Fix horizontal edge label width (#240)
Browse files Browse the repository at this point in the history
This commit fixes the width calculation for horizontal edge labels so they're centered
  • Loading branch information
ghsteff authored Nov 7, 2023
1 parent 0ede7d7 commit 1f58f91
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/layout/elkLayout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ function mapNode(nodes: NodeData[], edges: EdgeData[], node: NodeData) {

const children = nodes.filter((n) => n.parent === node.id).map((n) => mapNode(nodes, edges, n));

const childEdges = edges.filter((e) => e.parent === node.id).map((e) => mapEdge(e));
const childEdges = edges.filter((e) => e.parent === node.id).map((e) => mapEdge({ edge: e }));

const nodeLayoutOptions: ElkNodeLayoutOptions = {
'elk.padding': `[left=${nodePadding.left}, top=${nodePadding.top}, right=${nodePadding.right}, bottom=${nodePadding.bottom}]`,
Expand Down Expand Up @@ -234,9 +234,14 @@ function mapNode(nodes: NodeData[], edges: EdgeData[], node: NodeData) {
};
}

function mapEdge({ data, ...edge }: EdgeData) {
function mapEdge({ edge: { data, ...edge }, direction }: { edge: EdgeData; direction?: CanvasDirection }) {
const labelDim = measureText(edge.text);
const validEdgeData = data ? { data } : {};
let labelWidth = labelDim.width / 2;

if (direction === 'LEFT' || direction === 'RIGHT') {
labelWidth = labelDim.width;
}

return {
id: edge.id,
Expand All @@ -251,7 +256,7 @@ function mapEdge({ data, ...edge }: EdgeData) {
labels: edge.text
? [
{
width: labelDim.width / 2,
width: labelWidth,
height: -(labelDim.height / 2),
text: edge.text,
layoutOptions: {
Expand All @@ -263,7 +268,7 @@ function mapEdge({ data, ...edge }: EdgeData) {
};
}

function mapInput(nodes: NodeData[], edges: EdgeData[]) {
function mapInput({ nodes, edges, direction }: { nodes: NodeData[]; edges: EdgeData[]; direction?: CanvasDirection }) {
const children = [];
const mappedEdges = [];

Expand All @@ -278,7 +283,7 @@ function mapInput(nodes: NodeData[], edges: EdgeData[]) {

for (const edge of edges) {
if (!edge.parent) {
const mappedEdge = mapEdge(edge);
const mappedEdge = mapEdge({ edge, direction });
if (mappedEdge !== null) {
mappedEdges.push(mappedEdge);
}
Expand Down Expand Up @@ -328,7 +333,7 @@ export const elkLayout = (nodes: NodeData[], edges: EdgeData[], options: ElkCanv
.layout(
{
id: 'root',
...mapInput(nodes, edges)
...mapInput({ nodes, edges, direction: layoutOptions?.['elk.direction'] })
},
{
layoutOptions: layoutOptions
Expand Down

0 comments on commit 1f58f91

Please sign in to comment.