JSFiddle - React, Tailwind, and code Playground

by nrabinowitz

HTML

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

CSS

.node {
  stroke: #fff;
  stroke-width: 1.5px;
}
.node.fixed {
  fill: red;
}
.node.not-fixed {
  fill: steelblue;
}

.link {
  stroke: #999;
  stroke-opacity: .6;
}

JavaScript

var width = 960,
    height = 500;

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var group = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append('g');

function update(graph) {
  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

  var link = group.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = group.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", function(d) {
          return d.fixed ? 'node fixed' : 'node not-fixed';
      })
      .attr("r", 5);
    
  // attach the standard force drag to all but the fixed node
  group.selectAll('.not-fixed')
      .call(force.drag);

  // attach a different drag handler to the fixed node
  var groupDrag = d3.behavior.drag()
      .on("drag", function(d) {
        // mouse pos offset by starting node pos
        var x = d3.event.x - 200,
        	y = d3.event.y - 200;
        group.attr("transform", function(d) { return "translate(" + x + "," + y + ")"; });
      });
    
  group.call(groupDrag)
    
  node.append("title")
      .text(function(d) { return d.name; });

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
}

update({
  "nodes":[
    {"name":"Myriel","group":1},
    {"name":"Napoleon","group":1},
    {"name":"Mlle.Baptistine","group":1},
    {"name":"Mme.Magloire","group":1},
    {"name":"CountessdeLo","group":1},
    {"name":"Geborand","group":1},
    {"name":"Champtercier","group":1},
   ...