D3 - Hierarchy Editor

by bizamajig

HTML

<script src="https://d3js.org/d3.v4.min.js"></script>

CSS

.node rect {
  cursor: pointer;
  fill: #fff;
  fill-opacity: .5;
  stroke: #3182bd;
  stroke-width: 1px;
}

.node text {
  font: 10px sans-serif;
  pointer-events: none;
}

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

JavaScript

var treeData =
     {
      "name": "Top Level",
      "parent": "null",
      "children":  [
        {
          "name": "Level 2: A",
          "parent": "Top Level",
          "children": [
            {
              "name": "Son of A",
              "parent": "Level 2: A",
              "children" : [
                {
                  "name": "child of Son",
                  "parent": "Son of A"
                }
              ]
            },//children
            {
              "name": "Daughter of A",
              "parent": "Level 2: A"
            }
          ]
        },
        {
          "name": "Level 2: B",
          "parent": "Top Level"
        }
      ]
    }

var margin = {top: 30, right: 20, bottom: 30, left: 20},
    width = 960 - margin.right - margin.left,
    height = 800 - margin.top - margin.bottom,
    
    barHeight = 30,
    barWidth = width * .1;


var i = 0,
    duration = 400,
    root;


var svg = d3.select("body").append("svg")
    .attr('width', width + margin.right + margin.left)
    .attr('height', height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var root = d3.hierarchy(treeData) // Constructs a root node from the specified hierarchical data.

var tree = d3.tree().nodeSize([0, 30]) //Invokes tree

function update(source) {

  // Compute the flattened node list. TODO use d3.layout.hierarchy.
   nodes = tree(root); //returns a single node with the properties of d3.tree()
   nodesSort = [];

  d3.select("svg").transition()
      .duration(duration); //transition to make svg looks smoother

  // returns all nodes and each descendant in pre-order traversal (sort)
  nodes.eachBefore(function (n) {

     nodesSort.push(n); 
  });

  // Compute the "layout".
  nodesSort.forEach(function (n,i) {
    n.x = i *barHeight;
  })


  // Update the nodes…
  var node = svg.selectAll("g.node")
      .data(nodesSort, function(d) { return d.id || (d.id = ++i);...