|
| 1 | +import { isArray } from 'lodash/lang/isArray'; |
| 2 | + |
| 3 | +export default function() { |
| 4 | + return function graphChart(d3, DOMNode, props) { |
| 5 | + const { data, id, size, aspectRatio, charge, linkDistance, maxNodeSize } = props; |
| 6 | + const margin = { |
| 7 | + top: size / 100, |
| 8 | + right: size / 50, |
| 9 | + bottom: size / 100, |
| 10 | + left: 40 |
| 11 | + }; |
| 12 | + const width = size - margin.left - margin.right; |
| 13 | + const height = size * aspectRatio - margin.top - margin.bottom; |
| 14 | + const fullWidth = size; |
| 15 | + const fullHeight = size * aspectRatio; |
| 16 | + |
| 17 | + const root = d3.select(DOMNode); |
| 18 | + const vis = root.append('svg') |
| 19 | + .attr('id', id) |
| 20 | + .attr('preserveAspectRatio', 'xMinYMin slice') |
| 21 | + .attr('viewBox', `0 0 ${fullWidth} ${fullHeight}`) |
| 22 | + .append('g') |
| 23 | + .attr('transform', `translate(${margin.left}, ${margin.top})`); |
| 24 | + |
| 25 | + let node = vis.selectAll('circle'); |
| 26 | + |
| 27 | + const force = d3.layout.force() |
| 28 | + .size([width, height]) |
| 29 | + .nodes(data) |
| 30 | + .linkDistance(linkDistance) |
| 31 | + .charge(charge) |
| 32 | + .on('tick', function tick() { |
| 33 | + node.attr({ |
| 34 | + cx: d => Math.round(d.x), |
| 35 | + cy: d => Math.round(d.y) |
| 36 | + }); |
| 37 | + }); |
| 38 | + |
| 39 | + let nodes = force.nodes(); |
| 40 | + |
| 41 | + return function renderChart(nextNodes) { |
| 42 | + if (nextNodes) { |
| 43 | + nodes = [...nodes, ...nextNodes]; |
| 44 | + force.nodes(nodes); |
| 45 | + } |
| 46 | + |
| 47 | + node = node.data(nodes); |
| 48 | + node.enter() |
| 49 | + .insert('circle') |
| 50 | + .attr({ |
| 51 | + r: d => { |
| 52 | + const datum = d[d.key]; |
| 53 | + if (!isArray(datum)) return 10; |
| 54 | + const radius = 10 + 2 * d[d.key].length; |
| 55 | + return radius > maxNodeSize ? 10 : radius; |
| 56 | + }, |
| 57 | + fill: d => isArray(d[d.key]) ? 'blue' : 'red' |
| 58 | + }) |
| 59 | + .on({ |
| 60 | + mouseover: function nodeMouseover() { |
| 61 | + d3.select(this).style('fill-opacity', '0.5'); |
| 62 | + }, |
| 63 | + mouseout: function nodeMouseout() { |
| 64 | + d3.select(this).style('fill-opacity', '1'); |
| 65 | + } |
| 66 | + }) |
| 67 | + .call(force.drag); |
| 68 | + node.exit().remove(); |
| 69 | + |
| 70 | + force.start(); |
| 71 | + }; |
| 72 | + }; |
| 73 | +} |
0 commit comments