-
Notifications
You must be signed in to change notification settings - Fork 34
/
ReviewQueueHelper.user.js
1826 lines (1525 loc) · 64.2 KB
/
ReviewQueueHelper.user.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
// ==UserScript==
// @name Review Queue Helper
// @description Keyboard shortcuts, skips accepted questions and audits (to save review quota)
// @homepage https://github.com/samliew/SO-mod-userscripts
// @author Samuel Liew
// @version 5.0.13
//
// @match https://*.stackoverflow.com/review/*
// @match https://*.serverfault.com/review/*
// @match https://*.superuser.com/review/*
// @match https://*.askubuntu.com/review/*
// @match https://*.mathoverflow.net/review/*
// @match https://*.stackapps.com/review/*
// @match https://*.stackexchange.com/review/*
// @match https://stackoverflowteams.com/c/*/review/*
//
// @match https://*.stackoverflow.com/questions/*
// @match https://*.serverfault.com/questions/*
// @match https://*.superuser.com/questions/*
// @match https://*.askubuntu.com/questions/*
// @match https://*.mathoverflow.net/questions/*
// @match https://*.stackapps.com/questions/*
// @match https://*.stackexchange.com/questions/*
// @match https://stackoverflowteams.com/c/*/questions/*
//
// @match https://*.stackoverflow.com/admin/dashboard?flagtype=*
// @match https://*.serverfault.com/admin/dashboard?flagtype=*
// @match https://*.superuser.com/admin/dashboard?flagtype=*
// @match https://*.askubuntu.com/admin/dashboard?flagtype=*
// @match https://*.mathoverflow.net/admin/dashboard?flagtype=*
// @match https://*.stackapps.com/admin/dashboard?flagtype=*
// @match https://*.stackexchange.com/admin/dashboard?flagtype=*
// @match https://stackoverflowteams.com/c/*/admin/dashboard?flagtype=*
//
// @exclude */review/*/stats
//
// @exclude https://api.stackexchange.com/*
// @exclude https://data.stackexchange.com/*
// @exclude https://contests.stackoverflow.com/*
// @exclude https://winterbash*.stackexchange.com/*
// @exclude *chat.*
// @exclude *blog.*
// @exclude */tour
//
// @require https://raw.githubusercontent.com/samliew/SO-mod-userscripts/master/lib/se-ajax-common.js
// @require https://raw.githubusercontent.com/samliew/SO-mod-userscripts/master/lib/common.js
// ==/UserScript==
/* globals StackExchange, fkey, isSO, siteApiSlug, scriptName */
/// <reference types="./globals" />
'use strict';
/**
* @typedef {"close"|"first-answers"|"first-questions"|"late-answers"|"low-quality-posts"|"reopen"|"suggested-edits"|"triage"} QueueType
*/
const superusers = [584192];
const isSuperuser = superusers.includes(selfId);
/** @type {QueueType|null} */
const queueType = /^\/review/.test(location.pathname) ? location.pathname.replace(/\/\d+$/, '').split('/').pop() : null;
const filteredTypesElem = document.querySelector('.review-filter-summary');
const filteredTypes = filteredTypesElem ? (filteredTypesElem.innerText || '').replace(/; \[.*$/, '').split('; ') : [''];
const filteredElem = document.querySelector('.review-filter-tags');
const filteredTags = filteredElem ? (filteredElem.value || '').split(' ') : [''];
let processReview, currentReview = {}, post = {}, flaggedReason = null;
let isLinkOnlyAnswer = false, isCodeOnlyAnswer = false;
let numOfReviews = 0;
let remainingCloseVotes = null, remainingPostFlags = null;
let skipAudits = true, skipAccepted = false, skipUpvoted = false, skipMultipleAnswers = false, skipMediumQuestions = false, skipLongQuestions = false, autoCloseShortQuestions = false, autoCloseQuestions = false, downvoteAfterClose = false;
// Keywords to detect opinion-based questions
const opinionKeywords = ['fastest', 'best', 'recommended'];
// Helper functions to wait for SOMU options to load
const rafAsync = () => new Promise(resolve => { requestAnimationFrame(resolve); });
const waitForSOMU = async () => {
while (typeof SOMU === 'undefined' || !SOMU?.hasInit) { await rafAsync(); }
return SOMU;
};
/**
* @summary gets current close votes quota for the user
* @param {number[]} idPool ids of posts to open the popup on
* @returns {Promise<number>}
*/
const getCloseVotesQuota = async (idPool) => {
const firstId = idPool[0];
const res = await fetch(`${location.origin}/flags/questions/${firstId}/close/popup`);
if (!res.ok) {
console.debug(`[${scriptName}] failed to get VTC quota`);
return 0;
}
const data = await res.text();
if (/this question is now closed/i.test(data)) {
console.debug(`[${scriptName}] question ${firstId} is closed, attempting ${idPool[1]}`);
await delay(3e3 + 100); // close popups are rate-limited to once in 3 seconds;
return getCloseVotesQuota(idPool.slice(1));
}
if ($(data).find(".js-retract-close-vote").length) {
console.debug(`[${scriptName}] voted on question ${firstId}, attempting ${idPool[1]}`);
await delay(3e3 + 100); // close popups are rate-limited to once in 3 seconds;
return getCloseVotesQuota(idPool.slice(1));
}
const num = Number($('.bounty-indicator-tab, .popup-actions .ml-auto.fc-light', data).last().text().replace(/\D+/g, ''));
console.debug(`[${scriptName}] fetched VTC quota: ${num}`);
return num;
};
/**
* @summary requests and parses a list of post ids from /questions page
* @returns {Promise<number[]>}
*/
const getFirstQuestionPagePostIds = async () => {
/** @type {number[]} */
const ids = [];
const res = await fetch(`${location.origin}/questions`);
if (!res.ok) return ids;
const html = await res.text();
$(html).find(".js-post-summary").each((_, el) => {
const { postId } = el.dataset;
if (postId) ids.push(+postId);
});
return ids;
};
function getFlagsQuota(viewablePostId = 1) {
return new Promise(function (resolve, reject) {
$.get(`${location.origin}/flags/posts/${viewablePostId}/popup`)
.done(function (data) {
const num = Number($('.bounty-indicator-tab, .popup-actions .ml-auto.fc-light', data).last().text().replace(/\D+/g, ''));
console.debug(`[${scriptName}] flags quota: ${num}`);
resolve(num);
})
.fail(reject);
});
}
/**
* @summary builds a post summary stats item
* @param {...(string | Node)} content
* @returns {HTMLElement}
*/
const makePostSummaryItem = (...content) => {
const wrapper = document.createElement("div");
wrapper.classList.add("s-post-summary--stats-item");
wrapper.append(...content);
return wrapper;
};
/**
* @summary builds a badge indicator
* @param {string} text badge text
* @param {...string} classes additional CSS classes
* @returns {HTMLElement}
*/
const makeIndicator = (text, ...classes) => {
const wrapper = document.createElement("span");
wrapper.classList.add("s-badge", "s-badge__sm", ...classes);
wrapper.textContent = text;
return wrapper;
};
/**
* @summary appends a "Back" button to the review sidebar
* @returns {Promise<HTMLElement>}
*/
const addGoBackButton = async () => {
const goBackBtn = document.createElement("button");
goBackBtn.classList.add("s-btn", "s-btn__outlined");
goBackBtn.textContent = "Back";
goBackBtn.type = "button";
goBackBtn.addEventListener("click", () => history.back());
const [{
parentElement: reviewActionContainer
}] = await waitForElem(".js-review-submit");
if (!reviewActionContainer) {
console.debug(`[${scriptName}] missing review action container`);
return goBackBtn;
}
reviewActionContainer.append(goBackBtn);
return goBackBtn;
};
async function displayRemainingQuota() {
// Ignore mods, since we have unlimited power
if (StackExchange.options.user.isModerator) {
remainingCloseVotes = 0;
remainingPostFlags = 0;
}
const idPool = await getFirstQuestionPagePostIds();
// Oops, we don't have values yet, callback when done fetching
if (remainingCloseVotes == null || remainingPostFlags == null) {
try {
const [cvQuota, fQuota] = await Promise.all([
getCloseVotesQuota(idPool),
getFlagsQuota(idPool[0])
]);
remainingCloseVotes = cvQuota;
remainingPostFlags = fQuota;
displayRemainingQuota();
} catch (error) {
console.debug(`[${scriptName}] failed to fetch quotas:\n${error}`);
return;
}
return;
}
// Clear old values
$('.remaining-quota').remove();
const postStats = document.querySelector(".s-post-summary--stats");
if (!postStats) {
console.debug(`[${scriptName}] missing post stats`);
return;
}
// Display number of CVs and flags remaining
postStats.append(
makePostSummaryItem(makeIndicator(remainingCloseVotes, "coolbg"), " close votes left"),
makePostSummaryItem(makeIndicator(remainingPostFlags, "supernovabg"), " flags left")
);
}
function loadOptions(SOMU) {
if (queueType == null) return;
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Skip Accepted Questions', skipAccepted, 'bool');
// Get current custom value with default
skipAccepted = SOMU.getOptionValue(scriptName, 'Skip Accepted Questions', skipAccepted, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Skip Upvoted Posts', skipUpvoted, 'bool');
// Get current custom value with default
skipUpvoted = SOMU.getOptionValue(scriptName, 'Skip Upvoted Posts', skipUpvoted, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Skip Questions with >1 Answer', skipMultipleAnswers, 'bool');
// Get current custom value with default
skipMultipleAnswers = SOMU.getOptionValue(scriptName, 'Skip Questions with >1 Answer', skipMultipleAnswers, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Skip Medium-length Questions', skipMediumQuestions, 'bool');
// Get current custom value with default
skipMediumQuestions = SOMU.getOptionValue(scriptName, 'Skip Medium-length Questions', skipMediumQuestions, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Skip Long Questions', skipLongQuestions, 'bool');
// Get current custom value with default
skipLongQuestions = SOMU.getOptionValue(scriptName, 'Skip Long Questions', skipLongQuestions, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Auto-open close dialogs', autoCloseQuestions, 'bool');
// Get current custom value with default
autoCloseQuestions = SOMU.getOptionValue(scriptName, 'Auto-open close dialogs', autoCloseQuestions, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Try to close short Questions', autoCloseShortQuestions, 'bool');
// Get current custom value with default
autoCloseShortQuestions = SOMU.getOptionValue(scriptName, 'Try to close short Questions', autoCloseShortQuestions, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Downvote after Question Closure', downvoteAfterClose, 'bool');
// Get current custom value with default
downvoteAfterClose = SOMU.getOptionValue(scriptName, 'Downvote after Question Closure', downvoteAfterClose, 'bool');
// Set option field in sidebar with current custom value; use default value if not set before
SOMU.addOption(scriptName, 'Skip Review Audits', skipAudits, 'bool');
// Get current custom value with default
skipAudits = SOMU.getOptionValue(scriptName, 'Skip Review Audits', skipAudits, 'bool');
}
let toastTimeout, defaultDuration = 2;
/**
* @summary displays a toast message
* @param {string} msg message text
* @param {number} [durationSeconds] for how long to show it (seconds)
* @returns {void}
*/
const toastMessage = (msg, durationSeconds = defaultDuration) => {
const toast = document.getElementById("toasty");
if (!toast) {
const newToast = document.createElement("div");
newToast.id = "toasty";
newToast.textContent = msg;
document.body.append(newToast);
return toastMessage(msg, durationSeconds);
}
// Validation
durationSeconds = Number(durationSeconds);
if (typeof (msg) !== 'string') return;
if (isNaN(durationSeconds)) durationSeconds = defaultDuration;
// Clear existing timeout
if (toastTimeout) clearTimeout(toastTimeout);
// update toast message
toast.textContent = msg;
$(toast).show();
// Log in browser console as well
console.debug(`[${scriptName}] ${msg}`);
// Hide div
toastTimeout = setTimeout(() => $(toast).hide(), durationSeconds * 1000);
};
/**
* @summary Close a question
* @param {Number} pid question id
* @param {String} closeReasonId close reason id
* @param {Number} siteSpecificCloseReasonId off-topic reason id
* @param {String} siteSpecificOtherText custom close reason text
* @param {Number|null} duplicateOfQuestionId duplicate question id
* @returns {Promise<void>}
*/
// closeReasonId: 'NeedMoreFocus', 'SiteSpecific', 'NeedsDetailsOrClarity', 'OpinionBased', 'Duplicate'
// (SO) If closeReasonId is 'SiteSpecific', siteSpecificCloseReasonId: 18-notsoftwaredev, 16-toolrec, 13-nomcve, 11-norepro, 3-custom, 2-migration
function closeQuestionAsOfftopic(pid, closeReasonId = 'SiteSpecific', siteSpecificCloseReasonId = 3, siteSpecificOtherText = 'I’m voting to close this question because ', duplicateOfQuestionId = null) {
const isSO = location.hostname === 'stackoverflow.com';
return new Promise(function (resolve, reject) {
if (!isSO) { reject(); return; }
if (typeof pid === 'undefined' || pid === null) { reject(); return; }
if (typeof closeReasonId === 'undefined' || closeReasonId === null) { reject(); return; }
if (closeReasonId === 'SiteSpecific' && (typeof siteSpecificCloseReasonId === 'undefined' || siteSpecificCloseReasonId === null)) { reject(); return; }
if (closeReasonId === 'Duplicate') siteSpecificCloseReasonId = null;
// Logging actual action
console.debug(`[${scriptName}] %c Closing ${pid} as ${closeReasonId}, reason ${siteSpecificCloseReasonId}.`, 'font-weight: bold');
$.post({
url: `${location.origin}/flags/questions/${pid}/close/add`,
data: {
'fkey': fkey,
'closeReasonId': closeReasonId,
'duplicateOfQuestionId': duplicateOfQuestionId,
'siteSpecificCloseReasonId': siteSpecificCloseReasonId,
'siteSpecificOtherText': siteSpecificCloseReasonId == 3 && isSO ? 'This question does not appear to be about programming within the scope defined in the [help]' : siteSpecificOtherText,
//'offTopicOtherCommentId': '',
'originalSiteSpecificOtherText': 'I’m voting to close this question because '
}
})
.done(resolve)
.fail(reject);
});
}
// Vote for post
// type: 2 - up, 3 - down, omitted = unupdownvote
function votePost(pid, type = 0) {
return new Promise(function (resolve, reject) {
if (typeof pid === 'undefined' || pid === null) { reject(); return; }
$.post({
url: `${location.origin}/posts/${pid}/vote/${type}`,
data: { fkey: fkey }
})
.done(resolve)
.fail(reject);
});
}
function upvotePost(pid) {
return votePost(pid, 2);
}
function downvotePost(pid) {
return votePost(pid, 3);
}
// Follow/Unfollow post
function followPost(pid, undo = false) {
return new Promise(function (resolve, reject) {
if (typeof pid === 'undefined' || pid === null) { reject(); return; }
$.post({
url: `${location.origin}/posts/${pid}/vote/21?undo=${undo}`,
data: { fkey: fkey }
})
.done(resolve)
.fail(reject);
});
}
function skipReview() {
// If referred from meta or post timeline, and is first review, do not automatically skip
if ((document.referrer.includes('meta.') || /\/posts\/\d+\/timeline/.test(document.referrer)) && numOfReviews <= 1) {
console.debug(`[${scriptName}] review opened from Meta or post timeline page, not skipping`);
return;
}
setTimeout(function () {
// Remove instant actions
$('.instant-actions').remove();
// Click skip or next button
$('.js-review-actions').find('button[title^="skip this"], button[title="review next item"]').trigger('click');
}, 500);
}
function isAudit() {
let audit = false;
// Post does not have any of the filtered tags
if (post.tags && post.tags.length && filteredTags[0] !== '' && !filteredTags.some(t => post.tags.includes(t))) {
audit = true;
}
// Check post score
else if (!isNaN(post.votes)) {
let votes, error = false;
$.ajax({
url: `${location.origin}/posts/${post.id}/vote-counts`,
async: false
}).done(function (data) {
votes = Number(data.up) + Number(data.down);
}).fail(function () {
console.error('failed fetching vote counts');
error = true;
});
// Displayed post score not same as fetched vote score
if (!error && votes !== post.votes) audit = true;
}
console.debug(`[${scriptName}] is audit: ${audit}`);
return audit;
}
function displayPostKeywords() {
if (!post.isQuestion) return;
// Display post keywords
post.issues = [];
const header = $('.s-post-summary--stats').first();
const resultsDiv = $(`<div id="review-keywords"></div>`).appendTo(header);
const keywords = [
'suggest', 'software', 'tool', 'library', 'tutorial', 'guide', 'blog', 'resource', 'plugin',
'didn\'t work', 'doesn\'t work', 'want', 'help', 'advice', 'give',
'I am new', 'I\'m new', 'Im new', 'beginner', 'newbie', 'explain', 'understand', 'example', 'reference', 'imgur'
];
const foreignKeywords = [
' se ', ' de ', ' que ', ' untuk ',
];
try {
const paras = $(post.contentHtml).filter('p, ol, ul').text();
const text = (post.title + paras).toLowerCase();
const results = keywords.filter(v => text.includes(v.toLowerCase()));
results.forEach(v => {
$('<span>' + v + '</span>').appendTo(resultsDiv);
post.issues.push(v);
});
const code = $('code', post.contentHtml).text();
if (code.length < 60) {
$('<span>no-code</span>').prependTo(resultsDiv);
post.issues.unshift('no-code');
};
const postLinks = text.match(/href="http/g);
if (postLinks && postLinks.length > 1) {
$('<span>' + postLinks.length + ' links</span>').prependTo(resultsDiv);
post.issues.unshift(postLinks.length + ' links');
}
const questionMarks = paras.match(/\?+/g);
if (questionMarks && questionMarks.length > 1) {
$('<span>' + questionMarks.length + '?</span>').prependTo(resultsDiv);
post.issues.unshift(questionMarks.length + '?');
}
if (foreignKeywords.some(v => text.includes(v.toLowerCase()))) {
$('<span>non-english</span>').prependTo(resultsDiv);
post.issues.unshift('non-english');
};
}
catch (e) {
$('<span>bad-formatting</span>').appendTo(resultsDiv);
post.issues.push('bad-formatting code-only');
}
if (post.content.length <= 500) {
$('<span>short</span>').prependTo(resultsDiv);
post.issues.unshift('short');
}
else if (post.content.length >= 8000) {
$('<span>excessive</span>').prependTo(resultsDiv);
post.issues.unshift('excessive');
}
else if (post.content.length >= 5000) {
$('<span>long</span>').prependTo(resultsDiv);
post.issues.unshift('long');
}
}
function processCloseReview() {
// Question has an accepted answer, skip if enabled
if (skipAccepted && post.isQuestion && post.accepted) {
toastMessage('skipping accepted question');
skipReview();
return;
}
// Post has positive score, skip if enabled
if (skipUpvoted && post.votes > 3) {
toastMessage('skipping upvoted post');
skipReview();
return;
}
// Question has multiple answers, skip if enabled
if (skipMultipleAnswers && post.isQuestion && post.answers > 1) {
toastMessage('skipping question with >1 answer');
skipReview();
return;
}
// Question body is too long, skip if enabled
if (skipLongQuestions && post.isQuestion && post.content.length > 3000) {
toastMessage('skipping long-length question, length ' + post.content.length);
skipReview();
return;
}
// Question body is of medium length, skip if enabled
if (skipMediumQuestions && post.isQuestion && post.content.length > 1000) {
toastMessage('skipping medium-length question, length ' + post.content.length);
skipReview();
return;
}
// Question body is short, try to close if enabled
if (autoCloseQuestions || (autoCloseShortQuestions && post.isQuestion && post.content.length < 500)) {
$('.js-review-actions button[title*="Close"], .close-question-link[data-isclosed="false"]').first().trigger('click');
return;
}
}
function processReopenReview() {
// Post has positive score, skip if enabled
if (skipUpvoted && post.votes > 3) {
toastMessage('skipping upvoted post');
skipReview();
return;
}
// Question has multiple answers, skip if enabled
if (skipMultipleAnswers && post.isQuestion && post.answers > 1) {
toastMessage('skipping question with >1 answer');
skipReview();
return;
}
if (!isSuperuser) return;
const shortPostBody = post.content.length < 500;
const tooManyQuestions = post.content.includes('?') && post.content.match(/\?/g).length > 3;
const diff = $('.sidebyside-diff');
const adds = diff.find('.diff-add').text().length || 0;
const subs = diff.find('.diff-delete').text().length || 0;
const imageLinks = $('.inline-diff').find('a[href$="png"], a[href$="jpg"], a[href$="gif"]').length;
const images = $('.inline-diff').find('img').length;
const badImageLinks = imageLinks - images;
console.log('adds', adds, 'subs', subs, 'badImageLinks', badImageLinks);
// Question has comprehensive changes with no bad images, reopen
if (adds > 400 && badImageLinks === 0 && !shortPostBody && !tooManyQuestions) {
toastMessage('reopened');
$('.js-review-actions button[title^="agree"]').removeAttr('disabled').trigger('click');
$('#confirm-modal-body').next().children('.js-ok-button').trigger('click');
return;
}
// Question has some edits with no bad images, ignore
else if ((subs > 200 || adds > 200) && badImageLinks === 0) {
toastMessage('skipping minor edits', 3);
setTimeout(skipReview, 4000);
return;
}
// Leave closed
else {
toastMessage('leave closed' + (badImageLinks > 0 ? ', has badImageLinks' : '') + (shortPostBody ? ', too short' : ''));
$('.js-review-actions button[title^="disagree"]').removeAttr('disabled').trigger('click');
return;
}
}
function processLowQualityPostsReview() {
const postEl = $('.reviewable-answer .js-post-body');
const postText = postEl.text();
const postHtml = postEl.html();
const postNoCodeHtml = postEl.clone(true, true).find('pre, code').remove().end().html();
// If post type is an answer
if (!post.isQuestion) {
// If is a short answer and there is a link in the post, select "link-only answer" option in delete dialog
if (postText.length < 300 && /https?:\/\//.test(postHtml)) {
isLinkOnlyAnswer = true;
console.debug(`[${scriptName}] detected a possible link-only answer`);
}
// Try to detect if the post contains mostly code
else if (postEl.find('pre, code').length > 0 &&
(postNoCodeHtml.length < 50 || postHtml.length / postNoCodeHtml.length > 0.9)) {
isCodeOnlyAnswer = true;
console.debug(`[${scriptName}] detected a possible code-only answer`);
}
}
}
function insertInstantCloseButtons() {
const actionsCont = $('.js-review-actions-error-target').first();
if (actionsCont.length == 0) return;
actionsCont.children('.instant-actions').remove();
const instantActions = $(`
<span class="instant-actions grid gs8 jc-end ff-row-wrap">
<button class="s-btn s-btn__outlined flex--item" data-instant="unclear" title="Needs details or clarity">Unclear</button>
<button class="s-btn s-btn__outlined flex--item" data-instant="broad" title="Needs more focus">Broad</button>
<button class="s-btn s-btn__outlined flex--item" data-instant="softrec" title="It's seeking recommendations for books, software libraries, or other off-site resources">SoftRec</button>
<button class="s-btn s-btn__outlined flex--item" data-instant="debug" title="It's seeking debugging help but needs more information">Debug</button>
<button class="s-btn s-btn__outlined flex--item" data-instant="opinion" title="Opinion-based">Opinion</button>
</span>`).appendTo(actionsCont);
instantActions.one('click', 'button[data-instant]', function () {
actionsCont.find('.instant-actions button').prop('disabled', true);
const pid = post.id;
// closeQuestionAsOfftopic() :
// closeReasonId: 'NeedMoreFocus', 'SiteSpecific', 'NeedsDetailsOrClarity', 'OpinionBased', 'Duplicate'
// if closeReasonId is 'SiteSpecific', offtopicReasonId : 11-norepro, 13-nomcve, 16-toolrec, 3-custom
let error = false;
switch (this.dataset.instant) {
case 'unclear':
closeQuestionAsOfftopic(pid, 'NeedsDetailsOrClarity');
break;
case 'broad':
closeQuestionAsOfftopic(pid, 'NeedMoreFocus');
break;
case 'softrec':
closeQuestionAsOfftopic(pid, 'SiteSpecific', 16);
break;
case 'debug':
closeQuestionAsOfftopic(pid, 'SiteSpecific', 13);
break;
case 'opinion':
closeQuestionAsOfftopic(pid, 'OpinionBased');
break;
default: {
error = true;
console.error('invalid option');
}
}
if (!error) {
// immediately skip to next review
if (!isSuperuser) {
skipReview();
}
else {
location.reload();
}
}
});
}
function insertVotingButtonsIfMissing() {
const reviewablePost = $('.reviewable-post');
if (reviewablePost.length == 0) return; // e.g.: suggested edits
const pid = Number(reviewablePost[0].className.replace(/\D+/g, ''));
const isQuestion = reviewablePost.find('.question').length == 1;
const voteCont = reviewablePost.find('.js-voting-container').first();
if (voteCont.length == 0) return;
const upvoteBtn = `<button class="js-vote-up-btn flex--item s-btn s-btn__unset c-pointer" title="This question shows research effort; it is useful and clear" aria-pressed="false" aria-label="up vote" data-selected-classes="fc-theme-primary"><svg aria-hidden="true" class="svg-icon m0 iconArrowUpLg" width="36" height="36" viewBox="0 0 36 36"><path d="M2 26h32L18 10 2 26z"></path></svg></button>`;
const dnvoteBtn = `<button class="js-vote-down-btn flex--item s-btn s-btn__unset c-pointer" title="This question does not show any research effort; it is unclear or not useful" aria-pressed="false" aria-label="down vote" data-selected-classes="fc-theme-primary"><svg aria-hidden="true" class="svg-icon m0 iconArrowDownLg" width="36" height="36" viewBox="0 0 36 36"><path d="M2 10h32L18 26 2 10z"></path></svg></button>`;
if (voteCont.find('.js-vote-up-btn, .js-vote-down-btn').length != 2) {
voteCont.find('.fs-caption').remove();
voteCont.find('.js-vote-count').removeClass('mb8').addClass('fc-black-500 fd-column ai-center flex--item grid').unwrap().before(upvoteBtn).after(dnvoteBtn);
StackExchange.vote.init(pid);
}
}
function listenToKeyboardEvents() {
// Focus Delete button when radio button in delete dialog popup is selected
$(document).on('click', '#delete-question-popup input:radio', function () {
$('#delete-question-popup').find('input:submit, .js-popup-submit').focus();
});
// Focus Flag button when radio button in flag dialog popup is selected, UNLESS it's the custom reason option
$(document).on('click', '#popup-flag-post input:radio', function (evt) {
// If custom reason option, do nothing
if (this.value == 'PostOther') return;
$('#popup-flag-post').find('input:submit, .js-popup-submit').focus();
});
// Focus Reject button when radio button in edit reject dialog popup is selected
$(document).on('click', '#rejection-popup input:radio', function () {
if ($(this).hasClass('custom-reason')) $('textarea.custom-reason-text').focus();
else $('#rejection-popup').find('input:submit, .js-popup-submit').focus();
});
// Cancel existing handlers and implement our own keyboard shortcuts
$(document).off('keypress keyup');
// Keyboard shortcuts event handler
$(document).on('keyup', function (evt) {
// Back buttons: escape (27)
// Unable to use tilde (192) as on the UK keyboard it is swapped the single quote keycode
const cancel = evt.keyCode === 27;
const goback = evt.keyCode === 27;
// Get numeric key presses
let index = evt.keyCode - 49; // 49 = number 1 = 0 (index)
if (index == -1) index = 9; // remap zero to last index
if (index < 0 || index > 9) { // handle 1-0 number keys only (index 0-9)
// Try keypad keycodes instead
let altIndex = evt.keyCode - 97; // 97 = number 1 = 0 (index)
if (altIndex == -1) altIndex = 9; // remap zero to last index
if (altIndex >= 0 && altIndex <= 9) {
index = altIndex; // handle 1-0 number keys only (index 0-9)
}
else {
// Both are invalid
index = null;
}
}
// Do nothing if key modifiers were pressed
if (evt.shiftKey || evt.ctrlKey || evt.altKey) return;
// If edit mode, cancel if esc is pressed
if (cancel && $('.editing-review-content').length > 0) {
$('.js-review-cancel-button').trigger('click');
return;
}
// Get current popup
const currPopup = $('#delete-question-popup, #rejection-popup, #popup-flag-post, #popup-close-question').filter(':visible').last();
// #69 - If a textbox or textarea is focused, e.g.: comment box
// E.g.: if post is being edited or being commented on
if (document.activeElement.tagName == 'TEXTAREA' ||
(document.activeElement.tagName == 'INPUT' && document.activeElement.type == 'text') ||
document.getElementsByClassName('editing-review-content').length > 0) {
// Just unfocus the element if esc was pressed
if (currPopup.length && goback) document.activeElement.blur();
return;
}
// If there's an active popup
if (currPopup.length) {
// If escape key pressed, go back to previous pane, or dismiss popup if on main pane
if (goback) {
// If displaying a single duplicate post, go back to duplicates search
const dupeBack = currPopup.find('.original-display .navi a').filter(':visible');
if (dupeBack.length) {
dupeBack.trigger('click');
return false;
}
// Go back to previous pane if possible,
// otherwise default to dismiss popup
const link = currPopup.find('.popup-close a, .popup-breadcrumbs a, .js-popup-back').filter(':visible');
if (link.length) {
link.last().trigger('click');
// Always clear dupe closure search box on back action
$('#search-text').val('');
return false;
}
}
// If valid index, click it
else if (index != null) {
const currPopup = $('.popup:visible').last();
// Get active (visible) pane
const pane = currPopup.find('form .action-list, .popup-active-pane').filter(':visible').last();
// Get options
const opts = pane.find('input:radio');
// Click option
const opt = opts.eq(index).trigger('click');
// Job is done here. Do not bubble if an option was clicked
return opt.length !== 1;
}
} // end popup is active
// Review action buttons
if (index != null && index <= 4) {
const btns = $('.js-review-actions button');
// If there is only one button and is "Next", click it
const nextBtn = document.querySelector(".js-review-instructions button[value='254']")?.click();
// Default to clicking review buttons based on index
btns.eq(index).trigger('click');
return false;
}
// Instant action buttons
else if (index != null && index >= 5) {
const btns = $('.instant-actions button');
btns.eq(index - 5).trigger('click');
return false;
}
});
}
function doPageLoad() {
// Focus VTC button when radio button in close dialog popup is selected
$(document).on('click', '#popup-close-question input:radio', function (evt) {
// If dupe radio, do nothing
if (this.value === 'Duplicate') return;
// If custom reason option, do nothing
if (this.value == '3') return;
// If migrate anywhere radio, do nothing
if (this.id === 'migrate-anywhere') return;
$('#popup-close-question').find('input:submit, .js-popup-submit').focus();
});
// Review queues styles
if (/\/review\//.test(location.pathname)) {
addReviewQueueStyles();
}
// If in queue history page
if (/\/history$/.test(location.pathname)) {
let userId = location.search.match(/userId=\d+/) || '';
if (userId) userId = '&' + userId;
const filterTabs = $(`
<div id="review-history-tabs" class="tabs">
<a href="?skipped=true${userId}" class="${location.search.includes('skipped=true') ? 'youarehere' : ''}">Show All</a>
<a href="?skipped=false${userId}" class="${location.search.includes('skipped=true') ? '' : 'youarehere'}">Default</a>
</div>`);
const actions = $('.history-table tbody tr').map((i, el) => {
const actionName = el.children[2].innerText.trim();
el.dataset.actionType = actionName.toLowerCase().replace(/\W+/gi, '-');
return actionName;
}).get();
const historyTypes = [...new Set(actions)].sort();
historyTypes.forEach(function (actionName) {
const actionSlug = actionName.toLowerCase().replace(/\W+/gi, '-');
filterTabs.append(`<a data-filter="${actionSlug}">${actionName}</a>`);
});
$('.history-table').before(filterTabs);
// Filter options event
$('#review-history-tabs').on('click', 'a[data-filter]', function () {
// Unset if set, and show all
if ($(this).hasClass('youarehere')) {
$('.history-table tbody tr').show();
// Update active tab highlight class
$(this).removeClass('youarehere');
}
else {
// Filter posts based on selected filter
$('.history-table tbody tr').hide().filter(`[data-action-type="${this.dataset.filter}"]`).show();
// Update active tab highlight class
$(this).addClass('youarehere').siblings('[data-filter]').removeClass('youarehere');
}
return false;
});
// Triage, filter by "Requires Editing" (or new "Needs community edit") by default
if (/\/triage\/history$/.test(location.pathname)) {
$('a[data-filter="needs-community-edit"]').trigger('click');
}
}
// Not in a review queue, do nothing. Required for ajaxComplete function below
if (queueType == null) return;
console.debug(`[${scriptName}] queue type: ${queueType}`);
// Add additional class to body based on review queue
document.body.classList.add(queueType + '-review-queue');
// Detect queue type and set appropriate process function
switch (queueType) {
case 'close':
processReview = processCloseReview; break;
case 'reopen':
processReview = processReopenReview; break;
case 'suggested-edits':
processReview = processCloseReview; break;
case 'low-quality-posts':
processReview = processLowQualityPostsReview; break;
case 'triage':
processReview = processCloseReview; break;
case 'first-posts':
processReview = processCloseReview; break;
case 'late-answers':
processReview = processCloseReview; break;
default:
break;
}
// Handle follow/unfollow feature ourselves
$('#content').on('click', '.js-somu-follow-post', function () {
const link = this;
const postType = this.dataset.postType;
const undo = this.innerText === 'unfollow';
followPost(this.dataset.pid, undo).then(v => {
link.innerText = undo ? 'follow' : 'unfollow';
if (undo) StackExchange.helpers.showToast('You’re no longer following this ' + postType);
});
});
}
function repositionReviewDialogs(scrollTop = true) {
// option to scroll to top of page
scrollTop ? setTimeout(() => window.scrollTo(0, 0), 100) : 0;
// position dialog
$('.popup').css({
top: 100,
left: 680
});
}