简体   繁体   中英

In D3JS hierarchy charts how we can minimize previously expand tiles when clicking new tile?

We have used a D3JS hierarchy chart for showing company employees in a tree view. There we groped employees by there managers. Then if we click one of manager tile, it will expand and view related employees. There we got some UI issues with huge number of employees. If one manager had lot of employees tree is going to expand so big and hard to identify.

What we need is, Is there way to minimize previously expand Manager tiles when clicking new Manager tile. By doing this we can save more space to show currently checking view.

I assume you're expanding on the classic D3 collapsible tree example whose latest working version is now hosted on Observable . You just need to change one small block of code there in order to get what you want.

Here's how the original responds when a node is clicked:

.on("click", (event, d) => {
   d.children = d.children ? null : d._children;
   update(d);
 });

Change that too:

.on("click", (event, d) => {
  //// Store the ancestors of the node you've clicked on
  let ancestors = d.ancestors();
  //// Collapse everone
  root
    .descendants()
    .slice(1)
    .reverse()
    .forEach(function (node) {
      node.children = null;
    });
  //// Re-expand the ancestors
  ancestors.forEach(function (d) {
    d.children = d._children;
  });
  update(node);
});

I created a fork of that notebook with those modifications and, in addition, limited the initial expansion to just one step. Here's the result:

 <div id="observablehq-chart-e84da0ba"></div> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@observablehq/inspector@5/dist/inspector.css"> <script type="module"> import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@5/dist/runtime.js"; import define from "https://api.observablehq.com/d/6167a04a8d3471d2@390.js?v=3"; new Runtime().module(define, name => { if (name === "chart") return new Inspector(document.querySelector("#observablehq-chart-e84da0ba")); }); </script>

I did something similar for the University where I work. Rather than the auto-collapse on click approach you've described, I set up a search box that allows you to search for employees by name. When you search for someone, the whole tree collapses and re-expands just the path you want. The implementation is in this Observable notebook .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM