Условные стили для графа cytoscape.js - PullRequest
2 голосов
/ 24 сентября 2019

Я хочу изменить стиль моего графика в соответствии с глобальными переменными Javascript.Например, учитывая, что у моих ребер есть атрибуты name и price, я хотел бы сделать метки ребер разными в зависимости от глобальной переменной label_type:

let lable_type = 'I_want_name_labels'
switch(lable_type) {
  case 'I_want_name_labels':
    cy.style().selector('edge').style({'label': 'data(name)'});
    break;
  case 'I_want_price_labels':
    cy.style().selector('edge').style({'label': 'data(price)'});
    break;
}

Приведенный выше код неделать что-либо вообще (без метки отображается), я не очень понимаю, почему.Мои ребра имеют следующую структуру:

{
  "data": {
    "id": "node_node2",
    "source": "node1",
    "target": "node2",
    "directed": true,
    "name": "Baltazar",
    "price": 1095.73
  }
}

Примечание : я пытался использовать cy.filter('edge').style({'label': 'data(name)'}) вместо этого, но тогда data не кажется таким доступным, я получил этопредупреждение:

The style property `label: data(name)` is invalid

Итак, как получить условный стиль с помощью cytoscape.js?Что мне здесь не хватает?

1 Ответ

2 голосов
/ 25 сентября 2019

Вот строка, которую вы ищете:

// .data() gets you all properties of the target element, .id() for example directly the id of the element
targetElement.style('label', targetElement.data('faveColor'));

Вот рабочая демонстрация того, как инициализировать, а затем изменить метку узлов / ребер:

var cy = (window.cy = cytoscape({
  container: document.getElementById("cy"),

  boxSelectionEnabled: false,
  autounselectify: true,

  style: [{
      selector: "node",
      css: {
        "label": "data(id)",
        "text-valign": "center",
        "text-halign": "center",
        "height": "60px",
        "width": "100px",
        "shape": "rectangle",
        "background-color": "data(faveColor)"
      }
    },
    {
      selector: "edge",
      css: {
        "curve-style": "bezier",
        "control-point-step-size": 40,
        "target-arrow-shape": "triangle"
      }
    }
  ],

  elements: {
    nodes: [{
        data: {
          id: "Top",
          faveColor: "#2763c4"
        }
      },
      {
        data: {
          id: "yes",
          faveColor: "#37a32d"
        }
      },
      {
        data: {
          id: "no",
          faveColor: "#2763c4"
        }
      },
      {
        data: {
          id: "Third",
          faveColor: "#2763c4"
        }
      },
      {
        data: {
          id: "Fourth",
          faveColor: "#56a9f7"
        }
      }
    ],
    edges: [{
        data: {
          source: "Top",
          target: "yes"
        }
      },
      {
        data: {
          source: "Top",
          target: "no"
        }
      },
      {
        data: {
          source: "no",
          target: "Third"
        }
      },
      {
        data: {
          source: "Third",
          target: "Fourth"
        }
      },
      {
        data: {
          source: "Fourth",
          target: "Third"
        }
      }
    ]
  },
  layout: {
    name: "dagre"
  }
}));

cy.bind('click', 'node, edge', function(event) {
  // here are two examples on how the selectors work
  event.target.style('label', event.target.data('faveColor') || event.target.id());
});
body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#cy {
  height: 85%;
  width: 100%;
  float: right;
  position: absolute;
}
<html>

<head>
  <meta charset=utf-8 />
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
  <script src="https://unpkg.com/cytoscape@3.3.0/dist/cytoscape.min.js">
  </script>
  <!-- cyposcape dagre -->
  <script src="https://unpkg.com/dagre@0.7.4/dist/dagre.js"></script>
  <script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-dagre/1.5.0/cytoscape-dagre.js"></script>
</head>

<body>
  <div id="cy"></div>
</body>

</html>
...