-
Notifications
You must be signed in to change notification settings - Fork 15
/
sox.features.js
2626 lines (2189 loc) · 118 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
/* globals Notifier, fkey */
(function(sox, $) {
'use strict';
sox.features = { //SOX functions must go in here
moveBounty: function() {
// Description: For moving bounty to the top
const bountyLink = document.querySelector('.bounty-link.bounty');
if (!bountyLink) return; // question not eliglible for bounty
const bountyLinkDiv = bountyLink.parentElement.parentElement;
const cloneBounty = bountyLinkDiv.cloneNode(true);
bountyLinkDiv.previousElementSibling.insertAdjacentElement('beforebegin', cloneBounty);
bountyLinkDiv.remove();
},
dragBounty: function() {
// Description: Makes the bounty window draggable
sox.helpers.addAjaxListener('\\/posts\\/bounty\\/\\d+', () => {
const bountyPopup = document.querySelector('#start-bounty-popup');
$(bountyPopup).draggable({
drag: function() {
$(this).css({
'width': 'auto',
'height': 'auto',
});
},
});
bountyPopup.style.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];
}
},
copyCommentsLink: function() {
// Description: Adds the 'show x more comments' link before the commnents
// Test on e.g. https://meta.stackexchange.com/questions/125439/
function copyLinks() {
[...document.querySelectorAll('.js-show-link')].forEach(element => {
if (element.classList.contains('sox-copyCommentsLinkClone')) { // Don't run on already cloned elements
return;
}
const btnToAdd = element.cloneNode(true);
btnToAdd.classList.add('sox-copyCommentsLinkClone');
btnToAdd.addEventListener('click', event => {
event.preventDefault();
btnToAdd.style.display = 'none';
});
element.parentElement.parentElement.prepend(btnToAdd);
element.addEventListener('click', () => { btnToAdd.style.display = 'none'; }); // also hide the clone when the other button is clicked!
const addCommentLink = element.parentElement.querySelector('.js-add-link');
if (!addCommentLink) { // Deleted posts don't have an 'add comment' link
return;
}
addCommentLink.addEventListener('click', () => { element.style.display = 'none'; }); // https://github.com/soscripted/sox/issues/239
});
}
copyLinks();
document.addEventListener('sox-new-comment', copyLinks);
},
highlightQuestions: function() {
// Description: For highlighting only the tags of favorite questions
function highlight() {
[...document.querySelectorAll('.s-post-summary__watched')].forEach(interestingQuestion => {
interestingQuestion.classList.remove('s-post-summary__watched');
interestingQuestion.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('s-post-summary').length) {
sox.helpers.addAjaxListener('\\/posts\\/ajax-load-realtime-list', highlight);
}
},
displayName: function() {
// Description: For displaying username next to avatar on topbar
if (sox.user.loggedIn) {
const name = sox.user.name;
const spanUsernameHtml = `<span class="reputation links-container sox-displayName" title="${name}">${name}</span>`;
document.querySelector('.s-topbar--item.s-user-card').insertAdjacentHTML('afterbegin', spanUsernameHtml);
}
},
colorAnswerer: function() {
// Description: For highlighting the names of answerers on comments
function color() {
[...document.getElementsByClassName('answercell')].forEach(cell => {
const answerer = cell.querySelector('.post-signature:nth-last-of-type(1) a');
if (!answerer) return; // e.g. in case of a deleted user
const answererId = answerer.href.match(/\d+/)[0];
const commentUsers = [...cell.parentElement.querySelectorAll('.comments .comment-user')];
commentUsers.forEach(user => {
if (!user.href || !user.href.contains(`users/${answererId}`)) return;
user.classList.add('sox-answerer');
});
});
}
color();
document.addEventListener('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 addBullets(node) {
const list = '- ' + getSelection(node).split('\n').join('\n- ');
replaceSelectedText(node, list);
}
function addKbd(node) {
sox.helpers.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 "-" 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.addEventListener('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>
<section>${name}</section> <i><section>${text}</section></i>
<button class="grid--cell s-btn sox-editComment-editDialogButton" data-name="${name}">Edit</button>
<button class="grid--cell s-btn s-btn__danger 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',
'html': `<div id="currentValues" class="sox-editComment-currentValues"></div>
<br />
<h3 style="color: var(--fc-dark)">Add a custom reason</h3>
<div class="grid gs4 gsy fd-column" style="display: inline">
<div class="grid--cell" style="float: left">
<label class="d-block s-label" style="padding-top: 5px">Display reason: </label>
</div>
<div class="grid ps-relative" style="padding-left: 5px">
<input class="s-input" type="text" style="width: 40% !important" id="displayReason">
</div>
</div>
<div class="grid gs4 gsy fd-column" style="display: inline">
<div class="grid--cell" style="float: left">
<label class="d-block s-label" style="padding-top: 5px">Actual reason: </label>
</div>
<div class="grid ps-relative" style="padding-left: 5px">
<input class="s-input" type="text" style="width: 40% !important" id="actualReason">
</div>
</div>
<input class="s-btn s-btn__primary" type="button" id="submitUpdate" value="Submit">
<input class="s-btn s-btn__primary" 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();
}
});
document.body.appendChild(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 class="s-checkbox" type="checkbox" value="${text}"</input>${name}</label>
`);
});
$reasons.find('input[type="checkbox"]').change(function() {
const reason_value = $(this).val();
if (this.checked) { //Add it to the summary
if ($editCommentField.val()) {
$editCommentField.val($editCommentField.val() + '; ' + reason_value);
} else {
$editCommentField.val(toLocaleSentenceCase(reason_value));
}
const newEditComment = $editCommentField.val(); //Remove the last space and last semicolon
$editCommentField.val(newEditComment).focus();
} else { //Remove it from the summary
$editCommentField.val($editCommentField.val().replace('; ' + reason_value, '')); //for middle and end values
$editCommentField.val($editCommentField.val().replace(new RegExp(reason_value + ';? ?', 'i'), '')); //for start values
}
});
}
}
$(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]);
$(this).html('Save').addClass('sox-editComment-saveDialogButton').parent()
.find('section').attr('contenteditable', true).css('border', '1px solid var(--black-200)');
$(document).on('click', '.sox-editComment-saveDialogButton', function() {
$(this).html('Edit').removeClass('sox-editComment-saveDialogButton').parent().find('section').attr('contenteditable', false).css('border', 'none');
const newName = $(this).parent().find('section').first().html();
const newText = $(this).parent().find('section').eq(1).html();
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.addEventListener('sox-edit-window', addCheckboxes);
},
shareLinksPrivacy: function() {
// Description: Remove your user ID from the 'share' link
[...document.querySelectorAll('.js-share-link')].forEach(element => {
element.href = element.href.match(/\/(q|a)\/[0-9]+/)[0];
element.addEventListener('click', () => {
// Remove the 'includes your user id' string, do it on click because
// SE's code seems to re-add the element when the share tip is shown
element.parentElement.querySelector('.js-subtitle').remove();
});
});
},
shareLinksMarkdown: function() {
// Description: For changing the 'share' button link to the format [name](link)
// Remove [] with () in title: https://github.com/soscripted/sox/issues/226, https://github.com/soscripted/sox/issues/292
const title = document.querySelector('.fs-headline1.fl1').innerText.replace(/\[(closed|duplicate)\]/g, '($1)');
[...document.querySelectorAll('.js-share-link')].forEach(element => {
element.addEventListener('click', () => {
const $inputEl = element.parentElement.querySelector('.js-input');
// TODO: is there a way to do this without a hacky setTimeout?
// Seems like SE has some JS that populates the input field which overwrites
// anything we do unless there's a setTimeout
setTimeout(() => {
// The href is relative, so make it absolute
const href = new URL(element.href, window.location.href).href;
const textToCopy = `[${title}](${href})`;
$inputEl.value = textToCopy;
$inputEl.select();
GM_setClipboard(textToCopy); // https://github.com/soscripted/sox/issues/177
}, 0);
});
});
},
commentShortcuts: function() {
// Description: For adding support in comments for Ctrl + K, I, B to add code backticks, italicise, and bolden selection
$('.comments').on('keydown', 'textarea', function (e) {
const el = $(this).get(0);
if (e.which == 75 && e.ctrlKey) { // Ctrl + k: add code backticks (`code`)
sox.helpers.surroundSelectedText(el, '`', '`');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 73 && e.ctrlKey) { // Ctrl + i: italicize (*text*)
sox.helpers.surroundSelectedText(el, '*', '*');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 66 && e.ctrlKey) { // Ctrl + b bolden (**bold text**)
sox.helpers.surroundSelectedText(el, '**', '**');
e.stopPropagation();
e.preventDefault();
return false;
}
});
},
unspoil: function() {
// Description: For adding a button to reveal all spoilers in a post
[...document.querySelectorAll('#answers div[id*="answer"], div[id*="question"]')].forEach(element => {
const buttonHtml = `<span class="lsep">|</span><a id="showSpoiler-${element.id}" href="javascript:void(0)">unspoil</span>`;
if (element.querySelector('.spoiler')) {
element.querySelector('.post-menu').insertAdjacentHTML('beforeend', buttonHtml);
}
});
[...document.querySelectorAll('a[id*="showSpoiler"]')].forEach(element => {
element.addEventListener('click', () => {
const spoiler = element.id.split(/-(.+)?/)[1];
[...document.querySelectorAll(`#${spoiler} .spoiler`)].forEach(spoiler => spoiler.classList.remove('spoiler'));
});
});
},
commentReplies: function() {
// Description: For adding reply links to comments
if (!sox.user.loggedIn) return;
const replyButton = '<span class="soxReplyLink" title="reply to this user" style="margin-left: -7px">↵</span>';
function addReplyLinks() {
[...document.querySelectorAll('.comment')].forEach(comment => {
if (!comment.querySelector('.soxReplyLink')) { // if the link doesn't already exist
const commenterLink = comment.querySelector('.comment-text a.comment-user');
if (!commenterLink) { // If the commenter's account is now deleted, there will be no link
return;
}
if (sox.user.name !== commenterLink.innerText) { // make sure the link is not added to your own comments
comment.querySelector('.comment-text').overflowX = 'hidden';
comment.querySelector('.comment-text .comment-body').insertAdjacentHTML('beforeend', replyButton);
}
}
});
}
$(document).on('click', 'span.soxReplyLink', function() {
const parentDiv = $(this).closest('.post-layout');
const textToAdd = '@' + this.parentElement.querySelector('a.comment-user').innerText.replace(/\s/g, '').replace(/♦/, ''); // e.g. @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.addEventListener('sox-new-comment', addReplyLinks);
window.addEventListener('sox-new-review-post-appeared', addReplyLinks);
},
parseCrossSiteLinks: function() {
// Description: For converting cross-site links to their titles
const isQuestionLink = /\/(q|questions)\//;
const FILTER_QUESTION_TITLE = '!)5IW-5QufDkXACxq_MT8aYkZRhm9';
function expandLinks() {
[...document.querySelectorAll('.js-post-body a:not(.expand-post-sox), .comment-copy a:not(.expand-post-sox)')].forEach(anchor => {
const href = anchor.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) && anchor.innerText.replace(/https?:\/\//, '').replace(/www\./, '') === href) {
sox.helpers.getFromAPI({
endpoint: 'questions',
ids: questionID,
sitename,
filter: FILTER_QUESTION_TITLE,
featureId: 'parseCrossSiteLinks',
cacheDuration: 10, // Cache for 10 minutes
}, items => {
anchor.innerHTML = items[0].title;
});
}
});
}
expandLinks();
window.addEventListener('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
$(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
const sortButton = `<button class="s-btn s-btn__muted s-btn__outlined s-btn__sm s-btn__dropdown" role="button" data-controller="s-popover"
data-action="s-popover#toggle" data-target="se-uql.bountyAmount" aria-haspopup="true"
aria-expanded="false" aria-controls="sox-bounty-popover">SOX: sort by bounty</button>`;
const sortPopover = `<div class="s-popover z-dropdown ws2" id="sox-bounty-popover" data-target="se-uql.bountyAmount"
style="margin: 0px;" data-popper-placement="bottom">
<div class="s-popover--arrow" style="position: absolute; left: 0px; transform: translate(99px, 0px);"></div>
<ul class="list-reset mtn8 mbn8 js-uql-navigation">
<li class="uql-item my0"><a id="largestFirst" class="mln12 mrn12 px12 py6 fl1 s-block-link">Largest first</a></li>
<li class="uql-item my0"><a id="smallestFirst" class="mln12 mrn12 px12 py6 fl1 s-block-link">Smallest first</a></li>
</ul>
</div>`;
// Do nothing unless there is at least one bounty on the page
if (!document.getElementsByClassName('bounty-indicator').length) return;
[...document.querySelectorAll('.question-summary')].forEach(summary => {
const indicator = summary.querySelector('.bounty-indicator');
const bountyAmount = indicator ? indicator.innerText.replace('+', '') : undefined;
if (bountyAmount) {
summary.setAttribute('data-bountyamount', bountyAmount); // Add a 'bountyamount' attribute to all the questions
summary.classList.add('sox-hasBounty');
}
});
// Homepage/questions tab
const wrapper = document.getElementById('question-mini-list') || document.getElementById('questions');
// Filter buttons:
document.querySelector('.uql-nav .js-uql-navigation').insertAdjacentHTML('beforeend', sortButton);
document.querySelector('#uql-more-popover').insertAdjacentHTML('afterend', sortPopover);
// Thanks: http://stackoverflow.com/a/14160529/3541881
document.querySelector('#smallestFirst').addEventListener('click', () => { // Smallest first
[...wrapper.querySelectorAll('.question-summary.sox-hasBounty')].sort((a, b) => {
return +b.getAttribute('data-bountyamount') - +a.getAttribute('data-bountyamount');
}).forEach(element => wrapper.insertAdjacentElement('afterbegin', element));
});
document.querySelector('#largestFirst').addEventListener('click', () => { // Largest first
[...wrapper.querySelectorAll('.question-summary.sox-hasBounty')].sort((a, b) => {
return +a.getAttribute('data-bountyamount') - +b.getAttribute('data-bountyamount');
}).forEach(element => wrapper.insertAdjacentElement('afterbegin', element));
});
},
isQuestionHot: function() {
// Description: For adding some text to questions that are in the hot network questions list
function getHotDiv(className) {
const divToReturn = document.createElement('div');
divToReturn.title = 'SOX: this is a hot network question!';
divToReturn.className = `sox-hot ${className || ''}`;
divToReturn.appendChild(sox.sprites.getSvg('hot'));
return divToReturn;
}
function addHotText() {
if (document.getElementsByClassName('sox-hot').length) return;
document.getElementById('question-header').prepend(getHotDiv());
}
function addHotTextInSummary(summaryElement) {
summaryElement.querySelector('.summary h3').prepend(getHotDiv('question-list'));
}
function questionMatchesCriteria(revisionObject) {
return revisionObject.comment // there's comment, post was not created at that revision
&& !revisionObject.comment.includes('<b>Post Closed</b> as "') // post is not closed
&& !revisionObject.comment.includes('<b>Removed from Hot Network Questions</b> by') // post has not been removed from HNQ
&& revisionObject.comment === '<b></b> ' && new Date().getTime() / 1000 - revisionObject.creation_date <= 259200; // question is HNQ AND not 3 days old
}
if (sox.location.on('/questions/')) {
const postId = window.location.pathname.split('/')[2];
getIsQuestionHot(postId);
} else if (document.querySelector('.s-post-summary')) {
const questionIds = [];
[...document.querySelectorAll('.s-post-summary')].forEach(summary => {
// Check if .question-summary has an id attribute - SO Teams posts (at the top of the page, if any) don't!
if (!summary.id) return;
questionIds.push(summary.id.split('-')[2]);
});
getIsQuestionHot(questionIds);
}
function getIsQuestionHot(postIds) {
sox.helpers.getFromAPI({
endpoint: 'posts',
childEndpoint: 'revisions',
sitename: sox.site.currentApiParameter,
filter: '!SWJaL5tfbL4Ta*2*G*',
ids: postIds,
featureId: 'isQuestionHot',
cacheDuration: 60 * 8, // Cache for 8 hours
}, results => {
if (!results) return;
// There are two cases:
// 1. We are in a question page (/questions/\d+) and we want to check only 1 question => 1 API call
// 2. We are in a page with many questions (e.g. /questions). We collect or ids to reduce the API calls and avoid throttling
// In both cases, we return an array with the ids of the HNQs. Then, the icons are added where necessary
results.filter(result => questionMatchesCriteria(result))
.forEach(item => sox.location.on('/questions') ? addHotText() : addHotTextInSummary(document.querySelector(`#question-summary-${item.post_id}`)));
});
}
},
localTimestamps: function(settings) {
// Description: Gets local timestamp
function updateTimestamps(element) {
const utcTimestamp = element.title;
const matches = utcTimestamp.match(/^([\d]{4})-([\d]{2})-([\d]{2}) ([\d]{2}):([\d]{2}):([\d]{2}) ?(?:Z|UTC|GMT(?:[+-]00:?00))/);
if (!matches) return;
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
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 = month + ' ' + date.getDate() + (new Date().getFullYear() == date.getFullYear() ? '' : ' \'' + year) +' at ' + hour + ':' + minute + dayTime;
element.innerText = newTimestamp;
}
[...document.querySelectorAll('span.relativetime, span.relativetime-clean')].filter(el => el.innerText.contains('at'))
.forEach(element => updateTimestamps(element));
},
autoShowCommentImages: function() {
// Description: For auto-inlining any links to imgur images in comments
function showImages() {
[...document.querySelectorAll('.comment .comment-text .comment-copy a')].forEach(anchor => {
const href = anchor.href;
const parent = anchor.parentNode;
if (parent && href && (/i(\.stack)?\.imgur\.com|i\.sstatic\.net/.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. See https://github.com/soscripted/sox/issues/360
parent.insertAdjacentHTML('beforeend', `<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.addEventListener('sox-new-comment', showImages);
window.addEventListener('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() {
[...document.querySelectorAll('.history-table td b a[href*="#comment"]')].forEach(anchor => {
if (!anchor.parentElement.querySelector('.showCommentScore')) {
const id = +anchor.href.match(/comment(\d+)_/)[1];
anchor.insertAdjacentHTML('afterend', `<span class="showCommentScore" id="${id}">${WHITESPACES}show comment score</span>`);
}
});
[...document.querySelectorAll('.showCommentScore')].forEach(button => {
button.style.cursor = 'pointer';
button.addEventListener('click', function() {
sox.helpers.getFromAPI({
endpoint: 'comments',
ids: button.id,
sitename,
filter: COMMENT_SCORE_FILTER,
useCache: false, // Single ID, so no point
}, items => {
button.innerHTML = WHITESPACES + items[0].score;
});
});
});
}
addLabelsAndHandlers();
sox.helpers.addAjaxListener('\\/ajax\\/users\\/tab\\/\\d+\\?tab=activity&sort=comments', 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',
cacheDuration: 10, // Cache for 10 minutes
}, items => {
items.forEach(item => {
tagsForQuestionIDs[item.question_id] = item.tags;
});
answers.forEach(answer => {
const id = +answer.dataset.questionid;
const tagsForThisQuestion = tagsForQuestionIDs[id];
tagsForThisQuestion.forEach(currTag => {
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!
const containerTopMargin = sox.helpers.getCssProperty(document.querySelector('.container'), 'margin-top');
const bodyTopPadding = sox.helpers.getCssProperty(document.body, 'padding-top');
// .votecell is necessary; e.g., the number of votes of questions on the Questions list for a site uses the .vote class too
[...document.querySelectorAll('.votecell')].forEach(votecell => votecell.classList.add('sox-stickyVoteButtons'));
// Seems like most sites use margin-top on the container, but Meta and SO use padding on the body
[...document.querySelectorAll('.votecell .js-voting-container')].forEach(container => {
container.style.top = parseInt(containerTopMargin.replace('px', '')) + parseInt(bodyTopPadding.replace('px', '')) + 'px';
});
},
metaChatBlogStackExchangeButton: function() {
// Description: For adding buttons next to sites under the StackExchange button that lead to that site's meta and chat
[...document.querySelectorAll('#your-communities-section ul li a')].forEach(siteAnchor => {
siteAnchor.addEventListener('mouseenter', 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();
// We don't need "meta." in the chat links
chatLink = 'https://chat.stackexchange.com?tab=site&host=' + href.split('meta.').shift() + href.split('meta.').pop().split('/').shift();
} 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;
} else 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';
}
let buttonsHtml = '<div class="related-links" style="float: right; display: none;">';
if (link) {
buttonsHtml += href.indexOf('meta') > -1 ? `<a href="${link}">main</a>` : `<a href="${link}">meta</a>`; // if it's meta, link to main and the opposite!
}
if (chatLink) buttonsHtml += `<a href="${chatLink}">chat</a>`;
buttonsHtml += '</div>';
// All sites have either a chat link or meta link
$(this.querySelector('.rep-score')).stop(true).delay(135).fadeOut(20);
this.insertAdjacentHTML('beforeend', buttonsHtml);
$(this.querySelector('.related-links')).delay(135).css('opacity', 0).animate({
opacity: 1,
width: 'toggle',
}, 200);
});
siteAnchor.addEventListener('mouseleave', function() {
$(this.querySelector('.rep-score')).stop(true).fadeIn(110);
this.querySelector('.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, chat, or sites without a meta
if ((sox.site.type != 'main' && sox.site.type != 'beta') || !document.querySelector('.related-site')) return;
// Don't run if the user is a moderator
if (sox.Stack && sox.Stack.options.user.isModerator) return;
const NEWQUESTIONS = 'metaNewQuestionAlert-lastQuestions';
const favicon = sox.site.icon;
const sitename = sox.site.currentApiParameter;
// If it is a special site, add 'meta' before it, if not, replace the 'stackexchange' from the URL with 'meta'.
if (sitename.match(/stackoverflow|superuser|serverfault|askubuntu|stackapps|mathoverflow/)) {
var metaName = 'meta.' + sitename;
} else {
metaName = sitename.replace('stackexchange','meta');
}
const FILTER_QUESTION_TITLE_LINK = '!BHMIbze0EQ*ved8LyoO6rNk25qGESy';
const dialog = document.createElement('div');
dialog.id = 'metaNewQuestionAlertDialog';
dialog.className = 'topbar-dialog';
dialog.style.display = 'none';
const header = document.createElement('div');
header.className = 'header';
const anchorToAppend = document.createElement('a');
anchorToAppend.innerText = 'new meta posts';
anchorToAppend.href = `//meta.${sox.site.url}`;
anchorToAppend.style.color = '#0077cc';
header.appendChild(anchorToAppend);
const content = document.createElement('div');
content.className = 'modal-content';
const questions = document.createElement('ul');
questions.id = 'metaNewQuestionAlertDialogList';
questions.className = 'js-items items';
const diamond = document.createElement('a');
diamond.id = 'metaNewQuestionAlertButton';
diamond.className = 'sox-settings-button s-topbar--item';
diamond.title = 'Moderator inbox (recent meta questions)';
const diamondSvg = sox.sprites.getSvg('diamond');
diamondSvg.classList.add('svg-icon');
diamond.insertAdjacentElement('beforeend', diamondSvg);
dialog.appendChild(header);
content.appendChild(questions);
dialog.appendChild(content);
$('.s-topbar--item.s-user-card').parent().after($('<li/>').append(diamond));
dialog.style.top = sox.helpers.getCssProperty(document.querySelector('.s-topbar'), 'height');
if (document.querySelector('#metaNewQuestionAlertButton')) document.querySelector('.js-topbar-dialog-corral').appendChild(dialog);
window.addEventListener('mouseup', event => {
const dialogDisplay = sox.helpers.getCssProperty(dialog, 'display');
if (event.target.closest('#metaNewQuestionAlertButton') == diamond) { // diamond has been clicked!
event.preventDefault();
diamond.classList.toggle('is-selected');
dialog.style.display = dialogDisplay === 'none' ? 'block' : 'none';
} else if (dialogDisplay == 'block' && event.target.closest('#metaNewQuestionAlertDialog') != document.querySelector('#metaNewQuestionAlertDialog')) {
// if the user has clicked outside the dialog, then hide it
dialog.style.display = 'none';
diamond.classList.toggle('is-selected');
}
});