word_cloud.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. // queryLetters defined in people.js
  44. console.log(queryLetters);
  45. /**
  46. * COMPONENT CREATION SECTION
  47. *
  48. * */
  49. // Master function, takes data output from the query and creates the HTML for the Word Cloud component of the page
  50. function handle_word_network(json){
  51. // Pre-process data
  52. let words = processQuery(json);
  53. // Create page elements
  54. doListPersonNetwork(words);
  55. doWordCloud(words);
  56. }
  57. // Return structured object from raw query data for further processing
  58. function processQuery(json) {
  59. const tempArray = [];
  60. $.each(
  61. json['results']['bindings'],
  62. (index, value) => {
  63. let text = value['text']['value'];
  64. let link = value['uri2']['value'];
  65. let sent = parseInt(value['count1']['value']);
  66. let received = parseInt(value['count2']['value']);
  67. let count = sent + received;
  68. tempArray.push({'text': text, 'sent': sent, 'received': received, 'count': count, 'hlink': link});
  69. }
  70. );
  71. tempArray.sort((a, b) => b.count - a.count);
  72. return tempArray;
  73. }
  74. // Create formatted list of people in the network
  75. function doListPersonNetwork(words){
  76. let ArrayNames = "";
  77. words.forEach(element => {
  78. filteredText = element['text'].replace('"', '').replace("'", '');
  79. ArrayNames +=
  80. "<div class='item-place-person'>"+
  81. "<div class='item-place-person-label' id='list-" + filteredText + "'>" +
  82. element['text'] +
  83. "<br /><span onlick='sendLetter("+ filteredText + ", " + element['hlink'] + ", " + labelName + ", " + thisUrlParams.link +")' class='num_occ'>[Lettere inviate: " + element['sent'] + "]</span>" +
  84. "<br /><span onlick='receiveLetter("+ filteredText + ", " + element['hlink'] + ", " + labelName + ", " + thisUrlParams.link +")' class='num_occ'>[Lettere ricevute: " + element['received'] + "]</span>" +
  85. "<br /><span id='tot-"+filteredText+"' class='num_occ'>[Totale corrispondenza: " + element['count'] + "]</span>" +
  86. "</div>" +
  87. "<div class='item-place-person-action'>" +
  88. "<div class='persona' id='" + element['hlink'] +"'>" +
  89. "<i class='fa fa-user' style='cursor:pointer'></i>" +
  90. "</div>" +
  91. "</div>" +
  92. "</div>";
  93. });
  94. document.getElementById("list_person_network").innerHTML = ArrayNames;
  95. addEventsToNameList(words);
  96. }
  97. function addEventsToNameList(words){
  98. let counter = 0
  99. for(let word of words){
  100. if(counter>0) break;
  101. let listElem = document.getElementById('tot-' + word.text.replace('"', '').replace("'", ''));
  102. if(listElem!=null){
  103. listElem.addEventListener("click", filterLetters);
  104. listElem.addEventListener("mouseover", highlightWord);
  105. listElem.addEventListener("mouseout", unHighlightWord);
  106. }
  107. counter++;
  108. }
  109. }
  110. function filterLetters(e){
  111. try{
  112. let preText = e.target.parentNode.textContent;
  113. console.log('text content', preText);
  114. let name = preText.split("[")[0];
  115. console.log('name', name);
  116. // responseLet defined in people.js
  117. responseLet.then(data => {
  118. let lettersJson = data.results.bindings;
  119. console.log('AH!', lettersJson[0]);
  120. });
  121. } catch{
  122. console.log("Couldn't get the name");
  123. }
  124. }
  125. // Create the word cloud
  126. function doWordCloud(words){
  127. // Clear word cloud div
  128. $('#myWordCloud').empty();
  129. // OVERALL GRAPHIC SETTINGS for the cloud container -- id, dimensions, position
  130. let width = 0.5*window.outerWidth;
  131. let height = 0.6*width;
  132. // append the svg object to the body of the page
  133. let svg = d3.select("#myWordCloud")
  134. .append("svg")
  135. .attr("id", "wordcloudNetwork")
  136. .attr("preserveAspectRatio", "xMinYMin meet")
  137. .attr("viewBox", "0 0 " + width + " " + height)
  138. .classed("svg-content", true)
  139. .attr("width", width)
  140. .attr("height", height)
  141. .attr("style", "border:1px solid black")
  142. // In case of empty cloud, draw special page and exit
  143. if (words.length == 0){
  144. drawEmptyWordCloud();
  145. return;
  146. }
  147. // THE ACTUAL CLOUD
  148. svg = document.getElementById('wordcloudNetwork');
  149. console.log(svg);
  150. let zoom = window.devicePixelRatio;
  151. console.log('zoom', zoom);
  152. wcParameters = {
  153. svgWidth: svg.getBoundingClientRect().width,
  154. svgHeight: svg.getBoundingClientRect().height,
  155. maxFontSize: 30/((1+zoom)/2),
  156. minFontSize: 10/((1+zoom)/2)
  157. }
  158. let svgWords = hackWords(words, wcParameters);
  159. svg.innerHTML = svgWords;
  160. let wordCloudText = createWordCloud(words, wcParameters);
  161. svg.innerHTML = wordCloudText;
  162. addEventsToWordCloud(words);
  163. }
  164. // Helper function -- draw special empty word cloud if there are no occurrences
  165. function drawEmptyWordCloud(){
  166. let wordIcon = "<div id='users_icon' class='no_info_icon'> \
  167. <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' width='30' height='30' viewBox='0 0 256 256' xml:space='preserve'> \
  168. <g transform='translate(128 128) scale(0.72 0.72)'> \
  169. <g style='stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: none; fill-rule: nonzero; opacity: 1;' transform='translate(-175.05 -175.05000000000004) scale(3.89 3.89)'> \
  170. <path d='M 45 49.519 L 45 49.519 c -7.68 0 -13.964 -6.284 -13.964 -13.964 v -5.008 c 0 -7.68 6.284 -13.964 13.964 -13.964 h 0 c 7.68 0 13.964 6.284 13.964 13.964 v 5.008 C 58.964 43.236 52.68 49.519 45 49.519 z' style='stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;' transform='matrix(1 0 0 1 0 0)' stroke-linecap='round' /> \
  171. <path d='M 52.863 51.438 c -2.362 1.223 -5.032 1.927 -7.863 1.927 s -5.501 -0.704 -7.863 -1.927 C 26.58 53.014 18.414 62.175 18.414 73.152 v 14.444 c 0 1.322 1.082 2.403 2.403 2.403 h 48.364 c 1.322 0 2.403 -1.082 2.403 -2.403 V 73.152 C 71.586 62.175 63.42 53.014 52.863 51.438 z' style='stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;' transform='matrix(1 0 0 1 0 0)' stroke-linecap='round' /> \
  172. <path d='M 71.277 34.854 c -2.362 1.223 -5.032 1.927 -7.863 1.927 c -0.004 0 -0.007 0 -0.011 0 c -0.294 4.412 -2.134 8.401 -4.995 11.43 c 10.355 3.681 17.678 13.649 17.678 24.941 v 0.263 h 11.511 c 1.322 0 2.404 -1.082 2.404 -2.404 V 56.568 C 90 45.59 81.834 36.429 71.277 34.854 z' style='stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;' transform='matrix(1 0 0 1 0 0)' stroke-linecap='round' /> \
  173. <path d='M 63.414 0 c -7.242 0 -13.237 5.589 -13.898 12.667 c 8 2.023 13.947 9.261 13.947 17.881 v 2.385 c 7.657 -0.027 13.914 -6.298 13.914 -13.961 v -5.008 C 77.378 6.284 71.094 0 63.414 0 z' style='stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;' transform='matrix(1 0 0 1 0 0)' stroke-linecap='round' /> \
  174. <path d='M 13.915 73.152 c 0 -11.292 7.322 -21.261 17.677 -24.941 c -2.861 -3.029 -4.702 -7.019 -4.995 -11.43 c -0.004 0 -0.007 0 -0.011 0 c -2.831 0 -5.5 -0.704 -7.863 -1.927 C 8.166 36.429 0 45.59 0 56.568 v 14.444 c 0 1.322 1.082 2.404 2.404 2.404 h 11.511 V 73.152 z' style='stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;' transform='matrix(1 0 0 1 0 0)' stroke-linecap='round' /> \
  175. <path d='M 26.536 32.932 v -2.385 c 0 -8.62 5.946 -15.858 13.947 -17.881 C 39.823 5.589 33.828 0 26.586 0 c -7.68 0 -13.964 6.284 -13.964 13.964 v 5.008 C 12.622 26.635 18.879 32.905 26.536 32.932 z' style='stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;' transform='matrix(1 0 0 1 0 0)' stroke-linecap='round' /> \
  176. </g> \
  177. </g> \
  178. </svg> \
  179. <p>Nessuna persona trovata</p> \
  180. </div>";
  181. $("#person_map").css("display", "none");
  182. $("#wordcloudNetwork").css("display", "none");
  183. $("#references_network").css("display", "none");
  184. document.getElementById("person_map_no_res").innerHTML = wordIcon;
  185. }
  186. /*****************************
  187. * Customized word cloud code *
  188. *****************************/
  189. function hackWords(words, parameters){
  190. let weights = words.map(word => word.count);
  191. let minWeight = Math.min(...weights);
  192. let maxFontSize = parameters.maxFontSize;
  193. let minFontSize = parameters.minFontSize;
  194. console.log('weights', weights);
  195. console.log('maxFontSize', maxFontSize);
  196. console.log('minFontSize',minFontSize);
  197. let stringOfWords = "";
  198. for(let ind=0; ind<words.length; ind++){
  199. let word = words[ind];
  200. word.fontSize = getFontSize(words[ind].count, minWeight, maxFontSize, minFontSize);
  201. stringOfWords = stringOfWords+
  202. '<text x="100" y ="' + (maxFontSize + maxFontSize*ind).toString() + '" + font-family="Verdana" font-size="'+(word.fontSize)+'" id="word' + ind + '">'+words[ind].text+'</text>\n';
  203. }
  204. return stringOfWords;
  205. }
  206. // Takes a list of words, returns the innerHTML for a Word Cloud as a string containing multiple <g> svg elements
  207. function createWordCloud(words, parameters){
  208. let actualUsefulWidth = parameters.svgWidth;
  209. let actualUsefulHeight = parameters.svgHeight;
  210. console.log('Actual SVG dimensions', actualUsefulWidth, actualUsefulHeight);
  211. maxFontSize = parameters.maxFontSize;
  212. minFontSize = parameters.minFontSize;
  213. const rectObjs = []
  214. let allBooms = 0
  215. let attempts = 0;
  216. let outOfBorder = 0;
  217. for(let ind=0;ind<words.length;ind++){
  218. //for(let ind=0;ind<3;ind++){
  219. // Control vars
  220. if(allBooms>=20*(ind+1)) break;
  221. attempts++;
  222. let boom = false;
  223. // word + bounding box parameters definition
  224. let word = words[ind];
  225. let id0 = "word"+ind;
  226. let wordBB = document.getElementById(id0).getBoundingClientRect();
  227. let fontSize = word.fontSize;
  228. let width = wordBB.width;
  229. let height = wordBB.height;
  230. let multiplier = 0.1 + 0.4*Math.max((maxFontSize-fontSize)/(maxFontSize-minFontSize), allBooms/(20*(ind+1)));
  231. let xR = Math.floor(actualUsefulWidth/2-width/2 + randomRange(-multiplier*actualUsefulWidth, multiplier*actualUsefulWidth));
  232. let yR = Math.floor(actualUsefulHeight/2 + randomRange(-multiplier*actualUsefulHeight, multiplier*actualUsefulHeight));
  233. //console.log('x', 'y', xR, yR)
  234. let angle;
  235. if(word.received/word.sent>3) angle = -3;
  236. else if(word.received/word.sent<0.3) angle = 3;
  237. let text = word.text;
  238. //console.log('Rect:', width, height, xR, yR, angle, text);
  239. //
  240. let newRect = new Rect(width, height, xR, yR, angle, text, fontSize);
  241. boom = checkBorder(newRect, 0, actualUsefulWidth, 0, actualUsefulHeight)
  242. if(boom){
  243. outOfBorder++;
  244. if(outOfBorder<30){
  245. ind--;
  246. continue;
  247. } else{
  248. boom = false;
  249. }
  250. }
  251. for(let rect of rectObjs){
  252. boom = checkColl(newRect, rect);
  253. if(boom) break;
  254. }
  255. if(boom){
  256. allBooms++;
  257. ind--;
  258. continue;
  259. }
  260. allBooms = 0;
  261. rectObjs.push(newRect);
  262. }
  263. console.log('Attempted:', attempts);
  264. console.log('Placed:', rectObjs.length);
  265. console.log('booms!', allBooms);
  266. const rectTexts = [];
  267. rectObjs.forEach(rect => rectTexts.push(rect.printCoords(false, maxFontSize, minFontSize)));
  268. let rects = rectTexts.join('\n');
  269. return rects;
  270. }
  271. function getFontSize(weight, minWeight, maxFontSize, minFontSize){
  272. let r1 = weight/10*minWeight - 1/10; // between 0 and a big num
  273. let res = minFontSize + (maxFontSize-minFontSize)*r1/Math.sqrt(1+r1**2);
  274. return res;
  275. }
  276. function randomRange(a, b=0){
  277. return (a-b)*Math.random()+b;
  278. }
  279. function randomInt(a){
  280. return Math.floor(a*Math.random());
  281. }
  282. function randomRangeInt(a, b=0){
  283. let ap = Math.floor(a);
  284. let bp = Math.floor(b);
  285. return Math.floor((ap-bp)*Math.random())+bp;
  286. }
  287. // Check border collision
  288. function checkBorder(rect, minX, maxX, minY, maxY){
  289. if(rect.minX<minX) return true;
  290. if(rect.maxX>maxX) return true;
  291. if(rect.minY<minY) return true;
  292. if(rect.maxY>maxY) return true;
  293. return false;
  294. }
  295. function addEventsToWordCloud(words){
  296. for(let word of words){
  297. let wcElem = document.getElementById('word-' + word.text.replace('"', '').replace("'", ''));
  298. if(wcElem!=null){
  299. wcElem.addEventListener("click", focusPersonInList);
  300. wcElem.addEventListener("mouseover", highlightWord);
  301. wcElem.addEventListener("mouseout", unHighlightWord);
  302. }
  303. }
  304. }
  305. function focusPersonInList(e){
  306. let targetId = e.target.id;
  307. console.log(targetId);
  308. let listElem = document.getElementById(targetId.replace('word-', 'list-'));
  309. listElem.scrollIntoView({behavior: "smooth", block: "center"});
  310. }
  311. function highlightWord(e){
  312. e.target.style['text-decoration'] = "underline";
  313. }
  314. function unHighlightWord(e){
  315. e.target.style['text-decoration'] = "";
  316. }