positionrestorecytoscape.js

Is it possible to store Cytoscape.js layout data directly to a file format in app/web server and re-launch the same layout to minimize re-computation?


Some of the cytoscape layout is randomize where the position is not fix every time we launch it. I understand from multiple stack overflow questions where we can save the layout data (i.e. including its position x and y) into browser local storage or session storage so that we can display the same layout using the same data.

However, the problem with local storage or session storage is good for one users. But, imagine if there are thousands of users using the same app, the server will undergo mass computation for each user to store respective data to individual browsers. Can we save the data into a file format directly into app/web server so that 1000 users will see the same layout and this reduces the computation of different data set as well.

Thank you. Would like to know the possibility to convert data into a file and store in the web/app server.


Solution

  • Yes, you can store position data. Actually, there are 2 options in my mind:

    1) Use cy.json()

    You can store the elements as JSON: JSON.stringify(cy.json().elements) and then save this JSON string.

    cy.json().elements stores your data as shown below:

    cy.json().elements response

    You can restore this data easily like cy.json({elements: JSON.parse(jsonStr));

    2) Only save position data

    As you could see cy.json().elements is a bit big thing. Position data is just a small object like {x: 0, y: 0}. Additional to position it contains many other data. So if you only need to restore the positions, you could store them manually easily with a code like below. You can use ele.id and node.position() functions.

    function storePositions() {
      const nodes = cy.nodes(); 
      const nodePositions = {};
      for (let i = 0; i < nodes.length; i++) {
        nodePositions[nodes[i].id()] = nodes[i].position();
      }
      return nodePositions;
    }
    

    You can also restore node positions easily. You can use getElementById and node.position() functions.

    function restorePositions(nodePositions) {
      const nodes = cy.nodes(); 
      const nodePositions = {};
      for (let k in nodePositions) {
        const node = cy.getElementById(k);
        if (node && node.length > 0) {
          node.position(nodePositions[k]);
        }
      }
      return nodePositions;
    }