Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>
<meta charset="UTF-8">
<body>
  <div class="tree">
  </div>
</body>
</html>

              
            
!

CSS

              
                



/* .link {
  fill: none;
  stroke: #B2CDF4;
  stroke-width: 2px;
} */
.container{
  overflow:auto;
}
div.tooltip {
  position: absolute;
  text-align: center;
  width: 118px;
  height: 24px;
  padding: 8px;
  font: 14px PingFangSC-Medium;
  color: #fff;
  background: rgba(0,0,0,0.65);
  border: solid 1px #aaa;
  border-radius: 3px;
  box-shadow: 0 2px 4px 0 rgba(0,0,0,0.35);
  pointer-events: none;
}
              
            
!

JS

              
                // http://blockbuilder.org/rijine/4efad194a4b8cc1b3851227272ace3d7
var treeData = {
    name: 'root',
    children: [{
        name: 'child1',
        children: [{
            name: 'child1_1',
            children: []
        }, { name: 'child1_2', children: [] }]
    }, {
        name: 'child2',
        children: [{
            name: 'child2_1',
            children: []
        }]
    }, {
        name: 'child3',
        children: [{
            name: 'child2_1',
            children: []
        }]
    }]
};
var treeData1 = {
    "name": "Top Level",
    "value": 75,
    "children": [
      { 
        "name": "Level 2: A",
        "value": 40,
        "children": [
          { "name": "Son of A" ,"value": 30},
          { "name": "Daughter of A" ,"value": 20},
          { "name": "Daughter of A",
           "value": 45,
          "children": [
            { "name": "Son of A",
           "value": 24,
            "children": [
            { "name": "Son of A",
             "value": 19
            },
          ]
            },
          ]
          }
        ]
      },
      { "name": "Level 2: B" , "value": 33}
    ]
  };

// Set the dimensions and margins of the diagram
// console.log("data--",treeData);
let op = {
  separationY: 2, // 节点y轴之间距离  (0.1, ∞) 之间 
  separationX: 1,
  margin: {
    top: 300,
    right: 90,
    bottom: 30,
    left: 90
  },
  duration: 550
}
let margin = op.margin,
  width = 960 - margin.left - margin.right,
  height = 600 - margin.top - margin.bottom;
let widthScale = d3.scaleLinear()
  .domain([1, 80])
  .range([1, 10])

