在节点上隐藏和显示子节点点击Cytoscape

时间:2017-01-06 13:20:57

标签: javascript cytoscape.js cytoscape

我正在尝试使用breadthfirst布局在Cytoscape中创建可折叠树结构,以复制D3 collapsible tree

我正在尝试在节点上复制此类点击操作,但另外添加了还原功能 - Images & breadthfirst layout

我选择Cytoscape的原因是因为我有一个场景,其中树的节点有超过1个父节点。

我尝试使用以下代码添加点击事件:

cy.on('tap', 'node', function() {
    if (this.scratch().restData == null) {
       // Save node data and remove
       this.scratch({
            restData: this.connectedEdges().targets().remove()
       });
    } else {
       // Restore the removed nodes from saved data
       this.scratch().restData.restore();
       this.scratch({
            restData: null
       });
    }
}

但是,这只能成功折叠和扩展其直接子节点(其余节点仍然可见),并且当我点击叶节点时也会导致问题。

如果有人知道扩展和折叠节点的方法,请提供帮助。

编辑:大家,如果有人知道简单的多级树的解决方案,那也是一个好的开始......

2 个答案:

答案 0 :(得分:2)

我替换了这行代码:

 restData: this.connectedEdges().targets().remove()

这一个:

restData: this.successors().targets().remove()

此代码现在折叠子节点和孙子节点(仅在3个级别上测试),并且叶子节点在单击时不再折叠到其父节点中。

答案 1 :(得分:1)

我找到了一些方法来实现这种效果。

  1. 使用删除和恢复。加载树时,节点'孩子们被存放。

    var childrenData = new Map(); //holds nodes' children info for restoration
    var nodes = elems.nodes
    for(var x = 0; x < nodes.length; x++){
      var curNode = cy.$("#" + nodes[x].data.id);
      var id = curNode.data('id');
      //get its connectedEdges and connectedNodes
      var connectedEdges = curNode.connectedEdges(function(){
        //filter on connectedEdges
        return !curNode.target().anySame( curNode );
      });
      var connectedNodes = connectedEdges.targets();
      //and store that in childrenData
      //removed is true because all children are removed at the start of the graph
      childrenData.set(id, {data:connectedNodes.union(connectedEdges), removed: true}); 
    }  
    

    然后,可以在节点单击中删除和恢复此数据,类似于原始代码。我使用Cytoscape的图像折叠树演示作为我的示例的基础:jsfiddle

  2. 使用节点的display属性。由于节点是隐藏的而不是删除的,因此它们的连接边和节点仍可访问,因此您无需存储数据事先。

    cy.on('tap', 'node', function(){
      //if the node's children have been hidden
      //getting the element at 1 because the element at 0 is the node itself
      //want to check if its children are hidden
      if (this.connectedEdges().targets()[1].style("display") == "none"){
        //show the nodes and edges
        this.connectedEdges().targets().style("display", "element");
      } else {
        //hide the children nodes and edges recursively
        this.successors().targets().style("display", "none");
      }
    }); 
    

    jsfiddle

  3. 在GitHub上还有一个名为 cytoscape.js-expand-collapse 的Cytoscape扩展。我没有亲自使用它,但它的描述符合您描述的功能:
      

    用于扩展/折叠节点的Cytsocape.js扩展,以更好地管理复合图的复杂性