create-nodes.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import _ from 'lodash'
  2. import * as d3 from 'd3'
  3. import addLabel from './label/add-label'
  4. import util from './util'
  5. function createNodes (selection, g, shapes) {
  6. const simpleNodes = g.nodes().filter(function (v) { return !util.isSubgraph(g, v) })
  7. let svgNodes = selection.selectAll('g.node')
  8. .data(simpleNodes, function (v) { return v })
  9. .classed('update', true)
  10. svgNodes.selectAll('*').remove()
  11. svgNodes.enter()
  12. .append('g')
  13. .attr('class', 'node')
  14. .style('opacity', 0)
  15. svgNodes = selection.selectAll('g.node')
  16. svgNodes.each(function (v) {
  17. const node = g.node(v)
  18. const thisGroup = d3.select(this)
  19. util.applyClass(thisGroup, node['class'], (thisGroup.classed('update') ? 'update ' : '') + 'node')
  20. const labelGroup = thisGroup.append('g').attr('class', 'label')
  21. const labelDom = addLabel(labelGroup, node)
  22. const shape = shapes[node.shape]
  23. const bbox = _.pick(labelDom.node().getBBox(), 'width', 'height')
  24. node.elem = this
  25. if (node.id) { thisGroup.attr('id', node.id) }
  26. if (node.labelId) { labelGroup.attr('id', node.labelId) }
  27. if (_.has(node, 'width')) { bbox.width = node.width }
  28. if (_.has(node, 'height')) { bbox.height = node.height }
  29. bbox.width += node.paddingLeft + node.paddingRight
  30. bbox.height += node.paddingTop + node.paddingBottom
  31. labelGroup.attr('transform', 'translate(' +
  32. ((node.paddingLeft - node.paddingRight) / 2) + ',' +
  33. ((node.paddingTop - node.paddingBottom) / 2) + ')')
  34. const shapeSvg = shape(d3.select(this), bbox, node)
  35. util.applyStyle(shapeSvg, node.style)
  36. const shapeBBox = shapeSvg.node().getBBox()
  37. node.width = shapeBBox.width
  38. node.height = shapeBBox.height
  39. })
  40. util.applyTransition(svgNodes.exit(), g)
  41. .style('opacity', 0)
  42. .remove()
  43. return svgNodes
  44. }
  45. export default createNodes