sankey-init-widget.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. (function (global) {
  2. var dispatch = d3.dispatch("click");
  3. // ----
  4. /*This software is released under the MIT License
  5. MIT License 2014 Denes Csala http://www.csaladen.es
  6. The following software uses the javascript frameworks below,
  7. all of which are distributed under the MIT or GNU/GPL license:
  8. D3.js http://d3js.org/ data-oriented javascript framework.
  9. - Sankey plugin http://bost.ocks.org/mike/sankey/ for D3.js (modified) by Mike Bostock,
  10. which is based on the initial version http://tamc.github.io/Sankey/ by Thomas Counsell.
  11. I have incorporated the ability to render Sankey cycles, as pioneered by https://github.com/cfergus
  12. - Dragdealer.js href="http://skidding.github.io/dragdealer/ by Ovidiu Chereches
  13. */
  14. //<!--DATA INIT-->
  15. var data={"nodes": [], "links": []}
  16. //<!--DATA ENTRY-->
  17. nodesform=d3.select("#nodes-form");
  18. function addnode() {
  19. var a=nodesform.append("div");
  20. a.text(nodesform[0][0].children.length-1+' ');
  21. a.append("input").attr("value",'{"name":"New Node"}');
  22. }
  23. function removenode() {
  24. nodesform[0][0].children[nodesform[0][0].children.length-1].remove("div")
  25. }
  26. linksform=d3.select("#links-form");
  27. function addlink() {
  28. linksform.append("div").append("input").attr("value",'{"source":0,"target":1,"value":0.52}');
  29. }
  30. function removelink() {
  31. linksform[0][0].children[linksform[0][0].children.length-1].remove("div")
  32. }
  33. function draw() {
  34. change(data);
  35. }
  36. function save(){
  37. d3.select('#save').style('z-index',100).transition().style('opacity',0.9);
  38. st='{"sankey":{"nodes":['
  39. for (i = 0; i < nodesform[0][0].children.length; i++) {
  40. st=st+nodesform[0][0].children[i].children[0].value+',';
  41. }
  42. st=st.substring(0, st.length - 1)+'],"links":[';
  43. for (i = 0; i < linksform[0][0].children.length; i++) {
  44. st=st+linksform[0][0].children[i].children[0].value+',';
  45. }
  46. st = st.substring(0, st.length - 1)+']},"params":['+densityslider.value.current[0]+','+opacityslider.value.current[0]+','+labelformat+','+labeltextformat+','+showlinkcount+']';
  47. if (document.getElementById("fixedlayout").checked){
  48. var coords=[]
  49. sankey.nodes().forEach(function(d){
  50. coords.push([d.x,d.y])
  51. })
  52. st=st+',"fixedlayout":'+JSON.stringify(coords);
  53. }
  54. st=st+'}';
  55. d3.select('#savetext').text(st);
  56. }
  57. function load(){
  58. d3.select('#load').style('z-index',100).transition().style('opacity',0.9);
  59. }
  60. function loadsubmit(){
  61. d3.select('#load').transition().style('opacity',0).style('z-index',-1);
  62. var rawtext=d3.select('#load')[0][0].children[1].value;
  63. if (rawtext!="") {
  64. //parse data
  65. var rawdata=JSON.parse(rawtext);
  66. if ("sankey" in rawdata) {
  67. var newdata=rawdata.sankey;
  68. }
  69. else {
  70. var newdata=rawdata;
  71. }
  72. var loadtext=JSON.stringify(newdata)
  73. //remove existing node entry boxes
  74. var n=nodesform[0][0].children.length;
  75. for (i = 0; i < n; i++) {
  76. nodesform[0][0].children[0].remove("div");
  77. }
  78. //remove existing link entry boxes
  79. var n=linksform[0][0].children.length;
  80. for (i = 0; i < n; i++) {
  81. linksform[0][0].children[0].remove("div");
  82. }
  83. //add new node entry boxes
  84. var newdata2=JSON.parse(loadtext.substring(loadtext.indexOf('"nodes":[')+8, loadtext.indexOf('"links":[')-1));
  85. for (i = 0; i < newdata2.length; i++) {
  86. var a=nodesform.append("div");
  87. a.text(nodesform[0][0].children.length-1+' ');
  88. a.append("input").attr("value",JSON.stringify(newdata2[i]));
  89. }
  90. //add new link entry boxes
  91. var newdata2=JSON.parse(loadtext.substring(loadtext.indexOf('"links":[')+8, loadtext.length - 1))
  92. for (i = 0; i < newdata2.length; i++) {
  93. linksform.append("div").append("input").attr("value",JSON.stringify(newdata2[i]));
  94. }
  95. //set parameters
  96. if ("fixedlayout" in rawdata) {
  97. fixedlayout=document.getElementById("ignorelayout").checked?[]:rawdata.fixedlayout;
  98. } else {
  99. fixedlayout=[];
  100. }
  101. if ("params" in rawdata) {
  102. labelformat=rawdata.params[2];
  103. labeltextformat=rawdata.params[3];
  104. if (rawdata.params.length>4) showlinkcount=rawdata.params[4];
  105. else showlinkcount=0;
  106. document.getElementById("vlabel").checked=(labelformat==0)?true:false;
  107. document.getElementById("tlabel").checked=(labeltextformat==0)?true:false;
  108. document.getElementById("clabel").checked=(showlinkcount==1)?true:false;
  109. densityslider.setValue(rawdata.params[0]);
  110. opacityslider.setValue(rawdata.params[1]);
  111. }
  112. else {
  113. change(newdata);
  114. }
  115. }
  116. }
  117. //<!--SANKEY DIAGRAM-->
  118. var parallelrendering=false;
  119. var minnodewidth = 50;
  120. var padding = 28;
  121. var labelformat = 0;
  122. var labeltextformat = 0;
  123. var showlinkcount = 0;
  124. var paddingmultiplier = 100;
  125. var lowopacity = 0.3;
  126. var highopacity = 0.7;
  127. var fixedlayout=[];
  128. var sankeyColor = d3.scale.category20();
  129. var sankeyNumberFormat = d3.format(",.0f");
  130. // d3.select("#ndec")
  131. // .on("change",draw);
  132. // d3.select("#ldec")
  133. // .on("change",draw);
  134. var margin = {
  135. top: 10,
  136. right: 10,
  137. bottom: 10,
  138. left: 40
  139. };
  140. var width = 1000; //document.getElementById("chart").offsetWidth - margin.left - margin.right,
  141. var height = 500; // document.getElementById("chart").offsetHeight - margin.bottom;
  142. var svg = null;//d3.select("#chart").append("svg")
  143. //svg.append("rect").attr("x",0).attr("y",0).attr("width","100%").attr("height","100%").attr("fill","white").attr('class','background')
  144. //svg=svg.attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  145. //set svg background color via rectangle trick
  146. // d3.select("#chart").select("svg")
  147. var sankey = null;
  148. // var sankey = d3.sankey().nodeWidth(30).nodePadding(padding).size([width, height]);
  149. // var path = sankey.reversibleLink();
  150. var change = function(d) {
  151. svg.selectAll("g").remove();
  152. sankey = d3.sankey().nodeWidth(30).nodePadding(padding).size([width, height]);
  153. sankey.nodes(d.nodes).links(d.links).layout(500);
  154. var g = svg.append("g") //link
  155. .selectAll(".link").data(d.links).enter().append("g").attr("class", "link").sort(function(j, i) {
  156. return i.dy - j.dy
  157. });
  158. var path = sankey.reversibleLink();
  159. var h = g.append("path") //path0
  160. .attr("d", path(0));
  161. var f = g.append("path") //path1
  162. .attr("d", path(1));
  163. var e = g.append("path") //path2
  164. .attr("d", path(2));
  165. g.attr("fill", function(i) {
  166. if (i.fill) return i.fill;
  167. else if (i.source.fill) return i.source.fill;
  168. else return i.source.color = sankeyColor(i.source.name.replace(/ .*/, ""))
  169. }).attr("opacity", lowopacity).on("mouseover", function(d) {
  170. d3.select(this).style('opacity', highopacity);
  171. }).on("mouseout", function(d) {
  172. d3.select(this).style('opacity', lowopacity);
  173. }).append("title") //link
  174. .text(function(i) {
  175. return i.source.name + " → " + i.target.name + "\n" + sankeyNumberFormat(i.value)
  176. });
  177. var c = svg.append("g") //node
  178. .selectAll(".node").data(d.nodes).enter().append("g").attr("class", "node").attr("transform", function(i) {
  179. return "translate(" + i.x + "," + i.y + ")"
  180. }).call(d3.behavior.drag().origin(function(i) {
  181. return i
  182. }).on("dragstart", function() {
  183. this.parentNode.appendChild(this)
  184. }).on("drag", b));
  185. c.append("rect") //node
  186. .attr("height", function(i) {
  187. return i.dy
  188. }).attr("width", sankey.nodeWidth()).style("fill", function(i) {
  189. if (i.fill) return i.color = i.fill;
  190. else return i.color = sankeyColor(i.name.replace(/ .*/, ""))
  191. }).style("stroke", function(i) {
  192. return d3.rgb(i.color).darker(2)
  193. }).on("mouseover", function(d) {
  194. svg.selectAll(".link").filter(function(l) {
  195. return l.source == d || l.target == d;
  196. }).transition().style('opacity', highopacity);
  197. }).on("mouseout", function(d) {
  198. svg.selectAll(".link").filter(function(l) {
  199. return l.source == d || l.target == d;
  200. }).transition().style('opacity', lowopacity);
  201. }).on("dblclick", function(d) {
  202. svg.selectAll(".link").filter(function(l) {
  203. return l.target == d;
  204. }).attr("display", function() {
  205. if (d3.select(this).attr("display") == "none") return "inline"
  206. else return "none"
  207. });
  208. }).append("title").text(function(i) {
  209. return i.name + "\n" + sankeyNumberFormat(i.value)
  210. });
  211. c.append("text") //node
  212. .attr("x", -6).attr("y", function(i) {
  213. return i.dy / 2
  214. }).attr("dy", ".35em").attr("text-anchor", "end").attr("font-size","16px")
  215. .text(function(i) {
  216. if (labeltextformat<1){
  217. return i.name;
  218. } else {
  219. return "";
  220. }
  221. }).filter(function(i) {
  222. return i.x < width / 2
  223. }).attr("x", 6 + sankey.nodeWidth()).attr("text-anchor", "start")
  224. if (showlinkcount>0) c.append("text") //node
  225. .attr("x", -6).attr("y", function(i) {
  226. return i.dy / 2 + 20
  227. }).attr("dy", ".35em").attr("text-anchor", "end").attr("font-size","16px")
  228. .text(function(i) {
  229. return "→ "+(i.targetLinks.length)+" | "+(i.sourceLinks.length)+" →";
  230. }).filter(function(i) {
  231. return i.x < width / 2
  232. }).attr("x", 6 + sankey.nodeWidth()).attr("text-anchor", "start")
  233. c.append("text") //node
  234. .attr("x", function(i) {return -i.dy / 2})
  235. .attr("y", function(i) {return i.dx / 2 + 9})
  236. .attr("transform", "rotate(270)").attr("text-anchor", "middle").attr("font-size","23px").text(function(i) {
  237. if ((i.dy>minnodewidth)&&(labelformat<1)){
  238. return sankeyNumberFormat(i.value);
  239. }
  240. }).attr("fill",function(d){
  241. return d3.rgb(d["color"]).brighter(2)
  242. }).attr("stroke",function(d){
  243. return d3.rgb(d["color"]).darker(2)
  244. }).attr("stroke-width","1px");
  245. svg.selectAll('rect')
  246. .on('mouseover', (a, b, c, d, e) => {console.log('mouseover', a, b, c, d, e)})
  247. .on('mouseout', (a, b, c, d, e) => {console.log('mouseout', a, b, c, d, e)})
  248. .on('mousedown', (a, b, c, d, e) => {console.log('mousedown', a, b, c, d, e)})
  249. .on('mouseup', (a) => {
  250. dispatch.click({
  251. nativeEvent: d3.event,
  252. node: a,
  253. element: d3.event.srcElement
  254. })
  255. });
  256. function b(i) { //dragmove
  257. // if (document.getElementById("ymove").checked) {
  258. // if (document.getElementById("xmove").checked) {
  259. // d3.select(this).attr("transform", "translate(" + (i.x = Math.max(0, Math.min(width - i.dx, d3.event.x))) + "," + (i.y = Math.max(0, Math.min(height - i.dy, d3.event.y))) + ")")
  260. // } else {
  261. dragged = true;
  262. d3.select(this).attr("transform", "translate(" + i.x + "," + (i.y = Math.max(0, Math.min(height - i.dy, d3.event.y))) + ")")
  263. // }
  264. // } else {
  265. // if (document.getElementById("xmove").checked) {
  266. // d3.select(this).attr("transform", "translate(" + (i.x = Math.max(0, Math.min(width - i.dx, d3.event.x))) + "," + i.y + ")")
  267. // }
  268. // }
  269. // sankey.relayout();
  270. // f.attr("d", path(1));
  271. // h.attr("d", path(0));
  272. // e.attr("d", path(2))
  273. };
  274. };
  275. // draw();
  276. //<!-- SAVE FUNCTION-->
  277. d3.select("#pngdownloadwrapper")
  278. .on("click",function(){
  279. seturl();
  280. setTimeout(function(){d3.select("#pngdownload").node().click();},500);
  281. })
  282. function seturl(){
  283. exportInlineSVG(d3.select("#chart").select("svg").node(), function(data) {
  284. d3.select("#pngdownload").node().href=data;
  285. });
  286. }
  287. // ----
  288. renderGraph = (htmlNode, data, opts) => {
  289. var opts = opts || {}
  290. if (!htmlNode) throw "Missing html node";
  291. if (!data) throw "Missing data";
  292. //svg = d3.select("#chart").append("svg")
  293. htmlNode.append("rect").attr("x",0).attr("y",0).attr("width","100%").attr("height","100%").attr("fill","white")
  294. width = 1020
  295. height = 500
  296. margin = {
  297. top: 10,
  298. right: 10,
  299. bottom: 10,
  300. left: 40
  301. };
  302. htmlNode.attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom)
  303. svg = htmlNode.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  304. change(data);
  305. return dispatch
  306. }
  307. global.parallelrendering = parallelrendering
  308. global.fixedlayout = fixedlayout
  309. global.renderGraph = renderGraph
  310. })(window)