Skip to content

Commit

Permalink
feat(graph): draw label for curved links
Browse files Browse the repository at this point in the history
  • Loading branch information
davidballester committed Nov 16, 2019
1 parent dbdfea6 commit 4619d1e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/components/canvas/canvas.component.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export default ({
}
}}
linkCanvasObjectMode={() => 'after'}
linkCanvasObject={renderLink}
linkCanvasObject={(link, ctx, globalScale) => renderLink(link, ctx, globalScale, linksGraphData)}
/>
</div>
);
Expand Down
25 changes: 22 additions & 3 deletions src/components/canvas/services/link-renderer.service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import orange from '@material-ui/core/colors/orange';
import grey from '@material-ui/core/colors/grey';
import _get from 'lodash/get';
import { default as Bezier } from 'bezier-js';

export function getLinkColor(link) {
const groupColor = _get(link, 'groups[0].color');
Expand All @@ -18,23 +19,26 @@ export function getLinkColor(link) {
}
}

export function renderLink(link, ctx, globalScale) {
export function renderLink(link, ctx, globalScale, links) {
if (!!link.label) {
const fontSize = globalScale * 0.8;
ctx.font = `${fontSize}px Sans-Serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#666';
const { x, y } = getLabelPosition(link);
const { x, y } = getLabelPosition(link, links);
ctx.fillText(link.label, x, y);
}
}

function getLabelPosition(link) {
function getLabelPosition(link, links) {
const { source, target } = link;
if (source.id === target.id) {
return getSelfLinkPosition(link);
}
if (!!findOppositeLabelledLink(link, links)) {
return getCurvedLinkPosition(link);
}
return {
x: (source.x + target.x) / 2,
y: (source.y + target.y) / 2,
Expand All @@ -48,3 +52,18 @@ function getSelfLinkPosition(link) {
y: source.y - 10,
};
}

function getCurvedLinkPosition({ source, target, __controlPoints: controlPoints }) {
if (!controlPoints || !controlPoints.length) {
return {
x: (source.x + target.x) / 2,
y: (source.y + target.y) / 2,
};
}
const bzLine = new Bezier(source.x, source.y, ...controlPoints, target.x, target.y);
return bzLine.get(0.6);
}

function findOppositeLabelledLink(link, links) {
return links.find(({ id, source, target, label }) => id !== link.id && !!label && source.id === link.target.id && target.id === link.source.id);
}

0 comments on commit 4619d1e

Please sign in to comment.