/
sox.features.js
2736 lines (2304 loc) · 113 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
(function(sox, $) {
'use strict';
sox.features = { //SOX functions must go in here
moveBounty: function() {
// Description: For moving bounty to the top
$('.bounty-notification').insertAfter('.question .fw-wrap');
$('.bounty-link.bounty').closest('ul').insertAfter('.question .fw-wrap');
},
dragBounty: function() {
// Description: Makes the bounty window draggable
const target = document.getElementById('question');
sox.helpers.observe(target, '#start-bounty-popup', () => {
$('#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') {
const 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
const anchors = [...document.querySelectorAll('.comment a, .deleted-answer-info a, .employee-name a, .user-details a, .question-summary .started a')].filter(el => {
return el.href.startsWith('/users/');
});
const ids = [];
for (let i = 0; i < anchors.length; i++) {
const href = anchors[i].href;
const id = href.split('/')[2];
if (ids.indexOf(id) === -1) ids.push(id);
}
sox.debug('markEmployees user IDs', ids);
// TODO is pagination needed?
sox.helpers.getFromAPI({
endpoint: 'users',
ids,
sitename: sox.site.url,
filter: '!*MxJcsv91Tcz6yRH',
limit: 100,
featureId: 'markEmployees',
}, items => {
sox.debug('markEmployees returned data', items);
for (let i = 0; i < items.length; i++) {
const userId = items[i].user_id;
const isEmployee = items[i].is_employee;
if (!isEmployee) continue;
anchors.filter(el => el.href.startsWith(`/users/${userId}/`)).forEach(el => {
el.insertAdjacentHTML('afterend', '<span class="fab fa-stack-overflow" title="employee (added by SOX)" style="padding: 0 5px; color: ' + $('.mod-flair').css('color') + '"></span>');
});
}
});
},
copyCommentsLink: function() {
// Description: Adds the 'show x more comments' link before the commnents
// Test on e.g. https://meta.stackexchange.com/questions/125439/
$('.js-show-link.comments-link').each(function() {
if (!$(this).parent().prev().find('.comment-text').length) return; //https://github.com/soscripted/sox/issues/196
const $btnToAdd = $(this).clone();
$btnToAdd.on('click', function(e) {
e.preventDefault();
$(this).hide();
});
$(this).parent().parent().prepend($btnToAdd);
$(this).click(() => {
$btnToAdd.hide();
});
});
$(document).on('click', '.js-add-link', function() { //https://github.com/soscripted/sox/issues/239
const commentParent = ($(this).parents('.answer').length ? '.answer' : '.question');
$(this).closest(commentParent).find('.js-show-link.comments-link').hide();
});
},
highlightQuestions: function() {
// Description: For highlighting only the tags of favorite questions
function highlight() {
const interestingQuestions = [...document.getElementsByClassName('tagged-interesting')];
const questionsLength = interestingQuestions.length;
for (let i = 0; i < questionsLength; i++) {
const question = interestingQuestions[i];
question.classList.remove('tagged-interesting');
question.classList.add('sox-tagged-interesting');
}
}
let color;
if (sox.location.on('superuser.com')) {
color = '#00a1c9';
} else if (sox.location.on('stackoverflow.com')) {
color = '#f69c55';
} else if (sox.location.on('serverfault.com')) {
color = '#EA292C';
} else {
const existingPostTags = document.getElementsByClassName('post-tag');
if (existingPostTags.length) {
color = existingPostTags[0].style.color;
} else {
// Default colour if we can't find one on the page already
color = '#39739d';
}
}
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(`.sox-tagged-interesting:before{ background: ${color} }`));
document.head.appendChild(style);
highlight();
if (document.getElementsByClassName('question-summary').length) {
const targetMainPage = document.getElementById('question-mini-list');
const targetQuestionsPage = document.getElementById('questions');
sox.helpers.observe([targetMainPage, targetQuestionsPage], '.question-summary', highlight);
}
},
displayName: function() {
// Description: For displaying username next to avatar on topbar
const name = sox.user.name;
const $span = $('<span/>', {
class: 'reputation links-container',
style: $('.top-bar').css('background-color') == 'rgb(250, 250, 251)' ? 'color: #535a60; padding-right: 12px; font-size: 13px;' : 'color: white; padding-right: 12px; font-size: 13px;',
title: name,
text: name,
});
$span.insertBefore('.gravatar-wrapper-24');
},
colorAnswerer: function() {
// Description: For highlighting the names of answerers on comments
function color() {
const answerCells = [...document.getElementsByClassName('answercell')];
for (let i = 0; i < answerCells.length; i++) {
const cell = answerCells[i];
const answererID = cell.querySelector('.post-signature:nth-last-of-type(1) a').href.match(/\d+/)[0];
const commentUsers = [...cell.nextElementSibling.getElementsByClassName('comment-user')]
.filter(c => c.href && c.href.contains(`/users/${answererID}/`));
for (let c = 0; c < commentUsers.length; c++) {
commentUsers[c].classList.add('sox-answerer');
}
}
}
color();
$(document).on('sox-new-comment', color);
},
kbdAndBullets: function() {
// Description: For adding buttons to the markdown toolbar to surround selected test with KBD or convert selection into a markdown list
function replaceSelectedText(node, newText) {
const sS = node.selectionStart;
const sE = node.selectionEnd;
const val = node.value;
const valBefore = val.substring(0, sS);
const valAfter = val.substring(sE);
// situation contrary to our expectation
if (sS === sE) return;
node.value = valBefore + newText + valAfter;
node.selectionStart = node.selectionEnd = sS + newText.length;
sox.Stack.MarkdownEditor.refreshAllPreviews();
node.focus();
}
function getSelection(node) {
return node.value.substring(node.selectionStart, node.selectionEnd);
}
function surroundSelectedText(textarea, start, end) {
// same wrapper code on either side (`$...$`)
if (typeof end === 'undefined') end = start;
/*--- Expected behavior:
When there is some text selected: (unwrap it if already wrapped)
"]text[" --> "**]text[**"
"**]text[**" --> "]text["
"]**text**[" --> "**]**text**[**"
"**]**text**[**" --> "]**text**["
When there is no text selected:
"][" --> "**placeholder text**"
"**][**" --> ""
Note that `]` and `[` denote the selected text here.
*/
const selS = textarea.selectionStart;
const selE = textarea.selectionEnd;
const value = textarea.value;
const startLen = start.length;
const endLen = end.length;
let valBefore = value.substring(0, selS);
let valMid = value.substring(selS, selE);
let valAfter = value.substring(selE);
let generatedWrapper;
// handle trailing spaces
const trimmedSelection = valMid.match(/^(\s*)(\S?(?:.|\n|\r)*\S)(\s*)$/) || ['', '', '', ''];
// determine if text is currently wrapped
if (valBefore.endsWith(start) && valAfter.startsWith(end)) {
textarea.value = valBefore.substring(0, valBefore.length - startLen) + valMid + valAfter.substring(endLen);
textarea.selectionStart = valBefore.length - startLen;
textarea.selectionEnd = (valBefore + valMid).length - startLen;
textarea.focus();
} else {
valBefore += trimmedSelection[1];
valAfter = trimmedSelection[3] + valAfter;
valMid = trimmedSelection[2];
generatedWrapper = start + valMid + end;
textarea.value = valBefore + generatedWrapper + valAfter;
textarea.selectionStart = valBefore.length + start.length;
textarea.selectionEnd = (valBefore + generatedWrapper).length - end.length;
textarea.focus();
}
sox.Stack.MarkdownEditor.refreshAllPreviews();
}
function addBullets(node) {
const list = '- ' + getSelection(node).split('\n').join('\n- ');
replaceSelectedText(node, list);
}
function addKbd(node) {
surroundSelectedText(node, '<kbd>', '</kbd>');
node.focus();
}
function getTextarea(button) {
// li -> ul -> #wmd-button-bar -> .wmd-container
return button.parentNode.parentNode.parentNode.querySelector('textarea');
}
const kbdBtn = '<li class="wmd-button wmd-kbd-button-sox" title="surround selected text with <kbd> tags"><span style="background-image:none;">kbd</span></li>';
const listBtn = '<li class="wmd-button wmd-bullet-button-sox" title="add dashes (\'-\') before every line to make a bullet list"><span style="background-image:none;">●</span></li>';
function loopAndAddHandlers() {
const redoButtons = [...document.querySelectorAll('[id^="wmd-redo-button"]')];
for (let i = 0; i < redoButtons.length; i++) {
const button = redoButtons[i];
if (!button.dataset.kbdAdded) {
// Compatability with https://stackapps.com/q/3341 as requested in https://github.com/soscripted/sox/issues/361
// The SOX kbd button isn't added if that script is installed
if (button.parentNode.querySelector('.tmAdded.wmd-kbd-button')) {
button.insertAdjacentHTML('afterend', listBtn);
} else {
button.insertAdjacentHTML('afterend', kbdBtn + listBtn);
}
button.dataset.kbdAdded = true;
}
}
}
$(document).on('sox-edit-window', loopAndAddHandlers);
loopAndAddHandlers();
document.addEventListener('keydown', event => {
const kC = event.keyCode;
const target = event.target;
if (target && target.tagName === 'TEXTAREA' && event.altKey) {
if (kC === 76) addBullets(target); // l
else if (kC === 75) addKbd(target); // k
}
});
$(document).on('click', '.wmd-kbd-button-sox, .wmd-bullet-button-sox', function() {
const textarea = getTextarea(this);
if (this.classList.contains('wmd-kbd-button-sox')) addKbd(textarea);
else addBullets(textarea);
});
},
editComment: function() {
// Description: For adding checkboxes when editing to add pre-defined edit reasons
const DEFAULT_OPTIONS = [
{ 'formatting': 'Improved Formatting' },
{ 'spelling': 'Corrected Spelling' },
{ 'grammar': 'Fixed grammar' },
{ 'greetings': 'Removed thanks/greetings' },
{ 'retag': 'Improved usage of tags' },
{ 'title': 'Improved title' },
];
function toLocaleSentenceCase(str) {
return str.substr(0, 1).toLocaleUpperCase() + str.substr(1);
}
function convertOptionsToNewFormat(options) {
// Storage format was changed 03-02-19
// Old storage format was an array of arrays: [[name, text], [name, text], ...]
// This converts it to an object (like DEFAULT_OPTIONS above)
const newOptions = [];
options.forEach(opt => {
newOptions.push({
[opt[0]]: opt[1],
});
});
return newOptions;
}
function saveOptions(options) {
GM_setValue('editReasons', JSON.stringify(options));
}
function getOptions() {
let options = GM_getValue('editReasons', -1);
if (options === -1) {
options = DEFAULT_OPTIONS;
saveOptions(options);
} else {
options = JSON.parse(options);
}
// If options are being stored in the old format, convert them to the new
if (Array.isArray(options[0])) {
options = convertOptionsToNewFormat(options);
saveOptions(options);
}
return options;
}
function addOptionsToDialog() {
$('#currentValues').html(' ');
const options = getOptions();
options.forEach(opt => {
const [[name, text]] = Object.entries(opt);
$('#currentValues').append(`
<div>
${name} - <i>${text}</i>
<button class="grid--cell s-btn s-btn__muted discard-question sox-editComment-editDialogButton" data-name="${name}">Edit</button>
<button class="grid--cell s-btn s-btn__danger discard-question sox-editComment-deleteDialogButton" data-name="${name}">Delete</button>
</div>`);
});
addCheckboxes();
}
function createDialogEditReasons() {
const $settingsDialog = sox.helpers.createModal({
'header': 'SOX: View/Remove Edit Reasons',
'id': 'dialogEditReasons',
'css': {
'min- width': '50%',
},
'html': `<div id="currentValues" class="sox-editComment-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">
<input type="button" id="resetEditReasons" style="float:right;" value="Reset">`,
});
$(document).on('click', '#resetEditReasons', () => { //manual reset
if (confirm('Are you sure you want to reset the settings to the default ones? The page will be refreshed afterwards')) {
saveOptions(DEFAULT_OPTIONS);
location.reload();
}
});
$('body').append($settingsDialog);
$('#dialogEditReasons').show(500);
}
function addCheckboxes() {
const $editCommentField = $('input[id^="edit-comment"]'); //NOTE: input specifcally needed, due to https://github.com/soscripted/sox/issues/363
if (!$editCommentField.length) return; //https://github.com/soscripted/sox/issues/246
$('#reasons').remove(); //remove the div containing everything, we're going to add/remove stuff now:
if (/\/edit/.test(sox.site.href) || $('[class^="inline-editor"]').length || $('.edit-comment').length) {
$editCommentField.after('<div id="reasons" style="float:left;clear:both"></div>');
const $reasons = $('#reasons');
const options = getOptions();
options.forEach(opt => {
const [[name, text]] = Object.entries(opt);
$reasons.append(`
<label class="sox-editComment-reason"><input type="checkbox" value="${text}"</input>${name}</label>
`);
});
$reasons.find('input[type="checkbox"]').change(function() {
if (this.checked) { //Add it to the summary
if ($editCommentField.val()) {
$editCommentField.val($editCommentField.val() + '; ' + $(this).val());
} else {
$editCommentField.val(toLocaleSentenceCase($(this).val()));
}
const newEditComment = $editCommentField.val(); //Remove the last space and last semicolon
$editCommentField.val(newEditComment).focus();
} else { //Remove it from the summary
$editCommentField.val(toLocaleSentenceCase($editCommentField.val().replace(new RegExp(toLocaleSentenceCase($(this).val()) + ';? ?'), ''))); //for beginning values
$editCommentField.val($editCommentField.val().replace($(this).val() + '; ', '')); //for middle values
$editCommentField.val($editCommentField.val().replace(new RegExp(';? ?' + $(this).val()), '')); //for last value
}
});
}
}
$(document).on('click', '#dialogEditReasons .sox-editComment-deleteDialogButton', function () { //Click handler to delete an option
const optionToDelete = $(this).attr('data-name');
const options = getOptions();
const index = options.findIndex(opt => opt[optionToDelete]);
options.splice(index, 1); //actually delete it
saveOptions(options);
addOptionsToDialog(); //display the items again (update them)
});
$(document).on('click', '#dialogEditReasons .sox-editComment-editDialogButton', function () { //Click handler to edit an option
const optionToEdit = $(this).attr('data-name');
const options = getOptions();
const index = options.findIndex(opt => opt[optionToEdit]);
const [[name, text]] = Object.entries(options[index]);
const newName = window.prompt('Enter new name', name);
const newText = window.prompt('Enter new text', text);
if (!newName || !newText) return;
options[index] = { [newName]: newText };
saveOptions(options);
addOptionsToDialog(); //display the items again (update them)
});
$(document).on('click', '#dialogEditReasons #submitUpdate', () => { //Click handler to update the array with custom value
const name = $('#displayReason').val();
const text = $('#actualReason').val();
if (!name || !text) {
alert('Please enter something in both the textboxes!');
} else {
const optionToAdd = { [name]: text };
const options = getOptions();
options.push(optionToAdd);
saveOptions(options);
addOptionsToDialog(); //display the items again (update them)
$('#displayReason, #actualReason').val('');
}
});
//Add the button to update and view the values in the help menu:
sox.helpers.addButtonToHelpMenu({
'id': 'editReasonsLink',
'linkText': 'Edit Reasons',
'summary': 'Edit your personal edit reasons (edit summary checkboxes)',
'click': function () {
createDialogEditReasons(); //Show the dialog to view and update values
addOptionsToDialog();
},
});
addCheckboxes();
$(document).on('sox-edit-window', addCheckboxes);
},
shareLinksPrivacy: function() {
// Description: Remove your user ID from the 'share' link
const questionTarget = document.getElementById('question');
const answersTargets = document.getElementsByClassName('answer');
sox.helpers.observe([questionTarget, ...answersTargets], '.share-tip', () => {
const toRemove = ' (includes your user id)';
const popup = document.getElementsByClassName('share-tip')[0];
if (!popup) return;
// Do nothing if the function's already done its thing
const origHtml = popup.innerHTML;
if (origHtml.indexOf(toRemove) == -1) return;
popup.innerHTML = origHtml.replace(toRemove, '');
const input = popup.querySelector('input');
const origLink = input.value;
input.value = origLink.match(/.+\/(q|a)\/[0-9]+/g);
input.select();
});
},
shareLinksMarkdown: function() {
// Description: For changing the 'share' button link to the format [name](link)
const questionTarget = document.getElementById('question');
const answersTargets = document.getElementsByClassName('answer');
sox.helpers.observe([questionTarget, ...answersTargets], '.share-tip', () => {
const input = document.querySelector('.share-tip input');
if (!input) return;
const title = document.querySelector('meta[name="twitter:title"]').getAttribute('content').replace(/\[(.*?)\]/g, '[$1]'); // https://github.com/soscripted/sox/issues/226, https://github.com/soscripted/sox/issues/292
const link = input.value;
// Do nothing if the function's already done its thing
if (link.indexOf(title) !== -1) return;
input.value = `[${title}](${link})`;
input.select();
document.execCommand('copy'); // https://github.com/soscripted/sox/issues/177
});
},
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() {
const 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
function addSpoilerTip() {
const $spoiler = $('.spoiler');
$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);
});
}
addSpoilerTip();
$(document).on('sox-new-review-post-appeared', addSpoilerTip);
},
commentReplies: function() {
// Description: For adding reply links to comments
if (!sox.user.loggedIn) return;
function addReplyLinks() {
// Delay needed because of https://github.com/soscripted/sox/issues/379#issuecomment-460001854
setTimeout(() => {
$('.comment').each(function () {
if (!$(this).find('.soxReplyLink').length) { //if the link doesn't already exist
if (sox.user.name !== $(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).find('.comment-text .comment-body').append('<span class="soxReplyLink" title="reply to this user" style="margin-left: -7px">↵</span>');
}
}
});
}, 100);
}
$(document).on('click', 'span.soxReplyLink', function() {
const parentDiv = $(this).closest('.post-layout');
const textToAdd = '@' + $(this).parent().find('a.comment-user').text().replace(/\s/g, '').replace(/♦/, ''); //eg. @USERNAME
if (!parentDiv.find('textarea').length) parentDiv.find('a.js-add-link')[0].click(); //show the textarea, http://stackoverflow.com/a/10559680/
const $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();
$(document).on('sox-new-comment', addReplyLinks);
$(document).on('sox-new-review-post-appeared', addReplyLinks);
},
parseCrossSiteLinks: function() {
// Description: For converting cross-site links to their titles
function expandLinks() {
const isQuestionLink = /\/(q|questions)\//;
const FILTER_QUESTION_TITLE = '!)5IW-5QufDkXACxq_MT8aYkZRhm9';
$('.post-text a:not(.expand-post-sox), .comment-copy a:not(.expand-post-sox)').each(function() {
const href = this.href.replace(/https?:\/\//, '').replace(/www\./, '');
if (!href) return;
const sitename = sox.helpers.getSiteNameFromLink(href);
const questionID = sox.helpers.getIDFromLink(href);
// if it is a bare link is to a question on a SE site
if (questionID && sitename && isQuestionLink.test(href) && this.innerText.replace(/https?:\/\//, '').replace(/www\./, '') === href) {
sox.helpers.getFromAPI({
endpoint: 'questions',
ids: questionID,
sitename,
filter: FILTER_QUESTION_TITLE,
featureId: 'parseCrossSiteLinks',
}, items => {
this.innerHTML = items[0].title;
});
}
});
}
expandLinks();
$(document).on('sox-new-review-post-appeared', expandLinks);
},
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', () => {
const textarea = document.querySelector('.comment-form textarea');
if (textarea && textarea.value) {
return 'Do you really want to navigate away? Anything you have written will be lost!';
}
return;
});
}
},
sortByBountyAmount: function() {
// Description: For adding some buttons to sort bounty's by size
// Do nothing unless there is at least one bounty on the page
if (!document.getElementsByClassName('bounty-indicator').length) return;
[...document.getElementsByClassName('question-summary')].forEach(summary => {
const indicator = summary.querySelector('.bounty-indicator');
const bountyAmount = indicator ? indicator.innerText.replace('+', '') : undefined;
if (bountyAmount) {
summary.setAttribute('data-bountyamount', bountyAmount);
summary.classList.add('hasBounty'); // Add a 'bountyamount' attribute to all the questions
}
});
// Homepage/questions tab
const wrapper = document.getElementById('question-mini-list') || document.getElementById('questions');
// 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', () => { // Largest first
[...wrapper.querySelectorAll('.question-summary.hasBounty')].sort((a, b) => {
return +b.getAttribute('data-bountyamount') - +a.getAttribute('data-bountyamount');
}).prependTo($(wrapper));
});
$('#smallestFirst').css('cursor', 'pointer').on('click', () => { // Smallest first
[...wrapper.querySelectorAll('.question-summary.hasBounty')].sort((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 (!document.getElementsByClassName('sox-hot').length) {
document.getElementById('feed').innerHTML = '<p>SOX: One of the 100 hot network questions!</p>';
//display:block to fix https://github.com/soscripted/sox/issues/243:
$(document.getElementById('question-header')).css('display', 'block').prepend('<div title="SOX: this is a hot network question!" ' + (sox.location.on('english.stackexchange.com') ? 'style="padding:13px"' : '') + ' class="sox-hot"><i class="fab fa-free-code-camp"></i><div>');
}
}
$(document.getElementById('qinfo')).after('<div id="feed"></div>');
if (sox.location.on('/questions') || $('.question-summary').length) {
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'; //CORS proxy
const hnqJSONUrl = 'https://stackexchange.com/hot-questions-for-mobile';
const requestUrl = proxyUrl + hnqJSONUrl;
$.get(requestUrl, results => {
if (sox.location.on('/questions/')) {
$.each(results, (i, o) => {
if (document.URL.indexOf(o.site + '/questions/' + o.question_id) > -1) addHotText();
});
} else {
$('.question-summary').each(function() {
const id = $(this).attr('id').split('-')[2];
if (results.filter(d => {
return d.question_id == id;
}).length) {
$(this).find('.summary h3').prepend('<div title="SOX: this question is a hot network question!" class="sox-hot" style="font-size:x-large;float:none;display:inline"><i class="fab fa-free-code-camp"></i></div>');
}
});
}
});
}
},
localTimestamps: function(settings) {
// Description: Gets local timestamp
$('span.relativetime:contains(at), span.relativetime-clean:contains(at)').each(updateTS);
function updateTS() {
const utcTimestamp = $(this).attr('title');
const matches = utcTimestamp.match(/^([\d]{4})-([\d]{2})-([\d]{2}) ([\d]{2}):([\d]{2}):([\d]{2}) ?(?:Z|UTC|GMT(?:[+-]00:?00))$/);
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (!matches) return;
const date = new Date(
Date.UTC(
parseInt(matches[1], 10),
parseInt(matches[2], 10) - 1,
parseInt(matches[3], 10),
parseInt(matches[4], 10),
parseInt(matches[5], 10),
parseInt(matches[6], 10)
)
);
const month = monthNames[date.getMonth()];
const minute = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
const year = ((date.getFullYear() - 2000) < 10 ? '0' : '') + (date.getFullYear() - 2000);
let hour = date.getHours();
let dayTime = '';
if (settings.twelveHours) {
dayTime = 'am';
if (date.getHours() >= 12) {
dayTime = 'pm';
hour -= 12;
}
if (hour === 0)
hour += 12;
}
const newTimestamp = (new Date()).getFullYear() == date.getFullYear() ? month + ' ' + date.getDate() + ' at ' + hour + ':' + minute + dayTime : month + ' ' + date.getDate() + ' \'' + year + ' at ' + hour + ':' + minute + dayTime;
$(this).attr('title', newTimestamp).text(newTimestamp);
}
},
autoShowCommentImages: function() {
// Description: For auto-inlining any links to imgur images in comments
function showImages() {
$('.comment .comment-text .comment-copy a').each(function() {
const href = this.href;
const parent = this.parentNode;
if (parent && href && (/i(\.stack)?\.imgur\.com/.test(href))) {
if (!parent.querySelectorAll('img[src="' + href + '"]').length) {
//DO NOT USE innerHTML -- it *removes* the old DOM and inserts a new one (https://stackoverflow.com/a/23539150), meaning it won't work for multiple imgur links in the same comment
//https://github.com/soscripted/sox/issues/360
$(parent).append('<br><a href="' + href + '"><img class="sox-autoShowCommentImages-image" src="' + href + '" style="max-width:100%"></a>');
}
}
});
}
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.
$(document).on('sox-new-comment', showImages);
$(document).on('sox-new-review-post-appeared', showImages);
},
showCommentScores: function() {
// Description: For adding a button on your profile comment history pages to show your comment's scores
const sitename = sox.site.currentApiParameter;
const WHITESPACES = ' ';
const COMMENT_SCORE_FILTER = '!)5IW-5QufDkXACxq_MT8bhYD9b.m';
function addLabelsAndHandlers() {
$('.history-table td b a[href*="#comment"]').each(function() {
if (!$(this).parent().find('.showCommentScore').length) {
const id = +this.href.match(/comment(\d+)_/)[1];
$(this).after('<span class="showCommentScore" id="' + id + '">' + WHITESPACES + 'show comment score</span>');
}
});
$('.showCommentScore').css('cursor', 'pointer').on('click', function() {
sox.helpers.getFromAPI({
endpoint: 'comments',
ids: this.id,
sitename,
filter: COMMENT_SCORE_FILTER,
useCache: false, // Single ID, so no point
}, items => {
this.innerHTML = WHITESPACES + items[0].score;
});
});
}
addLabelsAndHandlers();
const target = document.getElementById('mainbar-full');
if (target) sox.helpers.observe(target, '.history-table', addLabelsAndHandlers);
},
answerTagsSearch: function() {
// Description: For adding tags to answers in search
function getQuestionIDFromAnswerDIV(answerDIV) {
return sox.helpers.getIDFromAnchor(answerDIV.querySelector('.result-link a'));
}
function addClassToInsertedTag(tagLink) {
if (/status-/.test(tagLink.innerText)) {
tagLink.classList.add('moderator-tag');
} else if (/\b(discussion|feature-request|support|bug)\b/.test(tagLink.innerText)) {
tagLink.classList.add('required-tag');
}
}
const tagsForQuestionIDs = {};
const QUESTION_TAGS_FILTER = '!)8aDT8Opwq-vdo8';
const questionIDs = [];
const answers = [...document.getElementsByClassName('question-summary')].filter(q => /answer-id/.test(q.id));
// Get corresponding question's ID for each answer
answers.forEach(answer => {
const questionID = getQuestionIDFromAnswerDIV(answer);
// Cache value for later reference
answer.dataset.questionid = questionID;
questionIDs.push(questionID);
});
sox.helpers.getFromAPI({
endpoint: 'questions',
ids: questionIDs,
sitename: sox.site.currentApiParameter,
filter: QUESTION_TAGS_FILTER,
limit: 60,
sort: 'creation',
featureId: 'answerTagsSearch',
}, items => {
const itemsLength = items.length;
for (let i = 0; i < itemsLength; i++) {
const item = items[i];
tagsForQuestionIDs[item.question_id] = item.tags;
}
answers.forEach(answer => {
const id = +answer.dataset.questionid;
const tagsForThisQuestion = tagsForQuestionIDs[id];
for (let x = 0; x < tagsForThisQuestion.length; x++) {
const currTag = tagsForThisQuestion[x];
const $insertedTag = $(answer.querySelector('.summary .tags')).append('<a href="/questions/tagged/' + currTag + '" class="post-tag">' + currTag + '</a>');
addClassToInsertedTag($insertedTag);
}
});
});
},
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!
$('.votecell > .js-voting-container').css({ //.votecell is necessary; e.g., the number of votes of questions on the Questions list for a site uses the .vote class too
'position': '-webkit-sticky',
// eslint-disable-next-line no-dupe-keys
'position': 'sticky',
'top': parseInt($('.container').css('margin-top'), 10) + parseInt($('body').css('padding-top'), 10), //Seems like most sites use margin-top on the container, but Meta and SO use padding on the body
});
},
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('titleEditDiff: running betterTitle');
const $questionHyperlinkOriginal = $('.summary h2 .question-hyperlink');
const $questionHyperlink = $questionHyperlinkOriginal.clone();
const $questionHyperlinkTwo = $questionHyperlinkOriginal.clone();
const link = $questionHyperlinkOriginal.attr('href');
const added = ($questionHyperlinkTwo.find('.diff-delete').remove().end().text());
const removed = ($questionHyperlink.find('.diff-add').remove().end().text());
if ($questionHyperlinkOriginal.find('.diff-delete, .diff-add').length && !($('.sox-better-title').length)) {
if (!$('.sox-better-title-toggle').length) {
$('.summary h2 .question-hyperlink').before('<i class="sox-better-title-toggle fa fa-toggle-on" title="toggle SOX better title diff"></i>');
}
$questionHyperlinkOriginal.addClass('sox-original-title-diff').hide();
$questionHyperlinkOriginal.after('<a href="' + link + '" class="question-hyperlink sox-better-title"><span class="diff-delete">' + removed + '</span><span class="diff-add">' + added + '</span></a>');
}
}
// https://github.com/soscripted/sox/issues/166#issuecomment-269925059
$(document).on('click', '.sox-better-title-toggle', function() {
const $soxOriginalTitleDiff = $('.sox-original-title-diff');
if ($soxOriginalTitleDiff.is(':visible')) {
$(this).addClass('fa-toggle-on').removeClass('fa-toggle-off');
$soxOriginalTitleDiff.hide();
$('.sox-better-title').show();
} else {
$(this).removeClass('fa-toggle-on').addClass('fa-toggle-off');
$soxOriginalTitleDiff.show();
$('.sox-better-title').hide();
}
});
betterTitle();
const target = document.querySelector('.review-content');
sox.helpers.observe(target, '.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
$(document).on('mouseenter', '#your-communities-section > ul > li > a', function() {
const href = this.href.replace(/https?:\/\//, '');
let link;
let chatLink = 'https://chat.stackexchange.com?tab=site&host=' + href.replace(/\/.*/, '');
if (href === 'meta.stackexchange.com/') { //Meta SE's chat link is a bit different
chatLink = 'https://chat.meta.stackexchange.com';
} else if (href.indexOf('meta') > -1) { //For the usual meta sites
link = 'https://' + href.split('meta.').shift() + href.split('meta.').pop();
chatLink = 'https://chat.stackexchange.com?tab=site&host=' + href.split('meta.').shift() + href.split('meta.').pop().split('/').shift(); //We don't need "meta." in the chat links
} else if (href.indexOf('.stackexchange.com') > -1 || href.indexOf('.stackoverflow.com') > -1) { //For the majority of SE sites, and other languages of SO
link = 'https://' + href.split('.').shift() + '.meta' + href.split(href.split('.').shift()).pop();
} else if (href.indexOf('stackapps') == -1) { //For sites that have unique URLs, e.g. serverfault.com (except StackApps, which has no meta)
link = 'https://meta.' + href;
}
if (href.indexOf('stackoverflow.com') > -1 && !href.match(/(pt|ru|es|ja|.meta)/i)) { //English Stack Overflow has a unique chat link
chatLink = 'https://chat.stackoverflow.com';
}
//All sites have either a chat link or meta link
$(this).find('.rep-score').stop(true).delay(135).fadeOut(20);
$(this).append('<div class="related-links" style="float: right; display: none;">' +
(link ?
(href.indexOf('meta') > -1 ? '<a href="' + link + '">main</a>' : '<a href="' + link + '">meta</a>') :
'') +