Reddit highlight newest comments

Highlights new comments in a thread since your last visit

当前为 2015-03-02 提交的版本,查看 最新版本

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