<script type="text/javascript">
    const width = 1200, height = 1000;
    const tooltip = d3.select('body')
        .append("div")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("color", '#5F9EA0')
        .style('visibility', 'hidden')
        .style('font-size', '12px')
        .style('font-weight', 'bold')
        .text('');
    const force = d3.layout.force()
            .charge(-1000).linkDistance(150).size([width, height]);
    const svg = d3.select("#graph").append("svg")
            .attr("width", width).attr("height", height)
            .attr("pointer-events", "all");
    d3.json("/graph", function(error, graph) {
        if (error) return;
        force.nodes(graph.nodes).links(graph.links).start();
        const g = svg.append("g");
        const link = svg.select("g").selectAll(".link")
                .data(graph.links).enter()
                .append("line").attr("class", "link");
        const node = svg.select("g").selectAll(".node")
                .data(graph.nodes).enter()
                .append("circle")
                .attr("class", function (d) { return "node "+d.label })
                .attr("r", 20)
                .on("mouseover", function(d,i){
                    //TOOLTIP
                    tooltip.style('visibility','visible').text(d.name)
                })
                .call(force.drag);
        const nodeText = svg.select("g").selectAll("text")
                .data(graph.nodes).enter()
                .append("text")
                .attr('dy', '.3em') //偏移量
                .attr('text-anchor', 'middle') //text放在节点中心
                .style('fill', 'black')
                .style('pointer-events', 'none')
                .text(function(d){return d.name;})
        // force feed algo ticks
        force.on("tick", function() {
            link.attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });
            node.attr("cx", function(d) { return d.x; })
                .attr("cy", function(d) { return d.y; });
            nodeText.attr("x", function(d) { return d.x; })
                    .attr("y", function(d) { return d.y; });
        });
    });
</script>