Reddit - Unread Comment Helper (fork)

On topic pages, show "X unread comments (Y total)"; on comment pages, highlight unread comments. Local storage only -- does not work across multiple computers.

当前为 2015-06-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Reddit - Unread Comment Helper (fork)
  3. // @description On topic pages, show "X unread comments (Y total)"; on comment pages, highlight unread comments. Local storage only -- does not work across multiple computers.
  4. // @author Sam Angove <sam a-inna-circle rephrase period network>
  5. // @namespace http://rephrase.net/box/user-js/
  6. // @include http://reddit.com/
  7. // @include https://reddit.com/
  8. // @include http://reddit.com/?*
  9. // @include https://reddit.com/?*
  10. // @include http://reddit.com/r/*
  11. // @include https://reddit.com/r/*
  12. // @include http://www.reddit.com/
  13. // @include https://www.reddit.com/
  14. // @include http://www.reddit.com/*
  15. // @include https://www.reddit.com/*
  16. // @include http://www.reddit.com/r/*
  17. // @include https://www.reddit.com/r/*
  18. // @grant none
  19. // @version f.5.4
  20. // ==/UserScript==
  21.  
  22. /*
  23. Features:
  24.  
  25. * Replaces "10 comments" with "5 unread comments (10 total)"
  26. * The unread comments link goes directly to the first unread comment
  27. * Unread comments are highlighted for ease of skimming
  28. * You can navigate through unread comments with the following hotkeys:
  29. Alt+Q / Alt+W -or- Ctrl+Up arrow / Ctrl+Down arrow
  30.  
  31. Version history:
  32.  
  33. 0.1.0 - 2007-06-18 - initial release
  34. 0.2.0 - 2008-05-27 - revise to work with new Reddit, and finally remove
  35. the (long superfluous) cross-subdomain messaging crap
  36. 0.2.1 - 2008-07-23 - update to work with new URL form
  37. 0.2.2 - 2009-02-03 - update to work with new HTML
  38. 0.2.3 - 2009-06-03 - update to handle additional classnames with "entry"
  39. 0.2.4 - 2009-06-03 - fix "jump to new comment"
  40. 0.3.0 - 2010-02-19 - rewrite to use localStorage instead of Google Gears;
  41. exclude comscore iframe
  42. 0.3.1 - 2010-02-24 - don't @exclude valid links with 'help' etc. in title,
  43. version stored data, use non-b36 separator
  44. f.4.0 - 2013-10-03 - fix bugs with incorrect unread count, allow to
  45. navigate through unread comments
  46. f.5.0 - 2013-10-27 - delete items older than 7 days to avoid the
  47. localStorage size quota
  48. f.5.1 - 2013-11-06 - fixed a bug in deletion date calculation
  49. f.5.2 - 2014-03-21 - fixed a breakage due to an update of Reddit
  50. f.5.4 - 2015-06-26 - https support
  51. */
  52. (function(){
  53.  
  54. var DATA_VERSION = 'ruch2';
  55. var DELETE_OLDER_THAN = 1000*60*60*24*7; // Items older than 7 days
  56. /* Shove an item into local storage */
  57. function getData(id) {
  58. var data = localStorage.getItem(DATA_VERSION + '|' + id);
  59. //console.log("getData", document.location.href, id, data);
  60. if (data === null || data.substr(0, 1) != "{")
  61. return null;
  62. return JSON.parse(data);
  63. }
  64. /* Get an item out of local storage */
  65. function setData(id, data) {
  66. //console.log("setData", document.location.href, id, data);
  67. localStorage.setItem(DATA_VERSION + '|' + id, JSON.stringify(data));
  68. }
  69. /* Delete old items out of local storage */
  70. function deleteOldItems() {
  71. var data = localStorage.getItem(DATA_VERSION + '_last_clean_time');
  72. if (data !== null && Date.now() - data < 1000*60*60*24) { // Cleanup every 24 hours
  73. return;
  74. }
  75. var key, row;
  76. for (var i = 0; i < localStorage.length; i++) {
  77. //console.log(localStorage.key(i));
  78. key = localStorage.key(i);
  79. if (key.lastIndexOf(DATA_VERSION + '|', 0) !== 0) {
  80. continue;
  81. }
  82. data = localStorage.getItem(key);
  83. if (data === null || data.substr(0, 1) != "{") {
  84. continue;
  85. }
  86. row = JSON.parse(data);
  87. if (Date.now() - row["seentime"] < DELETE_OLDER_THAN) {
  88. continue;
  89. }
  90. localStorage.removeItem(key);
  91. }
  92. localStorage.setItem(DATA_VERSION + '_last_clean_time', Date.now());
  93. }
  94. /* Apply a style to highlight unread comments */
  95. function highlightUnread(comment) {
  96. comment.style.setProperty("border-left", "2px solid orange", null);
  97. comment.style.setProperty("padding-left", "5px", null);
  98. comment.classList.add('unreadHighlighted');
  99. }
  100. /* Get sorted array of unread comments offsets. */
  101. function getCommentsOffsetTop() {
  102. var comments = document.getElementsByClassName('unreadHighlighted');
  103. var arr = new Array(comments.length);
  104. for (var i = 0; i < comments.length; i++) {
  105. arr[i] = comments[i].offsetTop;
  106. }
  107. arr.sort(function(a, b) {
  108. return a - b;
  109. });
  110. return arr;
  111. }
  112. /* Jump to the next new comment. */
  113. function jumpToNextComment() {
  114. var unread = getCommentsOffsetTop();
  115. var scrollUnread;
  116. for (var i = 0; i < unread.length; i++) {
  117. scrollUnread = unread[i] - Math.round(window.innerHeight/2);
  118. if (scrollUnread > document.documentElement.scrollTop) {
  119. window.scrollTo(0, scrollUnread);
  120. break;
  121. }
  122. }
  123. }
  124. /* Jump to the previous new comment. */
  125. function jumpToPrevComment() {
  126. var unread = getCommentsOffsetTop().reverse();
  127. var scrollUnread;
  128. for (var i = 0; i < unread.length; i++) {
  129. scrollUnread = unread[i] - Math.round(window.innerHeight/2);
  130. if (scrollUnread < document.documentElement.scrollTop) {
  131. window.scrollTo(0, scrollUnread);
  132. break;
  133. }
  134. }
  135. }
  136.  
  137. /*
  138. Handle a list page, adding "n unread comments" links etc.
  139. */
  140. function handleListPage() {
  141. var snap = document.evaluate("//a" +
  142. "[contains(concat(' ', normalize-space(@class), ' '), ' comments ')]" +
  143. "[contains(@href, '/comments')]",
  144. document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  145.  
  146. var b36tid, row, match, comments, seen, newcomments, newlink;
  147. for(var elm = null, i = 0; (elm = snap.snapshotItem(i)); i++) {
  148. match = elm.firstChild.nodeValue.match(/(\d+) comment/);
  149. // No comments; bail early.
  150. if (!match)
  151. continue;
  152.  
  153. comments = match[1];
  154.  
  155. // Alphanumeric base-36 id, like "1lp5".
  156. b36tid = elm.getAttribute("href").match(/\/comments\/([^\/]+)/)[1];
  157. row = getData(b36tid);
  158.  
  159. seen = row ? row["seencount"] : 0;
  160.  
  161. newcomments = comments - seen;
  162. // Can be negative if comments are deleted.
  163. if (newcomments < 0) newcomments = 0;
  164.  
  165. newlink = elm.cloneNode(false);
  166. if (newcomments > 0)
  167. newlink.style.color = "#333";
  168.  
  169. var cstring = "unread comment" + (newcomments != 1 ? "s" : "");
  170.  
  171. newlink.appendChild( document.createTextNode(newcomments + " " + cstring) );
  172. elm.parentNode.insertBefore(newlink, elm);
  173.  
  174. // Some comments have been read already.
  175. // Show both read and unread counts.
  176. if (comments > newcomments) {
  177. // Magic fragment causes a jump to the first unread comment.
  178. newlink.href += "#new";
  179. elm.removeChild(elm.firstChild);
  180. elm.appendChild(document.createTextNode("(" + comments + " total)"));
  181. elm.style.setProperty("background-color", "#fff", null);
  182. } else {
  183. // All comments are unread.
  184. elm.parentNode.removeChild(elm);
  185. }
  186. }
  187. }
  188.  
  189. /*
  190. Handle a comments page: highlight new comments, save the ID of the highest
  191. comment, etc.
  192. */
  193. function handleCommentsPage() {
  194. var url = document.location.href.split("#");
  195. var frag = url.length > 1 ? url[1] : false;
  196. var b36tid = url[0].match(/\/comments\/([^\/]+)/)[1];
  197.  
  198. var row = getData(b36tid);
  199.  
  200. var update, max_cid = 0, newmax = 0, seencount = 0;
  201. if (row) {
  202. newmax = max_cid = row["max_cid"];
  203. seencount = row["seencount"];
  204. }
  205.  
  206. var comments, i, split, b36cid, cid;
  207. comments = document.getElementsByClassName('comment');
  208. for(i=0; i<comments.length; i++) {
  209. split = comments[i].className.split("_");
  210. if(split.length == 2)
  211. {
  212. b36cid = split[1].split(' ')[0].substr(1);
  213. cid = parseInt(b36cid, 36);
  214. if (cid > max_cid) {
  215. highlightUnread(comments[i].getElementsByClassName("entry")[0]);
  216. if (cid > newmax) {
  217. newmax = cid;
  218. }
  219. }
  220. }
  221. }
  222.  
  223. if (frag == "new") {
  224. jumpToNextComment();
  225. }
  226.  
  227. var elm = document.getElementsByClassName('comments')[0];
  228.  
  229. comments = elm.innerHTML.match(/\b\d+\b/);
  230. if (comments) {
  231. comments = comments[0];
  232. if (comments > 0) {
  233. setData(b36tid, {"max_cid": newmax, "seencount": comments, "seentime": Date.now()});
  234. }
  235. }
  236. }
  237.  
  238. if (document.location.href.match(/\/comments(\/|\?|#|$)/)) {
  239. if (document.location.href.match(/\/comments\/[^\/?#]+(\/([^\/?#]+\/?)?)?(\?|#|$)/)) {
  240. deleteOldItems();
  241. handleCommentsPage();
  242.  
  243. document.addEventListener('keydown', function(e) {
  244. // Alt+Q
  245. if (e.keyCode == "Q".charCodeAt(0) && !e.shiftKey && !e.ctrlKey && e.altKey && !e.metaKey) {
  246. jumpToPrevComment();
  247. e.preventDefault();
  248. return false;
  249. }
  250. // Alt+W
  251. if (e.keyCode == "W".charCodeAt(0) && !e.shiftKey && !e.ctrlKey && e.altKey && !e.metaKey) {
  252. jumpToNextComment();
  253. e.preventDefault();
  254. return false;
  255. }
  256.  
  257. // Ctrl+up
  258. if (e.keyCode == 38 && !e.shiftKey && e.ctrlKey && !e.altKey && !e.metaKey) {
  259. jumpToPrevComment();
  260. e.preventDefault();
  261. return false;
  262. }
  263. // Ctrl+down
  264. if (e.keyCode == 40 && !e.shiftKey && e.ctrlKey && !e.altKey && !e.metaKey) {
  265. jumpToNextComment();
  266. e.preventDefault();
  267. return false;
  268. }
  269. }, false);
  270. }
  271. } else {
  272. handleListPage();
  273. }
  274.  
  275. })();