word_cloud copy.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /**
  2. * QUERY SECTION
  3. *
  4. * */
  5. // SPARQL Query text -- 'prefixes' and 'thisUrlParams' defined in people.js;
  6. let queryNetwork = prefixes + " SELECT COUNT(?event1) AS ?count1 COUNT(?event2) AS ?count2 ?uri2 SAMPLE(?label2) AS ?text \
  7. WHERE { \
  8. {?event1 rdf:type crm:EL1_Exchange_Letters . \
  9. ?event_to rdfs:subClassOf ?event1; \
  10. rdf:type crm:EL2_Send_Letter ; \
  11. crm:P01_has_domain ?pc_to . \
  12. ?pc_to crm:P02_has_range ?uri . \
  13. ?uri rdfs:label ?label . \
  14. ?event_from rdfs:subClassOf ?event1; \
  15. rdf:type crm:EL3_Receive_Letter; \
  16. crm:P01_has_domain ?pc_from . \
  17. ?pc_from crm:P02_has_range ?uri2 . \
  18. ?uri2 rdfs:label ?label2 . \
  19. FILTER (?uri = <" + thisUrlParams.link + ">) \
  20. } UNION { \
  21. ?event2 rdf:type crm:EL1_Exchange_Letters . \
  22. ?event_to rdfs:subClassOf ?event2; \
  23. rdf:type crm:EL3_Receive_Letter ; \
  24. crm:P01_has_domain ?pc_from . \
  25. ?pc_from crm:P02_has_range ?uri . \
  26. ?uri rdfs:label ?label . \
  27. ?event_from rdfs:subClassOf ?event2; \
  28. rdf:type crm:EL2_Send_Letter; \
  29. crm:P01_has_domain ?pc_to . \
  30. ?pc_to crm:P02_has_range ?uri2 . \
  31. ?uri2 rdfs:label ?label2 . \
  32. FILTER (?uri = <" + thisUrlParams.link + ">) \
  33. } \
  34. }"
  35. // 'prepareQueryURL' defined in people.js
  36. let queryNet = prepareQueryURL(queryNetwork);
  37. // do the query, call data processor on successful output
  38. $.ajax({
  39. url: queryNet,
  40. dataType: "json",
  41. success: (data) => handle_word_network(data)
  42. });
  43. /**
  44. * COMPONENT CREATION SECTION
  45. *
  46. * */
  47. // Master function, takes data output from the query and creates the HTML for the Word Cloud component of the page
  48. function handle_word_network(json){
  49. // Pre-process data
  50. let tempArray = processQuery(json);
  51. let words = prepareWords(tempArray);
  52. // Create page elements
  53. doListPersonNetwork(tempArray);
  54. doWordCloud(words);
  55. }
  56. // Return structured object from raw query data for further processing
  57. function processQuery(json) {
  58. const tempArray = [];
  59. $.each(
  60. json['results']['bindings'],
  61. (index, value) => {
  62. let text = value['text']['value'];
  63. let link = value['uri2']['value'];
  64. let sent = parseInt(value['count1']['value']);
  65. let received = parseInt(value['count2']['value']);
  66. let count = sent + received;
  67. tempArray.push({'text': text, 'sent': sent, 'received': received, 'count': count, 'hlink': link});
  68. }
  69. );
  70. tempArray.sort((a, b) => b.count - a.count);
  71. return tempArray;
  72. }
  73. // Define font size, according to the number of words and limiting the impact of huge counts -- to refactor??
  74. function prepareWords(tempArray){
  75. const words = [];
  76. if (tempArray.length < 8) { // Less than 8 results -- font size is just = count/2 + constant
  77. for (let k=tempArray.length-1; k>=0; k--) {
  78. let text = tempArray[k]['text'];
  79. let preSize = tempArray[k]['count'] + 36;
  80. console.log('mann', preSize)
  81. let link = tempArray[k]['hlink'];
  82. words.push(
  83. {
  84. 'text': text,
  85. 'size': preSize/2 + 6,
  86. 'hlink': link
  87. }
  88. );
  89. }
  90. } else { // More than 8 results -- font size = count except for especially "big" words
  91. let temp = 0;
  92. for (let k=tempArray.length-1; k>=0; k--) {
  93. let text = tempArray[k]['text'];
  94. let count = tempArray[k]['count'];
  95. let link = tempArray[k]['hlink'];
  96. let preSize = 0;
  97. if ((count - temp) > 50) {
  98. preSize = temp + 12;
  99. } else {
  100. preSize = count;
  101. }
  102. words.push(
  103. {
  104. 'text': text,
  105. 'size': preSize/2 + 6,
  106. 'hlink': link
  107. }
  108. );
  109. temp = preSize;
  110. }
  111. }
  112. console.log('tempArray', tempArray)
  113. console.log('words', words)
  114. return words;
  115. }
  116. // Create formatted list of people in the network
  117. function doListPersonNetwork(tempArray){
  118. let ArrayNames = "";
  119. tempArray.forEach(element => {
  120. ArrayNames +=
  121. "<div class='item-place-person'>\
  122. <div class='item-place-person-label'>" +
  123. element['text'] +
  124. "<br /><span class='num_occ'>[Lettere inviate: " + element['sent'] + "]</span>\
  125. <br /><span class='num_occ'>[Lettere ricevute: " + element['received'] + "]</span>\
  126. <br /><span class='num_occ'>[Totale corrispondenza: " + element['count'] + "]</span>\
  127. </div>\
  128. <div class='item-place-person-action'>\
  129. <div class='persona' id='" + element['hlink'] +"'>\
  130. <i class='fa fa-user' style='cursor:pointer'></i>\
  131. </div>\
  132. </div>\
  133. </div>";
  134. });
  135. document.getElementById("list_person_network").innerHTML = ArrayNames;
  136. }
  137. // Create the word cloud
  138. function doWordCloud(myWords){
  139. // Clear word cloud div
  140. $('#myWordCloud').empty();
  141. // OVERALL GRAPHIC SETTINGS for the cloud container -- id, dimensions, position
  142. // set the dimensions and margins of the graph
  143. let modifierWidth = 0.4;
  144. let modifierHeigth = 0.4;
  145. let marginHeight = 0;
  146. let marginWidth = 0;;
  147. let margin = {
  148. top: marginHeight,
  149. right: marginWidth,
  150. bottom: marginHeight,
  151. left: marginWidth};
  152. let width = modifierWidth*window.innerWidth;
  153. let height = modifierHeigth*window.innerHeight;
  154. // append the svg object to the body of the page
  155. let svg = d3.select("#myWordCloud")
  156. .append("svg")
  157. .attr("id", "wordcloudNetwork")
  158. .attr("width", width + margin.left + margin.right)
  159. .attr("height", height + margin.top + margin.bottom)
  160. .attr("style", "border:1px solid black")
  161. .append("g")
  162. .attr("transform", "translate(" + (width*0.5) + "," + (height*0.5) + ")")
  163. .attr("overflow","scroll");
  164. // In case of empty cloud, draw special page and exit
  165. if (myWords.length == 0){
  166. drawEmptyWordCloud();
  167. return;
  168. }
  169. // THE ACTUAL CLOUD
  170. // Constructs a new cloud layout instance. It runs an algorithm to find the position of words that suits your requirements
  171. // Wordcloud features that are different from one word to the other must be here
  172. let layout = d3.layout.cloud() // Constructs the cloud
  173. .size([1.5*width, 1.2*height]) // Sets width and height
  174. .words(myWords) // put words in; expects an array of objects. Format is free, it all depends on the definition of the functions that are applied to define the cloud structure.
  175. //
  176. // A js curiosity: ~ is a bitwise not operator. On a number, the double bitwise not ~~ has the net effect of giving the integer part, that is: floor on positives and ceiling on negatives.
  177. .rotate( () => { return ~~(Math.random() * 2);} )
  178. .fontSize( word => { return word['size']; } ) // font size of words
  179. .on("end", word => draw(word, svg));
  180. layout.start();
  181. }
  182. // Helper function for the Word Cloud --
  183. // it draws the words
  184. // Wordcloud features that are THE SAME from one word to the other can be here ??
  185. function draw(words, svg) {
  186. let cloud = svg.selectAll("g text")
  187. .data(words, word => word.text) // What does this do?
  188. //Entering words
  189. cloud.enter()
  190. .append("text")
  191. .style("font-family", "Impact")
  192. .attr("text-anchor", "middle")
  193. .attr('font-size', 1)
  194. .append("a")
  195. .attr("href", word => word.hlink)
  196. .attr("data-toggle", "tooltip")
  197. .text( word => { return word.text; });
  198. //Entering and exiting words
  199. cloud.transition()
  200. .duration(600)
  201. .style("font-size", function(d) { return d.size + "px"; })
  202. .attr("transform", function(d) {
  203. return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
  204. })
  205. .style("fill-opacity", 1);
  206. //Exiting words
  207. cloud.exit()
  208. .transition()
  209. .duration(200)
  210. .style('fill-opacity', 1e-6)
  211. .attr('font-size', 1)
  212. .remove();
  213. }
  214. // Helper function -- draw special empty word cloud if there are no occurrences
  215. function drawEmptyWordCloud(){
  216. let wordIcon = "<div id='users_icon' class='no_info_icon'> \
  217. <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 512'> \
  218. <!--! Font Awesome Pro 6.1.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d='M319.9 320c57.41 0 103.1-46.56 103.1-104c0-57.44-46.54-104-103.1-104c-57.41 0-103.1 46.56-103.1 104C215.9 273.4 262.5 320 319.9 320zM369.9 352H270.1C191.6 352 128 411.7 128 485.3C128 500.1 140.7 512 156.4 512h327.2C499.3 512 512 500.1 512 485.3C512 411.7 448.4 352 369.9 352zM512 160c44.18 0 80-35.82 80-80S556.2 0 512 0c-44.18 0-80 35.82-80 80S467.8 160 512 160zM183.9 216c0-5.449 .9824-10.63 1.609-15.91C174.6 194.1 162.6 192 149.9 192H88.08C39.44 192 0 233.8 0 285.3C0 295.6 7.887 304 17.62 304h199.5C196.7 280.2 183.9 249.7 183.9 216zM128 160c44.18 0 80-35.82 80-80S172.2 0 128 0C83.82 0 48 35.82 48 80S83.82 160 128 160zM551.9 192h-61.84c-12.8 0-24.88 3.037-35.86 8.24C454.8 205.5 455.8 210.6 455.8 216c0 33.71-12.78 64.21-33.16 88h199.7C632.1 304 640 295.6 640 285.3C640 233.8 600.6 192 551.9 192z'/> \
  219. </svg> \
  220. <p>Nessuna persona trovata</p> \
  221. </div>";
  222. $("#wordcloudNetwork").css("display", "none");
  223. $("#references_network").css("display", "none");
  224. document.getElementById("myWordCloud").innerHTML = wordIcon;
  225. }
  226. // Customized word cloud code
  227. // Takes a list of words, returns the innerHTML for a Word Cloud as a string containing multiple <g> svg elements
  228. function createWordCloud(words){
  229. const rectObjs = []
  230. let allBooms = 0
  231. let attempts = 0;
  232. for(let ind=0;ind<words.length;ind++){
  233. let id0 = "word"+ind;
  234. let praaaa = document.getElementById(id0).getBoundingClientRect();
  235. //console.log('BB of '+id0, praaaa);
  236. attempts++;
  237. let boom = false;
  238. // rectangle definition
  239. // let width = 120 + Math.round(50*Math.random());
  240. // let height = 40;
  241. let fontSize = getFontSize(ind);
  242. let width = praaaa.width;
  243. //let height = fontSize;
  244. let height = praaaa.height;
  245. let xR = 1250 + Math.round( (Math.random()-0.5)*(1000 + 6*ind) );
  246. let yR = 750 + Math.round( (Math.random()-0.5)*(400 + 4*ind) );
  247. let angle = 90*(Math.floor(3*Math.random())-1);
  248. let text = words[ind];
  249. //console.log('Rect:', width, height, xR, yR, angle, text);
  250. let newRect = new Rect(width, height, xR, yR, angle, text, fontSize);
  251. //console.log('nnn', newRect);
  252. for(let rect of rectObjs){
  253. boom = checkColl(newRect, rect);
  254. if(boom) break;
  255. }
  256. if(boom){
  257. allBooms++;
  258. if(allBooms<10) ind--;
  259. else(allBooms = 0);
  260. continue;
  261. }
  262. allBooms = 0;
  263. rectObjs.push(newRect);
  264. }
  265. console.log('Attempted:', attempts);
  266. console.log('Placed:', rectObjs.length);
  267. const rectTexts = [];
  268. rectObjs.forEach(rect => rectTexts.push(rect.printCoords()));
  269. let rects = rectTexts.join('\n');
  270. return rects;
  271. }
  272. function getFontSize(weight){
  273. return Math.max(80-weight, 30);
  274. }