datastorm-open / visNetwork

R package, using vis.js library for network visualization
Other
542 stars 126 forks source link

display all pathways of selected node. #378

Open SaharTaheri91 opened 4 years ago

SaharTaheri91 commented 4 years ago

I built a large hierarchical network. How can I use Shiny to display/list all paths that the selected node belongs to? The list should contain node labels and edge labels in path order. A selected node could be anywhere (root, leaf, …) and be selected from fluidPage.

Something like this: (Paths start from roots to leaves) A ---r1---> B ---r3---> C (selected Node) --- r2---> D E ---r1---> C (selected Node) --- r2---> F---r2--->X

Thanks!

fpierrat commented 4 years ago

Hi,

I had the same needs but only for descendants, not parents. Here is how I got it working. I wanted to integrate it IN visNetwork and make a pull request, never had time for it though. Note: my function doesn't "display" the descendants, it "selects" them. But once you have the recursive logic working, I think the main part is done.

See if you can adapt this for your needs.

In my use-case, it was called on shift-click, so there's a calling event on "click" and a test on "shift" in the called function:

network.on("click", selectDescendants );

function selectDescendants(params) {
    if(!params.event.srcEvent.shiftKey || !params.nodes.length ){return true;} //if not a shift-click on a node, just let propagate
    var descendants=[];
    function getDescendants(node){//recursive function to get all children, grandchildren, etc. 
        let children=network.getConnectedNodes(node, 'to');
        children.forEach(function(child){
            if(descendants.indexOf(child)===-1){//avoids infinite loops on A child of B child of C child of A...
                descendants.push(child);
                getDescendants(child);
            }
        })
    }
    getDescendants(params.nodes[0]);// all ancestors...
    descendants.push(params.nodes[0]);// ... and self !
    network.selectNodes(descendants,true);
    //return true;//let propagate (not sure it's a good thing, test and see...)
}
MaxKerney commented 4 years ago

This is really helpful, thank you! Excuse my naivety, but how would I use your function in R/Shiny? I'm guessing your code is javascript?