Collapsible Tree with Rectange and Circle

by Musakkhir Sayyed

HTML

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

CSS

.node circle {
      fill: #fff;
      stroke: steelblue;
      stroke-width: 3px;
    }
    
    .node rect {
      fill: #fff;
      stroke: steelblue;
      stroke-width: 3px;
    }
    
    .node text {
      font: 12px sans-serif;
    }
    
    .link path {
      fill: none;
      stroke: #ccc;
      stroke-width: 2px;
    }
    
    .link text {
      font: 12px sans-serif;
    }
    
    .arrow {
      fill: none;
      stroke: #ccc;
      stroke-width: 1px;
    }

JavaScript

var treeData = {
      "name": "File 1",
      "children": [{
        "name": "File 2",
        "children": [{
          "name": "File 3",
          "children": [{
            "name": "File 4",
            "type": "data"
          }]
        }, {
          "name": "File 5",
          "children": [{
            "name": "File 6",
            "type": "data",
            "children": [{
              "name": "File 7"
            }, {
              "name": "File 8",
              "type": "data"
            }]
          }]
        }],
      }],
      "type":"data"
    };

    // Set the dimensions and margins of the diagram
    var margin = {
        top: 20,
        right: 90,
        bottom: 30,
        left: 90
      },
      width = 5000 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    // appends a 'group' element to 'svg'
    // moves the 'group' element to the top left margin
    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 i = 0,
      duration = 750,
      root;

    // declares a tree layout and assigns the size
    var treemap = d3.tree().size([height, width]);

    // Assigns parent, children, height, depth
    root = d3.hierarchy(treeData, function(d) {
      return d.children;
    });
    root.x0 = height / 2;
    root.y0 = 0;

    // Collapse after the second level
    root.children.forEach(collapse);

    update(root);

    // Collapse the node and all it's children
    function collapse(d) {
      if (d.children) {
        d._children = d.children
        d._children.forEach(collapse)
        d.children = null
      }
    }

    function update(source) {

      // Assigns the x and y position for the nodes
      var treeData = treemap(root);

      //...