JSFiddle - React, Tailwind, and code Playground

by ninachroscicka

HTML

<script src="http://bl.ocks.org/mbostock/1093130"></script>
<div id="viz" />

CSS

.node circle {
    cursor: pointer;
    stroke:    #29a8ab;
    stroke-width: 19.5px;
    opacity:0.99;
}
.node text {
    font: 12px sans-serif;
    pointer-events: none;
    text-anchor: middle;
    font-weight: 600;
    text-transform: capitalize;
    letter-spacing: 4.5px;
}
line.link {
    fill: none;
    stroke:   #bdeaee ;
    stroke-width: 3.5px;
    opacity:0.75;
}

JavaScript

//Notes:
// Src: http://bl.ocks.org/mbostock/1093130
//Notes:
// * Each dom element is using 
//   children to store refs to expanded children
//   _children to store refs to collapsed children
//* It's using both a tree and a graph layout.

//root 
var g = {
    data: null,
    force:null
};

$(function () {

    //use a global var for the data:
    g.data = data;


    var width = 960,
        height = 500;

    //Create a sized SVG surface within viz:
    var svg = d3.select("#viz")
        .append("svg")
        .attr("width", width)
        .attr("height", height);


    g.link = svg.selectAll(".link"),
    g.node = svg.selectAll(".node");

    //Create a graph layout engine:
    g.force = d3.layout.force()
        .linkDistance(130)
        .charge(-120)
        .gravity(0.05)
        .size([width, height])
    //that invokes the tick method to draw the elements in their new location:
    .on("tick", tick);



    //Draw the graph:
    //Note that this method is invoked again
    //when clicking nodes:
    update();


});







//invoked once at the start, 
//and again when from 'click' method
//which expands and collapses a node.

function update() {

    //iterate through original nested data, and get one dimension array of nodes.
    var nodes = flatten(g.data);

    //Each node extracted above has a children attribute.
    //from them, we can use a tree() layout function in order
    //to build a links selection.
    var links = d3.layout.tree().links(nodes);

    // pass both of those sets to the graph layout engine, and restart it
    g.force.nodes(nodes)
        .links(links)
        .start();

    //-------------------
    // create a subselection, wiring up data, using a function to define 
    //how it's suppossed to know what is appended/updated/exited
    g.link = g.link.data(links, function (d) {return d.target.id;});

    //Get rid of old links:
    g.link.exit().remove();

    //Build new links by adding new svg lines:
    g.link
       ...