Get connected shapes

Is there any way to get all the elements connected to a specific element.
For example in the following image, how can I can get all the shape elements linked to the last shape?

Screenshot 2021-02-17 at 11.01.52

Hi mahamane,

Do you want to keep the existing connections AND connect every shape to the last one?
Do you want the last one to connect to itself?

Regardless, you will need to use

modeling.connect(source, target);

Take a look at this CodeSandbox, I hope it helps you.

Hi azeghers,

Thank you for your answer.

Sorry, my english is not clear enough. I would like to make a function which outputs in order the identifiers of upstream shapes to the shape 4 for example (following image) : [shape 3 id, shape 2 id, shape 1 id].

I don’t know if there is a simple way to do that.

Screenshot 2021-02-17 at 12.17.02

Fairly simple:

function getGraph(element, graph = {}) {
  const incoming = element.incoming || [];

  return incoming.reduce((graph, connection) => {
    const { source } = connection;

    let value = null;

    if (source.incoming?.length) {
      value = getGraph(source);
    }

    return { ...graph, [source.id]: value };
  }, graph);
}

CodeSandbox: Graph Example - CodeSandbox

1 Like

Thanks you, this helped me a lot.
That’s exactly what I wanted. For example on the following diagram and for the last element:

Screenshot 2021-03-05 at 15.22.09

If have the following result :

Screenshot 2021-03-05 at 15.21.04

So I can read the ids of the elements in each branch. The problem is the result is an object of objects that also contain objects.

I want to get the ids as a list of lists of the ids of elements in each branch (underlined in black on the image). I can’t seem to do this. Could you help?
Thank you very much.

I don’t know if there were any easier ways, but I did this and it works:

let graph = getGraph(element);

let getBranch = function (graph : any, firstElement : any){
          let i =0;
          let j = 0;

          
          let actualIter :any;
          let branch : Array<any> = [];

          while ( i!=1){

            if (j!=1){
              branch.push(firstElement);
            j=1;
            }
            
            if ( graph != null){
              
              if (Object.keys(graph).length > 0){

                if (Object.keys(graph).length > 1){
                  getBranch(graph[Object.keys(graph)[1] as keyof Object],Object.keys(graph)[1] )
                }

                actualIter = Object.keys(graph)[0];
                branch.push(actualIter);
                graph = graph[actualIter as keyof Object];
                
              } else {
              i=1;
              branches.push(branch);
              branch = [];
              }
              
            } else {
              
              i=1;
              branches.push(branch);
              branch = [];
              }
            

          }
        }
1 Like