JSFiddle - React, Tailwind, and code Playground

by Yaprak Ayazoğlu

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>

CSS

.node {
  cursor: pointer;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}

JavaScript

var root = {
    "name": "Controller1",
  "nodeType": "Controller",
  "children":[
    {
      "name" : "Switch2",
      "nodeType": "Switch",
      "children" : [
        {"name" : "Host3", "nodeType": "Host"},
        {"name": "Host4", "nodeType": "Host"}
      ]
    },
    {
      "name": "Switch1",
      "nodeType": "Switch",
      "children": [
        {"name" : "Host5" , "nodeType": "Host"}
      ]
    },
    {
      "name" : "Switch3",
      "nodeType" : "Switch",
      "children" : [
        {"name": "Host1", "nodeType": "Host"},
        {"name": "Host2", "nodeType": "Host"}
      ]
    }
  ]
};

  var width = 500,
    height = 500,
    rectW = 50,
    rectH = 25,
    r = 55,
    root;

  var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("pointer-events", "all")
    .append('svg:g')
    .call(d3.behavior.zoom().on("zoom", redraw))
    .append('svg:g')
    .on("click", function(){
      console.log("click");
    })
    .on("touchdown", function(){
      console.log("touch down");
    });

var force = d3.layout.force()
    .charge(-220)
    .linkDistance(function(d){
        if(d.source.nodeType === "Controller")
          return (50 + Math.floor( Math.random()*30 ));
        else if(d.source.nodeType === "Switch")
          return (50 + Math.floor( Math.random()*60) );
      }
    )
    .gravity(.05)
    .linkStrength(1)
    .size([width, height])
    .on("tick", tick);

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

//  d3.json("data.json", function(error, json) {
//    root = json;
    update();
//  });

function update() {
    var nodes = flatten(root),
      links = d3.layout.tree().links(nodes);

    links.push( {"source": 4, "target" : 2} );

    // Restart the force layout.
    force
      .nodes(nodes)
      .links(links)
      .start();

    // Update links.
    link = link.data(links, function(d) { return d.target.id; });

    link.exit().remove();

   ...