Cytoscape.js warning: "The style value of `label` is deprecated for `width`" when trying to have a node with same width of label

Viewed 430

I'm using Cytoscape.js to render a dagre layout graph.

When styling the node, I use the property width: label as you can see in the following code:

const cy = cytoscape({

  container: document.getElementById('cyGraph'),
  maxZoom: 3,
  minZoom: 0.3,
  elements: dataForCytoscape,

  style: [
    {
      selector: 'node',
      style: {
        'shape': 'round-rectangle',
        'background-color': '#fff',
        'label': 'data(name)',
        'text-valign': 'center',
        'color': '#333333',
        'border-width': 1,
        'border-color': '#2E1A61',
        'width': 'label',
        'font-size': '10px',
        "padding-left": '5px',
        "padding-right": '5px',
        "padding-top": '5px',
        "padding-bottom": '5px'
      }
    },
    {
      selector: 'edge',
      style: {
        ...
      }
    }
  ],

  layout: {
    name: 'dagre'
  }

});

Code is working and nodes get the same width of the inner labels, but I get the following warning in console:

The style value of `label` is deprecated for `width`

Question: Is there another way to let Cytoscape nodes to have a width that is the same of the inner label?

2 Answers

After some tests, I found a solution by myself: I decided to calculate the width starting from the data(name) field.

So, I changed 'width': 'label' with the following arrow function:

'width': (node:any) => { return node.data('name').length * 7 }

As you can see, I'm taking the length of the string of the label (that will contain name field) and I am multiplying it for a constant (I started from 10 but then I realized that 7 is the best in my case).

This way, I don't have any warning and the graph nodes fit the label (name) width.

Another solution is the one suggested by canbax in the comments to my question:

You can set a dynamic width using data properties. For example 'width': 'data(label_width)' Here every node should have a data property called label_width

I remembered another approach. Here you can dynamically generate a canvas element and set font and then measure the text.

'width': (node) => { 
    const ctx = document.createElement('canvas').getContext("2d");
    const fStyle = node.pstyle('font-style').strValue;
    const size = node.pstyle('font-size').pfValue + 'px';
    const family = node.pstyle('font-family').strValue;
    const weight = node.pstyle('font-weight').strValue;

    ctx.font = fStyle + ' ' + weight + ' ' + size + ' ' + family;
    return ctx.measureText(node.data('name'));
}

This approach might be more costly but it might give you more exact measurements

Related