D3 Adds Directed Graph Editor

I am trying to increase the d3 Directed Editor Editor with a few ideas that will make it a very intuitive interface for people who want to “manually grow” the graph. I managed to change the node identifiers to strings that the user can enter through the prompt. The same applies to adding a "type" value to links connecting nodes.

The part that I encounter is that I can’t get the link property “type” displayed in the middle of the link when the graph is redrawn. Can someone offer some help / code that I could handle?

Here are the lines that establish examples of nodes and links:

var nodes = [
    {id: 'some name', reflexive: false},
    {id: 'some other name', reflexive: true },
    {id: 'some 3rd name', reflexive: false}
],
links = [
    {source: nodes[0], target: nodes[1], left: false, right: true ,type: 'some type I'},
    {source: nodes[1], target: nodes[2], left: false, right: true, type: 'some type II'}
];

When rendering nodes, a code appears that adds the identifier as a string:

g.append('svg:text')
    .attr('x', 0)
    .attr('y', 4)
    .attr('class', 'id')
    .text(function(d) { return d.id; });

However, when the links are redrawn, there is no function that receives the value of the type property and analyzes its 1/2 way between the coordinates of the source and target nodes. Here is the code that relates, as far as I can tell, using the link.

// update existing links
path.classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });


// add new links
path.enter().append('svg:path')
    .attr('class', 'link')
    .classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
    .on('mousedown', function(d) {
        if(d3.event.ctrlKey) return;

        // select link
        mousedown_link = d;
        if(mousedown_link === selected_link) selected_link = null;
        else selected_link = mousedown_link;
        selected_node = null;
        restart();
    });

Here is a link to jsfiddle with the latest version of the code .

+4
source share
1 answer

In your tick function, just recalculate the xy position of your text based on the source and target xy:

 function tick() {
   d3.selectAll("text")
   .attr("x", function(d) {return (d.source.x + d.target.x) / 2})
   .attr("y", function(d) {return (d.source.y + d.target.y) / 2})
 }

Here's the updated jsFiddle with path labels: http://jsfiddle.net/rco31ofe/2/

+2
source

Source: https://habr.com/ru/post/1570065/


All Articles