Reddit highlight newest comments

Highlights new comments in a thread since your last visit

目前為 2014-06-29 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Reddit highlight newest comments
  3. // @description Highlights new comments in a thread since your last visit
  4. // @namespace https://greasyfork.org/users/98-jonnyrobbie
  5. // @author JonnyRobbie
  6. // @include /https?:\/\/(www\.)?reddit\.com\/r\/[a-zA-Z]+\/comments\/.*/
  7. // @version 1.5.3
  8. // ==/UserScript==
  9.  
  10. /*-----settings-----*/
  11. highlightBGColorB = '7CB9F7'; //background color of a highlighted newest comment
  12. highlightBGColorA = 'CEE3F7'; //background color of a highlighted older comment
  13. highlightHalf = 2 //[hours]; when the algorithm should interpolate exactly 0.5 between A and B
  14. highlightBGBorder = '1px solid #425466'; //border style of a highlighted new comment
  15. expiration = 432000000; //expiraton time in millisesonds; default is 5 days (432000000ms)
  16. highlihhtBetterChild = true; //highlight child comment if it has better karma than its parent
  17. highlightNegative = true;
  18. betterChildStyle = '3px solid'; //border of said comment
  19. betterChildStyleGradientA = '99AAEE';
  20. betterChildStyleGradientB = 'F55220';
  21. betterChildStyleGradientC = 'ad3429';
  22. /*-----settings-----*/
  23.  
  24. /*
  25. Changelog:
  26. 1.5.3
  27. -fixed a bog which has caused the script to hkald when the comment was too young to display score
  28. 1.5.2
  29. -some more fugs resulting from reddit changes
  30. 1.5.1
  31. -fixed reddit changes
  32. 1.4.2
  33. -tweaked some colors and timing
  34. 1.4.1
  35. -added highlighting comment with negative karma
  36. -added color shading dependent on the new comment age
  37. -added an option to manually edit the time of the last thread visit
  38. 1.3.1
  39. -Added expiration for localstorage, defaulted to 14 days. It won't grow indefinately now.
  40. -Reduced the amount of console.log clutter
  41. */
  42.  
  43. haveGold = false; //inicialization
  44.  
  45. function isNumber(n) {
  46. return !isNaN(parseFloat(n)) && isFinite(n);
  47. }
  48.  
  49.  
  50. function hasClass(element, cls) {
  51. return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
  52. }
  53.  
  54. function getThread() {
  55. console.log("Logging reddit comment highlight.");
  56. console.log("Fetching thread ID...");
  57. if (document.querySelector('[rel="shorturl"]') === null) {
  58. console.log("Not a comment thread. Aborting userscript...");
  59. return;
  60. }
  61. haveGold = hasClass(document.getElementsByTagName("body")[0], "gold");
  62. console.log("hasgold: " + haveGold);
  63. purgeOldStorage(expiration);
  64. var threadID = "redd_id_" + document.querySelector('[rel="shorturl"]').href.substr(-6);
  65. console.log("Thread id: " + threadID);
  66. var lastVisit = localStorage.getItem(threadID);
  67. if (lastVisit === null) {
  68. console.log("Thread has not been visited yet. Creating localStorage...");
  69. localStorage.setItem(threadID, Date.parse(Date()));
  70. }
  71. else {
  72. var postMenu;
  73. postMenu = document.getElementById("siteTable").getElementsByClassName("flat-list")[0];
  74. if (!haveGold) {
  75. var timeDiff = Date.parse(Date()) - lastVisit;
  76. var goldBox = document.createElement("div");
  77. goldBox.className = "rounded gold-accent comment-visits-box";
  78. var goldBoxTitle = document.createElement("div");
  79. goldBoxTitle.className = "title";
  80. var goldBoxLabel = document.createElement("span");
  81. goldBoxLabel.innerHTML = "Highlight comments posted since previous visit [hh:mm] ago:";
  82. var goldBoxInput = document.createElement("input");
  83. goldBoxInput.type = "text";
  84. goldBoxInput.style.margin = "auto 5px";
  85. goldBoxInput.style.width = "64px";
  86. goldBoxInput.id = "timeInput"
  87. goldBoxInput.value = padToTwo(Math.floor(timeDiff/(1000*3600))) + ":" + padToTwo(Math.floor(60*(timeDiff/(1000*3600) - Math.floor(timeDiff/(1000*3600)))));
  88. var goldBoxOK = document.createElement("input");
  89. goldBoxOK.type = "button";
  90. goldBoxOK.value = "OK";
  91. goldBoxOK.addEventListener("click", function(){timeSetBack(threadID, goldBoxInput);}, false)
  92. goldBox.appendChild(goldBoxTitle);
  93. goldBoxTitle.appendChild(goldBoxLabel);
  94. goldBoxTitle.appendChild(goldBoxInput);
  95. goldBoxTitle.appendChild(goldBoxOK);
  96. insertNodeAfter(goldBox, document.getElementsByClassName("commentarea")[0].getElementsByClassName("usertext")[0]);
  97. }
  98. }
  99. commentReg = /^https?:\/\/(www\.)reddit\.com\/r\/[a-zA-Z]+\/comments\/[0-9a-z]+\/[0-9a-z_]+\/$/;
  100. isCommentPage = commentReg.test(document.URL);
  101. highlightComments(lastVisit, isCommentPage);
  102. console.log("Match for full comment page(" + document.URL + "): " + isCommentPage);
  103. if (isCommentPage == true) {
  104. console.log("Setting localStorage to now...");
  105. localStorage.setItem(threadID, Date.parse(Date()));
  106. } else
  107. {
  108. console.log("not a comment page")
  109. }
  110. }
  111.  
  112. function padToTwo(number) {
  113. if (number<=99) { number = ("0"+number).slice(-2); }
  114. return number;
  115. }
  116.  
  117.  
  118. function timeSetBack(threadID, textbox){
  119. console.log("setting time back");
  120. var timeBackArray = textbox.value.split(":")
  121. if (timeBackArray.length > 2) {
  122. alert("You have not entered a valid time");
  123. console.log("too many colons");
  124. return
  125. }
  126. var timeBack = parseInt(timeBackArray[0], 10) + (parseInt(timeBackArray[1], 10)/60)
  127. if (timeBack != null && isNumber(timeBack) == true) {
  128. var lastVisit = Date.parse(Date())-timeBack*3600000;
  129. if (lastVisit > localStorage.getItem(threadID)) alert("The time has been set lower than it was before. Please, refresh the page to properly display the changes.");
  130. localStorage.setItem(threadID, lastVisit);
  131. console.log("Setting localStorage " + threadID + " " + timeBack*3600000 + " ms back");
  132. highlightComments(lastVisit, true);
  133. }
  134. }
  135.  
  136. function purgeOldStorage(difference) {
  137. var thisTime = Date.parse(Date());
  138. var total=0;
  139. for (var i=0;i<localStorage.length;i++) {
  140. if (localStorage.key(i).substr(0,8)=="redd_id_" && parseInt(localStorage.getItem(localStorage.key(i)))+difference<thisTime) {
  141. localStorage.removeItem(localStorage.key(i));
  142. total++;
  143. i=0;
  144. }
  145. }
  146. console.log(total + " localStorage older than " + difference + "ms has been removed");
  147. }
  148.  
  149. function isProperThread() {
  150. return true;
  151. }
  152.  
  153. function insertNodeAfter(node, sibling) {
  154. sibling.parentNode.insertBefore(node, sibling.nextSibling);
  155. }
  156.  
  157. function highlightComments(lastVisit, isCommentPage) {
  158. console.log("Thread last visited in: " + lastVisit);
  159. comments = document.getElementsByClassName('comment');
  160. console.log("Comment count: " + comments.length);
  161. nowtime = Date.parse(Date());
  162. highlightHalf = Math.pow(0.5, (1/(-highlightHalf)));
  163. for(i=0; i<comments.length; i++) {
  164. if ((' ' + comments[i].className + ' ').indexOf(' deleted ') > -1) {continue;} //if the comment contains class 'deleted', skip this iteration
  165. var ctime = Date.parse(comments[i].childNodes[2].childNodes[0].getElementsByTagName('time')[0].getAttribute('title'));
  166. var scoreTag = comments[i].getElementsByClassName("collapsed")[0].getElementsByClassName("unvoted");
  167. if (scoreTag.length > 0) {
  168. scorechild = parseInt(scoreTag[0].innerHTML);
  169. } else {
  170. scorechild = 0;
  171. }
  172. var scoreTag = comments[i].parentNode.parentNode.parentNode.getElementsByClassName("collapsed")[0].getElementsByClassName("unvoted");
  173. if (scoreTag.length > 0) {
  174. scoreparent = parseInt(scoreTag[0].innerHTML);
  175. } else {
  176. scoreparent = 0;
  177. }
  178. var voted = comments[i].getElementsByClassName("midcol")[0].className;
  179. if (voted == "midcol likes") {
  180. scorechild++;
  181. } else if (voted == "midcol dislikes") {
  182. scorechild--;
  183. }
  184. var voted = comments[i].parentNode.parentNode.parentNode.getElementsByClassName("midcol")[0].className
  185. if (voted == "midcol likes") {
  186. scoreparent++;
  187. } else if (voted == "midcol dislikes") {
  188. scoreparent--;
  189. }
  190. if (parseInt(ctime) > parseInt(lastVisit) && haveGold == false) {
  191. usertextBody = comments[i].getElementsByClassName("usertext-body")[0];
  192. console.log("comment(" + i + "," + 0 + "): gradient(" + nowtime + "," + ctime + ") = " + getGradient(nowtime-ctime));
  193. usertextBody.style.backgroundColor = interpolateColor(highlightBGColorA, highlightBGColorB, getGradient(nowtime-ctime));
  194. usertextBody.style.sborder = highlightBGBorder;
  195. }
  196. if (scoreparent < scorechild && highlihhtBetterChild == true && comments[i].parentNode.parentNode.parentNode.className != "content") {
  197. comments[i].style.setProperty('border-left',betterChildStyle + " #" + betterChildStyleGradientA, 'important');
  198. }
  199. if (scorechild < 0 && highlightNegative == true) {
  200. comments[i].style.setProperty('border-left','1px solid #' + betterChildStyleGradientC, 'important');
  201. }
  202. }
  203. if (haveGold == true && isCommentPage == true) {highlightNew();}
  204. var goldSelect = document.getElementById("comment-visits");
  205. if (goldSelect != null) goldSelect.addEventListener("change", function(){console.log("changed highlighting");highlightNew();;}, false);
  206. window.addEventListener("load", function(){console.log("window loaded, highlighting");highlightNew();;}, false)
  207. }
  208.  
  209. function highlightNew(){
  210. comments = document.getElementsByClassName("new-comment");
  211. console.log("gold " + comments.length + " new comments");
  212. nowtime = Date.parse(Date());
  213. highlightHalf = Math.pow(0.5, (1/(-highlightHalf)));
  214. for(i=0; i<comments.length; i++) {
  215. var titleDate;
  216. titleDate = comments[i].childNodes[2].childNodes[0].getElementsByTagName('time')[0].getAttribute('datetime')
  217. var ctime = Date.parse(titleDate);
  218. usertextBody = comments[i].getElementsByClassName("usertext-body")[0];
  219. console.log("comment(" + i + "," + 0 + "): gradient(" + nowtime + "," + ctime + ") = " + getGradient(nowtime-ctime));
  220. usertextBody.style.backgroundColor = interpolateColor(highlightBGColorA, highlightBGColorB, getGradient(nowtime-ctime));
  221. usertextBody.style.sborder = highlightBGBorder;
  222. }
  223. }
  224.  
  225. function finalBGColor(ctime) {
  226. nowtime = Date.parse(Date());
  227. }
  228.  
  229. function getGradient(time) {
  230. return Math.pow(highlightHalf, -(time/3600000));
  231. }
  232.  
  233. function interpolateColor(minColor,maxColor,depth){
  234. function d2h(d) {return d.toString(16);}
  235. function h2d(h) {return parseInt(h,16);}
  236. if(depth == 0){
  237. return minColor;
  238. }
  239. if(depth == 1){
  240. return maxColor;
  241. }
  242. var color = "#";
  243. for(var i=0; i < 6; i+=2){
  244. var minVal = new Number(h2d(minColor.substr(i,2)));
  245. var maxVal = new Number(h2d(maxColor.substr(i,2)));
  246. var nVal = minVal + (maxVal-minVal) * depth;
  247. var val = d2h(Math.floor(nVal));
  248. while(val.length < 2){
  249. val = "0"+val;
  250. }
  251. color += val;
  252. }
  253. return color;
  254. }
  255.  
  256. function formatDate(unixtime) {
  257. var t = new Date(unixtime);
  258. //return t.toString();
  259. return t.getDate() + "." + (t.getMonth()+1) + "." + t.getFullYear() + " " + (t.getUTCHours()+UTCDifference) + ":" + pad2(t.getMinutes()) + ":" + pad2(t.getSeconds()) + " " + timeZoneDesc;
  260. }
  261. function dateDifference(unixtime) {
  262. var diff = new Date();
  263. var unixtime2 = new Date(unixtime);
  264. var secDiff = (diff.getSeconds() - unixtime2.getSeconds());
  265. var minDiff = (diff.getMinutes() - unixtime2.getMinutes());
  266. var hourDiff = (diff.getHours() - unixtime2.getHours());
  267. var dayDiff = (diff.getDate() - unixtime2.getDate());
  268. var monthDiff = (diff.getMonth() - unixtime2.getMonth());
  269. var yearDiff = (diff.getFullYear() - unixtime2.getFullYear());
  270. var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  271. if (secDiff < 0) {
  272. minDiff--;
  273. secDiff += 60;
  274. }
  275. if (minDiff < 0) {
  276. hourDiff--;
  277. minDiff += 60;
  278. }
  279. if (hourDiff < 0) {
  280. dayDiff--;
  281. hourDiff += 24;
  282. }
  283. if (dayDiff < 0) {
  284. monthDiff--;
  285. dayDiff += months[diff.getMonth()-2]; // -2 as the months array is zero-indexed too
  286. }
  287. if (monthDiff < 0) {
  288. yearDiff--;
  289. monthDiff += 12;
  290. }
  291. //console.log(yearDiff+' years, '+monthDiff+' months, '+dayDiff+' days');
  292. return (yearDiff == 0 ? "" : yearDiff + " years ") + (monthDiff == 0 ? "" : monthDiff + " months ") + (dayDiff == 0 ? "" : dayDiff + " days ") + (hourDiff == 0 ? "" : hourDiff + " hours ") + (minDiff == 0 ? "" : minDiff + " minutes ") + (secDiff == 0 ? "" : secDiff + " seconds");
  293. //return yearDiff + " years " + monthDiff + " months " + dayDiff + " days " + hourDiff + " hours " + minDiff + " minutes " + secDiff + " seconds";
  294. }
  295. function addCss(cssCode) {
  296. //thanks for the function from this blog http://www.tomhoppe.com/index.php/2008/03/dynamically-adding-css-through-javascript/
  297. var styleElement = document.createElement("style");
  298. styleElement.type = "text/css";
  299. if (styleElement.styleSheet) {
  300. styleElement.styleSheet.cssText = cssCode;
  301. } else {
  302. styleElement.appendChild(document.createTextNode(cssCode));
  303. }
  304. document.getElementsByTagName("head")[0].appendChild(styleElement);
  305. }
  306. function pad2(number) {
  307. return (number < 10 ? '0' : '') + number
  308. }
  309. getThread();