Newer
Older
moodlog_web / script.js
0xRoM on 5 Jan 2024 12 KB minor debug removal
  1. /*var datas = [
  2. {date: "2018-09-09", value: 10},
  3. {date: "2018-09-08", value: 5},
  4. {date: "2018-09-07", value: 8},
  5. {date: "2018-09-07", value: 7},
  6. {date: "2018-09-06", value: 9},
  7. {date: "2018-09-05", value: 6},
  8. {date: "2018-09-04", value: 5},
  9. {date: "2018-09-03", value: 4},
  10. {date: "2018-09-02", value: 7},
  11. {date: "2018-08-02", value: 1}
  12. ]
  13.  
  14. /*
  15. var parser = function(data) {
  16. var stats = {};
  17. console.log(data);
  18. for (var d in data) {
  19. console.log(data[d].date);
  20. var dateTime = new Date(data[d].date).toISOString();
  21. var timestamp = Math.floor(dateTime / 1000);
  22. let toTimestamp = strDate => Date.parse(data[d].date);
  23. stats[timestamp] = data[d].value;
  24. }
  25. console.log(stats);
  26. return stats;
  27.  
  28. };
  29. */
  30. /*
  31. var stats = {};
  32. var parser = function(data) {
  33. //console.log(data);
  34. for (var d in data) {
  35. //console.log("date:"+data[d]);
  36. //var date = new Date(data[d].date); // Date of activity
  37. //var sec = date.getTime()/1000; // Convert to sec
  38. stats[d] = data[d];
  39. //cal.subDomainTextFormat(d, data[d]);
  40. }
  41.  
  42. return stats;
  43. };
  44. */
  45. //var mainurl = "http://localhost:8080/test.json";
  46. var mainurl = "/?action=main_cal";
  47. var cal = new CalHeatMap();
  48. var resultArray;
  49.  
  50. fetchData(mainurl)
  51. .then(data => {
  52. resultArray = data; // Rename to avoid variable shadowing
  53. console.log("setting up");
  54. setUpCal();
  55. })
  56. .catch(error => {
  57. console.error('Error fetching data:', error);
  58. });
  59.  
  60.  
  61.  
  62.  
  63. function setUpCal(){
  64.  
  65. console.log("setting up cal");
  66. var datethen = new Date();
  67. datethen.setMonth(datethen.getMonth() - 9);
  68.  
  69. cal.init({
  70. //data: "http://localhost:8080/index.php?action=main_cal",
  71. data: mainurl,
  72. dataType: "json",
  73. //afterLoadData: parser,
  74. start: datethen,
  75. id : "graph",
  76. domain : "month", // Group data by month
  77. subDomain : "day", // Split each month by days
  78. cellSize: 15,
  79. cellPadding: 2,
  80. cellRadius: 3,
  81. domainGutter:2,
  82. subDomainTitleFormat: {
  83. empty: "{date}",
  84. filled: "{count} - {date}"
  85. },
  86. //itemSelector: "#cal-heatmap",
  87. range : 10, // Just display 10 months
  88. legend: [2,3,4,5,6,7,8,9], // Custom threshold for the scale
  89. tooltip: false,
  90. displayLegend: false,
  91. label: {
  92. position: "bottom",
  93. align: "center",
  94. offset: {x:0,y:-10},
  95. },
  96. considerMissingDataAsZero: true,
  97. legendHorizontalPosition: "center",
  98. legendColors: {
  99. min: "#6b6de5",
  100. max: "#46e260",
  101. },
  102.  
  103. subDomainTextFormat: function(dateString, value) {
  104. //console.log("datestring: " + dateString);
  105.  
  106. // Parse dateString in a consistent way (e.g., assuming it's in a specific time zone)
  107. var date = new Date(dateString);
  108.  
  109. // Set the time to midnight local time
  110. date.setHours(0, 0, 0, 0);
  111.  
  112. var unixTimestamp = Math.floor(date.getTime() / 1000); // Convert to seconds
  113.  
  114. // Assuming resultArray is an array of objects with a 'timestamp' property
  115. var result = resultArray.find(item => {
  116. // Convert the item's timestamp to a Date object
  117. var itemDate = new Date(item.timestamp * 1000); // Assuming item.timestamp is in seconds
  118.  
  119. // Set the time to midnight local time
  120. itemDate.setHours(0, 0, 0, 0);
  121.  
  122. // Convert the modified item's timestamp back to a Unix timestamp
  123. var modifiedUnixTimestamp = Math.floor(itemDate.getTime() / 1000);
  124.  
  125. // Check if the modified timestamp matches the target timestamp (midnight local time)
  126. return modifiedUnixTimestamp === unixTimestamp;
  127. });
  128.  
  129. // Log timestamp, unixTimestamp, resultArray, and result for debugging
  130. // console.log("Timestamp:", date.getTime());
  131. // console.log("Unix Timestamp:", unixTimestamp * 1000);
  132. // console.log("Result Array:", resultArray);
  133. // console.log("Result:", result);
  134.  
  135. // Check if result is defined and has a value property
  136. // console.log("Comparing:", date, unixTimestamp, resultArray);
  137.  
  138. if (result && result.value !== undefined) {
  139. //console.log(date + ":" + result.value);
  140. return result.value;
  141. }
  142.  
  143. // If result is not found or does not have a value property, return a default value or an empty string
  144. return ""; // You can set a default value or return an empty string here
  145. },
  146.  
  147. highlight: "now",
  148. onClick: function(date, count) {
  149. //alert("Oh gosh, " + count + " things occured on " + date.toISOString());
  150. updateDayLog(date.toISOString().slice(0, 19).replace('T', ' '));
  151. }
  152. });
  153. }
  154.  
  155.  
  156. function checkStats(timestamp){
  157. var finval = 0;
  158. $.getJSON('test.json', function (data) {
  159. $.each(data, function(i, field){
  160. //console.log(field);
  161. if(timestamp == i){
  162. console.log("found: "+field);
  163. finval = field;
  164. }
  165.  
  166. });
  167. //if (finval == 0){finval = "";}
  168. return finval;
  169. });
  170. }
  171.  
  172. var availableTags = [];
  173.  
  174. $( function() {
  175.  
  176. $( "#tags" ).autocomplete({
  177. source: availableTags
  178. });
  179. } );
  180.  
  181. function updateTime() {
  182. var now = new Date();
  183. var datestring = now.getFullYear() + "-" + ("0"+(now.getMonth()+1)).slice(-2) + "-" + ("0" + now.getDate()).slice(-2) + " " + ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2);
  184. $("span.date").html(datestring.toString());
  185. }
  186.  
  187. $("#happyval").on("input change", function() {
  188. $(".hpyno").html("[" + $("#happyval").val() + "]");
  189. });
  190. removespan = function(span) {
  191. span.remove();
  192. }
  193.  
  194. /***
  195. * filter adding and removing code
  196. */
  197. var filter = 0;
  198. function addFilterPos(word){
  199. filter++;
  200. $('.filtitle').after('<span class="filpos" onclick="removefilter(this);">'+word+'</span>');
  201. $(".filter").show();
  202. }
  203. function addFilterNeg(word){
  204. filter++;
  205. $('.filtitle').after('<span class="filneg" onclick="removefilter(this);">'+word+'</span>');
  206. $(".filter").show();
  207. }
  208. function addFilterCon(word){
  209. filter++;
  210. $('.filtitle').after('<span class="filcon" onclick="removefilter(this);">'+word+'</span>');
  211. $(".filter").show();
  212. }
  213. function addFilterTag(word){
  214. filter++;
  215. $('.filtitle').after('<span class="filtag" onclick="removefilter(this);">'+word+'</span>');
  216. $(".filter").show();
  217. }
  218. removefilter = function(span) {
  219. filter--;
  220. span.remove();
  221. if(filter == 0){
  222. $(".filter").hide();
  223. updateCal("/?action=main_cal");
  224. }
  225. }
  226.  
  227. /***
  228. * updating description
  229. */
  230. function updatePretext(){
  231. var toadd = $("#tags").val();
  232. switch(toadd.charAt(0)){
  233. case "+":
  234. $('.pretext').after('<span class="prepos" onclick="removespan(this);">'+toadd+'</span>');
  235. break;
  236. case "-":
  237. $('.pretext').after('<span class="preneg" onclick="removespan(this);">'+toadd+'</span>');
  238. break;
  239. case "@":
  240. $('.preview').append('<span class="precon" onclick="removespan(this);">'+toadd+'</span>');
  241. break;
  242. default:
  243. $(".pretext").html( toadd );
  244. }
  245. $("#tags").val("");
  246. //$(".pretext").html( );
  247. }
  248.  
  249. function submitMood(){
  250. var toadd = $(".preview").text();
  251.  
  252. console.log(toadd);
  253. }
  254.  
  255. /***
  256. * update main calendar values
  257. */
  258. function updateCal(url){ //updateCal("/?action=main_cal");
  259. mainurl = url;
  260. cal.destroy(function(){
  261. cal = new CalHeatMap();
  262. setUpCal();
  263. });
  264. }
  265.  
  266. /***
  267. * update specific day log
  268. */
  269. function updateDayLog(date){
  270. $.ajax({
  271. url: "/?action=date&date="+date,
  272. async: true,
  273. dataType: 'html',
  274. success: function (response) {
  275. //console.log(response);
  276. if(response != "0"){
  277. $(".previewhist").html(response);
  278. }
  279. }
  280. });
  281. }
  282.  
  283. /***
  284. * update latest tags
  285. */
  286. function updateLatest(tag){
  287. var string = "";
  288. switch(tag) {
  289. case "pos":
  290. string = "<div class=\"sub-header\">Latest 5 positive</div>";
  291. break;
  292. case "neg":
  293. string = "<div class=\"sub-header\">Latest 5 negative</div>";
  294. break;
  295. case "con":
  296. string = "<div class=\"sub-header\">Latest 5 context</div>";
  297. break;
  298. }
  299. $.ajax({
  300. url: "/?action=latest&tag="+tag,
  301. async: true,
  302. dataType: 'json',
  303. success: function (response) {
  304. if(response != "0"){
  305.  
  306. $.each(response, function(i, item) {
  307. var ntag = tag.charAt(0).toUpperCase() + tag.substr(1);
  308. string += "<span onclick=\"addFilter"+ntag+"($(this).text());\">"+item+"</span><br />";
  309. });
  310.  
  311. //console.log(response);
  312. $(".lat"+tag).html(string);
  313. }
  314. }
  315. });
  316. }
  317.  
  318. /***
  319. * update top tags
  320. */
  321. function updateTop(tag){
  322. var string = "";
  323. switch(tag) {
  324. case "pos":
  325. string = "<div class=\"sub-header\">Top 5 positive</div>";
  326. break;
  327. case "neg":
  328. string = "<div class=\"sub-header\">Top 5 negative</div>";
  329. break;
  330. case "con":
  331. string = "<div class=\"sub-header\">Top 5 context</div>";
  332. break;
  333. }
  334. $.ajax({
  335. url: "/?action=top&tag="+tag,
  336. async: true,
  337. dataType: 'json',
  338. success: function (response) {
  339. if(response != "0"){
  340.  
  341. $.each(response, function(i, item) {
  342. //console.log(item);
  343. var ntag = tag.charAt(0).toUpperCase() + tag.substr(1);
  344. string += "<span onclick=\"addFilter"+ntag+"($(this).text());\">"+item+"</span><br />";
  345. });
  346.  
  347. //console.log(response);
  348. $(".top"+tag).html(string);
  349. }
  350. }
  351. });
  352. }
  353.  
  354. /***
  355. * update available tags
  356. */
  357. function updateAvailable(){
  358. $.ajax({
  359. url: "/?action=alltag",
  360. async: true,
  361. dataType: 'json',
  362. success: function (response) {
  363. if(response != "0"){
  364. availableTags = response;
  365. $( "#tags" ).autocomplete({
  366. source: availableTags
  367. });
  368. }
  369. }
  370. });
  371. }
  372.  
  373. /***
  374. * display filtered calendar
  375. */
  376. function applyFilters(){
  377. var filttstring ="";
  378. $(".filter").find("span").each(function() {
  379. filttstring += $(this).html();
  380. });
  381. filttstring = filttstring.slice(8);
  382. filttstring = filttstring.replace(/\s+/g, '');
  383. filttstring = filttstring.replace(/\+/g , "%2B");
  384. filttstring = filttstring.replace(/#/g, '%23');
  385. //filttstring = encodeURIComponent(filttstring);
  386. //console.log(filttstring);
  387. updateCal("/?action=filtered_cal&filter="+filttstring);
  388. }
  389.  
  390. /***
  391. * save to moodlog
  392. */
  393. function submitMood(){
  394. var filttstring = [];
  395. var sendString = "";
  396. $(".preview").find("span").each(function() {
  397. filttstring.push( $(this).html() );
  398. });
  399. filttstring.shift(); // remove date
  400. filttstring[0] = filttstring[0].replace(/\[/g, ''); //fix no.
  401. filttstring[0] = filttstring[0].replace(/\]/g, '|'); //fix no.
  402.  
  403. for (var i = 0, len = filttstring.length; i < len; i++) { //tidy for URL
  404. filttstring[i] = filttstring[i].replace(/\+/g , "%2B");
  405. filttstring[i] = filttstring[i].replace(/ /g , "%20");
  406. sendString += filttstring[i]
  407. }
  408.  
  409. console.log(sendString);
  410. $.ajax({
  411. url: "/?action=save&log="+sendString,
  412. async: true,
  413. dataType: 'html',
  414. success: function (response) {
  415. if(response != "0"){
  416.  
  417. var now = new Date();
  418. var datestring = now.getFullYear() + "-" + ("0"+(now.getMonth()+1)).slice(-2) + "-" + ("0" + now.getDate()).slice(-2);
  419. var fulldatestring = now.getFullYear() + "-" + ("0"+(now.getMonth()+1)).slice(-2) + "-" + ("0" + now.getDate()).slice(-2) + " " + ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2);
  420.  
  421. $(".preview").html("<span class=\"date\">"+fulldatestring+"</span><span class=\"hpyno\">[5]</span><span class=\"pretext\" onclick=\"updatePretext();\"></span></div>")
  422. $("#happyval").val(5);
  423. updateCal("/?action=main_cal");
  424. updateDayLog(datestring);
  425. updateTop("pos");
  426. updateTop("neg");
  427. updateTop("con");
  428. updateLatest("pos");
  429. updateLatest("neg");
  430. updateLatest("con");
  431. }
  432. }
  433. });
  434. }
  435.  
  436. /***
  437. * for getting the data from URL and putting in array
  438. */
  439. function fetchData(url) {
  440. return fetch(url)
  441. .then(response => response.json())
  442. .then(data => {
  443. // Create an array of timestamps and values
  444. var resultArray = [];
  445. for (var timestamp in data) {
  446. if (data.hasOwnProperty(timestamp)) {
  447. resultArray.push({ timestamp: parseInt(timestamp), value: data[timestamp] });
  448. }
  449. }
  450. return resultArray;
  451. })
  452. .catch(error => {
  453. console.error('Error fetching data:', error);
  454. });
  455. }
  456.  
  457.  
  458. /***
  459. * once app loaded
  460. */
  461. $(document).ready(function(){
  462.  
  463. $('#tags').keypress(function(e){
  464. if(e.keyCode==13)
  465. updatePretext();
  466. });
  467.  
  468. updateTop("pos");
  469. updateTop("neg");
  470. updateTop("con");
  471. updateLatest("pos");
  472. updateLatest("neg");
  473. updateLatest("con");
  474.  
  475. updateAvailable();
  476.  
  477. updateTime();
  478. setInterval(updateTime, 5000); // 5 * 1000 miliseconds
  479. var interval1 = setInterval(function () { updateCal(mainurl); }, 300000); // update every 5 mins (300000)
  480.  
  481. var interval1 = setInterval(function () { updateTop("pos"); }, 300000);
  482. var interval1 = setInterval(function () { updateTop("neg"); }, 300000);
  483. var interval1 = setInterval(function () { updateTop("con"); }, 300000);
  484. var interval1 = setInterval(function () { updateLatest("pos"); }, 300000);
  485. var interval1 = setInterval(function () { updateLatest("neg"); }, 300000);
  486. var interval1 = setInterval(function () { updateLatest("con"); }, 300000);
  487. });
Buy Me A Coffee