This repository has been archived by the owner on Aug 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 88
/
script.coffee
4720 lines (4306 loc) · 147 KB
/
script.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Config =
main:
Enhancing:
'404 Redirect': [true, 'Redirect dead threads and images']
'Keybinds': [true, 'Binds actions to keys']
'Time Formatting': [true, 'Arbitrarily formatted timestamps, using your local time']
'File Info Formatting': [true, 'Reformats the file information']
'Comment Expansion': [true, 'Expand too long comments']
'Thread Expansion': [true, 'View all replies']
'Index Navigation': [true, 'Navigate to previous / next thread']
'Rollover': [true, 'Index navigation will fallback to page navigation.']
'Reply Navigation': [false, 'Navigate to top / bottom of thread']
Filtering:
'Anonymize': [false, 'Make everybody anonymous']
'Filter': [true, 'Self-moderation placebo']
'Recursive Filtering': [true, 'Filter replies of filtered posts, recursively']
'Reply Hiding': [true, 'Hide single replies']
'Thread Hiding': [true, 'Hide entire threads']
'Show Stubs': [true, 'Of hidden threads / replies']
Imaging:
'Image Auto-Gif': [false, 'Animate gif thumbnails']
'Image Expansion': [true, 'Expand images']
'Image Hover': [false, 'Show full image on mouseover']
'Sauce': [true, 'Add sauce to images']
'Reveal Spoilers': [false, 'Replace spoiler thumbnails by the original thumbnail']
'Expand From Current': [false, 'Expand images from current position to thread end.']
Menu:
'Menu': [true, 'Add a drop-down menu in posts.']
'Report Link': [true, 'Add a report link to the menu.']
'Delete Link': [true, 'Add post and image deletion links to the menu.']
'Download Link': [true, 'Add a download with original filename link to the menu. Chrome-only currently.']
'Archive Link': [true, 'Add an archive link to the menu.']
Monitoring:
'Thread Updater': [true, 'Update threads. Has more options in its own dialog.']
'Unread Count': [true, 'Show unread post count in tab title']
'Unread Favicon': [true, 'Show a different favicon when there are unread posts']
'Post in Title': [true, 'Show the op\'s post in the tab title']
'Thread Stats': [true, 'Display reply and image count']
'Thread Watcher': [true, 'Bookmark threads']
'Auto Watch': [true, 'Automatically watch threads that you start']
'Auto Watch Reply': [false, 'Automatically watch threads that you reply to']
Posting:
'Quick Reply': [true, 'Reply without leaving the page.']
'Cooldown': [true, 'Prevent "flood detected" errors.']
'Persistent QR': [false, 'The Quick reply won\'t disappear after posting.']
'Auto Hide QR': [true, 'Automatically hide the quick reply when posting.']
'Open Reply in New Tab': [false, 'Open replies in a new tab that are made from the main board.']
'Remember QR size': [false, 'Remember the size of the Quick reply (Firefox only).']
'Remember Subject': [false, 'Remember the subject field, instead of resetting after posting.']
'Remember Spoiler': [false, 'Remember the spoiler state, instead of resetting after posting.']
'Hide Original Post Form': [true, 'Replace the normal post form with a shortcut to open the QR.']
Quoting:
'Quote Backlinks': [true, 'Add quote backlinks']
'OP Backlinks': [false, 'Add backlinks to the OP']
'Quote Highlighting': [true, 'Highlight the previewed post']
'Quote Inline': [true, 'Show quoted post inline on quote click']
'Quote Preview': [true, 'Show quote content on hover']
'Resurrect Quotes': [true, 'Linkify dead quotes to archives']
'Indicate OP quote': [true, 'Add \'(OP)\' to OP quotes']
'Indicate Cross-thread Quotes': [true, 'Add \'(Cross-thread)\' to cross-threads quotes']
'Forward Hiding': [true, 'Hide original posts of inlined backlinks']
'Quote Threading': [false, 'Thread conversations']
filter:
name: [
'# Filter any namefags:'
'#/^(?!Anonymous$)/'
].join '\n'
uniqueid: [
'# Filter a specific ID:'
'#/Txhvk1Tl/'
].join '\n'
tripcode: [
'# Filter any tripfags'
'#/^!/'
].join '\n'
mod: [
'# Set a custom class for mods:'
'#/Mod$/;highlight:mod;op:yes'
'# Set a custom class for moot:'
'#/Admin$/;highlight:moot;op:yes'
].join '\n'
email: [
'# Filter any e-mails that are not `sage` on /a/ and /jp/:'
'#/^(?!sage$)/;boards:a,jp'
].join '\n'
subject: [
'# Filter Generals on /v/:'
'#/general/i;boards:v;op:only'
].join '\n'
comment: [
'# Filter Stallman copypasta on /g/:'
'#/what you\'re refer+ing to as linux/i;boards:g'
].join '\n'
country: [
''
].join '\n'
filename: [
''
].join '\n'
dimensions: [
'# Highlight potential wallpapers:'
'#/1920x1080/;op:yes;highlight;top:no;boards:w,wg'
].join '\n'
filesize: [
''
].join '\n'
md5: [
''
].join '\n'
sauces: [
'http://iqdb.org/?url=$1'
'http://www.google.com/searchbyimage?image_url=$1'
'#http://tineye.com/search?url=$1'
'#http://saucenao.com/search.php?db=999&url=$1'
'#http://3d.iqdb.org/?url=$1'
'#http://regex.info/exif.cgi?imgurl=$2'
'# uploaders:'
'#http://imgur.com/upload?url=$2;text:Upload to imgur'
'#http://omploader.org/upload?url1=$2;text:Upload to omploader'
'# "View Same" in archives:'
'#http://archive.foolz.us/search/image/$3/;text:View same on foolz'
'#http://archive.foolz.us/$4/search/image/$3/;text:View same on foolz /$4/'
'#https://archive.installgentoo.net/$4/image/$3;text:View same on installgentoo /$4/'
].join '\n'
time: '%m/%d/%y(%a)%H:%M'
backlink: '>>%id'
fileInfo: '%l (%p%s, %r)'
favicon: 'ferongr'
hotkeys:
# QR & Options
openQR: ['i', 'Open QR with post number inserted']
openEmptyQR: ['I', 'Open QR without post number inserted']
openOptions: ['ctrl+o', 'Open Options']
close: ['Esc', 'Close Options or QR']
spoiler: ['ctrl+s', 'Quick spoiler tags']
code: ['alt+c', 'Quick code tags']
sage: ['alt+g', 'Sage keybind']
submit: ['alt+s', 'Submit post']
# Thread related
watch: ['w', 'Watch thread']
update: ['u', 'Update now']
unreadCountTo0: ['z', 'Reset unread status']
threading: ['t', 'Toggle threading']
# Images
expandImage: ['m', 'Expand selected image']
expandAllImages: ['M', 'Expand all images']
# Board Navigation
zero: ['0', 'Jump to page 0']
nextPage: ['L', 'Jump to the next page']
previousPage: ['H', 'Jump to the previous page']
# Thread Navigation
nextThread: ['n', 'See next thread']
previousThread: ['p', 'See previous thread']
expandThread: ['e', 'Expand thread']
openThreadTab: ['o', 'Open thread in new tab']
openThread: ['O', 'Open thread in current tab']
# Reply Navigation
nextReply: ['J', 'Select next reply']
previousReply: ['K', 'Select previous reply']
hide: ['x', 'Hide thread']
updater:
checkbox:
'Scrolling': [false, 'Scroll updated posts into view. Only enabled at bottom of page.']
'Scroll BG': [false, 'Scroll background tabs']
'Verbose': [true, 'Show countdown timer, new post count']
'Auto Update': [true, 'Automatically fetch new posts']
'Interval': 30
'Max Interval': 600
Conf = {}
d = document
g = {}
# XXX GreaseMonkey can't into console.log.bind
log = console.log.bind? console
UI =
dialog: (id, position, html) ->
el = d.createElement 'div'
el.className = 'reply dialog'
el.innerHTML = html
el.id = id
el.style.cssText = localStorage.getItem("#{Main.namespace}#{id}.position") or position
el.querySelector('.move')?.addEventListener 'mousedown', UI.dragstart, false
el
dragstart: (e) ->
#prevent text selection
e.preventDefault()
UI.el = el = @parentNode
d.addEventListener 'mousemove', UI.drag, false
d.addEventListener 'mouseup', UI.dragend, false
# distance from pointer to el edge is constant; calculate it here.
rect = el.getBoundingClientRect()
UI.dx = e.clientX - rect.left
UI.dy = e.clientY - rect.top
UI.width = d.documentElement.clientWidth - rect.width
UI.height = d.documentElement.clientHeight - rect.height
drag: (e) ->
left = e.clientX - UI.dx
top = e.clientY - UI.dy
left =
if left < 10 then '0px'
else if UI.width - left < 10 then null
else left + 'px'
top =
if top < 10 then '0px'
else if UI.height - top < 10 then null
else top + 'px'
#using null instead of '' is 4% faster
#these 4 statements are 40% faster than 1 style.cssText
{style} = UI.el
style.left = left
style.top = top
style.right = if left is null then '0px' else null
style.bottom = if top is null then '0px' else null
dragend: ->
localStorage.setItem "#{Main.namespace}#{UI.el.id}.position", UI.el.style.cssText
d.removeEventListener 'mousemove', UI.drag, false
d.removeEventListener 'mouseup', UI.dragend, false
delete UI.el
hover: (e) ->
{clientX, clientY} = e
{style} = UI.el
{clientHeight, clientWidth} = d.documentElement
height = UI.el.offsetHeight
top = clientY - 120
style.top =
if clientHeight <= height or top <= 0
'0px'
else if top + height >= clientHeight
clientHeight - height + 'px'
else
top + 'px'
if clientX <= clientWidth - 400
style.left = clientX + 45 + 'px'
style.right = null
else
style.left = null
style.right = clientWidth - clientX + 45 + 'px'
hoverend: ->
$.rm UI.el
delete UI.el
###
loosely follows the jquery api:
http://api.jquery.com/
not chainable
###
$ = (selector, root=d.body) ->
root.querySelector selector
$.extend = (object, properties) ->
for key, val of properties
object[key] = val
return
$.extend $,
NBSP: '\u00A0'
SECOND: 1000
MINUTE: 1000*60
HOUR : 1000*60*60
DAY : 1000*60*60*24
engine: /WebKit|Presto|Gecko/.exec(navigator.userAgent)[0].toLowerCase()
ready: (fc) ->
if /interactive|complete/.test d.readyState
# Execute the functions in parallel.
# If one fails, do not stop the others.
return setTimeout fc
cb = ->
$.off d, 'DOMContentLoaded', cb
fc()
$.on d, 'DOMContentLoaded', cb
sync: (key, cb) ->
$.on window, 'storage', (e) ->
cb JSON.parse e.newValue if e.key is "#{Main.namespace}#{key}"
id: (id) ->
d.getElementById id
formData: (arg) ->
if arg instanceof HTMLFormElement
fd = new FormData arg
else
fd = new FormData()
for key, val of arg
fd.append key, val if val
fd
ajax: (url, callbacks, opts={}) ->
#XXX `form` should be `data`
{type, headers, upCallbacks, form} = opts
r = new XMLHttpRequest()
type or= form and 'post' or 'get'
r.open type, url, true
for key, val of headers
r.setRequestHeader key, val
$.extend r, callbacks
$.extend r.upload, upCallbacks
r.send form
r
cache: (url, cb) ->
if req = $.cache.requests[url]
if req.readyState is 4
cb.call req
else
req.callbacks.push cb
else
req = $.ajax url,
onload: -> cb.call @ for cb in @callbacks
onabort: -> delete $.cache.requests[url]
onerror: -> delete $.cache.requests[url]
req.callbacks = [cb]
$.cache.requests[url] = req
cb:
checked: ->
$.set @name, @checked
Conf[@name] = @checked
value: ->
$.set @name, @value.trim()
Conf[@name] = @value
addStyle: (css) ->
style = $.el 'style',
textContent: css
$.add d.head, style
style
x: (path, root=d.body) ->
d.evaluate(path, root, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).
singleNodeValue
X: (path, root=d.body) ->
d.evaluate(path, root, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null)
addClass: (el, className) ->
el.classList.add className
rmClass: (el, className) ->
el.classList.remove className
rm: (el) ->
el.parentNode.removeChild el
tn: (s) ->
d.createTextNode s
nodes: (nodes) ->
# In (at least) Chrome, elements created inside different
# scripts/window contexts inherit from unequal prototypes.
# window_ext1.Node !== window_ext2.Node
unless nodes instanceof Array
return nodes
frag = d.createDocumentFragment()
for node in nodes
frag.appendChild node
frag
add: (parent, children) ->
parent.appendChild $.nodes children
prepend: (parent, children) ->
parent.insertBefore $.nodes(children), parent.firstChild
after: (root, el) ->
root.parentNode.insertBefore $.nodes(el), root.nextSibling
before: (root, el) ->
root.parentNode.insertBefore $.nodes(el), root
replace: (root, el) ->
root.parentNode.replaceChild $.nodes(el), root
el: (tag, properties) ->
el = d.createElement tag
$.extend el, properties if properties
el
on: (el, events, handler) ->
for event in events.split ' '
el.addEventListener event, handler, false
return
off: (el, events, handler) ->
for event in events.split ' '
el.removeEventListener event, handler, false
return
event: (el, e) ->
el.dispatchEvent e
globalEval: (code) ->
script = $.el 'script', textContent: "(#{code})()"
$.add d.head, script
$.rm script
bytesToString: (size) ->
unit = 0 # Bytes
while size >= 1024
size /= 1024
unit++
# Remove trailing 0s.
size =
if unit > 1
# Keep the size as a float if the size is greater than 2^20 B.
# Round to hundredth.
Math.round(size * 100) / 100
else
# Round to an integer otherwise.
Math.round size
"#{size} #{['B', 'KB', 'MB', 'GB'][unit]}"
RandomAccessList: class
constructor: ->
@first = null
@last = null
@length = 0
push: (id, el) ->
{last} = @
@[id] = item =
prev: last
next: null
el: el
id: id
@last = item
if last
last.next = item
else
@first = item
@length++
shift: ->
@rm @first.id
after: (root, item) ->
return if item.prev is root
@rmi item
{next} = root
root.next = item
item.prev = root
item.next = next
next.prev = item
rm: (id) ->
item = @[id]
return unless item
delete @[id]
@length--
@rmi item
rmi: (item) ->
{prev, next} = item
if prev
prev.next = next
else
@first = next
if next
next.prev = prev
else
@last = prev
$.cache.requests = {}
$.extend $,
if GM_deleteValue?
delete: (name) ->
name = Main.namespace + name
GM_deleteValue name
get: (name, defaultValue) ->
name = Main.namespace + name
if value = GM_getValue name
JSON.parse value
else
defaultValue
set: (name, value) ->
name = Main.namespace + name
# for `storage` events
localStorage.setItem name, JSON.stringify value
GM_setValue name, JSON.stringify value
open: (url) ->
#https://github.com/scriptish/scriptish/wiki/GM_openInTab
#string url, bool loadInBackground, bool reuseTab
GM_openInTab location.protocol + url, true
else
delete: (name) ->
localStorage.removeItem Main.namespace + name
get: (name, defaultValue) ->
if value = localStorage.getItem Main.namespace + name
JSON.parse value
else
defaultValue
set: (name, value) ->
localStorage.setItem Main.namespace + name, JSON.stringify value
open: (url) ->
window.open location.protocol + url, '_blank'
$$ = (selector, root=d.body) ->
Array::slice.call root.querySelectorAll selector
Filter =
filters: {}
init: ->
for key of Config.filter
@filters[key] = []
for filter in Conf[key].split '\n'
continue if filter[0] is '#'
unless regexp = filter.match /\/(.+)\/(\w*)/
continue
# Don't mix up filter flags with the regular expression.
filter = filter.replace regexp[0], ''
# Do not add this filter to the list if it's not a global one
# and it's not specifically applicable to the current board.
# Defaults to global.
boards = filter.match(/boards:([^;]+)/)?[1].toLowerCase() or 'global'
if boards isnt 'global' and boards.split(',').indexOf(g.BOARD) is -1
continue
try
if key is 'md5'
# MD5 filter will use strings instead of regular expressions.
regexp = regexp[1]
else
# Please, don't write silly regular expressions.
regexp = RegExp regexp[1], regexp[2]
catch e
# I warned you, bro.
alert e.message
continue
# Filter OPs along with their threads, replies only, or both.
# Defaults to replies only.
op = filter.match(/[^t]op:(yes|no|only)/)?[1] or 'no'
# Overrule the `Show Stubs` setting.
# Defaults to stub showing.
stub = switch filter.match(/stub:(yes|no)/)?[1]
when 'yes'
true
when 'no'
false
else
Conf['Show Stubs']
# Highlight the post, or hide it.
# If not specified, the highlight class will be filter_highlight.
# Defaults to post hiding.
if hl = /highlight/.test filter
hl = filter.match(/highlight:(\w+)/)?[1] or 'filter_highlight'
# Put highlighted OP's thread on top of the board page or not.
# Defaults to on top.
top = filter.match(/top:(yes|no)/)?[1] or 'yes'
top = top is 'yes' # Turn it into a boolean
@filters[key].push @createFilter regexp, op, stub, hl, top
# Only execute filter types that contain valid filters.
unless @filters[key].length
delete @filters[key]
if Object.keys(@filters).length
Main.callbacks.push @node
createFilter: (regexp, op, stub, hl, top) ->
test =
if typeof regexp is 'string'
# MD5 checking
(value) -> regexp is value
else
(value) -> regexp.test value
settings =
hide: !hl
stub: stub
class: hl
top: top
(value, isOP) ->
if isOP and op is 'no' or !isOP and op is 'only'
return false
unless test value
return false
settings
node: (post) ->
return if post.isInlined
isOP = post.ID is post.threadID
{root} = post
for key of Filter.filters
value = Filter[key] post
if value is false
# Continue if there's nothing to filter (no tripcode for example).
continue
for filter in Filter.filters[key]
unless result = filter value, isOP
continue
# Hide
if result.hide
if isOP
unless g.REPLY
ThreadHiding.hide root.parentNode, result.stub
else
continue
else
ReplyHiding.hide post.root, result.stub
return
# Highlight
$.addClass root, result.class
name: (post) ->
$('.name', post.el).textContent
uniqueid: (post) ->
if uid = $ '.posteruid', post.el
return uid.textContent[5...-1]
false
tripcode: (post) ->
if trip = $ '.postertrip', post.el
return trip.textContent
false
mod: (post) ->
if mod = $ '.capcode', post.el
return mod.textContent
false
email: (post) ->
if mail = $ '.useremail', post.el
# remove 'mailto:'
# decode %20 into space for example
return decodeURIComponent mail.href[7..]
false
subject: (post) ->
$('.postInfo .subject', post.el).textContent or false
comment: (post) ->
text = []
nodes = d.evaluate './/br|.//text()', post.blockquote, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
for i in [0...nodes.snapshotLength]
text.push if data = nodes.snapshotItem(i).data then data else '\n'
text.join ''
country: (post) ->
if flag = $ '.countryFlag', post.el
return flag.title
false
filename: (post) ->
{fileInfo} = post
if fileInfo
if file = $ '.fileText > span', fileInfo
return file.title
else
return fileInfo.firstElementChild.dataset.filename
false
dimensions: (post) ->
{fileInfo} = post
if fileInfo and match = fileInfo.textContent.match /\d+x\d+/
return match[0]
false
filesize: (post) ->
{img} = post
if img
return img.alt
false
md5: (post) ->
{img} = post
if img
return img.dataset.md5
false
menuInit: ->
div = $.el 'div',
textContent: 'Filter'
entry =
el: div
open: -> true
children: []
for type in [
['Name', 'name']
['Unique ID', 'uniqueid']
['Tripcode', 'tripcode']
['Admin/Mod', 'mod']
['E-mail', 'email']
['Subject', 'subject']
['Comment', 'comment']
['Country', 'country']
['Filename', 'filename']
['Image dimensions', 'dimensions']
['Filesize', 'filesize']
['Image MD5', 'md5']
]
# Add a sub entry for each filter type.
entry.children.push Filter.createSubEntry type[0], type[1]
Menu.addEntry entry
createSubEntry: (text, type) ->
el = $.el 'a',
href: 'javascript:;'
textContent: text
# Define the onclick var outside of open's scope to $.off it properly.
onclick = null
open = (post) ->
value = Filter[type] post
return false if value is false
$.off el, 'click', onclick
onclick = ->
# Convert value -> regexp, unless type is md5
re = if type is 'md5' then value else value.replace ///
/
| \\
| \^
| \$
| \n
| \.
| \(
| \)
| \{
| \}
| \[
| \]
| \?
| \*
| \+
| \|
///g, (c) ->
if c is '\n'
'\\n'
else if c is '\\'
'\\\\'
else
"\\#{c}"
re =
if type is 'md5'
"/#{value}/"
else
"/^#{re}$/"
if /\bop\b/.test post.class
re += ';op:yes'
# Add a new line before the regexp unless the text is empty.
save = if save = $.get type, '' then "#{save}\n#{re}" else re
$.set type, save
# Open the options and display & focus the relevant filter textarea.
Options.dialog()
select = $ 'select[name=filter]', $.id 'options'
select.value = type
$.event select, new Event 'change'
$.id('filter_tab').checked = true
ta = select.nextElementSibling
tl = ta.textLength
ta.setSelectionRange tl, tl
ta.focus()
$.on el, 'click', onclick
true
return el: el, open: open
StrikethroughQuotes =
init: ->
Main.callbacks.push @node
node: (post) ->
return if post.isInlined
for quote in post.quotes
if (el = $.id quote.hash[1..]) and el.hidden
$.addClass quote, 'filtered'
if Conf['Recursive Filtering']
show_stub = !!$.x 'preceding-sibling::div[contains(@class,"stub")]', el
ReplyHiding.hide post.root, show_stub
return
ExpandComment =
init: ->
for a in $$ '.abbr'
$.on a.firstElementChild, 'click', ExpandComment.expand
return
expand: (e) ->
e.preventDefault()
[_, threadID, replyID] = @href.match /(\d+)#p(\d+)/
@textContent = "Loading #{replyID}..."
a = @
$.cache @pathname, -> ExpandComment.parse @, a, threadID, replyID
parse: (req, a, threadID, replyID) ->
if req.status isnt 200
a.textContent = "#{req.status} #{req.statusText}"
return
doc = d.implementation.createHTMLDocument ''
doc.documentElement.innerHTML = req.response
# Import the node to fix quote.hashes
# as they're empty when in a different document.
node = d.importNode doc.getElementById("m#{replyID}"), true
quotes = node.getElementsByClassName 'quotelink'
for quote in quotes
href = quote.getAttribute 'href'
continue if href[0] is '/' # Cross-board quote
quote.href = "res/#{href}" # Fix pathnames
post =
blockquote: node
threadID: threadID
quotes: quotes
backlinks: []
if Conf['Resurrect Quotes']
Quotify.node post
if Conf['Quote Preview']
QuotePreview.node post
if Conf['Quote Inline']
QuoteInline.node post
if Conf['Indicate OP quote']
QuoteOP.node post
if Conf['Indicate Cross-thread Quotes']
QuoteCT.node post
$.replace a.parentNode.parentNode, node
Main.prettify node
ExpandThread =
init: ->
for span in $$ '.summary'
a = $.el 'a',
textContent: "+ #{span.textContent}"
className: 'summary desktop'
href: 'javascript:;'
$.on a, 'click', -> ExpandThread.toggle @parentNode
$.replace span, a
toggle: (thread) ->
pathname = "/#{g.BOARD}/res/#{thread.id[1..]}"
a = $ '.summary', thread
switch a.textContent[0]
when '+'
a.textContent = a.textContent.replace '+', 'X Loading...'
$.cache pathname, -> ExpandThread.parse @, thread, a
when 'X'
a.textContent = a.textContent.replace 'X Loading...', '+'
$.cache.requests[pathname].abort()
when '-'
a.textContent = a.textContent.replace '-', '+'
#goddamit moot
num = switch g.BOARD
when 'b', 'vg' then 3
when 't' then 1
else 5
replies = $$ '.replyContainer', thread
replies.splice replies.length - num, num
for reply in replies
$.rm reply
return
parse: (req, thread, a) ->
if req.status isnt 200
a.textContent = "#{req.status} #{req.statusText}"
$.off a, 'click', ExpandThread.cb.toggle
return
a.textContent = a.textContent.replace 'X Loading...', '-'
doc = d.implementation.createHTMLDocument ''
doc.documentElement.innerHTML = req.response
threadID = thread.id[1..]
nodes = []
for reply in $$ '.replyContainer', doc
reply = d.importNode reply, true
for quote in $$ '.quotelink', reply
href = quote.getAttribute 'href'
continue if href[0] is '/' # Cross-board quote
quote.href = "res/#{href}" # Fix pathnames
id = reply.id[2..]
link = $ 'a[title="Highlight this post"]', reply
link.href = "res/#{threadID}#p#{id}"
link.nextSibling.href = "res/#{threadID}#q#{id}"
nodes.push reply
# eat everything, then replace with fresh full posts
for post in $$ '.summary ~ .replyContainer', a.parentNode
$.rm post
for backlink in $$ '.backlink', a.previousElementSibling
# Keep backlinks from other threads.
$.rm backlink unless $.id backlink.hash[1..]
$.after a, nodes
ThreadHiding =
init: ->
hiddenThreads = $.get "hiddenThreads/#{g.BOARD}/", {}
for thread in $$ '.thread'
a = $.el 'a',
className: 'hide_thread_button'
innerHTML: '<span>[ - ]</span>'
href: 'javascript:;'
$.on a, 'click', ThreadHiding.cb
$.prepend thread, a
if thread.id[1..] of hiddenThreads
ThreadHiding.hide thread
return
cb: ->
ThreadHiding.toggle $.x 'ancestor::div[parent::div[@class="board"]]', @
toggle: (thread) ->
hiddenThreads = $.get "hiddenThreads/#{g.BOARD}/", {}
id = thread.id[1..]
if thread.hidden or /\bhidden_thread\b/.test thread.firstChild.className
ThreadHiding.show thread
delete hiddenThreads[id]
else
ThreadHiding.hide thread
hiddenThreads[id] = Date.now()
$.set "hiddenThreads/#{g.BOARD}/", hiddenThreads
hide: (thread, show_stub=Conf['Show Stubs']) ->
unless show_stub
thread.hidden = true
thread.nextElementSibling.hidden = true
return
return if /\bhidden_thread\b/.test thread.firstChild.className # already hidden once by the filter
num = 0
if span = $ '.summary', thread
num = Number span.textContent.match /\d+/
num += $$('.opContainer ~ .replyContainer', thread).length
text = if num is 1 then '1 reply' else "#{num} replies"
opInfo = $('.op > .postInfo > .nameBlock', thread).textContent
stub = $.el 'div',
className: 'hide_thread_button hidden_thread'
innerHTML: '<a href="javascript:;"><span>[ + ]</span> </a>'
a = stub.firstChild
$.on a, 'click', ThreadHiding.cb
$.add a, $.tn "#{opInfo} (#{text})"
if Conf['Menu']
menuButton = Menu.a.cloneNode true
$.on menuButton, 'click', Menu.toggle
$.add stub, [$.tn(' '), menuButton]
$.prepend thread, stub
show: (thread) ->
if stub = $ '.hidden_thread', thread
$.rm stub
thread.hidden = false
thread.nextElementSibling.hidden = false
ReplyHiding =
init: ->
Main.callbacks.push @node
node: (post) ->
return if post.isInlined or post.ID is post.threadID
side = $ '.sideArrows', post.root
$.addClass side, 'hide_reply_button'
side.innerHTML = '<a href="javascript:;"><span>[ - ]</span></a>'
$.on side.firstChild, 'click', ReplyHiding.toggle
if post.ID of g.hiddenReplies
ReplyHiding.hide post.root
toggle: ->
button = @parentNode
root = button.parentNode
id = root.id[2..]
quotes = $$ ".quotelink[href$='#p#{id}'], .backlink[href$='#p#{id}']"
if /\bstub\b/.test button.className
ReplyHiding.show root
for quote in quotes
$.rmClass quote, 'filtered'
delete g.hiddenReplies[id]
else
ReplyHiding.hide root
for quote in quotes
$.addClass quote, 'filtered'
g.hiddenReplies[id] = Date.now()
$.set "hiddenReplies/#{g.BOARD}/", g.hiddenReplies
hide: (root, show_stub=Conf['Show Stubs']) ->
side = $ '.sideArrows', root
return if side.hidden # already hidden once by the filter
side.hidden = true
el = side.nextElementSibling
el.hidden = true
$.addClass root, 'hidden'
return unless show_stub
stub = $.el 'div',
className: 'hide_reply_button stub'
innerHTML: '<a href="javascript:;"><span>[ + ]</span> </a>'
a = stub.firstChild
$.on a, 'click', ReplyHiding.toggle
$.add a, $.tn $('.nameBlock', el).textContent
if Conf['Menu']
menuButton = Menu.a.cloneNode true
$.on menuButton, 'click', Menu.toggle
$.add stub, [$.tn(' '), menuButton]
$.prepend root, stub
show: (root) ->
if stub = $ '.stub', root
$.rm stub
$('.sideArrows', root).hidden = false
$('.post', root).hidden = false
$.rmClass root, 'hidden'
Menu =
entries: []
init: ->
@a = $.el 'a',
className: 'menu_button'
href: 'javascript:;'