#todo: remove close()?, make hiddenReplies/hiddenThreads local, comments, gc
#todo: remove stupid 'obj', arr el, make hidden an object, smarter xhr, text(), @this, images, clear hidden
#todo: watch - add board in updateWatcher?, redundant move divs?, redo css / hiding, manual clear
#
#TODO - 4chan time
#addClass, removeClass; remove hide / show; makeDialog el, 'center'
#TODO - expose 'hidden' configs
config =
'Thread Hiding': [true, 'Hide entire threads']
'Reply Hiding': [true, 'Hide single replies']
'Show Stubs': [true, 'Of hidden threads / replies']
'Thread Navigation': [true, 'Navigate to previous / next thread']
'Keyboard Navigation': [false, 'Navigate threads w/ your keyboard']
'Reply Navigation': [true, 'Navigate to the beginning / end of a thread']
'Thread Watcher': [true, 'Bookmark threads']
'Thread Expansion': [true, 'View all replies']
'Comment Expansion': [true, 'Expand too long comments']
'Quick Report': [true, 'Add quick report buttons']
'Quick Reply': [true, 'Reply without leaving the page']
'Persistent QR': [false, 'Quick reply won\'t disappear after posting. Only in replies.']
'Anonymize': [false, 'Make everybody anonymous']
'Auto Watch': [true, 'Automatically watch threads that you start (Firefox only)']
'404 Redirect': [true, 'Redirect dead threads']
'Post in Title': [true, 'Show the op\'s post in the tab title']
'Sauce': [true, 'Add sauce to images']
#utility
AEOS =
init: ->
#x-browser
unless GM_deleteValue?
window.GM_setValue = (name, value) ->
value = (typeof value)[0] + value
localStorage.setItem name, value
window.GM_getValue = (name, defaultValue) ->
unless value = localStorage.getItem name
return defaultValue
type = value[0]
value = value.substring 1
switch type
when 'b'
return value == 'true'
when 'n'
return Number value
else
return value
window.GM_addStyle = (css) ->
style = document.createElement 'style'
style.type = 'text/css'
style.textContent = css
document.getElementsByTagName('head')[0].appendChild style
#dialog styling
GM_addStyle '
div.dialog {
border: 1px solid;
}
div.dialog > div.move {
cursor: move;
}
div.dialog label,
div.dialog a {
cursor: pointer;
}
'
#dialog creation
makeDialog: (id, position) ->
dialog = document.createElement 'div'
dialog.className = 'reply dialog'
dialog.id = id
switch position
when 'topleft'
left = '0px'
top = '0px'
when 'topright'
left = null
top = '0px'
when 'bottomleft'
left = '0px'
top = null
when 'bottomright'
left = null
top = null
left = GM_getValue "#{id}Left", left
top = GM_getValue "#{id}Top", top
if left then dialog.style.left = left else dialog.style.right = '0px'
if top then dialog.style.top = top else dialog.style.bottom = '0px'
dialog
#movement
move: (e) ->
div = @parentNode
AEOS.div = div
#distance from pointer to div edge is constant; calculate it here.
AEOS.dx = e.clientX - div.offsetLeft
AEOS.dy = e.clientY - div.offsetTop
#factor out div from document dimensions
AEOS.width = document.body.clientWidth - div.offsetWidth
AEOS.height = document.body.clientHeight - div.offsetHeight
document.addEventListener 'mousemove', AEOS.moveMove, true
document.addEventListener 'mouseup', AEOS.moveEnd, true
moveMove: (e) ->
div = AEOS.div
left = e.clientX - AEOS.dx
if left < 20 then left = '0px'
else if AEOS.width - left < 20 then left = ''
right = if left then '' else '0px'
div.style.left = left
div.style.right = right
top = e.clientY - AEOS.dy
if top < 20 then top = '0px'
else if AEOS.height - top < 20 then top = ''
bottom = if top then '' else '0px'
div.style.top = top
div.style.bottom = bottom
moveEnd: ->
document.removeEventListener 'mousemove', AEOS.moveMove, true
document.removeEventListener 'mouseup', AEOS.moveEnd, true
div = AEOS.div
id = div.id
GM_setValue "#{id}Left", div.style.left
GM_setValue "#{id}Top", div.style.top
d = document
g = null #globals
$ = (selector, root) ->
root or= d.body
root.querySelector selector
$$ = (selector, root) ->
root or= d.body
result = root.querySelectorAll selector
#magic that turns the results object into an array:
node for node in result
addTo = (parent, children...) ->
for child in children
parent.appendChild child
getConfig = (name) ->
GM_getValue name, config[name][0]
getTime = ->
Math.floor(new Date().getTime() / 1000)
hide = (el) ->
el.style.display = 'none'
inAfter = (root, el) ->
root.parentNode.insertBefore el, root.nextSibling
inBefore = (root, el) ->
root.parentNode.insertBefore el, root
m = (el, props) -> #mod
if l = props.listener
delete props.listener
[event, funk] = l
el.addEventListener event, funk, true
(el[key] = val) for key, val of props
el
n = (tag, props) -> #new
el = d.createElement tag
if props then m el, props
el
remove = (el) ->
el.parentNode.removeChild el
replace = (root, el) ->
root.parentNode.replaceChild el, root
show = (el) ->
el.style.display = ''
slice = (arr, id) ->
# the while loop is the only low-level loop left in coffeescript.
# we need to use it to see the index.
# would it be better to just use objects and the `delete` keyword?
i = 0
l = arr.length
while (i < l)
if id == arr[i].id
arr.splice i, 1
return arr
i++
tn = (s) ->
d.createTextNode s
x = (path, root) ->
root or= d.body
d.evaluate(path, root, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).
singleNodeValue
#funks
autohide = ->
qr = $ '#qr'
klass = qr.className
if klass.indexOf('auto') is -1
klass += ' auto'
else
klass = klass.replace(' auto', '')
qr.className = klass
autoWatch = ->
#TODO look for subject
autoText = $('textarea', this).value.slice(0, 25)
GM_setValue('autoText', "/#{g.BOARD}/ - #{autoText}")
closeQR = ->
div = this.parentNode.parentNode
remove div
if not g.REPLY and getConfig 'Keyboard Navigation'
d.addEventListener 'keydown', keyboardNav, true
clearHidden = ->
#'hidden' might be misleading; it's the number of IDs we're *looking* for,
# not the number of posts actually hidden on the page.
GM_deleteValue("hiddenReplies/#{g.BOARD}/")
GM_deleteValue("hiddenThreads/#{g.BOARD}/")
@value = "hidden: 0"
g.hiddenReplies = []
g.hiddenThreads = []
cooldown = ->
submit = $ '#qr input[type=submit]'
seconds = parseInt submit.value
if seconds == 0
submit.disabled = false
submit.value = 'Submit'
auto = submit.previousSibling.lastChild
if auto.checked
$('#qr form').submit()
#submit.click() doesn't work
else
submit.value = seconds - 1
window.setTimeout cooldown, 1000
editSauce = ->
ta = $ '#options textarea'
if ta.style.display then show ta else hide ta
expandComment = (e) ->
e.preventDefault()
a = this
href = a.getAttribute('href')
r = new XMLHttpRequest()
r.onload = ->
onloadComment(this.responseText, a, href)
r.open('GET', href, true)
r.send()
g.xhrs.push {
r: r,
id: href.match(/\d+/)[0]
}
expandThread = ->
id = x('preceding-sibling::input[1]', this).name
span = this
#close expanded thread
if span.textContent[0] is '-'
#goddamit moot
num = if board is 'b' then 3 else 5
table = x "following::br[@clear][1]/preceding::table[#{num}]", span
while (prev = table.previousSibling) and (prev.nodeName is 'TABLE')
remove prev
span.textContent = span.textContent.replace '-', '+'
return
span.textContent = span.textContent.replace '+', 'X Loading...'
#load cache
for xhr in g.xhrs
if xhr.id == id
#why can't we just xhr.r.onload()?
onloadThread xhr.r.responseText, span
return
#create new request
r = new XMLHttpRequest()
r.onload = ->
onloadThread this.responseText, span
r.open 'GET', "res/#{id}", true
r.send()
g.xhrs.push {
r: r,
id: id
}
formSubmit = (e) ->
if span = @nextSibling
remove(span)
recaptcha = $('input[name=recaptcha_response_field]', this)
if recaptcha.value
$('#qr input[title=autohide]:not(:checked)')?.click()
else
e.preventDefault()
span = n 'span',
className: 'error'
textContent: 'You forgot to type in the verification.'
addTo @parentNode, span
alert 'You forgot to type in the verification.'
recaptcha.focus()
hideReply = (reply) ->
if p = this.parentNode
reply = p.nextSibling
g.hiddenReplies.push {
id: reply.id
timestamp: getTime()
}
GM_setValue("hiddenReplies/#{g.BOARD}/", JSON.stringify(g.hiddenReplies))
name = $('span.commentpostername', reply).textContent
trip = $('span.postertrip', reply)?.textContent or ''
table = x 'ancestor::table', reply
hide table
if getConfig 'Show Stubs'
a = n 'a',
textContent: "[ + ] #{name} #{trip}"
className: 'pointer'
listener: ['click', showReply]
div = n 'div'
addTo div, a
inBefore table, div
hideThread = (div) ->
if p = @parentNode
div = p
g.hiddenThreads.push {
id: div.id
timestamp: getTime()
}
GM_setValue("hiddenThreads/#{g.BOARD}/", JSON.stringify(g.hiddenThreads))
hide div
if getConfig 'Show Stubs'
if span = $ '.omittedposts', div
num = Number(span.textContent.match(/\d+/)[0])
else
num = 0
num += $$('table', div).length
text = if num is 1 then "1 reply" else "#{num} replies"
name = $('span.postername', div).textContent
trip = $('span.postername + span.postertrip', div)?.textContent || ''
a = n 'a',
textContent: "[ + ] #{name}#{trip} (#{text})"
className: 'pointer'
listener: ['click', showThread]
inBefore div, a
iframeLoad = ->
if g.iframe = !g.iframe
return
$('iframe').src = 'about:blank'
qr = $ '#qr'
if error = GM_getValue 'error'
span = n 'span',
textContent: error
className: 'error'
addTo qr, span
$('input[title=autohide]:checked', qr)?.click()
else if g.REPLY and getConfig 'Persistent QR'
$('textarea', qr).value = ''
$('input[name=recaptcha_response_field]', qr).value = ''
submit = $ 'input[type=submit]', qr
submit.value = 30
submit.disabled = true
window.setTimeout cooldown, 1000
auto = submit.previousSibling.lastChild
if auto.checked
#unhide the qr so you know it's ready for the next item
$('input[title=autohide]:checked', qr)?.click()
else
remove qr
if not g.REPLY and getConfig 'Keyboard Navigation'
d.addEventListener 'keydown', keyboardNav, true
recaptchaReload()
keyboardNav = (e) ->
char = String.fromCharCode e.keyCode
unless char in '1234567890GHJKL'
return
e.preventDefault()
hash = location.hash
if not hash or hash == '#navtop'
position = 0
else
position = Number(hash.substring 2) or 0
count = g.count
if char in '1234567890'
temp = Number char
if temp is 0 and count is 0 # special - immediately go to page 0
location.pathname = "/#{g.BOARD}/#1"
else
g.count = (count * 10) + temp
return
if char is "G"
if count
temp = if count > 15 then 15 else count
location.pathname = "/#{g.BOARD}/#{temp}#1"
else
if e.shiftKey
location.hash = 10
else
location.hash = 'navtop'
count or= 1
switch char
when "H"
temp = g.PAGENUM - count
if temp < 0 then temp = 0
location.pathname = "/#{g.BOARD}/#{temp}#1"
when "J"
temp = position + count
if temp > 10 then temp = 10
location.hash = 'p' + temp
when "K"
temp = position - count
if temp <= 0 then temp = 'navtop' else temp = 'p' + temp
location.hash = temp
when "L"
temp = g.PAGENUM + count
if temp > 15 then temp = 15
location.pathname = "/#{g.BOARD}/#{temp}#1"
g.count = 0
nodeInserted = (e) ->
target = e.target
if target.nodeName is 'TABLE'
for callback in g.callbacks
callback target
else if target.id is 'recaptcha_challenge_field' and qr = $ '#qr'
$('#recaptcha_image img', qr).src = "http://www.google.com/recaptcha/api/image?c=" + target.value
$('#recaptcha_challenge_field', qr).value = target.value
onloadComment = (responseText, a, href) ->
[_, op, id] = href.match /(\d+)#(\d+)/
[replies, opbq] = parseResponse responseText
if id is op
html = opbq.innerHTML
else
#css selectors don't like ids starting with numbers,
# getElementById only works for root document.
for reply in replies
if reply.id == id
html = $('blockquote', reply).innerHTML
bq = x 'ancestor::blockquote', a
bq.innerHTML = html
onloadThread = (responseText, span) ->
[replies, opbq] = parseResponse responseText
span.textContent = span.textContent.replace 'X Loading...', '- '
#make sure all comments are fully expanded
span.previousSibling.innerHTML = opbq.innerHTML
while (next = span.nextSibling) and not next.clear#
remove next
if next
for reply in replies
inBefore next, x('ancestor::table', reply)
else#threading
div = span.parentNode
for reply in replies
addTo div, x 'ancestor::table', reply
options = ->
if div = $ '#options'
remove div
else
div = AEOS.makeDialog 'options', 'center'
hiddenNum = g.hiddenReplies.length + g.hiddenThreads.length
html = '