word_cloud.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. console.log(jsonLetters)
  44. //filterLetters("");
  45. // queryLetters defined in people.js
  46. console.log(queryLetters);
  47. /**
  48. * COMPONENT CREATION SECTION
  49. *
  50. * */
  51. // Master function, takes data output from the query and creates the HTML for the Word Cloud component of the page
  52. function handle_word_network(json){
  53. // Pre-process data
  54. let words = processQuery(json);
  55. // Create page elements
  56. doListPersonNetwork(words);
  57. doWordCloud(words);
  58. }
  59. // Return structured object from raw query data for further processing
  60. function processQuery(json) {
  61. const tempArray = [];
  62. $.each(
  63. json['results']['bindings'],
  64. (index, value) => {
  65. let text = value['text']['value'];
  66. let link = value['uri2']['value'];
  67. let sent = parseInt(value['count1']['value']);
  68. let received = parseInt(value['count2']['value']);
  69. let count = sent + received;
  70. tempArray.push({'text': text, 'sent': sent, 'received': received, 'count': count, 'hlink': link});
  71. }
  72. );
  73. tempArray.sort((a, b) => b.count - a.count);
  74. return tempArray;
  75. }
  76. // Create formatted list of people in the network
  77. function doListPersonNetwork(words){
  78. let ArrayNames = "";
  79. words.forEach(element => {
  80. filteredText = element['text'].replace('"', '').replace("'", '');
  81. ArrayNames +=
  82. "<div class='item-place-person'>"+
  83. "<div class='item-place-person-label' id='list-" + filteredText + "'>" +
  84. element['text'] +
  85. "<br /><span class='num_occ'>[Lettere inviate: " + element['sent'] + "]</span>" +
  86. "<br /><span class='num_occ'>[Lettere ricevute: " + element['received'] + "]</span>" +
  87. "<br /><span id='tot-"+filteredText+"' class='num_occ'>[Totale corrispondenza: " + element['count'] + "]</span>" +
  88. "</div>" +
  89. "<div class='item-place-person-action'>" +
  90. "<div class='persona' id='" + element['hlink'] +"'>" +
  91. "<i class='fa fa-user' style='cursor:pointer'></i>" +
  92. "</div>" +
  93. "</div>" +
  94. "</div>";
  95. });
  96. document.getElementById("list_person_network").innerHTML = ArrayNames;
  97. addEventsToNameList(words);
  98. }
  99. function addEventsToNameList(words){
  100. let counter = 0
  101. for(let word of words){
  102. if(counter>0) break;
  103. let listElem = document.getElementById('tot-' + word.text.replace('"', '').replace("'", ''));
  104. if(listElem!=null){
  105. listElem.addEventListener("click", filterLetters);
  106. listElem.addEventListener("mouseover", highlightWord);
  107. listElem.addEventListener("mouseout", unHighlightWord);
  108. }
  109. counter++;
  110. }
  111. }
  112. function filterLetters(e){
  113. try{
  114. let preText = e.target.parentNode.textContent;
  115. console.log('text content', preText);
  116. let name = preText.split("[")[0];
  117. console.log('name', name);
  118. // responseLet defined in people.js
  119. responseLet.then(data => {
  120. let lettersJson = data.results.bindings;
  121. console.log('AH!', lettersJson[0]);
  122. });
  123. } catch{
  124. console.log("Couldn't get the name");
  125. }
  126. }
  127. // Create the word cloud
  128. function doWordCloud(words){
  129. // Clear word cloud div
  130. $('#myWordCloud').empty();
  131. // OVERALL GRAPHIC SETTINGS for the cloud container -- id, dimensions, position
  132. let width = 0.5*window.outerWidth;
  133. let height = 0.6*width;
  134. // append the svg object to the body of the page
  135. let svg = d3.select("#myWordCloud")
  136. .append("svg")
  137. .attr("id", "wordcloudNetwork")
  138. .attr("preserveAspectRatio", "xMinYMin meet")
  139. .attr("viewBox", "0 0 " + width + " " + height)
  140. .classed("svg-content", true)
  141. .attr("width", width)
  142. .attr("height", height)
  143. .attr("style", "border:1px solid black")
  144. // In case of empty cloud, draw special page and exit
  145. if (words.length == 0){
  146. drawEmptyWordCloud();
  147. return;
  148. }
  149. // THE ACTUAL CLOUD
  150. svg = document.getElementById('wordcloudNetwork');
  151. console.log(svg);
  152. let zoom = window.devicePixelRatio;
  153. console.log('zoom', zoom);
  154. wcParameters = {
  155. svgWidth: svg.getBoundingClientRect().width,
  156. svgHeight: svg.getBoundingClientRect().height,
  157. maxFontSize: 30/((1+zoom)/2),
  158. minFontSize: 10/((1+zoom)/2)
  159. }
  160. let svgWords = hackWords(words, wcParameters);
  161. svg.innerHTML = svgWords;
  162. let wordCloudText = createWordCloud(words, wcParameters);
  163. svg.innerHTML = wordCloudText;
  164. addEventsToWordCloud(words);
  165. }
  166. // Helper function -- draw special empty word cloud if there are no occurrences
  167. function drawEmptyWordCloud(){
  168. let wordIcon = "<div id='users_icon' class='no_info_icon'> \
  169. <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 512'> \
  170. <!--! 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'/> \
  171. </svg> \
  172. <p>Nessuna persona trovata</p> \
  173. </div>";
  174. $("#wordcloudNetwork").css("display", "none");
  175. $("#references_network").css("display", "none");
  176. document.getElementById("myWordCloud").innerHTML = wordIcon;
  177. }
  178. /*****************************
  179. * Customized word cloud code *
  180. *****************************/
  181. function hackWords(words, parameters){
  182. let weights = words.map(word => word.count);
  183. let minWeight = Math.min(...weights);
  184. let maxFontSize = parameters.maxFontSize;
  185. let minFontSize = parameters.minFontSize;
  186. console.log('weights', weights);
  187. console.log('maxFontSize', maxFontSize);
  188. console.log('minFontSize',minFontSize);
  189. let stringOfWords = "";
  190. for(let ind=0; ind<words.length; ind++){
  191. let word = words[ind];
  192. word.fontSize = getFontSize(words[ind].count, minWeight, maxFontSize, minFontSize);
  193. stringOfWords = stringOfWords+
  194. '<text x="100" y ="' + (maxFontSize + maxFontSize*ind).toString() + '" + font-family="Verdana" font-size="'+(word.fontSize)+'" id="word' + ind + '">'+words[ind].text+'</text>\n';
  195. }
  196. return stringOfWords;
  197. }
  198. // Takes a list of words, returns the innerHTML for a Word Cloud as a string containing multiple <g> svg elements
  199. function createWordCloud(words, parameters){
  200. let actualUsefulWidth = parameters.svgWidth;
  201. let actualUsefulHeight = parameters.svgHeight;
  202. console.log('Actual SVG dimensions', actualUsefulWidth, actualUsefulHeight);
  203. maxFontSize = parameters.maxFontSize;
  204. minFontSize = parameters.minFontSize;
  205. const rectObjs = []
  206. let allBooms = 0
  207. let attempts = 0;
  208. let outOfBorder = 0;
  209. for(let ind=0;ind<words.length;ind++){
  210. //for(let ind=0;ind<3;ind++){
  211. // Control vars
  212. if(allBooms>=20*(ind+1)) break;
  213. attempts++;
  214. let boom = false;
  215. // word + bounding box parameters definition
  216. let word = words[ind];
  217. let id0 = "word"+ind;
  218. let wordBB = document.getElementById(id0).getBoundingClientRect();
  219. let fontSize = word.fontSize;
  220. let width = wordBB.width;
  221. let height = wordBB.height;
  222. let multiplier = 0.1 + 0.4*Math.max((maxFontSize-fontSize)/(maxFontSize-minFontSize), allBooms/(20*(ind+1)));
  223. let xR = Math.floor(actualUsefulWidth/2-width/2 + randomRange(-multiplier*actualUsefulWidth, multiplier*actualUsefulWidth));
  224. let yR = Math.floor(actualUsefulHeight/2 + randomRange(-multiplier*actualUsefulHeight, multiplier*actualUsefulHeight));
  225. //console.log('x', 'y', xR, yR)
  226. let angle;
  227. if(word.received/word.sent>3) angle = -3;
  228. else if(word.received/word.sent<0.3) angle = 3;
  229. let text = word.text;
  230. //console.log('Rect:', width, height, xR, yR, angle, text);
  231. //
  232. let newRect = new Rect(width, height, xR, yR, angle, text, fontSize);
  233. boom = checkBorder(newRect, 0, actualUsefulWidth, 0, actualUsefulHeight)
  234. if(boom){
  235. outOfBorder++;
  236. if(outOfBorder<30){
  237. ind--;
  238. continue;
  239. } else{
  240. boom = false;
  241. }
  242. }
  243. for(let rect of rectObjs){
  244. boom = checkColl(newRect, rect);
  245. if(boom) break;
  246. }
  247. if(boom){
  248. allBooms++;
  249. ind--;
  250. continue;
  251. }
  252. allBooms = 0;
  253. rectObjs.push(newRect);
  254. }
  255. console.log('Attempted:', attempts);
  256. console.log('Placed:', rectObjs.length);
  257. console.log('booms!', allBooms);
  258. const rectTexts = [];
  259. rectObjs.forEach(rect => rectTexts.push(rect.printCoords(false, maxFontSize, minFontSize)));
  260. let rects = rectTexts.join('\n');
  261. return rects;
  262. }
  263. function getFontSize(weight, minWeight, maxFontSize, minFontSize){
  264. let r1 = weight/10*minWeight - 1/10; // between 0 and a big num
  265. let res = minFontSize + (maxFontSize-minFontSize)*r1/Math.sqrt(1+r1**2);
  266. return res;
  267. }
  268. function randomRange(a, b=0){
  269. return (a-b)*Math.random()+b;
  270. }
  271. function randomInt(a){
  272. return Math.floor(a*Math.random());
  273. }
  274. function randomRangeInt(a, b=0){
  275. let ap = Math.floor(a);
  276. let bp = Math.floor(b);
  277. return Math.floor((ap-bp)*Math.random())+bp;
  278. }
  279. // Check border collision
  280. function checkBorder(rect, minX, maxX, minY, maxY){
  281. if(rect.minX<minX) return true;
  282. if(rect.maxX>maxX) return true;
  283. if(rect.minY<minY) return true;
  284. if(rect.maxY>maxY) return true;
  285. return false;
  286. }
  287. function addEventsToWordCloud(words){
  288. for(let word of words){
  289. let wcElem = document.getElementById('word-' + word.text.replace('"', '').replace("'", ''));
  290. if(wcElem!=null){
  291. wcElem.addEventListener("click", focusPersonInList);
  292. wcElem.addEventListener("mouseover", highlightWord);
  293. <<<<<<< Updated upstream
  294. wcElem.addEventListener("mouseout", unHighlightWord);
  295. =======
  296. wcElem.addEventListener("mouseout", unHighlightWord);
  297. >>>>>>> Stashed changes
  298. }
  299. }
  300. }
  301. function focusPersonInList(e){
  302. let targetId = e.target.id;
  303. console.log(targetId);
  304. let listElem = document.getElementById(targetId.replace('word-', 'list-'));
  305. listElem.scrollIntoView({behavior: "smooth", block: "center"});
  306. }
  307. function highlightWord(e){
  308. e.target.style['text-decoration'] = "underline";
  309. }
  310. function unHighlightWord(e){
  311. e.target.style['text-decoration'] = "";
  312. }
  313. <<<<<<< Updated upstream
  314. =======
  315. function filterLetters(name){
  316. // responseLet defined in people.js
  317. let arra = responseLet['results']['bindings'];
  318. console.log(arra);
  319. }
  320. >>>>>>> Stashed changes