Last active
August 29, 2015 14:08
-
-
Save mattandrews/90a567cd5561a15e7d39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Show New Guardian Comments | |
// @namespace http://www.theguardian.com/ | |
// @description Shows new comments | |
// @include http://www.theguardian.com/* | |
// @version 1 | |
// @grant none | |
// ==/UserScript== | |
var prefix = 'gu-discussion-'; | |
var delayTimer = 5000; | |
var getUUID = function () { | |
return guardian.config.page.shortUrl.replace('http://gu.com/', ''); | |
}; | |
var setLastVisited = function () { | |
window.localStorage.setItem(prefix + getUUID(), new Date()); | |
} | |
var getLastVisited = function () { | |
return new Date(window.localStorage.getItem(prefix + getUUID())) || new Date(); | |
}; | |
var isFirstVisit = function () { | |
return !(window.localStorage.getItem(prefix + getUUID())); | |
} | |
var originalLastVisit = getLastVisited(); | |
var highlightNewComments = function(newSince) { | |
function isNewer(d1, d2) { | |
if (d1.getTime() > d2.getTime()){ | |
return true; | |
} | |
return false; | |
} | |
var count = 0; | |
var comments = document.querySelectorAll('.discussion__main-comments li.d-comment'); | |
for (var i=0, l=comments.length; i<l; i++) { | |
var c = comments[i]; | |
var timestamp = new Date(c.getAttribute('data-comment-timestamp')); | |
// if timestamp is newer than last viewed | |
if ( isNewer(timestamp, new Date(newSince)) ) { | |
c.style.backgroundColor = '#EEF6F9'; | |
c.style.borderLeft = '10px solid #E2EEF3'; | |
count++; | |
} | |
} | |
var commentCount = document.querySelector('.js-discussion-comment-count'); | |
var commentCountHTML = commentCount.innerHTML; | |
commentCount.innerHTML = commentCountHTML + '<br />' + count + ' new'; | |
}; | |
var reloadOnPagination = function () { | |
var pagination = document.querySelectorAll('.pagination__list a'); | |
for (var i=0, l=pagination.length; i<l; i++) { | |
pagination[i].addEventListener('click', function () { | |
window.setTimeout(function(){ | |
highlightNewComments(originalLastVisit); | |
}, delayTimer); | |
}); | |
} | |
}; | |
window.setTimeout(function(){ | |
if (!isFirstVisit()) { | |
highlightNewComments(originalLastVisit); | |
reloadOnPagination(); | |
} | |
setLastVisited(); | |
}, delayTimer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Todo list:
localStorage
data occasionally (otherwise voracious readers will have tons of entries)