-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathSECloseVoteRequestGenerator.user.js
5115 lines (4964 loc) · 266 KB
/
SECloseVoteRequestGenerator.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 Stack Exchange CV Request Generator
// @namespace https://github.com/SO-Close-Vote-Reviewers/
// @version 2.0.4
// @description This script generates formatted close-/delete-/reopen-/undelete-vote requests, spam/offensive flag requests, Smoke Detector reports, and approve-/reject-pls requests for suggested edits, then sends them to a specified chat room.
// @author @TinyGiant @Makyen
// @contributor @rene @Tunaki
// @include /^https?://(?:[^/.]+\.)*(?:stackexchange\.com|stackoverflow\.com|serverfault\.com|superuser\.com|askubuntu\.com|stackapps\.com|mathoverflow\.net)/(?:q(?:uestions)?\/\d+|review|tools|admin|users|search|\?|$)/
// @exclude *://chat.stackoverflow.com/*
// @exclude *://chat.stackexchange.com/*
// @exclude *://chat.*.stackexchange.com/*
// @exclude *://stackexchange.com/*
// @exclude *://api.*.stackexchange.com/*
// @exclude *://data.stackexchange.com/*
// @require https://code.jquery.com/jquery-3.5.0.min.js
// @require https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/gm4-polyfill.js
// @require https://cdn.jsdelivr.net/gh/makyen/extension-and-userscript-utilities@94cbac04cb446d35dd025974a7575b25b9e134ca/executeInPage.js
// @connect raw.githubusercontent.com
// @connect chat.stackoverflow.com
// @connect chat.stackexchange.com
// @connect chat.meta.stackexchange.com
// @grant GM_openInTab
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_addValueChangeListener
// @grant GM.openInTab
// @grant GM.xmlHttpRequest
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.addValueChangeListener
// @updateURL https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js
// @downloadURL https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js
// ==/UserScript==
/* jshint jquery: true */
/* globals unsafeWindow, StackExchange, Markdown, toStaticHTML, tagRendererRaw, GM_getValue, GM_setValue, GM_deleteValue, GM_addValueChangeListener, GM_openInTab, GM, $, jQuery, makyenUtilities */ // eslint-disable-line no-unused-vars, no-redeclare
(function() {
'use strict';
const executeInPage = makyenUtilities.executeInPage;
const parser = new DOMParser();
//The RoomList is the list of chat rooms to which to send requests. It's effectively a class, but a one-off.
const RoomList = {};
var CVRGUI;
const isGmStorageValid = typeof GM_getValue === 'function' && typeof GM_setValue === 'function';
const socvrModeratedSites = ['stackoverflow.com'];
const delayedRequestStorage = 'delayedRequests';
const rememberedRequestStorage = 'rememberedRequests';
let rememberedRequests;
//Only those request states with matching times which are not automatically filled by the constructor.
const requestInfoStateWithMatchingTime = ['posted', 'delayed', 'closeVoted', 'deleteVoted'];
const delayableRequestTypes = ['revisit'];
const delayableRequestRegex = / \(in (?:(\d+(?:\.\d+)?)|N) days?\)/;
const SDRegex = / *\(?\bSD report\b\)?/ig;
const NATORegex = / *\(?\bNATO\b\)?/ig;
const scriptInstanceIdentifier = Math.random().toString(); //Not perfectly unique, but should be close.
const canListenGMStorage = typeof GM_addValueChangeListener === 'function'; //Not available: Greasemonkey
const isQuestionPage = window.location.pathname.indexOf('/questions/') === 0;
const SECOND_IN_MILLISECONDS = 1000;
const MINUTE_IN_MILLISECONDS = 60 * SECOND_IN_MILLISECONDS;
const HOUR_IN_MILLISECONDS = 60 * MINUTE_IN_MILLISECONDS;
const DAY_IN_MILLISECONDS = 24 * HOUR_IN_MILLISECONDS;
const MORE_THAN_MONTH_IN_MILLISECONDS = Math.round((365.25 / 12) + 3) * DAY_IN_MILLISECONDS;
const questionActivityWarningAge = (6 * MORE_THAN_MONTH_IN_MILLISECONDS) + (7 * DAY_IN_MILLISECONDS); //6 months plus a bit
let openedAsDelayedRequestNoticeId = [];
const requestTypesWithNoReason = ['!!/reportuser', '!!/addblu-', '!!/rmblu-', '!!/addwlu-', '!!/rmwlu-'];
const requestTypesWithOptionalReason = ['!!/report', '!!/report-force', '!!/scan', '!!/scan-force', 'spam', 'offensive', 'reflag NAA', 'reflag VLQ'];
const knownRooms = {
SOCVR: {
urlDetectionRegExp: /chat\.stackoverflow\.com\/rooms\/41570(?:$|\/)/,
room: {
host: 'https://chat.stackoverflow.com',
url: 'https://chat.stackoverflow.com/rooms/41570/', // SOCVR
id: '41570',
name: 'SO Close Vote Reviewers',
},
},
charcoal: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/11540(?:$|\/)/,
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/11540/', // charcoal-hq
id: '11540',
name: 'Charcoal HQ',
},
},
tavern: {
urlDetectionRegExp: /chat\.meta\.stackexchange\.com\/rooms\/89(?:$|\/)/,
room: {
host: 'https://chat.meta.stackexchange.com',
url: 'https://chat.meta.stackexchange.com/rooms/89/', // Tavern on the Meta
id: '89',
name: 'Tavern on the Meta',
},
},
CRCQR: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/85306(?:$|\/)/,
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/85306/', // SE Code Review Close Questions room
id: '85306',
name: 'SE Code Review Close Questions room',
},
},
CRUDE: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/2165(?:$|\/)/,
useMetaTag: false, //default
useSiteTag: true, //default
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/2165/', // SE Code Review Close Questions room
id: '2165',
name: 'CRUDE',
},
},
seNetwork: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/11254(?:$|\/)/,
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/11254/', // The Stack Exchange Network
id: '11254',
name: 'The Stack Exchange Network',
},
},
};
//Options
function CheckboxOption(_defaultValue, _text, _tooltip) {
//Constructor for a checkbox option
this.defaultValue = _defaultValue;
this.text = _text;
this.tooltip = _tooltip;
}
function ButtonOption(_buttonAction, _dynamicText, _text, _tooltip) {
//Constructor for a button option
this.buttonAction = _buttonAction;
this.dynamicText = _dynamicText;
this.text = _text;
this.tooltip = _tooltip;
}
function NumberOption(_defaultValue, _min, _max, _style, _textPre, _textPost, _tooltip) {
//Constructor for a number option
this.defaultValue = _defaultValue;
this.min = _min;
this.max = _max;
this.style = _style;
this.textPre = _textPre;
this.textPost = _textPost;
this.tooltip = _tooltip;
}
//Object describing the options displayed in the GUI.
/* beautify preserve:start */
var knownOptions = {
checkboxes: {
onlySocvrModeratedSites: new CheckboxOption(false, 'Don\'t show this GUI on non-SOCVR moderated sites.', 'SOCVR moderates only ' + socvrModeratedSites.join(',') + '. Checking this prevents the cv-pls/del-pls GUI from being added on sites which SOCVR does not moderate.'),
onlyKnownSites: new CheckboxOption(false, 'Don\'t show this GUI on sites not pre-configured in this script.', 'Known sites are those moderated by SOCVR: ' + socvrModeratedSites.join(',') + '; Code Review; Mathematics; and Meta Stackexchange. Checking this prevents the cv-pls/del-pls GUI from being added on other sites.'),
onlyCharcoalSDSpamOnUnknownSites: new CheckboxOption(true, 'On sites not specifically configured in this script, use Charcoal HQ as default & show only SD reports/spam report options.', 'On sites not specifically configured in this script, use Charcoal HQ as the default room and show only SD reports, spam and offensive as report options. This will not replace the room currently defined on any site. Basically, for any site you have visited prior to setting this option, the site will have already been defined (used to be SOCVR, then changed to "The Stack Exchange Network"). On those sites, you will need to manually change the room.'),
alwaysCharcoal: new CheckboxOption(true, 'Always send SD commands to Charcoal HQ.', 'Regardless of the current room selection, always send SD commands to Charcoal HQ and show the SD command options on all sites.'),
canReportSmokeDetectorSOCVR: new CheckboxOption(false, 'SOCVR: Show request types for Smoke Detector.', 'When the target Room is SOCVR, show request type options for reporting to Smoke Detector (SD) that the question is spam/offensive, or that all the user\'s posts are spam/offensive. Using SD in SOCVR requires that you are approved to do so in SOCVR. If you\'re not yet approved, sending such reports will just have SD respond saying that you\'re not approved.'),
canReportSmokeDetectorOther: new CheckboxOption(true, 'non SOCVR/non Charcoal HQ rooms: Show request types for Smoke Detector.', 'For target rooms other than SOCVR, show request type options for reporting to Smoke Detector (SD) that the question is spam/offensive and other SD commands. Using SD requires that you are approved to do so in that Room. If you\'re not yet approved, sending such reports will just have SD respond saying that you\'re not approved.'),
alwaysAddNato: new CheckboxOption(true, 'Add " (NATO)" to requests from NATO.', 'When submitting a request from New Answers To Old questions (NATO, part of the 10k tools), add " (NATO)" to the request reason to help people see why you\'re submitting a request about an old question.'),
automaticlyPostDelayedRequests: new CheckboxOption(false, 'Automatically post delayed requests.', 'For delayed requests (e.g. "del-pls (in 2 days)"), don\'t open a page to allow you to manually post the request; just automatically post the request.\r\nNOTE: You are responsible for all requests you post. This includes things like posting duplicate requests. Thus, it\'s much better to manually verify that the request is valid (e.g. the question has not been reopened).'),
},
buttons: {
deleteDelayedRequests: new ButtonOption(deleteDelayedRequests, getNumberDelayedRequestsAsAddedText, 'Discard delayed requests', 'Delete all requests which you have requested be delayed (i.e. "del-pls (in 2 days)").'),
},
numbers: {
daysRememberRequests: new NumberOption(30, 0, 365, 'width: 5em', 'Days to remember requests (does not apply to revisits)', '', 'Number of days to remember the requests you have made. This is used to inform you if you try to make the same request again (you still can, you just have to confirm you want to post a duplicate). It\'s also used to better remember the reason you wrote (e.g. if you reload the page). Set to 0 if you don\'t want this information stored. This limit does not apply to delayed requests (i.e. revisits).'),
},
};
/* beautify preserve:end */
function QuickSubstitutions(_substitutions) {
this.substitutions = _substitutions;
}
QuickSubstitutions.prototype.get = function(r) {
//Substitute space separated words in the input text which
// match the properties above with the property's value.
var a = r.split(' ');
a.forEach(function(v, i) {
a[i] = Object.prototype.hasOwnProperty.call(this.substitutions, v) && v !== 'get' ? this.substitutions[v] : v;
}, this);
return a.join(' ');
};
function SiteConfig(_name, _siteRegExp, _offTopicCloseReasons, _quickSubstitutions, _offTopicScrapeMatch, _defaultRoomKey) {
this.name = _name;
this.siteRegExp = _siteRegExp;
this.offTopicCloseReasons = _offTopicCloseReasons;
this.quickSubstitutions = new QuickSubstitutions(_quickSubstitutions);
//The offTopicScrapeMatch object defines matches which are tested against the information provided in the
// question post notices in order to determine the reason that the question was closed.
this.offTopicScrapeMatch = _offTopicScrapeMatch;
this.defaultRoomKey = _defaultRoomKey;
this.defaultRoom = JSON.parse(JSON.stringify(knownRooms[_defaultRoomKey].room));
}
//The quick substitutions are changed in the text a user types for their request reason.
// They are usually a single character, but can be more. As a single character, they need
// to stay away from anything the user is going to type as a single character. In particular,
// that means they need to not be "a".
const defaultQuickSubstitutions = {
't': 'Too Broad',
'f': 'Needs More Focus',
'u': 'Unclear',
'c': 'Needs Details or Clarity',
'p': 'Primarily Opinion Based',
'o': 'Opinion Based',
'd': 'Duplicate',
};
const defaultOffTopicCloseReasons = {
1: 'Blatantly off-topic', //In close-flag dialog, but not the close-vote dialog on most sites, but is in the CV dialog on some sites.
2: 'Belongs on another site',
3: 'custom',
};
const defaultOffTopicCloseReasonsWithoutOtherSite = Object.assign({}, defaultOffTopicCloseReasons);
delete defaultOffTopicCloseReasonsWithoutOtherSite[2];
var configsForSites = [];
//The keys used for the close reasons below should match the "value" attribute in the <input> used for
// that close reason in the off-topic pane of the close-vote-/flag-dialog.
//Stack Overflow
configsForSites.push(new SiteConfig('Stack Overflow', /^stackoverflow.com$/, Object.assign({
18: 'Not About Programming',
11: 'Typo or Cannot Reproduce',
13: 'No MCVE',
16: 'Request for Off-Site Resource',
19: 'Not in English',
}, defaultOffTopicCloseReasons), Object.assign({
'm': 'No MCVE',
'n': 'Not About Programming',
'r': 'Typo or Cannot Reproduce',
'g': 'General Computing',
'l': 'Request for Off-Site Resource',
'e': 'Not in English',
'F': '(FireAlarm)',
'N': '(NATO)',
'S': '(SD report)',
'D': '(not enough code to duplicate)',
'B': '(no specific expected behavior)',
'E': '(no specific problem or error)',
}, defaultQuickSubstitutions), {
//2022-08-03: The code which used these values is currently non-operable, due to past changes to post notices.
'reproduced': 'r',
'programming': 'n',
'recommend': 'l',
'working': 'm',
}, 'SOCVR'));
//Meta Stack Exchange
configsForSites.push(new SiteConfig('Meta Stack Exchange', /^meta.stackexchange.com$/, Object.assign({
5: 'Does not seek input or discussion',
6: 'Cannot be reproduced',
8: 'Not about Stack Exchange Network software',
11: 'Specific to a single site',
//This site does not have a 2: 'Belongs on another site'
}, defaultOffTopicCloseReasonsWithoutOtherSite), Object.assign({
'i': 'Does not seek input or discussion',
'r': 'Cannot be reproduced',
'n': 'Not about Stack Exchange Network software',
's': 'Specific to a single site',
}, defaultQuickSubstitutions), {
'reproduced': 'r', //Needs verification.
'only': 's',
'input': 'i',
}, 'tavern'));
//Code Review Stack Exchange
configsForSites.push(new SiteConfig('Code Review Stack Exchange', /^codereview.stackexchange.com$/, Object.assign({
20: 'Lacks concrete context',
23: 'Code not implemented or not working as intended',
25: 'Authorship of code',
}, defaultOffTopicCloseReasons), Object.assign({
'l': 'Lacks concrete context',
'i': 'Code not implemented or not working as intended',
's': 'Authorship of code',
}, defaultQuickSubstitutions), {
//The default method of using what's bold or italics works reasonably for this site.
}, 'CRCQR'));
//Mathematics Stack Exchange
configsForSites.push(new SiteConfig('Mathematics Stack Exchange', /^math.stackexchange.com$/, Object.assign({
6: 'Not about mathematics',
8: 'Seeking personal advice',
9: 'Missing context or other details',
}, defaultOffTopicCloseReasons), Object.assign({
'b': 'Blatantly off-topic',
'n': 'Not about mathematics',
'm': 'Missing context or other details',
's': 'Seeking personal advice',
}, defaultQuickSubstitutions), {
//All of the off-topic reasons need to be specified, because the "Not about mathematics" reason contains no bold or italic text.
// As a result, we match against '', which will match anything.
'context': 'm',
'advice': 's',
'': 'n', //The closed text for this reason contains no bold or italic characters.
}, 'CRUDE'));
//Default site configuration
var currentSiteConfig = new SiteConfig('Default', /./, defaultOffTopicCloseReasons, defaultQuickSubstitutions, {}, 'seNetwork');
//If we are not trying to be compatible with IE, then could use .find here.
var isKnownSite = configsForSites.some((siteConfig) => {
if (siteConfig.siteRegExp.test(window.location.hostname)) {
currentSiteConfig = siteConfig;
return true;
} // else
return false;
});
const reasons = currentSiteConfig.quickSubstitutions;
const offTopicCloseReasons = currentSiteConfig.offTopicCloseReasons;
//Set some global variables
const isSocvrSite = socvrModeratedSites.indexOf(window.location.hostname) > -1;
const isSocvrRoomUrlRegEx = knownRooms.SOCVR.urlDetectionRegExp;
const isNato = window.location.pathname.indexOf('tools/new-answers-old-questions') > -1;
const isSuggestedEditReviewPage = /^\/review\/suggested-edits(?:\/|$)/i.test(window.location.pathname);
const isReviewPage = /^\/review\//i.test(window.location.pathname);
//Restore the options
var configOptions = getConfigOptions();
//If the options are set such that we don't show on non-SOCVR sites and this is not a SOCVR site, or we are only to run on known sites and this one isn't known, then stop processing.
if ((configOptions.checkboxes.onlySocvrModeratedSites && !isSocvrSite) || (configOptions.checkboxes.onlyKnownSites && !isKnownSite)) {
return;
}
var onlySdSpamOffensive;
function setGlobalVariablesByConfigOptions() {
onlySdSpamOffensive = configOptions.checkboxes.onlyCharcoalSDSpamOnUnknownSites && !isSocvrSite && !isKnownSite;
RoomList.defaultRoomUrl = currentSiteConfig.defaultRoom.url;
if (onlySdSpamOffensive) {
RoomList.defaultRoomUrl = knownRooms.charcoal.room.url; // charcoal-hq
}
}
setGlobalVariablesByConfigOptions();
//Get the href for the user's profile.
var currentUserHref = $('.s-topbar a.s-user-card').attr('href');
//*This is not effective for some users.
//MathJax corrupts the text contents of titles (from a programmatic POV: .text(),
// .textContent, and .innerText). In order have requests contain the actual title text,
// we save a copy of the text for each title we find in the DOM, hopefully prior to
// MathJax changing them. There's a race condition here where it's assumed this is run
// between when the title(s) exist in the DOM and before MathJax runs. Currently, there
// isn't an effort to guarantee that.
function saveCopyOfQuestionTitles() {
$('#question-header h1 a, h1 a, .question-hyperlink, .answer-hyperlink').each(function() {
const $this = $(this);
if (!$this.attr('data-orig-text')) {
$this.attr('data-orig-text', $this.text());
}
});
}
saveCopyOfQuestionTitles();
//NATO: Prep page so we can place del-pls normally, and detect if NATO Enhancements is being used
var isNatoWithoutEnhancement = false;
if (isNato) {
isNatoWithoutEnhancement = true;
const rows = $('body.tools-page #mainbar > table.default-view-post-table > tbody > tr');
rows.each(function() {
const $this = $(this);
$this.addClass('answer cvrgFakeQuestionContext');
const answerId = $('.answer-hyperlink', $this).first().attr('href').replace(/^.*#(\d+)$/, '$1');
$this.attr('data-answerid', answerId);
const lastCellWithoutPostMenu = $this.children('td:last-of-type').filter(function() {
return !$(this).find('.post-menu, .js-post-menu').length;
});
lastCellWithoutPostMenu
.append($('<div class="js-post-menu pt2 cvrgFakePostMenu"><div class="d-flex gs8 s-anchors s-anchors__muted fw-wrap"></div></div>')) //The .js-post-menu should be given a data-post-id attribute with the current post number.
.find('.js-post-menu')
.attr('data-post-id', answerId);
});
/* Disabled: This is currently detecting other things than just NATO Enhancements
//Observe for a change to the first TD within the first row of the page to detect the NATO Enhancements userscript.
(new MutationObserver(function(mutations, observer) {
if (mutations.some((mutation) => (mutation.addedNodes ? mutation.target.nodeName === 'TD' : false))) {
//Found an added node that targeted a TD. It's assumed that means NATO Enhancements
// is going to be reorganizing the page & we will handle it after that's done.
//For now, back-out the changes we made to the DOM for NATO w/o Enhancements.
isNatoWithoutEnhancement = false;
observer.disconnect();
$('.cvrgFakeQuestionContext').removeClass('answer cvrgFakeQuestionContext').removeData('answerid');
$('.cvrgFakePostMenu').remove();
}
})).observe(rows.first().children('td')[0], {
childList: true,
}); //Only need to watch the first TD.
*/
}
function addNatoIfIsNato(text) {
//If the current page is NATO, then add a notation to the text that it's NATO.
if (knownOptions.checkboxes.alwaysAddNato && isNato && !/\bnato\b/i.test(text)) {
text += ' (NATO)';
}
return text;
}
function addNatoToValueIfIsNatoAndNotEmpty(element) {
//Add NATO notation if it's already not there and the value isn't currently empty.
var $el = (element instanceof jQuery) ? element : $(element);
if ($el.val()) {
//Only add if not empty
$el.val(addNatoIfIsNato($el.val()));
}
}
function addNoCodeToValueIfIsMcve(element) {
//If No MCVE, and no code at all, then state that's the case.
var $el = (element instanceof jQuery) ? element : $(element);
var questionContext = getQuestionContext(element);
var currentVal = $el.val();
if (/\bmcve\b/i.test(currentVal) && !/\bno code\b/i.test(currentVal)) {
if (!$('.question code', questionContext).length) {
$el.val(currentVal + ': no code');
} else if (!$('.question pre > code', questionContext).length) {
$el.val(currentVal + ': no code block');
}
}
}
function capitalizeFirstLetterOfFlexItemChildLink(element) {
const $element = $(element);
if ($element.is('.flex--item')) {
$element.children('a').first().each(function() {
const child = this.firstChild;
if (child.nodeName === '#text') {
const childText = child.textContent;
child.textContent = childText[0].toUpperCase() + childText.slice(1);
}
});
}
}
function addSlinkClassToAllLinkChildren(el) {
el.find('a').addClass('s-link');
}
function getRequestTypeByQuestionStatus(inPost) {
//Based on the question's current status return the text for the
// type(s) of requests which are appropriate/default.
var questionContext = getQuestionContext(inPost);
var isSOCVR = isCurrentRoomSOCVR();
if (onlySdSpamOffensive) {
return ((isSOCVR && configOptions.checkboxes.canReportSmokeDetectorSOCVR) || (!isSOCVR && (configOptions.checkboxes.canReportSmokeDetectorOther || onlySdSpamOffensive))) ? 'sd-report' : 'spam';
} //else
if (isQuestionDeleted(questionContext)) {
return 'undel-pls';
} //else
return isQuestionClosed(questionContext) ? 'reopen/del-pls' : 'cv-pls';
}
function anyElementTextStartsWithClosed($obj) {
return $obj.filter(function() {
return /^Closed/.test($(this).text().trim());
}).length > 0;
}
function isQuestionClosed(questionContext) {
//True if the question is closed.
const pre201910CloseBannerExists = $('.special-status .question-status H2 B', questionContext).filter(function() {
return /hold|closed|marked/i.test($(this).text());
}).length > 0;
const postNotices = $('.js-post-notice', questionContext);
const postNoticeIsDuplicateClosure = postNotices.filter(function() {
return /already has (?:an answer|answers)|close\/reopen/i.test($(this).text());
}).length > 0;
const postNoticeBoldStartsWithClosed = anyElementTextStartsWithClosed($('b', postNotices));
const postNoticesRelativetimeContainers = $('.relativetime', postNotices).parent();
const postNoticesRelativetimeContainerStartsWithClosed = anyElementTextStartsWithClosed(postNoticesRelativetimeContainers);
const post201910CloseBannerExists = postNoticeIsDuplicateClosure || postNoticeBoldStartsWithClosed || postNoticesRelativetimeContainerStartsWithClosed;
const closeButton = $('.js-close-question-link', questionContext);
const closeButtonIsClose = closeButton.attr('data-isclosed') || closeButton.text().toLowerCase().indexOf('reopen') > -1;
return pre201910CloseBannerExists || post201910CloseBannerExists || closeButtonIsClose;
}
function isQuestionDeleted(questionContext) {
//True if the question is deleted.
return $('.question', questionContext).first().is('.deleted-answer');
}
function isPostLocked(post) {
let isLocked = false;
$(post).find('.iconLightbulb, .iconLock').closest('.d-flex').each(function() {
const firstBoldText = $(this).find('b').first().text();
isLocked = isLocked || /community wiki|locked/i.test(firstBoldText);
});
return isLocked;
}
function isPostCommentLocked(post) {
let isCommentLocked = false;
$(post).find('.iconLightbulb, .iconLock').closest('.d-flex').each(function() {
const $this = $(this);
const firstBoldText = $this.find('b').first().text();
const isLocked = /community wiki|locked/i.test(firstBoldText);
if (isLocked) {
isCommentLocked = /Comments .{0,30}\bhave been disabled/.test($this.text());
}
});
return isCommentLocked;
}
function getQuestionContext(element) {
//If there's more than one question, the context is the closest .mainbar
//This is different in
// Normal pages with a single question (#mainbar)
// Some review queues and the reopen queue with a question closed as duplicate (.mainbar)
// Other review queues for answers: (.review-content)
// In these cases (e.g. First Posts), the answer will find .mainbar, but it does not include the question, so we look for the next match further up the DOM.
// MagicTag: (#mainbar-full)
// Inside the Close Dialog within previewing a potential duplicate question. (.show-original)
// 10k tools (NATO with NATO Enhancements): (body.tools-page #mainbar > table > tbody > tr > td)
// 10k tools (NATO without NATO Enhancements): (.cvrgFakeQuestionContext is added to the DOM)
const $el = (element instanceof jQuery) ? element : $(element);
if (isSuggestedEditReviewPage && element.closest('.s-page-title').length) {
return $('.js-review-task');
}
const context = $el.closest('#mainbar, .review-content, .mainbar, #mainbar-full, .show-original, .cvrgFakeQuestionContext, body.tools-page #mainbar > table.default-view-post-table > tbody > tr > td, .js-review-task, .makyen-flag-post-preview-container');
if (!context.length) {
//A containing element which we recognize as the context for the element's question wasn't found.
return $(document);
}
if (context.is('.cvrgFakeQuestionContext') || context.find('.question').length) {
return context;
}
//There was no .question in what was found, try higher up the DOM.
return getQuestionContext(context.parent());
}
//Substitution rules for request reasons.
//Construct a tooltip showing the substitutions which will be made in request reasons.
var reasonTooltip = 'Enter your reason for the request.\r\nIf you want to type less text, there are\r\nsome single character text shortcuts when\r\na character is surrounded by whitespace:\r\n' + Object.keys(reasons.substitutions).filter(function(key) {
return key !== 'get';
}).sort().map(function(key) {
return key + ' --> ' + reasons.substitutions[key];
}).join('\r\n');
var URL = 'https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js';
/* linkifyTextURLs was originally highlight text via RegExp
* Copied by Makyen from Makyen's use of it in MagicTag2, which was copied from Makyen's
* answer to: Highlight a word of text on the page using .replace() at:
* https://stackoverflow.com/a/40712458/3773011
* and substantially rewritten for the SOCVR Archiver. This was copied from there.
*/
function linkifyTextURLs(element, useSpan) {
//This changes bare http/https/ftp URLs into links with link-text a shortened version of the URL.
// If useSpan is truthy, then a span with the new elements replaces the text node.
// If useSpan is falsy, then the new nodes are added as children of the same element as the text node being replaced.
// The [\u200c\u200b] characters are added by SE chat to facilitate word-wrapping & should be removed from the URL.
const urlSplitRegex = /((?:\b(?:https?|ftp):\/\/)(?:[\w.~:\/?#[\]@!$&'()*+,;=\u200c\u200b-]{2,}))/g; // eslint-disable-line no-useless-escape
const urlRegex = /(?:\b(?:https?|ftp):\/\/)([\w.~:\/?#[\]@!$&'()*+,;=\u200c\u200b-]{2,})/g; // eslint-disable-line no-useless-escape
if (!element) {
throw new Error('element is invalid');
}
function handleTextNode(textNode) {
const textNodeParent = textNode.parentNode;
if (textNode.nodeName !== '#text' ||
textNodeParent.nodeName === 'SCRIPT' ||
textNodeParent.nodeName === 'STYLE'
) {
//Don't do anything except on text nodes, which are not children
// of <script> or <style>.
return;
}
const origText = textNode.textContent;
urlSplitRegex.lastIndex = 0;
const splits = origText.split(urlSplitRegex);
//Only change the DOM if we detected a URL in the text
if (splits.length > 1) {
//Create a span to hold the new elements.
const newSpan = document.createElement('span');
splits.forEach((split) => {
if (!split) {
return;
} //else
urlRegex.lastIndex = 0;
//Remove the extra characters SE chat adds to long character sequences.
split = split.replace(/[\u200c\u200b]/g, '');
const newHtml = split.replace(urlRegex, (match, p1) => {
//Try to match what SE uses.
if (p1.length > 32) {
//Reduce length & add ellipse.
p1 = p1.split(/\//g).reduce((sum, part, index) => {
if (sum[sum.length - 1] === '…' || sum.length >= 31) {
//We've found all we want.
return sum;
}
if (index === 0) {
if (part.length > 31) {
return part.slice(0, 29) + '…';
}
return part;
}
if ((sum.length + part.length) > 29) {
return sum + '/…';
}
return sum + '/' + part;
}, '');
}
return `<a href="${match}">${p1}</a>`;
});
//Compare the strings, as it should be faster than a second RegExp operation and
// lets us use the RegExp in only one place.
if (newHtml !== split) {
newSpan.insertAdjacentHTML('beforeend', newHtml);
} else {
//No text replacement was made; just add a text node.
// These are placed as explicit text nodes because it's possible that the textContent could be valid HTML.
// e.g. what if we're replacing into "You want it to look like <b>https://example.com</b>", where that's
// the <b> & </b> are actual text, not elements.
newSpan.appendChild(document.createTextNode(split));
}
});
//Replace the textNode with either the new span, or the new nodes.
if (useSpan) {
//Replace the textNode with the new span containing the link.
textNodeParent.replaceChild(newSpan, textNode);
} else {
const textNodeNextSibling = textNode.nextSibling;
while (newSpan.firstChild) {
textNodeParent.insertBefore(newSpan.firstChild, textNodeNextSibling);
}
textNode.remove();
}
}
}
const textNodes = [];
//Create a NodeIterator to get the text nodes in the body of the document
const nodeIter = document.createNodeIterator(element, NodeFilter.SHOW_TEXT);
let currentNode = nodeIter.nextNode();
//Add the text nodes found to the list of text nodes to process, if it's not a child of an <a>, <script>, or <style>.
while (currentNode) {
let parent = currentNode.parentNode;
while (
parent && parent.nodeName !== 'A' &&
parent.nodeName !== 'SCRIPT' &&
parent.nodeName !== 'STYLE' &&
parent.nodeName !== 'CODE'
) {
parent = parent.parentElement;
}
if (!parent && currentNode.textContent.length > 7) {
textNodes.push(currentNode);
}
currentNode = nodeIter.nextNode();
}
//Process each text node
textNodes.forEach(function(el) {
handleTextNode(el);
});
return element;
}
//For Chat Markdown converter
const hostname = window.location.hostname;
//Site list: https://stackoverflow.com/topbar/site-switcher/site-list
const mainMetaDomain = 'meta.stackexchange.com';
const isMetaSite = /\bmeta\./.test(hostname);
const isMainSite = !isMetaSite || hostname === mainMetaDomain;
const mainDomain = (function() {
if (isMainSite) {
return hostname;
} //else
if (isMetaSite) {
return hostname.replace(/\bmeta\./, '');
}
return '';
})();
const metaDomain = (function() {
if (isMetaSite) {
return hostname;
} //else
if (hostname === 'stackapps.com') {
return mainMetaDomain;
}
if (hostname.indexOf('stackoverflow.com') > -1) {
return hostname.replace('stackoverflow.com', 'meta.stackoverflow.com');
}
if (hostname.indexOf('stackexchange.com') > -1) {
return hostname.replace('stackexchange.com', 'meta.stackexchange.com');
}
return 'meta.' + hostname;
})();
//We have a global list, so we're not re-compiling the regexes each time we convert chat Markdown text.
const chatMarkdownMagicTagSubstitutions = [
//"Magic" links: https://meta.stackexchange.com/questions/92060/add-data-se-style-magic-links-to-comments/94000#94000
//Straight "magic" link substitutions:
[/\[so\]/gi, linkAsHTML('Stack Overflow', 'https://stackoverflow.com/')],
[/\[su\]/gi, linkAsHTML('Super User', 'https://superuser.com/')],
[/\[sf\]/gi, linkAsHTML('Server Fault', 'https://serverfault.com/')],
[/\[metase\]/gi, linkAsHTML('Meta Stack Exchange', 'https://meta.stackexchange.com/')],
[/\[meta.se\]/gi, linkAsHTML('Meta Stack Exchange', 'https://meta.stackexchange.com/')],
[/\[a51\]/gi, linkAsHTML('Area 51', 'https://area51.stackexchange.com/')],
[/\[se\]/gi, linkAsHTML('Stack Exchange', 'https://stackexchange.com/')],
[/\[es.so\]/gi, linkAsHTML('Stack Overflow en español', 'https://es.stackoverflow.com/')],
[/\[pt.so\]/gi, linkAsHTML('Stack Overflow em Português', 'https://pt.stackoverflow.com/')],
[/\[ja.so\]/gi, linkAsHTML('スタック・オーバーフロー', 'https://ja.stackoverflow.com/')],
[/\[ru.so\]/gi, linkAsHTML('Stack Overflow на русском', 'https://ru.stackoverflow.com/')],
[/\[ubuntu.se\]/gi, linkAsHTML('Ask Ubuntu', 'https://askubuntu.com/')],
[/\[mathoverflow.se\]/gi, linkAsHTML('MathOverflow', 'https://mathoverflow.net/')],
[/\[chat-faq\]/gi, linkAsHTML('chat faq', 'https://chat.stackoverflow.com/faq')], //This magic link only works in chat.
//Other SE sites (does not currently attempt to verify that the SE site actually exists or get the site's real name):
//[something.se]:
[/\[([\w-]+)\.se\]/gi, linkAsHTML('$1', '//$1.stackexchange.com/', 'If this is a real SE site, the full site name will be displayed in chat.')], //Does not attempt to use the user readable site name
//Other SE meta sites (does not currently attempt to verify that the SE site actually exists or get the site's real name):
//[sitename.meta.se]:
[/\[meta\.([\w-]+)\.se\]/gi, linkAsHTML('Meta $1', 'https://$1.meta.stackexchange.com/', 'If this is a real SE site, the full meta site name will be displayed in chat.')], //Does not attempt to use the user readable site name
//[meta.sitename.se]:
[/\[([\w-]+)\.meta\.se\]/gi, linkAsHTML('Meta $1', 'https://$1.meta.stackexchange.com/', 'If this is a real SE site, the full meta site name will be displayed in chat.')], //Does not attempt to use the user readable site name
[/\[main\]/gi, linkAsHTML('Main Site', `https:\//${mainDomain}/`, 'In chat, this will display the name of the main site')], // eslint-disable-line no-useless-escape
[/\[meta\]/gi, linkAsHTML('Meta Site', `https:\//${metaDomain}/`, 'In chat, this will display the name of the meta site')], // eslint-disable-line no-useless-escape
[/\[ask\]/gi, linkAsHTML('How to Ask', `https:\//${mainDomain}/questions/how-to-ask`)], // eslint-disable-line no-useless-escape
[/\[answer\]/gi, linkAsHTML('How to Answer', `https:\//${mainDomain}/questions/how-to-answer`)], // eslint-disable-line no-useless-escape
//Post-process tags, as they require HTML:
// https://regex101.com/r/DYvjhz/1/
//The regex used here is overly permissive of what characters are permitted in a tag. See:
// https://meta.stackexchange.com/questions/22624/what-symbols-characters-are-not-allowed-in-tags
//for more information about what is actually permitted in a tag.
//If we wanted the HTML which would actually be used in chat.SO (need to re-verify):
//.replace(/\[tag:([^+"<>\]\s-][^"<>\]\s]{0,34})\]/gi, `<span class="ob-post-tag" style="background-color: #E0EAF1; color: #3E6D8E; border-color: #3E6D8E; border-style: solid;"><a href="/questions/tagged/$1" class="post-tag js-gps-track" title="" rel="tag">$1</a></span>`)
//Main site HTML (when on a main site)
[/\[tag:([^+"<>\]\s-][^"<>\]\s]{0,34})\]/gi, `<a href="https://${mainDomain}/questions/tagged/$1" class="post-tag js-gps-track" title="" rel="tag">$1</a>`],
//Meta tags:
[/\[meta-tag:([^+"<>\]\s-][^"<>\]\s]{0,34})\]/gi, `<a href="https://${metaDomain}/questions/tagged/$1" class="post-tag js-gps-track" title="" rel="tag">$1</a>`],
].map(([basicRegex, replaceText]) => [
//None of these substitutions should happen for text in code format.
new RegExp(`${basicRegex.source}(?!(?:[^<]|<(?!\/?code>))*<\/code>)`, basicRegex.flags), // eslint-disable-line no-useless-escape
replaceText,
]);
function linkAsHTML(displayText, url, titleText) {
return `<a href="${url}"${titleText ? ` title="${titleText}"` : ''}>${displayText}</a>`;
}
function chatMarkdownToHTML(chatMarkdown) {
//Note: Uses parser (global);
//Deficiencies:
// Does not use actual SE site names, nor verify that in [foo.se] "foo.stackexchange.com" is a real SE site.
// Tags:
// Does not check what, if any, site is associated with the target Room. Tag Markdown doesn't work on chat.se unless the room has an associated site.
function applyAllChatMarkdownMagicTagSubstitutions(text) {
chatMarkdownMagicTagSubstitutions.forEach(([regex, replaceText]) => {
regex.lastIndex = 0;
text = text.replace(regex, replaceText);
});
return text;
}
const strikeoutChatMarkdown = chatMarkdown
.replace(/Q/g, 'Qa') //Any "Q" is now "Qa". This allows the use of any "Q[^a]" text sequence to hold special meaning during substitutions, until reversed.
.replace(/</g, 'Qb') //Prevent any existing HTML text from functioning, but don't have markdownToHTML affect it. Chat doesn't support user's directly adding HTML.
.replace(/(^|[^-])---((?:[^\s-].*?[^\s-]|[^\s-]))---(?!-)/g, '$1<s>$2</s>'); //Implement chat strikeout Markdown. https://regex101.com/r/NXXtwF/1/
const markdownHTMLWithoutMagicTags = markdownToHTML(strikeoutChatMarkdown)
//Undo the substitutions which prevented markdownToHTML from affecting existing HTML
.replace(/Qb/g, '<')
.replace(/Qa/g, 'Q');
const markdownAsHTML = applyAllChatMarkdownMagicTagSubstitutions(markdownHTMLWithoutMagicTags);
const asDOM = parser.parseFromString(`<div>${markdownAsHTML}</div>`, 'text/html');
const linkified = linkifyTextURLs(asDOM.body.firstChild, true);
return linkified.innerHTML;
}
function markdownToHTML(src) {
/* markdownToHTML is from
* https://github.com/p01/mmd.js/blob/master/mmd.js
* It is Copyright (c) 2012 Mathieu 'p01' Henri and released under the MIT license, which can be found at:
* https://github.com/p01/mmd.js/blob/master/LICENSE
* It has been modified.
*/
var h = '';
const whiteListedTagsRegex = /<((?:br|hr)\s*\/?|\/?(?:b|code|dd|del|dl|dt|em|h1|h2|h3|i|kbd|li|ol|p|pre|s|strike|strong|sub|sup|ul)\s*|\/(?:a|blockquote|div|ol|pre|span)\s*|(?:(?:a\b(?: +(?:href|title|rel|alt)="[^"<>]*")*)|(?:blockquote\b(?: +(?:class)="[^"<>]*")*)|(?:div\b(?: +(?:class|data-lang|data-hide|data-console|data-babel)="[^"<>]*")*)|(?:ol\b(?: +(?:start)="[^"<>]*")*)|(?:pre\b(?: +(?:class)="[^"<>]*")*)|(?:span\b(?: +(?:class|dir)="[^"<>]*")*)\s*)|(?:(?:img\b(?: +(?:src|width|height|alt|title)="[^"<>]*")*)\s*\/?))>/gi;
function escape(t, noWhitelistedTags) {
if (noWhitelistedTags) {
return new Option(t).innerHTML;
} // else
whiteListedTagsRegex.lastIndex = 0;
return new Option(t).innerHTML.replace(whiteListedTagsRegex, '<$1>');
}
function inlineEscape(s) {
const out = escape(s)
//Images
.replace(/!\[([^\]]*)]\(([^(]+)\)/g, '<img alt="$1" src="$2">')
//Links with alt text.
//https://regex101.com/r/ZUwKmC/1
//.replace(/\[((?:[^\]\\]|\\]|\\)+)]\(([^ (]+?)(?: +"([^\r\n]+?)")?\)/g, (match, p1, p2, p3) => `<a href="${p2}"${(p3 ? (` title=\"${p3.replace(/\"/g, '"')}\"`) : '')}>${p1.replace(/\\([\[\]])/g, '$1')}</a>`)
//Links with alt text and up to 3 levels of extra non-escaped () in the link URL.
//It looks like the Chat Markdown actually handles an arbitrary number of nested () in the URL, as long as they are matched, or escaped.
//We really should switch to actually parsing those, rather than using a regex for the full parse. We could reasonably use a regex to just get potential links and then
//code to parse them.
// p1 = link text
// p2 = URL
// p3 = title text, if it exists
//https://regex101.com/r/kjLtjp/1
.replace(/\[((?:[^\]\\]|\\]|\\)+)]\(((?:[^\s\\()]|\\(?![()\s])|\\[()]|\((?:[^\s\\()]|\\(?![()\s])|\\[()]|\((?:[^\s\\()]|\\(?![()\s])|\\[()]|\([^()\s]*\))+?\))+?\))+?)(?: +"([^\r\n]+?)")?\)/g, (match, p1, p2, p3) => `<a href="${p2.replace(/\\([()])/g, '$1')}"${(p3 ? (` title=\"${p3.replace(/\"/g, '"')}\"`) : '')}>${p1.replace(/\\([\[\]])/g, '$1')}</a>`) // eslint-disable-line no-useless-escape
//Code format
.replace(/`([^`]+)`/g, '<code>$1</code>')
//Bold/strong
.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>')
//Italics
.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
return out;
}
/*eslint-disable */
src
.replace(/^\s+|\r|\s+$/g, '')
.replace(/ +\r?\n/g, '<br>')
.replace(/\t/g, ' ')
.split(/\n\n+/)
.forEach(function(b, f, R) {
f = b[0];
R = {
'*':[/\n\* /,'<ul><li>','</li></ul>'],
'1':[/\n[1-9]\d*\.? /,'<ol><li>','</li></ol>'],
' ':[/\n /,'<pre><code>','</pre></code>','\n'],
'>':[/\n> /,'<blockquote>','</blockquote>','\n']
}[f];
h += R ? R[1] + ('\n' + b)
.split(R[0])
.slice(1)
.map(R[3] ? escape : inlineEscape)
.join(R[3] || '</li>\n<li>') + R[2] : f == '#' ? '<h' + (f = b.indexOf(' ')) + '>' + inlineEscape(b.slice(f + 1)) + '</h' + f + '>' : f == '<' ? b : '<p>' + inlineEscape(b) + '</p>';
});
return h;
/*eslint-enable */
}
// Message number, just a number used to start, which is not
// guaranteed to be unique (i.e. it could have collisions with other
// in-page/userscript uses).
//This would probably be better as just straight CSS, rather than an Object.
var notifyInt = 4873;
const notifyCSS = {
saveSuccess: {
'background-color': 'green',
},
sentSuccess: {
'background-color': '#0095ff',
},
fail: {
'background-color': 'red',
'font-weight': 'bold',
},
};
function removeOpenedAsDelayedRequestNotice() {
removeListOfNotifications(openedAsDelayedRequestNoticeId);
openedAsDelayedRequestNoticeId = [];
}
function removeListOfNotifications(notifications) {
if (Array.isArray(notifications)) {
notifications.forEach((noticeId) => {
removeSENotice(noticeId);
});
}
}
function removeSENotice(messageId_) {
function inPageRemoveNotice(messageId) {
StackExchange.ready(function() {
StackExchange.notify.close(messageId);
});
}
executeInPage(inPageRemoveNotice, false, 'cvrg-inPageRemoveNotice-' + messageId_, messageId_);
}
function notify(message_, time_, notifyCss_) {
//Display a SE notification for a number of milliseconds (optional).
time_ = (typeof time_ !== 'number') ? 0 : time_;
function inPageNotify(messageId, message, time, notifyCss) {
//Function executed in the page context to use SE.notify to display the
// notification.
if (typeof unsafeWindow !== 'undefined') {
//Prevent this running when not in the page context.
return;
}
var div = $('#notify-' + messageId);
if (div.length) {
//The notification already exists. Close it.
StackExchange.notify.close(messageId);
}
$('#cvrq-notify-css-' + messageId).remove();
if (typeof notifyCss === 'object' && notifyCss) {
$(document.documentElement).append('<style id="#cvrq-notify-css-' + messageId + '" type="text/css">\n#notify-container #notify-' + messageId + ' {\n' +
Object.keys(notifyCss).reduce((text, key) => (text + key + ':' + notifyCss[key] + ';\n'), '') + '\n}\n</style>');
}
StackExchange.ready(function() {
function waitUtilVisible() {
return new Promise((resolve) => {
function visibilityListener() {
if (!document.hidden) {
$(window).off('visibilitychange', visibilityListener);
resolve();
} // else
}
$(window).on('visibilitychange', visibilityListener);
visibilityListener();
});
}
//If something goes wrong, fallback to alert().
try {
StackExchange.notify.show(message, messageId);
} catch (e) {
console.log('Notification: ', message);
alert('Notification: ' + message);
}
if (time) {
waitUtilVisible().then(() => {
setTimeout(function() {
StackExchange.notify.close(messageId);
$('#cvrq-notify-css-' + messageId).remove();
$('#cvrg-inPageNotify-' + messageId).remove();
}, time);
});
} else {
$('#cvrg-inPageNotify-' + messageId).remove();
}
});
}
executeInPage(inPageNotify, true, 'cvrg-inPageNotify-' + notifyInt, notifyInt++, message_, time_, notifyCss_);
return notifyInt - 1;
}
function isVersionNewer(proposed, current) {
//Determine if the proposed version is newer than the current.
if (proposed.length > 30 || current.length > 30) {
//Something is wrong. No valid versions are this long.
// Versions should be around 10 characters, or so.
// So, stick with the current version of the script by
// returning false.
return false;
}
proposed = proposed.trim();
if (/[^\d.]/.test(proposed)) {
return false;
}
proposed = proposed.split('.');
current = current.split('.');
while (proposed.length < current.length) {
proposed.push('0');
}
while (current.length < proposed.length) {
current.push('0');
}
for (var i = 0; i < proposed.length; i++) {
if (parseInt(proposed[i]) > parseInt(current[i])) {
return true;
}
if (parseInt(proposed[i]) < parseInt(current[i])) {
return false;
}
}
return false;
}
function checkUpdates(force) {
//Check for updates to the version in SOCVR's userscript repository.
GM.xmlHttpRequest({
method: 'GET',
url: `https://raw.githubusercontent.com/SO-Close-Vote-Reviewers/UserScripts/master/SECloseVoteRequestGenerator.version?CVRGcacheBusting=${Date.now()}`,
onload: function(response) {
const receivedVersion = response.responseText.trim();
if (isVersionNewer(receivedVersion, GM.info.script.version)) {
var lastAcknowledgedVersion = getGMStorage('LastAcknowledgedVersion');
if (lastAcknowledgedVersion !== receivedVersion || force) {
if (confirm('A new version of the Close Vote Request Generator is available, would you like to install it now?')) {
window.location.href = URL;
} else {
setGMStorage('LastAcknowledgedVersion', receivedVersion);
}
}
} else if (force) {
notify('No new version available');
}
},
onerror: function(response) {
console.error('Got an error when trying to get the current script version information from GitHub: response:', response);
if (force) {
notify('Failed to get current script version information from GitHub. See console for more information.', 0, notifyCSS.fail);
}
},
});
}
function sendRequest(request, callback, ignoreNonSOCVRSite) {
//Actually post the cv-pls request to the chat room.
if (typeof callback !== 'function') {
callback = function() {}; // eslint-disable-line no-empty-function