Reddit highlight newest comments

Highlights new comments in a thread since your last visit

当前为 2015-10-13 提交的版本,查看 最新版本

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