Help with collapsible tree

Hi everybody,

I am trying to create an org chart based on the collapsible tree example.

My code is here (collapsible org chart).

Problem is that I didn’t understand how the diagonal function works.

Instead of using d3.linkVertical() I would like to connect the nodes using orthogonal lines, but I could not make this, because I didn’t grasp the code completely.

Why diagonal is called with the same coordinates for source and target in linkEnter and link.exit()?

const o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});

Why diagonal is called without arguments in link.merge?

link.merge(linkEnter).transition(transition)
    .attr("d", diagonal);

Thanks in advance,

1 Like

Welcome to the forums Paulo!

In that example, when you open or close a branch of the tree, there’s an animated transition: each link, drawn with diagonal, expands out of (or collapses into) its source node. So, at the instant the new node is added and the transition begins (or the transition ends and it’s removed), the link is shrunken down to zero size. To implement that, the example draws the link as beginning and ending at the same place; both source and target are set to the coordinates of the source, with const o = {x: source.x0, y: source.y0}. Once there’s a path in place, it’s transitioned (interpolated) to the full-size version by the next couple lines of code you pointed out:

// Transition links to their new position.
link.merge(linkEnter).transition(transition)
    .attr("d", diagonal);

Writing diagonal without arguments like that means that the example is passing the function diagonal itself to the .attr setter method. When you give that method a function, it passes the datum joined to each member of the selection. So, writing

.attr("d", diagonal)

is equivalent to writing

.attr("d", d => diagonal(d))

and d is an object that has source and target set, so it’s already in the “shape” that the diagonal function expects, as you can see in this example datum:

You can see that source and target both have x0 and y0 coordinates. And that format is what const o is made to match in the enter and exit selections.

2 Likes

Hi @tophtucker,

Thank you so much for your support.

For sure my code need some refactoring, but it is already working.

Wow cool! That looks handy!