Reddit highlight newest comments

Highlights new comments in a thread since your last visit

当前为 2014-06-20 提交的版本,查看 最新版本

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