<!DOCTYPE html>
<head>
	<meta charset="utf-8" />
	<meta name="name" content="Force Directed Graph" />
	<meta name="description" content="A force directed graph to show transition within a playlist"/>
	<meta name="mintags" content="1" />
	<meta name="maxtags" content="1" />
	<title>%(title)s</title>
	
<style>

.node {
  fill: rgb(31, 119, 180);
  stroke: #ffffff;
  stroke-width: 1.5px;
}

.node.hovered {
  stroke: black;
}

.node.dragging {
  fill: '#ff0000';
}

.link {
  fill: none;
  stroke: #999;
  stroke-opacity: .6;
}

text {
  font: 10px sans-serif;
  pointer-events: none;
  text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}

</style>
</head>
<body>
<script src="d3.min.js"></script>
<script>

//
// Generated by the Exaile Playlist Analyzer plugin.
// (C) 2014 Dustin Spicuzza <dustin@virtualroadside.com>
//
// This work is licensed under the Creative Commons Attribution 4.0
// International License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by/4.0/.
//
// based on http://bl.ocks.org/mbostock/1153292
//

var data = %(data)s;

// transform the data into a  single tag implementation, could
// probably do more with this.

var nodes = d3.map();     // size
var links = d3.map();     // weight

var tmp = [null];

// create the nodes/links
data.forEach(function(d){

    if (d == null)
    {
        tmp[0] = null;
        return;
    }
    
    if (d[0] == null) d[0] = '<unknown>'

    var nid = d[0].toString();
    var o = nodes.get(nid);
    if (o)
        o.size += 1;
    else
        nodes.set(nid, { id: nid, size: 1 });
    
    if (tmp[0] != null)
    {
        var lid = tmp[0] + ' -> ' + nid;
        o = links.get(lid);
        if (o)
            o.weight += 1;
        else
            links.set(lid, {id: lid, weight: 1, source: tmp[0], target: nid});
    }

    tmp[0] = nid;
});

// resolve links
links.forEach(function(lid, l){
    l.source = nodes.get(l.source);
    l.target = nodes.get(l.target);
});

nodes = nodes.values();
links = links.values();


//normal d3 things 

var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-400)
    .linkDistance(200)
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .on("tick", tick)
    .start();

var zoom = d3.behavior.zoom()
	.on("zoom", zoomed);

var drag = d3.behavior.drag()
	.origin(function(d) { return d; })
	.on("dragstart", dragstarted)
	.on("drag", dragged)
	.on("dragend", dragended);

var svg = d3.select("body").append("svg")
    .attr({"width": "100%%",
    	   "height": "100%%",
    	   "viewbox": "0 0 " + width + " " + height,
    	   "preserveAspectRatio": "xMidYMid meet",
    	   "pointer-events": "all"})
    .call(zoom);

//arrows
svg.append("defs").append("marker")
    .attr("id", "end")
    .attr("viewBox", "0 -5 10 10")
    .attr('refX', 10)
    .attr('refY', -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
  .append("path")
    .attr("d", "M0,-5L10,0L0,5");

svg = svg.append('g');

var link_weight = d3.scale.linear()
     .domain([1, d3.max(links, function(d) { return d.weight; })])
     .range([1, 20]);

var node_size = d3.scale.linear()
     .domain([1, d3.max(nodes, function(d) { return d.size; })])
     .range([5, 40]);

var path = svg.append("g").selectAll("path")
    .data(links)
  .enter().append("path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)");

var link = svg.append("g").selectAll(".link")
    .data(links)
  .enter().append("line")
    .attr("class", "link")
    .style("stroke-width", function(d) { return link_weight(d.weight) });

var node = svg.append("g").selectAll(".node")
    .data(nodes, function(d) { return d.id })
  .enter().append("circle")
    .attr("class", function(d) { return "node " + d.id; })
    .attr("r", function(d) { d.radius = node_size(d.size); return d.radius; })
    .on("mouseover", function(d) { d3.select(this).classed('hovered', true); })
	.on("mouseleave", function(d) { d3.select(this).classed('hovered', false); })
    .call(drag);

var text = svg.append("g").selectAll("text")
    .data(force.nodes())
  .enter().append("text")
    .attr("x", 8)
    .attr("y", ".31em")
  .text(function(d) { return d.id; });

//from http://bl.ocks.org/mbostock/6123708
function zoomed() {
  svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
}


//Use elliptical arc path segments to doubly-encode directionality.
function tick() {
  path.attr("d", linkArc);
  node.attr("transform", transform);
  text.attr("transform", transform);
}

function linkArc(d) {
  var offsetX = 0, offsetY = 0
  var dx = d.target.x - d.source.x,
      dy = d.target.y - d.source.y,
      dr = Math.sqrt(dx * dx + dy * dy);

  if (d.target.id != d.source.id)
  {	  
	  // x and y distances from center to outside edge of target node
	  offsetX = (dx * d.target.radius) / dr;
	  offsetY = (dy * d.target.radius) / dr;
  }
  
  coord = (d.target.x - offsetX) + "," + (d.target.y - offsetY);
  return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + coord;
}

function transform(d) {
  return "translate(" + d.x + "," + d.y + ")";
}

function dragstarted(d) {
	force.stop();
	d3.event.sourceEvent.stopPropagation();
	d3.select(this).classed("dragging", true);
}

function dragged(d) {

	if (!d.fixed)
		d.fixed = true;
	
	d.px = d.x = d3.event.x;
	d.py = d.y = d3.event.y;
	
	tick();
}

function dragended(d) {
	d3.select(this).classed('dragging', false);
	force.start();
}

</script>