// 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
let svg = d3.select(".tree").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})`);

let tooltip = d3.select('.tree')
    .append('div')
    .classed('tooltip arrow-box arrow-box-bottom', true)
    .style('visibility', 'hidden')

let i = 0,
  duration = 550

// declares a tree layout and assigns the size
let treemap = d3.tree()
   .size([height, width]);
  // .nodeSize([height, width])
  // .separation((a, b) => (a.parent == b.parent ? 1: 2) / (a.depth * 1/ op.separationY) )

// Assigns parent, children, height, depth
let root = d3.hierarchy(treeData, d => d.children )
// console.log(root)
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);
  // console.log('leaves', treeData.leaves())
  // console.log('...',treeData)
  // console.log('descendants',treeData.descendants())
  // console.log('slice',treeData.descendants().slice(1))
  // Compute the new tree layout.
  var nodes = treeData.descendants(),
    links = treeData.descendants().slice(1);

  // Normalize for fixed-depth.
  // nodes.forEach(d => {d.y = d.depth * 180 * op.separationX})
  nodes.forEach(function(d){ d.y = d.depth * 180});
  // console.log(nodes)

  // ****************** Nodes section ***************************

  // Update the nodes...
  var node = svg.selectAll('g.node')
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    })
    // .each(d => console.log("node",d))
  
  console.log("nodes",nodes)

  // Enter any new modes at the parent's previous position.
  var nodeEnter = node.enter().append('g')
    .attr('class', 'node')
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on('click', click);

  // Add Circle for the nodes
  nodeEnter.append('circle')
    .attr('class', 'node node-circle')
    .attr('r', 8)
    .style('fill', d => d._children ?  '#007FFF': '#B2CDF4')
    .attr('stroke','#2580FF')
    .attr('stroke-width', 2)
    .style('display', d => d.data.children ? 'inherit' : 'none')
    // .attr('cx', 40)
  
  nodeEnter.append('rect')
    .attr('class', 'node node-rect')
    .attr('width', 120)
    .attr('height', 32)
    .attr('rx', 3)
    .attr('ry', 3)
    .attr('x', 5)
    .attr('y', -16)
    .attr('fill', '#2580FF')
    .style('display', d => d.data.children ? 'none' : 'inherit')
    .style('border', '1px solid #2580FF')
    .on('mousemove', d => mousemove(tooltip, d))
    .on('mouseout', d => mouseout(tooltip, d))
   
  
 //  -
  nodeEnter.append('line')
    .attr('class', 'innerNode')
    // .each(d => console.log(d))
    .attr('x1', -5)
    .attr('y1', 0)
    .attr('x2', 5)
    .attr('y2', 0)
   .attr('stroke', '#2580FF')
   .attr('stroke-width', 2)
   // .style('display', d => d.children ? 'inherit' : 'none')
  
   // +
  nodeEnter.append('line')
    .attr('class', 'innerNode')
    // .each(d => console.log(d))
    .attr('x1', 0)
    .attr('y1', -5)
    .attr('x2', 0)
    .attr('y2', 5)
   .attr('stroke', '#fff')
   .attr('stroke-width', 2)
   .style('display', d => d.children ? 'none' : 'inherit')
  nodeEnter.append('line')
    .attr('class', 'innerNode')
    // .each(d => console.log(d))
    .attr('x1', -5)
    .attr('y1', 0)
    .attr('x2', 5)
    .attr('y2', 0)
   .attr('stroke', '#fff')
   .attr('stroke-width', 2)
   .style('display', d => d.children ? 'none' : 'inherit')
  
  // Add labels for the nodes
  nodeEnter.append('text')
    .attr("class", "label")
    .attr("dy", ".35em")
    .attr("x", function(d) {
      return d.children || d._children ? - 23 : 23;
    })
    // .attr("x", function(d) {
    //    return -15
    // })
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    // .attr('text-anchor', 'end')
    .text(function(d) {
      return d.data.name;
    })
    .style("fill", d => d.data.children? '#474747 ': '#fff')
    .style('font', '14px sans-serif')
    .on('mousemove', d => mousemove(tooltip, d))
    .on('mouseout', d => mouseout(tooltip, d))
    .each(wrapEllipsis)
  
// console.log('-------',d3.selectAll('.label').node().getComputedTextLength())
  // nodeEnter.append('text') 
  //   .attr("dy", ".4em")
  //   .attr("x", function(d) {
  //         return d.children || d._children ? 4 : -4;
  //    })
  //   .attr("text-anchor", function(d) {
  //     return d.children || d._children ? "end" : "start";
  //   })
  //   .text(function(d) {
  //     var children = d.children || d._children;
  //     return children ? '-' : '+';
  //   });

  // UPDATE
  var nodeUpdate = nodeEnter.merge(node);

  // Transition to the proper position for the node
  nodeUpdate.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  // Update the node attributes and style
  nodeUpdate.select('circle.node')
    .attr('r', 10)
    // .style("fill", function(d) {
    // console.log(d)
    //   //console.log("parentID",d.aspid);
    //   return d.data.children ? '#B2CDF4' : '#2580FF';
    // })
    // if(d._parentid !== null){
    // .style("fill", "blue")
    // }
    .attr('cursor', 'pointer');


  // Remove any exiting nodes
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  // On exit reduce the node circles size to 0
  nodeExit.select('circle')
    .attr('r', 1e-6);

  // On exit reduce the opacity of text labels
  nodeExit.select('text')
    .style('fill-opacity', 1e-6);

  // ****************** links section ***************************

  // Update the links...
  var link = svg.selectAll('path.link')
    .data(links, function(d) {
      // console.log('link', d)
      return d.id;
    })
    .style('stroke-width', 2)

  var linkEnter = link.enter().insert('path', "g")
    .attr("class", "link")
    .attr('d', function(d) {
      var o = {
        x: source.x0 ,
        y: source.y0 
      }
      return diagonal(o, o, d)
    })
   .attr('fill', 'none')
   .attr('stroke', '#B2CDF4')
   .attr('stroke-width', 2)
  

  // UPDATE
  var linkUpdate = linkEnter.merge(link);
  // console.log(linkUpdate)

  // Transition back to the parent element position
  linkUpdate.transition()
    .duration(duration)
    .attr('d', function(d) {
      // console.log('linkUpdate', d)
      return diagonal(d, d.parent, d)
    });

  // Remove any exiting links
  var linkExit = link.exit().transition()
    .duration(duration)
    .attr('d', function(d) {
      console.log('linkExit', d)
      var o = {
        x: source.x ,
        y: source.y 
      }
      return diagonal(o, o, d)
    })
    .remove();

  // Store the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });

  // Creates a curved (diagonal) path from parent to the child nodes
  function diagonal(s, d , item) {
    // console.log('..............')
    // console.log('-- s',s)
    // console.log('-- d',d)
   
    // let len = d3.selectAll('.label').node().getComputedTextLength() * 2
    // console.log(len)
    // .map(item=> item.node().getComputedTextLength())   
    // console.log(len)
    // console.log(d.data.childre? 
      let Numb = item.data.children ? 50 : 0
      path = `M ${s.y} ${s.x}
              C ${(s.y + d.y) / 2}  ${s.x},
                ${(s.y + d.y) / 2} ${d.x},
                ${d.y} ${d.x}`

      return path
    }

  function mousemove(tooltip, d) {
               tooltip.transition().duration(200).style('opacity', 0.9).style('visibility', 'visible')
                  .text( d.data.name)
                  .style("left", (d3.event.pageX ) + "px")
                  .style("top", (d3.event.pageY) + "px")
              }

  function mouseout(tooltip, d) {
              tooltip.transition()
                .duration(200)
                .style("opacity", 0);
            }

  // Toggle children on click.
  function click(d) {
    // console.log('this',this)
    d3.select(this).remove()
    // console.log('dataa---',d.data.parentid);
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
    if(d._children) {
       // +
      d3.select(this).append('line')
        .attr('class', 'innerNode')
        // .each(d => console.log(d))
        .attr('x1', 0)
        .attr('y1', -5)
        .attr('x2', 0)
        .attr('y2', 5)
       .attr('stroke', '#fff')
       .attr('stroke-width', 2)
       // .style('display', d => d._children ? 'none' : 'inherit')
      d3.select(this).append('line')
        .attr('class', 'innerNode')
        // .each(d => console.log(d))
        .attr('x1', -5)
        .attr('y1', 0)
        .attr('x2', 5)
        .attr('y2', 0)
       .attr('stroke', '#fff')
       .attr('stroke-width', 2)
       // .style('display', d => d._children ? 'none' : 'inherit')
    } else {
      d3.select(this).append('line')
        .attr('class', 'innerNode')
        // .each(d => console.log(d))
        .attr('x1', -5)
        .attr('y1', 0)
        .attr('x2', 5)
        .attr('y2', 0)
       .attr('stroke', '#2580FF')
       .attr('stroke-width', 2)
       // .style('display', d => d.children || d._children ? 'inherit' : 'none')
    }
    
    update(d);
  }
  function zoom() {
                        var scale = d3.event.scale,
                            translation = d3.event.translate,
                            tbound = -height * scale * 100,
                            bbound = height * scale,
                            lbound = (-width + margin.right) * scale,
                            rbound = (width - margin.bottom) * scale;
                        // console.log("pre min/max" + translation);
                        // limit translation to thresholds
                        translation = [
                            Math.max(Math.min(translation[0], rbound),
                                lbound),
                            Math.max(Math.min(translation[1], bbound),
                                tbound)
                        ];
                        // console.log("scale" + scale);
                        // console.log("translation" + translation);

                        svg.attr("transform", "translate(" + translation + ")" +
                            " scale(" + scale + ")");
                    }
  }

/* Word Wrap */
  function wrapNewLine(text, width) {
                    text.each(function() {
                        var text = d3.select(this),
                            words = text.text().split(/\s+/).reverse(),
                            word,
                            line = [],
                            lineNumber = 1,
                            lineHeight = 1, // ems
                            x = text.attr("x"),
                            y = text.attr("y"),
                            dy = 0, //parseFloat(text.attr("dy")),
                            tspan = text.text(null)
                            .append("tspan")
                            .attr("x", x)
                            .attr("y", y)
                            .attr("dy", dy + "em");
                        while (word = words.pop()) {
                            line.push(word);
                            tspan.text(line.join(" "));
                            if (tspan.node().getComputedTextLength() >
                                width) {
                                line.pop();
                                tspan.text(line.join(" "));
                                line = [word];
                                tspan = text.append("tspan")
                                    .attr("x", x)
                                    .attr("y", y)
                                    .attr("dy", lineNumber *
                                        lineHeight + dy + "em")
                                    .text(word);
                            }
                        }
                    });
                }

  function wrapEllipsis() {
      var self = d3.select(this),
        textLength = self.node().getComputedTextLength(),
        text = self.text()

      while (textLength > 98 && text.length > 0) {
        text = text.slice(0, -1)
        self.text(text + '...')
        textLength = self.node().getComputedTextLength()
      }
    }

              
            
!
999px

Console