forked from soscripted/sox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sox.features.js
2338 lines (2036 loc) · 115 KB
/
sox.features.js
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
/*jshint multistr: true, loopfunc: true*/
/*global GM_getValue, GM_setValue, fkey*/
(function(sox, $, undefined) {
'use strict';
sox.features = { //SOX functions must go in here
grayOutVotes: function() {
// Description: Grays out votes AND vote count
if ($('.deleted-answer').length) {
$('.deleted-answer .vote-down-off, .deleted-answer .vote-up-off, .deleted-answer .vote-count-post').css('opacity', '0.5');
}
},
moveBounty: function() {
// Description: For moving bounty to the top
if ($('.bounty-notification').length) {
$('.bounty-notification').insertAfter('.question .fw');
$('.question .bounty-notification .votecell').remove();
}
},
dragBounty: function() {
// Description: Makes the bounty window draggable
sox.helpers.observe('#start-bounty-popup', function() {
$('#start-bounty-popup').draggable({
drag: function() {
$(this).css({
'width': 'auto',
'height': 'auto'
});
}
}).css('cursor', 'move');
});
},
renameChat: function() {
// Description: Renames Chat tabs to prepend 'Chat' before the room name
if (sox.site.type == 'chat') {
var match = document.title.match(/^(\(\d*\*?\) )?(.* \| [^|]*)$/);
document.title = (match[1] || '') + 'Chat - ' + match[2];
}
},
markEmployees: function() {
// Description: Adds an Stack Overflow logo next to users that *ARE* a Stack Overflow Employee
function unique(list) {
//credit: GUFFA https://stackoverflow.com/questions/12551635/12551709#12551709
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
var $links = $('.comment a, .deleted-answer-info a, .employee-name a, .started a, .user-details a').filter('a[href^="/users/"]');
var ids = [];
$links.each(function() {
var href = $(this).attr('href'),
id = href.split('/')[2];
ids.push(id);
});
ids = unique(ids);
var url = 'https://api.stackexchange.com/2.2/users/{ids}?site={site}&key={key}&access_token={access_token}'
.replace('{ids}', ids.join(';'))
.replace('{site}', sox.site.currentApiParameter)
.replace('{key}', sox.info.apikey)
.replace('{access_token}', sox.settings.accessToken);
$.ajax({
url: url
}).success(function(data) {
for (var i = 0, len = data.items.length; i < len; i++) {
var userId = data.items[i].user_id,
isEmployee = data.items[i].is_employee;
if (isEmployee) {
$links.filter('a[href^="/users/' + userId + '/"]').append('<i class="fa fa-stack-overflow" title="employee" style="padding: 0 5px"></i>');
}
}
});
},
bulletReplace: function() {
// Description: Replaces disclosure bullets with normal ones
$('.dingus').each(function() {
$(this).html('●');
});
},
copyCommentsLink: function() {
// Description: Adds the 'show x more comments' link before the commnents
$('.js-show-link.comments-link').each(function() {
var $this2 = $(this);
$('<tr><td></td><td>' + $this2.clone().wrap('<div>').parent().html() + '</td></tr>').insertBefore($(this).parent().closest('tr')).click(function() {
$(this).hide();
});
var commentParent;
// Determine if comment is on a question or an answer
if ($(this).parents('.answer').length) {
commentParent = '.answer';
} else {
commentParent = '.question';
}
$(this).click(function() {
$(this).closest(commentParent).find('.js-show-link.comments-link').hide();
});
});
},
fixedTopbar: function() {
// Description: For making the topbar fixed (always stay at top of screen)
// Written by @IStoleThePies (https://github.com/soscripted/sox/issues/152#issuecomment-267463392) to fix lots of bugs and compatability issues
// Modified by shu8
//Add class to page for topbar, calculated for every page for different sites.
//If the Area 51 popup closes or doesn't exist, $('#notify-table').height() = 0
var paddingToAdd = ($('#notify-table').length ? $('#notify-table').height() : '') + $('.topbar').height() + 'px';
GM_addStyle('.fixed-topbar-sox { padding-top: ' + paddingToAdd + '}');
function adjust() { //http://stackoverflow.com/a/31408076/3541881 genius! :)
setTimeout(function() {
sox.debug('fixedtopbar adjust function running');
var id;
if (location.href.indexOf('#comment') > -1) {
id = window.location.hash.match(/^#comment(\d+)_/)[1];
sox.debug('fixedtopbar comment in hash and getBoundingClientRect', $('#comment-' + id)[0], $('#comment-' + id)[0].getBoundingClientRect());
if ($('#comment-' + id)[0].getBoundingClientRect().top < 30) {
window.scrollBy(0, -34);
sox.debug('fixedtopbar adjusting');
}
} else {
id = window.location.hash.match(/^#(\d+)/)[1];
sox.debug('fixedtopbar answer in hash and getBoundingClientRect', $('#answer-' + id)[0], $('#answer-' + id)[0].getBoundingClientRect());
if ($('#answer-' + id)[0].getBoundingClientRect().top < 30) {
window.scrollBy(0, -34);
sox.debug('fixedtopbar adjusting');
}
}
}, 10);
}
if (sox.site.type == 'chat') { //For some reason, chats don't need any modification to the body
$('.topbar').css({
'position': 'fixed',
'z-index': '900'
});
} else if (!sox.location.on('askubuntu.com')) { //Disable on Ask Ubuntu
$('body').addClass('fixed-topbar-sox');
$('.topbar').css({
'position': 'fixed',
'z-index': '900',
'margin-top': '-34px'
});
//Area 51 popup:
$('#notify-table').css({
'position': 'fixed',
'z-index': '900',
'margin-top': '-65px'
});
//https://github.com/soscripted/sox/issues/74
if (location.href.indexOf('#') > -1) adjust();
$(window).bind('hashchange', adjust);
if (typeof MathJax !== "undefined") MathJax.Hub.Queue(adjust);
sox.helpers.observe('#notify-container,#notify--1', function() { //Area51: https://github.com/soscripted/sox/issues/152#issuecomment-267885889
$('body').css('padding-top', $('.topbar').height() + 'px');
});
}
},
highlightQuestions: function() {
// Description: For highlighting only the tags of favorite questions
function highlight() {
$('.tagged-interesting').removeClass('tagged-interesting sox-tagged-interesting').addClass('sox-tagged-interesting');
}
var color;
if (sox.location.on('superuser.com')) { //superuser
color = '#00a1c9';
} else if (sox.location.on('stackoverflow.com')) { //stackoverflow
color = '#f69c55';
} else if (sox.location.on('serverfault.com')) {
color = '#EA292C';
} else { //for all other sites
color = $('.post-tag').css('color');
}
$('<style type="text/css">.sox-tagged-interesting:before{background: ' + color + ';}</style>').appendTo('head');
highlight();
if ($('.question-summary').length) {
var target = document.body;
// TODO use new observer helper
new MutationObserver(function(mutations) {
$.each(mutations, function(i, mutation) {
if (mutation.attributeName == 'class') {
highlight();
return false; //no point looping through everything; if *something* has changed, assume everything has
}
});
}).observe(target, {
"attributes": true,
"childList": true,
"characterData": true,
"subtree": true
});
}
},
displayName: function() {
// Description: For displaying username next to avatar on topbar
var name = sox.user.name;
var $span = $('<span/>', {
class: 'reputation links-container',
style: 'color: white;',
title: name,
text: name
});
$span.insertBefore('.gravatar-wrapper-24');
},
colorAnswerer: function() {
// Description: For highlighting the names of answerers on comments
$('.answercell').each(function(i, obj) {
var x = $(this).find('.user-details a').text();
$('.answer .comment-user').each(function() {
if ($(this).text() == x) {
$(this).css('background-color', 'orange');
}
});
});
sox.helpers.observe('.new_comment', function() {
sox.features.colorAnswerer();
}, document.querySelectorAll('.comments table'));
},
kbdAndBullets: function() {
// Description: For adding buttons to the markdown toolbar to surround selected test with KBD or convert selection into a markdown list
function addBullets($node) {
var list = '- ' + $node.getSelection().text.split('\n').join('\n- ');
$node.replaceSelectedText(list);
}
function addKbd($node) {
/*var start = $node.get(0).selectionStart,
end = $node.get(0).selectionEnd,
origVal = $node.val(),
selected = origVal.slice(start, end),
newVal = '';
console.log(start, end, selected);
newVal = origVal.slice(0, start) + "<kbd>" + selected + "</kbd>" + origVal.substr(end);
console.log(newVal);*/
$node.surroundSelectedText("<kbd>", "</kbd>");
}
var kbdBtn = '<li class="wmd-button" title="surround selected text with <kbd> tags" style="left: 400px;"><span id="wmd-kbd-button" style="background-image: none;">kbd</span></li>';
var listBtn = '<li class="wmd-button" title="add dashes (\"-\") before every line to make a bulvar point list" style="left: 425px;"><span id="wmd-bullet-button" style="background-image:none;">●</span></li>';
sox.helpers.observe('[id^="wmd-redo-button"]', function() {
$('[id^="wmd-redo-button"]').each(function() {
if (!$(this).parent().find('#wmd-kbd-button').length) $(this).after(kbdBtn);
});
$('[id^="wmd-redo-button"]').each(function() {
if (!$(this).parent().find('#wmd-bullet-button').length) $(this).after(listBtn);
});
$('#wmd-kbd-button').on('click', function() {
addKbd($(this).parents('div[id*="wmd-button-bar"]').parent().find('textarea'));
});
$('#wmd-bullet-button').on('click', function() {
addBullets($(this).parents('div[id*="wmd-button-bar"]').parent().find('textarea'));
});
});
$('[id^="wmd-input"]').bind('keydown', 'alt+l', function() {
addBullets($(this).parents('div[id*="wmd-button-bar"]').parent().find('textarea'));
});
$('[id^="wmd-input"]').bind('keydown', 'alt+k', function() {
addKbd($(this).parents('div[id*="wmd-button-bar"]').parent().find('textarea'));
});
},
editComment: function() {
// Description: For adding checkboxes when editing to add pre-defined edit reasons
function addCheckboxes() {
$('#reasons').remove(); //remove the div containing everything, we're going to add/remove stuff now:
if (/\/edit/.test(window.location.href) || $('[class^="inline-editor"]').length) {
$('.form-submit').before('<div id="reasons" style="float:left;"></div>');
$.each(JSON.parse(GM_getValue('editReasons')), function(i, obj) {
$('#reasons').append('<label><input type="checkbox" value="' + this[1] + '"</input>' + this[0] + '</label> ');
});
$('#reasons input[type="checkbox"]').css('vertical-align', '-2px');
$('#reasons label').hover(function() {
$(this).css({ //on hover
'background-color': 'gray',
'color': 'white'
});
}, function() {
$(this).css({ //on un-hover
'background-color': 'white',
'color': 'inherit'
});
});
var editCommentField = $('[id^="edit-comment"]');
$('#reasons input[type="checkbox"]').change(function() {
if (this.checked) { //Add it to the summary
if (!editCommentField.val()) {
editCommentField.val(editCommentField.val() + $(this).val().replace(/on$/g, ''));
} else {
editCommentField.val(editCommentField.val() + '; ' + $(this).val().replace(/on$/g, ''));
}
var newEditComment = editCommentField.val(); //Remove the last space and last semicolon
editCommentField.val(newEditComment).focus();
} else if (!this.checked) { //Remove it from the summary
editCommentField.val(editCommentField.val().replace($(this).val() + '; ', '')); //for middle/beginning values
editCommentField.val(editCommentField.val().replace(new RegExp(';? ?' + $(this).val()), '')); //for last value
}
});
}
}
function displayDeleteValues() {
//Display the items from list and add buttons to delete them
$('#currentValues').html(' ');
$.each(JSON.parse(GM_getValue('editReasons')), function(i, obj) {
$('#currentValues').append(this[0] + ' - ' + this[1] + '<input type="button" id="' + i + '" value="Delete"><br />');
});
addCheckboxes();
}
var div = '<div id="dialogEditReasons" class="sox-centered wmd-prompt-dialog"><span id="closeDialogEditReasons" style="float:right;">Close</span><span id="resetEditReasons" style="float:left;">Reset</span> \
<h2>View/Remove Edit Reasons</h2> \
<div id="currentValues"></div> \
<br /> \
<h3>Add a custom reason</h3> \
Display Reason: <input type="text" id="displayReason"> \
<br /> \
Actual Reason: <input type="text" id="actualReason"> \
<br /> \
<input type="button" id="submitUpdate" value="Submit"> \
</div>';
$('body').append(div);
$('#dialogEditReasons').draggable().css('position', 'absolute').css('text-align', 'center').css('height', '60%').hide();
$('#closeDialogEditReasons').css('cursor', 'pointer').click(function() {
$(this).parent().hide(500);
});
$('#resetEditReasons').css('cursor', 'pointer').click(function() { //manual reset
var options = [ //Edit these to change the default settings
['formatting', 'Improved Formatting'],
['spelling', 'Corrected Spelling'],
['grammar', 'Fixed grammar'],
['greetings', 'Removed thanks/greetings']
];
if (confirm('Are you sure you want to reset the settings to Formatting, Spelling, Grammar and Greetings')) {
GM_setValue('editReasons', JSON.stringify(options));
alert('Reset options to default. Refreshing...');
location.reload();
}
});
if (GM_getValue('editReasons', -1) == -1) { //If settings haven't been set/are empty
var defaultOptions = [
['formatting', 'Improved Formatting'],
['spelling', 'Corrected Spelling'],
['grammar', 'Fixed grammar'],
['greetings', 'Removed thanks/greetings']
];
GM_setValue('editReasons', JSON.stringify(defaultOptions)); //save the default settings
} else {
var options = JSON.parse(GM_getValue('editReasons')); //If they have, get the options
}
$('#dialogEditReasons').on('click', 'input[value="Delete"]', function() { //Click handler to delete when delete button is pressed
var delMe = $(this).attr('id');
options.splice(delMe, 1); //actually delete it
GM_setValue('editReasons', JSON.stringify(options)); //save it
displayDeleteValues(); //display the items again (update them)
});
$('#submitUpdate').click(function() { //Click handler to update the array with custom value
if (!$('#displayReason').val() || !$('#actualReason').val()) {
alert('Please enter something in both the textboxes!');
} else {
var arrayToAdd = [$('#displayReason').val(), $('#actualReason').val()];
options.push(arrayToAdd); //actually add the value to array
GM_setValue('editReasons', JSON.stringify(options)); //Save the value
// moved display call after setvalue call, list now refreshes when items are added
displayDeleteValues(); //display the items again (update them)
//reset textbox values to empty
$('#displayReason').val('');
$('#actualReason').val('');
}
});
setTimeout(function() {
addCheckboxes();
//Add the button to update and view the values in the help menu:
$('.topbar-dialog.help-dialog.js-help-dialog > .modal-content ul').append("<li><a href='javascript:void(0)' id='editReasonsLink'>Edit Reasons \
<span class='item-summary'>Edit your personal edit reasons for SE sites</span></a></li>");
$('.topbar-dialog.help-dialog.js-help-dialog > .modal-content ul #editReasonsLink').on('click', function() {
displayDeleteValues();
$('#dialogEditReasons').show(500); //Show the dialog to view and update values
});
}, 500);
$('.post-menu > .edit-post').click(function() {
setTimeout(function() {
addCheckboxes();
}, 500);
});
},
shareLinksMarkdown: function() {
// Description: For changing the 'share' button link to the format [name](link)
sox.helpers.observe('.share-tip', function() {
var link = $('.share-tip input').val();
$('.share-tip input').val('[' + $('#question-header a').html() + '](' + link + ')');
$('.share-tip input').select();
});
},
commentShortcuts: function() {
// Description: For adding support in comments for Ctrl+K,I,B to add code backticks, italicise, bolden selection
$('.comments').on('keydown', 'textarea', function(e) {
if (e.which == 75 && e.ctrlKey) { //ctrl+k (code)
$(this).surroundSelectedText('`', '`');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 73 && e.ctrlKey) { //ctrl+i (italics)
$(this).surroundSelectedText('*', '*');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 66 && e.ctrlKey) { //ctrl+b (bold)
$(this).surroundSelectedText('**', '**');
e.stopPropagation();
e.preventDefault();
return false;
}
});
},
unspoil: function() {
// Description: For adding a button to reveal all spoilers in a post
$('#answers div[id*="answer"], div[id*="question"]').each(function() {
if ($(this).find('.spoiler').length) {
$(this).find('.post-menu').append('<span class="lsep">|</span><a id="showSpoiler-' + $(this).attr("id") + '" href="javascript:void(0)">unspoil</span>');
}
});
$('a[id*="showSpoiler"]').click(function() {
var x = $(this).attr('id').split(/-(.+)?/)[1];
$('#' + x + ' .spoiler').removeClass('spoiler');
});
},
spoilerTip: function() {
// Description: For adding some text to spoilers to tell people to hover over it
$('.spoiler').prepend('<div id="isSpoiler" style="color:red; font-size:smaller; float:right;">hover to show spoiler<div>');
$('.spoiler').hover(function() {
$(this).find('#isSpoiler').hide(500);
}, function() {
$(this).find('#isSpoiler').show(500);
});
},
commentReplies: function() {
// Description: For adding reply links to comments
if (!sox.user.loggedIn) return;
function addReplyLinks() {
$('.comment').each(function() {
if (!$(this).find('.soxReplyLink').length) { //if the link doesn't already exist
if ($('.topbar-links a span:eq(0)').text() != $(this).find('.comment-text a.comment-user').text()) { //make sure the link is not added to your own comments
$(this).find('.comment-text').css('overflow-x', 'hidden');
$(this).append('<span class="soxReplyLink" title="reply to this user">↵</span>');
}
}
});
}
$(document).on('click', 'span.soxReplyLink', function() {
var parentDiv = $(this).parent().parent().parent().parent();
var textToAdd = '@' + $(this).parent().find('.comment-text a.comment-user').text().replace(/\s/g, '').replace(/♦/, ''); //eg. @USERNAME
if (!parentDiv.find('textarea').length) parentDiv.next('div').find('a.js-add-link')[0].click(); //show the textarea, http://stackoverflow.com/a/10559680/
var $textarea = parentDiv.find('textarea');
if ($textarea.val().match(/@[^\s]+/)) { //if a ping has already been added
$textarea.val($textarea.val().replace(/@[^\s]+/, textToAdd)); //replace the @name with the new @name
} else {
$textarea.val($textarea.val() + textToAdd + ' '); //add the @name
}
});
addReplyLinks();
sox.helpers.observe('.new_comment', addReplyLinks);
},
parseCrossSiteLinks: function() {
// Description: For converting cross-site links to their titles
var sites = ['stackexchange', 'stackoverflow', 'superuser', 'serverfault', 'askubuntu', 'stackapps', 'mathoverflow', 'programmers', 'bitcoin'];
$('.post-text a').not('.expand-post-sox').each(function() {
var anchor = $(this),
href = $(this).attr('href');
if (sites.indexOf(href.split('/')[2].split('.')[0]) > -1) { //if the link is to an SE site (not, for example, to google), do the necessary stuff
if (href.indexOf('/questions/') > -1) { //if the link is to a question
if ($(this).text() == href) { //if there isn't text on it (ie. bare url)
var sitename = href.split('/')[2].split('.')[0],
id = href.split('/')[4];
sox.helpers.getFromAPI('questions', id, sitename, function(json) {
anchor.html(json.items[0].title); //Get the title and add it in
}, 'activity');
}
}
}
});
},
confirmNavigateAway: function() {
// Description: For adding a 'are you ure you want to go away' confirmation on pages where you have started writing something
if (window.location.href.indexOf('questions/') >= 0) {
$(window).bind('beforeunload', function() {
if ($('.comment-form textarea').length && $('.comment-form textarea').val()) {
return 'Do you really want to navigate away? Anything you have written will be lost!';
} else {
return;
}
});
}
},
sortByBountyAmount: function() {
// Description: For adding some buttons to sort bounty's by size
if ($('.bounty-indicator').length) { //if there is at least one bounty on the page
$('.question-summary').each(function() {
var bountyAmount = $(this).find('.bounty-indicator').text().replace('+', '');
if (bountyAmount) {
$(this).attr('data-bountyamount', bountyAmount).addClass('hasBounty'); //add a 'bountyamount' attribute to all the questions
}
});
var $wrapper = $('#question-mini-list').length ? $('#question-mini-list') : $wrapper = $('#questions'); //homepage/questions tab
//filter buttons:
$('.subheader').after('<span>sort by bounty amount: </span><span id="largestFirst">largest first </span><span id="smallestFirst">smallest first</span>');
//Thanks: http://stackoverflow.com/a/14160529/3541881
$('#largestFirst').css('cursor', 'pointer').on('click', function() { //largest first
$wrapper.find('.question-summary.hasBounty').sort(function(a, b) {
return +b.getAttribute('data-bountyamount') - +a.getAttribute('data-bountyamount');
}).prependTo($wrapper);
});
//Thanks: http://stackoverflow.com/a/14160529/3541881
$('#smallestFirst').css('cursor', 'pointer').on('click', function() { //smallest first
$wrapper.find('.question-summary.hasBounty').sort(function(a, b) {
return +a.getAttribute('data-bountyamount') - +b.getAttribute('data-bountyamount');
}).prependTo($wrapper);
});
}
},
isQuestionHot: function() {
// Description: For adding some text to questions that are in the hot network questions list
function addHotText() {
if (!$('.sox-hot').length) {
$('#feed').html('<p>One of the 100 hot network questions!</p>');
$('#question-header').prepend('<div title="this question is a hot network question!" class="sox-hot">HOT<div>');
}
}
$('#qinfo').after('<div id="feed"></div>');
$.ajax({
type: 'get',
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D"http%3A%2F%2Fstackexchange.com%2Fhot-questions-for-mobile"&format=json',
success: function(d) {
var results = d.query.results.json.json;
$.each(results, function(i, o) {
if (document.URL.indexOf(o.site + '/questions/' + o.question_id) > -1) {
addHotText();
}
});
}
});
},
autoShowCommentImages: function() {
// Description: For auto-inlining any links to imgur images in comments
function showImages() {
$('.comment .comment-text .comment-copy a').each(function() {
if ($(this).attr('href') && $(this).attr('href').indexOf('imgur.com') != -1) {
var src = $(this).attr('href');
if (!$(this).parent().find('img[src="' + src + '"]').length) {
$(this).parent().append('<img src="' + src + '" width="100%">'); //add image to end of comments, but keep link in same position
}
}
});
}
setTimeout(showImages, 2000); //setTimeout needed because FF refuses to load the feature on page load and does it before so the comment isn't detected.
sox.helpers.observe('.new_comment', showImages, document.querySelectorAll('.comments table'));
},
showCommentScores: function() {
// Description: For adding a button on your profile comment history pages to show your comment's scores
var sitename = sox.site.currentApiParameter;
function addLabelsAndHandlers() {
$('.history-table td b a[href*="#comment"]').each(function() {
if (!$(this).parent().find('.showCommentScore').length) {
var id = $(this).attr('href').split('#')[1].split('_')[0].replace('comment', '');
$(this).after('<span class="showCommentScore" id="' + id + '"> show comment score</span>');
}
});
$('.showCommentScore').css('cursor', 'pointer').on('click', function() {
var $that = $(this);
sox.helpers.getFromAPI('comments', $that.attr('id'), sitename, function(json) {
$that.html(' ' + json.items[0].score);
});
});
}
addLabelsAndHandlers();
sox.helpers.observe('#user-tab-responses, #user-tab-activity', function() {
addLabelsAndHandlers();
});
},
answerTagsSearch: function() {
// Description: For adding tags to answers in search
var sitename = sox.site.currentApiParameter,
ids = [],
idsAndTags = {};
$('div[id*="answer"]').each(function() { //loop through all *answers*
ids.push($(this).find('.result-link a').attr('href').split('/')[2]); //Get the IDs for the questions for all the *answers*
});
sox.helpers.getFromAPI('questions', ids.join(';'), sitename, function(json) {
//$.getJSON('https://api.stackexchange.com/2.2/questions/' + ids.join(';') + '?pagesize=60&site=' + sitename, function(json) {
var itemsLength = json.items.length;
for (var i = 0; i < itemsLength; i++) {
idsAndTags[json.items[i].question_id] = json.items[i].tags;
}
$('div[id*="answer"]').each(function() { //loop through all *answers*
var id = $(this).find('.result-link a').attr('href').split('/')[2]; //get their ID
var $that = $(this);
for (var x = 0; x < idsAndTags[id].length; x++) { //Add the appropiate tags for the appropiate answer
$that.find('.summary .tags').append('<a href="/questions/tagged/' + idsAndTags[id][x] + '" class="post-tag">' + idsAndTags[id][x] + '</a>'); //add the tags and their link to the answers
}
$that.find('.summary .tags a').each(function() {
if ($(this).text().indexOf('status-') > -1) { //if it's a mod tag
$(this).addClass('moderator-tag'); //add appropiate class
} else if ($(this).text().match(/(discussion|feature-request|support|bug)/)) { //if it's a required tag
$(this).addClass('required-tag'); //add appropiate class
}
});
});
}, 'creation&pagesize=60');
},
stickyVoteButtons: function() {
// Description: For making the vote buttons stick to the screen as you scroll through a post
//https://github.com/shu8/SE_OptionalFeatures/pull/14:
//https://github.com/shu8/Stack-Overflow-Optional-Features/issues/28: Thanks @SnoringFrog for fixing this!
var $votecells = $(".votecell");
$votecells.css("width", "61px");
stickcells();
$(window).scroll(function() {
stickcells();
});
function stickcells() {
$votecells.each(function() {
var $topbar = $('.topbar'),
topbarHeight = $topbar.outerHeight(),
offset = 10;
if ($topbar.css('position') == 'fixed') {
offset += topbarHeight;
}
var $voteCell = $(this),
$vote = $voteCell.find('.vote'),
vcOfset = $voteCell.offset(),
scrollTop = $(window).scrollTop();
if (vcOfset.top - scrollTop - offset <= 0) {
if (vcOfset.top + $voteCell.height() - scrollTop - offset - $vote.height() > topbarHeight) {
$vote.css({
position: 'fixed',
left: vcOfset.left + 4,
top: offset
});
} else {
$vote.removeAttr("style");
}
} else {
$vote.removeAttr("style");
}
});
}
},
titleEditDiff: function() {
// Description: For showing the new version of a title in a diff separately rather than loads of crossing outs in red and additions in green
function betterTitle() {
sox.debug('ran');
var $questionHyperlink = $('.summary h2 .question-hyperlink').clone(),
$questionHyperlinkTwo = $('.summary h2 .question-hyperlink').clone(),
link = $('.summary h2 .question-hyperlink').attr('href'),
added = ($questionHyperlinkTwo.find('.diff-delete').remove().end().text()),
removed = ($questionHyperlink.find('.diff-add').remove().end().text());
if ($('.summary h2 .question-hyperlink').find('.diff-delete, .diff-add').length) {
$('.summary h2 .question-hyperlink').hide();
$('.summary h2 .question-hyperlink').after('<a href="' + link + '" class="question-hyperlink"><span class="diff-delete">' + removed + '</span><span class="diff-add">' + added + '</span></a>');
}
}
betterTitle();
sox.helpers.observe('.review-status, .review-content, .suggested-edit, .post-id', betterTitle);
},
metaChatBlogStackExchangeButton: function() {
// Description: For adding buttons next to sites under the StackExchange button that lead to that site's meta and chat
// NOTE: this feature used to have a 'blog' button as well, but it wasn't very useful so was removed
var link, chatLink;
$(document).on('mouseenter', '#your-communities-section > ul > li > a', function() {
var href = $(this).attr('href');
chatLink = 'http://chat.stackexchange.com?tab=site&host=' + (sox.location.matchWithPattern("*://stackexchange.com") ? href.substr(7) : href.substr(2));
if (href.indexOf('stackapps') > -1) {
link = undefined;
} else if (href.indexOf('area51') > -1 && href.indexOf('discuss.area51') === -1) {
link = 'http://discuss.area51.stackexchange.com/';
} else if (href.indexOf('meta.stackexchange.com') > -1) {
link = undefined;
chatLink = 'http://chat.meta.stackexchange.com';
} else if (href.indexOf('meta') > -1 || href.indexOf('discuss.area51') > -1) {
link = undefined;
chatLink = undefined;
} else {
link = 'http://meta.' + href.substr(2, href.length - 1);
}
if (href.indexOf('stackoverflow.com') > -1 && href.indexOf('meta') === -1 && !href.match(/(pt|ru|es)\.stackoverflow/i)) {
chatLink = 'http://chat.stackoverflow.com?tab=site';
}
if (link || chatLink) { //only hide rep if we're actually going to add anything
$(this).find('.rep-score').stop(true).delay(135).fadeOut(20);
$(this).prepend('<div class="related-links" style="float: right; display: none;">' +
(link ?
(link.indexOf('discuss.area51') > -1 ? '<a href="' + link + '">discuss</a>' : '<a href="' + link + '">meta</a>') :
'') +
(chatLink ? '<a href="' + chatLink + '">chat</a>' : '') +
'</div>');
$(this).find('.related-links').delay(135).css('opacity', 0).animate({
opacity: 1,
width: 'toggle'
}, 200);
}
}).on('mouseleave', '#your-communities-section > ul > li > a', function() {
$(this).find('.rep-score').stop(true).fadeIn(110);
$(this).find('.related-links').remove();
});
},
metaNewQuestionAlert: function() {
// Description: For adding a fake mod diamond that notifies you if there has been a new post posted on the current site's meta
//DO NOT RUN ON META OR CHAT OR SITES WITHOUT A META
if ((sox.site.type != 'main' && sox.site.type != 'beta') || !$('.related-site').length) return;
var NEWQUESTIONS = 'metaNewQuestionAlert-lastQuestions',
DIAMONDON = 'metaNewQuestionAlert-diamondOn',
DIAMONDOFF = 'metaNewQuestionAlert-diamondOff',
favicon = sox.site.icon,
metaName = 'meta.' + sox.site.currentApiParameter,
lastQuestions = {},
apiLink = 'https://api.stackexchange.com/2.2/questions?pagesize=5&order=desc&sort=activity&site=' + metaName,
$dialog = $('<div/>', {
id: 'metaNewQuestionAlertDialog',
'class': 'topbar-dialog achievements-dialog dno'
}),
$header = $('<div/>', {
'class': 'header'
}).append($('<h3/>', {
text: 'new meta posts'
})),
$content = $('<div/>', {
'class': 'modal-content'
}),
$questions = $('<ul/>', {
id: 'metaNewQuestionAlertDialogList',
'class': 'js-items items'
}),
$diamond = $('<a/>', {
id: 'metaNewQuestionAlertButton',
href: '#',
'class': 'topbar-icon yes-hover metaNewQuestionAlert-diamondOff',
title: 'Moderator inbox (recent meta questions)',
click: function(e) {
e.preventDefault();
$diamond.toggleClass('topbar-icon-on');
$dialog.toggle();
}
});
//'$('#metaNewQuestionAlertButton').position().left' from @IStoleThePies: https://github.com/soscripted/sox/issues/120#issuecomment-267857625:
$('#soxSettingsButton').after($diamond);
$dialog.css('left', $('#metaNewQuestionAlertButton').position().left).append($header).append($content.append($questions)).prependTo('.js-topbar-dialog-corral');
$('#metaNewQuestionAlertButton').hover(function() { //open on hover, just like the normal dropdowns
if ($('.topbar-icon').not('#metaNewQuestionAlertButton').hasClass('topbar-icon-on')) {
$('.topbar-dialog').hide();
$('.topbar-icon').removeClass('topbar-icon-on').removeClass('icon-site-switcher-on');
$(this).addClass('topbar-icon-on');
$('#metaNewQuestionAlertDialog').show();
}
}, function() {
$('.topbar-icon').not('#metaNewQuestionAlertButton').hover(function() {
if ($('#metaNewQuestionAlertButton').hasClass('topbar-icon-on')) {
$('#metaNewQuestionAlertDialog').hide();
$('#metaNewQuestionAlertButton').removeClass('topbar-icon-on');
var which = $(this).attr('class').match(/js[\w-]*\b/)[0].split('-')[1];
if (which != 'site') { //site-switcher dropdown is slightly different
$('.' + which + '-dialog').not('#sox-settings-dialog, #metaNewQuestionAlertDialog, #downvotedPostsEditAlertDialog').show();
$(this).addClass('topbar-icon-on');
} else {
$('.siteSwitcher-dialog').show();
$(this).addClass('topbar-icon-on').addClass('icon-site-switcher-on'); //icon-site-switcher-on is special to the site-switcher dropdown (StackExchange button)
}
}
});
});
$(document).mouseup(function(e) {
if (!$dialog.is(e.target) &&
$dialog.has(e.target).length === 0 &&
!$(e.target).is('#metaNewQuestionAlertButton')) {
$dialog.hide();
$diamond.removeClass("topbar-icon-on");
}
});
if (GM_getValue(NEWQUESTIONS, -1) == -1) {
GM_setValue(NEWQUESTIONS, JSON.stringify(lastQuestions));
} else {
lastQuestions = JSON.parse(GM_getValue(NEWQUESTIONS));
}
$.getJSON(apiLink, function(json) {
var latestQuestion = json.items[0].title;
if (latestQuestion == lastQuestions[metaName]) {
//if you've already seen the stuff
$diamond.removeClass(DIAMONDON).addClass(DIAMONDOFF);
} else {
$diamond.removeClass(DIAMONDOFF).addClass(DIAMONDON);
for (var i = 0; i < json.items.length; i++) {
var title = json.items[i].title,
link = json.items[i].link;
//author = json.items[i].owner.display_name;
addQuestion(title, link);
}
lastQuestions[metaName] = latestQuestion;
$diamond.click(function() {
GM_setValue(NEWQUESTIONS, JSON.stringify(lastQuestions));
});
}
});
function addQuestion(title, link) {
var $li = $('<li/>');
var $link = $('<a/>', {
href: link
});
var $icon = $('<div/>', {
'class': 'site-icon favicon ' + favicon
});
var $message = $('<div/>', {
'class': 'message-text'
}).append($('<h4/>', {
html: title
}));
$link.append($icon).append($message).appendTo($li);
$questions.append($li);
}
},
betterCSS: function() {
// Description: For adding the better CSS for the voting buttons and favourite button
$('.vote-down-off, .vote-down-on, .vote-up-off, .vote-up-on, .star-off, .star-on').addClass('sox-better-css');
$('head').append('<link rel="stylesheet" href="https://rawgit.com/shu8/SE-Answers_scripts/master/coolMaterialDesignCss.css" type="text/css" />');
$('#hlogo').css('-webkit-transform', 'translate3d(0,0,0)'); //Thanks to @IStoleThePies: https://github.com/soscripted/sox/issues/79#issuecomment-267868040
},
standOutDupeCloseMigrated: function() {
// Description: For adding cooler signs that a questions has been closed/migrated/put on hod/is a dupe
function addLabel($question) {
if ($question.attr('data-sox-question-state')) return; //don't run if question already has tag added
var $anchor = $question.find('.summary a:eq(0)');
var text = $anchor.text().trim();
var id = $anchor.attr('href').split('/')[2];
if (text.substr(text.length - 11) == '[duplicate]') {
$anchor.text(text.substr(0, text.length - 11)); //remove [duplicate]
$question.attr('data-sox-question-state', 'duplicate'); //used for hideCertainQuestions feature compatability
$.get('//' + location.hostname + '/questions/' + id, function(d) {
$anchor.after(" <a href='" + $(d).find('.question-status.question-originals-of-duplicate a:eq(0)').attr('href') + "'><span class='duplicate' title='click to visit duplicate'> duplicate </span></a>"); //add appropiate message
});
} else if (text.substr(text.length - 8) == '[closed]') {
$anchor.text(text.substr(0, text.length - 8)); //remove [closed]
$question.attr('data-sox-question-state', 'closed'); //used for hideCertainQuestions feature compatability
$.get('//' + location.hostname + '/questions/' + id, function(d) {
$anchor.after(" <span class='closed' title='" + $(d).find('.question-status h2').text() + "'> closed </span>"); //add appropiate message
});
} else if (text.substr(text.length - 10) == '[migrated]') {
$anchor.text(text.substr(0, text.length - 10)); //remove [migrated]
$question.attr('data-sox-question-state', 'migrated'); //used for hideCertainQuestions feature compatability
$.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent('http://' + location.hostname + '/questions/' + id) + "%22&diagnostics=true", function(d) {
$anchor.after(" <span class='migrated' title='migrated to " + $(d).find('.current-site .site-icon').attr('title') + "'> migrated </span>"); //add appropiate message
});
} else if (text.substr(text.length - 9) == '[on hold]') {
$anchor.text(text.substr(0, text.length - 9)); //remove [on hold]
$question.attr('data-sox-question-state', 'on hold'); //used for hideCertainQuestions feature compatability
$.get('//' + location.hostname + '/questions/' + id, function(d) {
$anchor.after(" <span class='onhold' title='" + $(d).find('.question-status h2').text() + "'> onhold </span>"); //add appropiate message
});
}