简体   繁体   中英

Vis.js How to show only children/descendents of selected node?

If not posible with vis.js, I could do the entire thing on something else. But this functionality is crucial. So, show everything if nothing selected; show only children (with the "from" arrow) of some node if that node is selected. Or to select the node in some list, or type it somewhere. https://codepen.io/andre-fr-silva/pen/ZEBPpqK

var container = document.getElementById("mynetwork");
var data = {
  nodes: nodes,
  edges: edges,
};

This can be achieved using the select event defined in the documentation here in combination with the hidden property on nodes defined here . You can update the data in the DataSet, the network will then display the updates. In summary the logic I would suggest is to:

  1. If no nodes are selected
    1. Unhide all nodes
  2. If one or more nodes are selected
    1. Hide all nodes
    2. Display the selected nodes
    3. Display nodes connected from the selected node

The following implements this logic.

network.on('select', function (properties) {
  // Define an array of nodes ot update, this is quicker than
  // updating each node individually
  let nodesToUpdate = [];
  
  // If no nodes are selected, unhide all hidden nodes
  if(properties.nodes.length === 0){
    // Populate array with list of nodes to unhide
    data.nodes.forEach(node => {
      if(node.hidden){ 
        nodesToUpdate.push({id:node.id, hidden: false});
      }
    });
    
    // Update nodes and return
    data.nodes.update(nodesToUpdate);
    return;
  }
    
  // One or more nodes are selected
  // Populate array with list of all nodes, hiding them
  data.nodes.forEach(node => {
    nodesToUpdate.push({id:node.id, hidden: true});
  });

  // Pouplate array with list of selected and connected nodes to unhide
  // Note: Nodes will already exist in the array, but these later updates
  //       will overwrite the earlier ones.
  properties.nodes.forEach(node => {
    // Add selected node
    nodesToUpdate.push({id:node, hidden:false});
    
    // Add connected nodes to the selected node
    data.edges.forEach(edge => {
      // Unhide if connected from selected node and connected node exists
      if(edge.from === node && data.nodes.get(edge.to)){
        nodesToUpdate.push({id:edge.to, hidden: false});
      }
    });
  }); 
  
  // Submit updates to hide/unhide nodes
  data.nodes.update(nodesToUpdate);
});

Please note this could be optimised further, removing or updating items in the nodesToUpdate array instead of duplicating them.

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