-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMonicasFlagToC.user.js
1458 lines (1278 loc) · 59 KB
/
MonicasFlagToC.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 Monica's Flag ToC
// @description Implement https://meta.stackexchange.com/questions/305984/suggestions-for-improving-the-moderator-flag-overlay-view/305987#305987
// @author Shog9
// @namespace https://github.com/Shog9/flagfilter/
// @version 0.92
// @include http*://stackoverflow.com/questions/*
// @include http*://*.stackoverflow.com/questions/*
// @include http*://dev.stackoverflow.com/questions/*
// @include http*://askubuntu.com/questions/*
// @include http*://*.askubuntu.com/questions/*
// @include http*://superuser.com/questions/*
// @include http*://*.superuser.com/questions/*
// @include http*://serverfault.com/questions/*
// @include http*://*.serverfault.com/questions/*
// @include http*://mathoverflow.net/questions/*
// @include http*://*.mathoverflow.net/questions/*
// @include http*://*.stackexchange.com/questions/*
// @include http*://local.mse.com/questions/*
// @exclude http*://chat.*.com/*
// ==/UserScript==
// this serves only to avoid embarassing mistakes caused by inadvertently loading this script onto a page that isn't a Stack Exchange page
var isSEsite = false;
for (var s of document.querySelectorAll("script")) isSEsite = isSEsite||/StackExchange\.ready\(/.test(s.textContent);
// don't bother running this if the user isn't a moderator on the current site
if (!isSEsite || typeof StackExchange === "undefined" || !StackExchange.options.user.isModerator)
{
return;
}
function with_jquery(f)
{
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "if (window.jQuery) (" + f.toString() + ")(window.jQuery)" + "\n\n//# sourceURL=" + encodeURI(GM_info.script.namespace.replace(/\/?$/, "/")) + encodeURIComponent(GM_info.script.name).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16)); // make this easier to debug;
document.body.appendChild(script);
}
with_jquery(function()
{
window.FlagFilter = window.FlagFilter || {};
initStyles();
initTools();
initQuestionPage();
function initStyles()
{
var flagStyles = document.createElement("style");
flagStyles.textContent = `
#postflag-bar
{
display: none;
background-color: rgba( 239,240,241, 0.75);
opacity: 1;
z-index: 1050; -- rise above left sidebar
}
#postflag-bar>div
{
display: grid;
}
#postflag-bar .flag-summary, .js-post-flag-bar .flag-summary
{
display: flex;
flex: 1 auto;
flex-direction: column;
margin-left: 40px;
margin-right: 40px;
}
.flagToC
{
list-style-type: none;
margin: 0px;
padding: 0px;
}
.flagToC>li
{
padding: 4px;
width:15em;
float:left;
box-shadow: 0 0 8px rgba(214,217,220,.7);
margin: 4px;
border-radius: 4px;
background-color: #fff;
}
.flagToC>li ul
{
margin: 0px;
padding: 0px;
}
.flagToC>li ul>li::before
{
content: attr(data-count);
color: #6A7E7C;
padding-right: 1em;
}
.flagToC>li ul>li
{
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.flagToC>li ul>li.inactive, .flagToC>li ul>li.inactive a
{
color: #6A7E7C;
}
.mod-tools.mod-tools-post,
.mod-tools .mod-tools-comment > :first-child
{
border-left: 8px solid #8D8D8D;
}
.mod-tools.mod-tools-post.active-flag,
.mod-tools .mod-tools-comment.active-flag > :first-child
{
border-left: 8px solid #DB5D5D;
}
.mod-tools.mod-tools-post
{
grid-column: 1 / span 2;
padding: 10px 10px 10px 30px;
margin-bottom: 20px;
background-color: #EFF0F1;
}
.mod-tools ul.flags li
{
margin:5px;
padding: 5px;
line-height:17px;
background-color: #EFF0F1;
list-style:none;
}
.mod-tools ul.flags .flag-dismiss, .comment .comment-actions .flag-dismiss
{
visibility: hidden;
}
.mod-tools ul.flags:hover .flag-dismiss, .comment:hover .comment-actions .flag-dismiss
{
visibility: visible;
}
.comment .comment-actions .flag-dismiss
{
grid-column: 1 / span 2;
padding-left: 2px;
text-align: center;
}
.mod-tools ul.flags .flag-info
{
/* white-space: nowrap; */
}
/**/
/* in which I mangle the site's flexbox styles to work for a purpose they were never intended to serve.
this is almost certainly a bad idea, but hopefully easier than chasing site styling and beats 9 bold blue buttons in 18 sq.in.
pretty unlikely a designer will ever see this, so I should be safe
*/
.dismiss-flags-popup
{
padding: 16px 0;
display: none;
}
.dismiss-flags-popup form
{
display: flex;
}
.dismiss-flags-popup form .g-row>.-btn
{
flex: initial;
}
.dismiss-flags-popup form>button.g-col
{
text-align: left;
}
.dismiss-flag-popup { display:none; }
/**/
.mod-tools ul.flags .flag-info .flag-creation-user
{
white-space: nowrap;
}
/* fix close button in the flag bar to make the whole thing clickable */
#postflag-bar .nav-button.close {
color: unset;
padding: unset;
border: unset;
border-radius: unset;
background-color: unset;
}
#postflag-bar .nav-button.close:hover {
color: unset;
}
#postflag-bar .nav-button.close a {
background-color: #6a737c;
border: 1px solid #9fa6ad;
border-radius: 10px;
color: white;
display: block;
padding: 2px 5px;
}
#postflag-bar .nav-button.close a:hover {
background-color: white;
color: #9fa6ad;
}
/*
Put comment delete link in consistent place
*/
.comment, .comment .flags
{
clear: both;
}
.comment .js-comment-delete
{
float: right;
}
@supports (display: grid) and (not (display: contents) )
{
ul.comments-list .active-flag .comment-actions
{
width: 54px;
}
}
`;
document.head.appendChild(flagStyles);
}
//
// Generally-useful moderation routines
//
function initTools()
{
FlagFilter.tools = $.extend({}, FlagFilter.tools, {
CloseReasons: { Duplicate: 'Duplicate', OffTopic: 'OffTopic', Unclear: 'Unclear', TooBroad: 'TooBroad', OpinionBased: 'OpinionBased' },
UniversalOTReasons: { Default: 1, BelongsOnSite: 2, Other: 3 },
// format for close options:
// { closeReasonId string - one of the close reasons above
// duplicateOfQuestionId number - question id for duplicate, otherwise not set
// closeAsOffTopicReasonId number - site-specific reason ID for OT, otherwise not set
// belongsOnBaseHostAddress string - host domain for destination site for OT, otherwise not set
// offTopicOtherText string - custom OT text for when the OT reason is "other"
// and offTopicOtherCommentId is not set
// offTopicOtherCommentId string - reference to an existing comment on the post describing
// why the question is off-topic for when the OT reason is "other"
// and offTopicOtherText is not specified.
// originalOffTopicOtherText string - the placeholder / prefix text used to prompt for the OT other reason,
// used when offTopicOtherText is specified, otherwise not set
// }
closeQuestion: function(postId, closeOptions)
{
closeOptions.fkey = StackExchange.options.user.fkey;
return $.post('/flags/questions/' + postId + '/close/add', closeOptions)
},
migrateTo: function(postId, destinationHost)
{
return FlagFilter.tools.closeQuestion(postId,
{
closeReasonId: FlagFilter.tools.CloseReasons.OffTopic,
closeAsOffTopicReasonId: FlagFilter.tools.UniversalOTReasons.BelongsOnSite,
belongsOnBaseHostAddress: destinationHost
});
},
annotateUser: function(userId, annotation)
{
return $.post('/admin/users/' + userId + '/annotate',
{
"mod-actions": "annotate",
annotation: annotation,
fkey: StackExchange.options.user.fkey
});
},
reviewBanUser: function(userId, days, explanation)
{
var params = {
userId: userId,
reviewBanDays: days,
fkey: StackExchange.options.user.fkey
};
if ( explanation )
params.explanation = explanation;
return $.post('/admin/review/ban-user', params);
},
// hate safari
parseISODate: function(isoDate, def)
{
var parsed = Date.parse((isoDate||'').replace(' ','T'));
return parsed ? new Date(parsed) : def;
},
formatDate: function(date)
{
if ( !date.getTime() ) return "(??)";
// mostly stolen from SE.com
var delta = (((new Date()).getTime() - date.getTime()) / 1000);
if (delta < 2) {
return 'just now';
}
if (delta < 60) {
return Math.floor(delta) + ' secs ago';
}
if (delta < 120) {
return '1 min ago';
}
if (delta < 3600) {
return Math.floor(delta / 60) + ' mins ago';
}
if (delta < 7200) {
return '1 hour ago';
}
if (delta < 86400) {
return Math.floor(delta / 3600) + ' hours ago';
}
if (delta < 172800) {
return 'yesterday';
}
if (delta < 259200) {
return '2 days ago';
}
return date.toLocaleString(undefined, {month: "short", timeZone: "UTC"})
+ ' ' + date.toLocaleString(undefined, {day: "2-digit", timeZone: "UTC"})
+ ( delta > 31536000 ? ' \'' + date.toLocaleString(undefined, {year: "2-digit", timeZone: "UTC"}) : '')
+ ' at'
+ ' ' + date.toLocaleString(undefined, {minute: "2-digit", hour: "2-digit", hour12: false, timeZone: "UTC"});
},
formatISODate: function(date)
{
return date.toJSON().replace(/\.\d+Z/, 'Z');
},
dismissAllCommentFlags: function(commentId, flagIds)
{
// although the UI implies it's possible, we can't currently dismiss individual comment flags
return $.post('/admin/comment/' + commentId+ '/clear-flags', {fkey:StackExchange.options.user.fkey});
},
dismissFlag: function(postId, flagIds, helpful, declineId, comment)
{
var ticks = StackExchange.moderator.renderTimeTicks||(Date.now()*10000+621355968000000000);
return $.post('/messages/delete-moderator-messages/' + postId + '/'
+ ticks + '?valid=' + helpful + '&flagIdsSemiColonDelimited=' + (flagIds.join ? flagIds.join(';') : flagIds),
{comment: comment||declineId||'', fkey:StackExchange.options.user.fkey});
},
dismissAllFlags: function(postId, helpful, declineId, comment)
{
var ticks = StackExchange.moderator.renderTimeTicks||(Date.now()*10000+621355968000000000);
return $.post('/messages/delete-moderator-messages/' + postId + '/'
+ ticks+ '?valid=' + helpful,
{comment: comment||declineId||'', fkey:StackExchange.options.user.fkey});
},
moveCommentsToChat: function(postId)
{
return $.post('/admin/posts/' + postId + '/move-comments-to-chat', {fkey:StackExchange.options.user.fkey});
},
makeWait: function(msecs)
{
return function()
{
var args = arguments;
var result = $.Deferred();
setTimeout(function() { result.resolve.apply(result, args) }, msecs);
return result.promise();
}
},
flagHelpfulUI: function(uiParent)
{
var result = $.Deferred();
var helpfulForm = $(`
<div class="dismiss-flags-popup">
<form class="g-column _gutters">
<label class="f-label">Reason flag was helpful</label>
<div class="g-col g-row _gutters">
<div class="g-col -input">
<input type="text" maxlength="200" placeholder="optional feedback (visible to the user)" class="f-input">
</div>
<div class="g-col -btn">
<button class="btn-outlined mark-flag-helpful" type="submit">mark helpful</button>
</div>
</div>
<span class="text-counter cool">enter nothing at all, or up to 200 characters of cheerful guidance</span>
</form>
</div>
`);
uiParent.find(".dismiss-flags-popup").remove();
helpfulForm
.appendTo(uiParent)
.slideDown()
.find("button,input").first().focus();
helpfulForm.find("input[type=text]").charCounter({min: 0, max: 200, target: helpfulForm.find(".text-counter")});
helpfulForm.find(".mark-flag-helpful").click(function(ev)
{
ev.preventDefault();
helpfulForm.remove();
result.resolve({helpful: true, declineId: 0, comment: helpfulForm.find("input[type=text]").val()});
});
return result.promise();
},
flagDeclineUI: function(uiParent)
{
var result = $.Deferred();
var declineForm = $(`
<div class="dismiss-flags-popup">
<form class="g-column _gutters">
<label class="f-label">Reason for declining</label>
<div class="g-col g-row _gutters">
<div class="g-col -input">
<input type="text" maxlength="200" placeholder="optional feedback (visible to the user)" class="f-input">
</div>
<div class="g-col -btn">
<button class="btn-outlined mark-flag-declined" value="other" type="submit" disabled>decline</button>
</div>
</div>
<span class="text-counter cool">enter at least 10 characters of righteous indignation</span>
</form>
</div>
`);
var reasons = {
technical: {
id: 1,
prompt: "flags should not be used to indicate technical inaccuracies, or an altogether wrong answer",
title: "use when the post does not violate the standards of the site, but is simply misleading or inaccurate"
},
noevidence: {
id: 2,
prompt: "a moderator reviewed your flag, but found no evidence to support it",
title: "use when you were unable to find any evidence that the problem described by the flag actually occurred"
},
nomods: {
id: 3,
prompt: "flags should only be used to make moderators aware of content that requires their intervention",
title: "use when the problem described could be corrected by the flagger, passers-by, the passage of time, or being less pedantic"
},
stdflags: {
id: 4,
prompt: "using standard flags helps us prioritize problems and resolve them faster...",
title: "Using standard flags helps us prioritize problems and resolve them faster. Please familiarize yourself with the list of standard flags: see What is Flagging?"
}
};
var lastDecline = localStorage["flaaaaags.last-decline"];
if ( lastDecline )
{
reasons["lastEntered"] = {
id: 9999,
prompt: lastDecline,
title: "this is the last custom reason you used to decline a flag"
};
}
for (let reason in reasons)
{
$('<button class="btn-outlined g-col -btn mark-flag-declined" type="button"></button>')
.attr({value: reason, title: reasons[reason].title})
.text(reasons[reason].prompt)
.insertAfter(declineForm.find("form>label,form>button:last").last());
}
uiParent.find(".dismiss-flags-popup").remove();
declineForm
.appendTo(uiParent)
.slideDown()
.find("button,input").first().focus();
var customDeclineField = declineForm.find("input[type=text]")
.on("input", function()
{
var text = customDeclineField.val();
declineForm.find(".mark-flag-declined[value=other]").prop("disabled", text.length < 10);
})
.charCounter({min: 10, max: 200, target: declineForm.find(".text-counter")})
declineForm.find(".mark-flag-declined").click(function(ev)
{
ev.preventDefault();
var declineReason = reasons[this.value] ? reasons[this.value].id : 0;
var declineText = "";
if ( declineReason == 9999 )
{
declineText = lastDecline;
declineReason=0;
}
else if ( declineReason == 0 )
{
declineText = customDeclineField.val();
localStorage["flaaaaags.last-decline"] = declineText;
}
declineForm.remove();
result.resolve({helpful: false, declineId: declineReason, comment: declineText});
});
return result.promise();
},
flagDismissUI: function(uiParent)
{
var result = $.Deferred();
var dismissTools = $(`
<div class="dismiss-flag-popup">
<button class="flag-dismiss-helpful" type="button" title="mark any pending flags as helpful">Helpful…</button>
<button class="flag-dismiss-decline" type="button" title="mark any pending flags as declined">Decline…</button>
</div>
`);
uiParent.find(".dismiss-flag-popup").remove();
dismissTools
.appendTo(uiParent)
.slideDown()
.find("button,input").first().focus();
dismissTools.find("button").click(function()
{
var btn = $(this);
var choice = btn.is(".flag-dismiss-helpful")
? FlagFilter.tools.flagHelpfulUI(btn.parent())
: FlagFilter.tools.flagDeclineUI(btn.parent());
choice.then(function(dismissal)
{
dismissTools.remove();
result.resolve(dismissal);
});
});
return result.promise();
},
predictMigrationDest: function(flagText)
{
return loadMigrationSites()
.then(function(sites)
{
var ret = {baseHostAddress: '', name: ''};
if ( !/belongs on|moved? to|migrat|better fit/.test(flagText) )
return ret;
sites.forEach(function(site)
{
var baseHost = site.site_url.replace(/^https?:\/\//, '');
if ( baseHost == window.location.host ) return;
if ( (RegExp(baseHost.replace('.stackexchange.com', ''), 'i').test(flagText)
|| RegExp(site.name.replace(' ', '\\s?'), 'i').test(flagText))
&& ret.baseHostAddress.length < baseHost.length )
ret = { baseHostAddress: baseHost, name: site.name };
});
return ret;
});
function loadMigrationSites()
{
var ret = $.Deferred();
var cachekey = "flaaaaags.site-cache";
var cacheExpiration = new Date();
cacheExpiration = cacheExpiration.setHours(cacheExpiration.getHours()-24);
var siteCache = localStorage.getItem(cachekey);
if (siteCache) siteCache = JSON.parse(siteCache);
if (siteCache && siteCache.age > cacheExpiration)
{
ret.resolve(siteCache.sites);
return ret;
}
return $.get('https://api.stackexchange.com/2.2/sites?pagesize=500')
.then(function(data)
{
var sites = [];
var siteArray = data.items;
if ( siteArray && siteArray.length && siteArray[0].name )
{
sites = siteArray;
localStorage.setItem(cachekey, JSON.stringify({age: Date.now(), sites: sites}));
}
return sites;
});
}
}
});
}
function initQuestionPage()
{
var flagCache = {};
var waffleFlags = GetFlagInfoFromWaffleBar();
if ( !waffleFlags.length )
waffleFlags = GetFlagInfoFromNewFlagBar();
for (let fp of waffleFlags)
flagCache[fp.postId] = fp;
// give up on the waffle bar if it's listing all flags as handled for a given post - load full flag info.
// also do this if any flag might've put the post into review, so we can indicate that too
var loadingFlags = waffleFlags.filter(pf => pf.dirty || pf.flags.some(f => IsReviewFlag(f))).map( pf => RefreshFlagsForPost(pf.postId) );
RenderToCInWaffleBar();
StackExchange.initialized
.then(initFlags);
// Wire up prototype mod tools
$("#content")
// Comment flag dismissal
.on("click", ".comment .flag-dismiss", function(ev)
{
ev.preventDefault();
var dismissLink = $(this);
var post = dismissLink.parents(".question, .answer");
var postId = post.data("questionid") || post.data("answerid");
var commentId = dismissLink.parents(".comment").attr("id").match(/comment-(\d+)/)[1];
var flagInfo = dismissLink.parents(".flag-info");
if ( !flagInfo.length )
flagInfo = dismissLink.parents(".comment").find(".flag-info");
var flagIds = flagInfo.data("flag-ids");
var flagListItem = flagInfo.parent();
if ( !commentId || !flagListItem.length )
return;
FlagFilter.tools.dismissAllCommentFlags(commentId, flagIds)
.done(function() { flagListItem.hide('medium'); dismissLink.hide(); /* annoying - don't do this RefreshFlagsForPost(postId); */ });
})
// Make individual flag dismissal work
.on("click", ".mod-tools.mod-tools-post .flag-dismiss", function()
{
var post = $(this).parents(".question, .answer");
var postId = post.data("questionid") || post.data("answerid");
var flagIds = $(this).parents(".flag-info").data("flag-ids");
var flagListItem = $(this).parents(".flag-info").parent();
if ( !postId || !flagIds || !flagListItem.length )
return;
FlagFilter.tools.flagDismissUI(flagListItem).then(function(dismissal)
{
FlagFilter.tools.dismissFlag(postId, flagIds, dismissal.helpful, dismissal.declineId, dismissal.comment)
.done(function(){ flagListItem.hide('medium'); RefreshFlagsForPost(postId); });
});
})
// Make "dismiss all" work
.on("click", ".mod-tools .flag-dismiss-all-helpful, .mod-tools .flag-dismiss-all-decline", function()
{
var btn = $(this);
var post = btn.parents(".question, .answer");
var postId = post.data("questionid") || post.data("answerid");
var choice = btn.is(".flag-dismiss-all-helpful")
? FlagFilter.tools.flagHelpfulUI(btn.parent())
: FlagFilter.tools.flagDeclineUI(btn.parent());
choice.then(function(dismissal)
{
FlagFilter.tools.dismissAllFlags(postId, dismissal.helpful, dismissal.declineId, dismissal.comment)
.done(function()
{
post.find('tr.mod-tools').slideUp();
RefreshFlagsForPost(postId).then( () => post.find('tr.mod-tools').sideDown('fast') );
});
});
})
// historical flag expansion
.on("click", "a.show-all-flags", function()
{
var holder = $(this).parent();
var postId = $(this).data('postid');
var link = holder.find('a.show-all-flags');
var spinner = $("<span>loading<img src='//sstatic.net/img/progress-dots.gif'></span>");
spinner.insertAfter(link.hide());
RefreshFlagsForPost(postId, true)
.catch(function() {
link.show();
spinner.remove();
});
});
$(document)
.ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions)
{
if (/\/posts\/\d+\/comments/.test(ajaxOptions.url))
{
var postId = +ajaxOptions.url.match(/\/posts\/(\d+)\/comments/)[1];
setTimeout(() => ShowCommentFlags(postId), 1);
}
/* uncomment to allow live refreshes while deleting comments - I find this annoying.
else if ( /\/posts\/comments\/\d+\/vote\/10/.test(ajaxOptions.url))
{
var commentId = +ajaxOptions.url.match(/\/(\d+)\//)[1];
var post = $("#comment-" + commentId).parents(".question,.answer");
var postId = post.data("answerid")||post.data("questionid");
setTimeout(() => RefreshFlagsForPost(postId), 1);
} */
else if ( /\/posts\/\d+\/vote\/10/.test(ajaxOptions.url))
{
var postId = +ajaxOptions.url.match(/\/(\d+)\//)[1];
setTimeout(() => RefreshFlagsForPost(postId), 1);
}
});
function RefreshFlagsForPost(postId, expandComments)
{
var postContainer = $(".answer[data-answerid='"+postId+"'],.question[data-questionid='"+postId+"']")
if ( !postContainer.length ) return;
return LoadAllFlags(postId)
.then(flags => ShowFlags(postContainer, flags, expandComments))
.then(flags => RenderToCInWaffleBar());
}
function initFlags()
{
var posts = $(".question, .answer");
posts.each(function()
{
var postContainer = $(this),
postId = postContainer.data('questionid') || postContainer.data('answerid'),
issues = postContainer.find(".js-post-issue"),
flagsLink = issues.filter("a[href='/admin/posts/" + postId + "/show-flags']"),
commentsLink = issues.filter("a[href='/admin/posts/" + postId + "/comments']"),
flags = flagCache[postId],
totalFlags = flagsLink.length ? +flagsLink.text().match(/\d+/)[0] : 0;
if (!flagsLink.length) return;
var tools = $(`<div class="mod-tools mod-tools-post" data-totalflags="${totalFlags}">
<h3 class='flag-summary'><a class='show-all-flags' data-postid='${postId}'>${totalFlags} resolved flags</a></h3>
<ul class="flags">
</ul>
<div class="mod-actions">
</div>
<ul class="reviews">
</ul>
</div>`)
.insertBefore(postContainer.find("div:has(>.comments)"));
if (flags)
ShowFlags(postContainer, flags, true);
});
}
function ShowFlags(postContainer, postFlags, forceCommentVisibility)
{
var tools = postContainer.find(".mod-tools-post");
var modActions = tools.find(".mod-actions")
.empty();
var flagContainer = tools.find("ul.flags")
.empty();
var activeCount = 0;
var inactiveCount = 0;
for (let flag of postFlags.flags)
{
if (flag.active)
activeCount += flag.flaggers.length;
else
inactiveCount += flag.flaggers.length;
if ( (flag.description === "spam" || flag.description === "rude or abusive")
&& !flag.active
&& !tools.find(".flag-dispute-spam").length )
{
$("<input class='flag-dispute-spam' type='button' value='Clear all spam/rude/abusive' title='Disputes all rude or abusive and spam flags on this post, and removes all associated automatic reputation penalties from its author. If this post reached the flag limit, it will be undeleted and unlocked.'>")
.appendTo(modActions)
.click(function()
{
if ( !confirm("This will undelete the post, remove any penalties against the author, and dispute ALL spam / rude / abusive flags ever raised on it. Are you sure?") )
return;
$.post("/admin/posts/" + postFlags.postId + "/clear-offensive-spam-flags", {fkey: StackExchange.options.user.fkey})
.then(() => location.reload(),
function(err) { console.log(err); alert("something went wrong") });
});
}
FlagFilter.tools.predictMigrationDest(flag.description)
.done(function(site)
{
if (modActions.find(".migration-link").length) return;
if (!site.name) return;
$("<input class='migration-link' type='button' title='migrate this question to a site chosen by the magic 8-ball'>")
.val("belongs on " + site.name + "?")
.click(function()
{
var questionId = location.pathname.match(/\/questions\/(\d+)/)[1];
if ( confirm("Really migrate this question to " + site.name + "?") )
FlagFilter.tools.migrateTo(questionId, site.baseHostAddress)
.done(function() { location.reload() })
.fail(function() { alert("something went wrong") });
})
.appendTo(modActions);
})
let flagItem = RenderFlagItem(flag, postFlags.reviews);
flagContainer.append(flagItem);
}
tools.toggleClass("active-flag", !!activeCount);
if (activeCount > 0)
{
modActions.prepend(`
<button class="flag-dismiss-all-helpful" type="button" title="mark any pending flags as helpful">Helpful…</button>
<button class="flag-dismiss-all-decline" type="button" title="mark any pending flags as declined">Decline…</button>
<!-- <input class="flag-delete-with-comment" type="button" value="delete with comment…" title="deletes this post with a comment the owner will see, as well as marking all flags as helpful"> -->
`);
}
var totalFlags = tools.data("totalflags");
var commentFlags = postFlags.commentFlags.reduce((acc, f) => acc + f.flaggers.length, 0);
// this... really just hacks around incomplete information in the waffle bar
postFlags.assumeInactiveCommentFlagCount = totalFlags - (activeCount+inactiveCount) - commentFlags;
if (postFlags.flags.length)
{
let flagSummary = [];
if (activeCount > 0) flagSummary.push(activeCount + " active post flags");
if (inactiveCount) flagSummary.push(inactiveCount + " resolved post flags");
if (postFlags.assumeInactiveCommentFlagCount) flagSummary.push(`(*<a class='show-all-flags' data-postid='${postFlags.postId}' title='Not sure about these flags; click to load accurate information for ${postFlags.assumeInactiveCommentFlagCount} undefined flags'>load full flag info</a>)`);
tools.show()
.find("h3.flag-summary").html(flagSummary.join("; "));
}
else if ( postFlags.assumeInactiveCommentFlagCount )
{
tools.show()
.find("h3.flag-summary").html(`(*<a class='show-all-flags' data-postid='${postFlags.postId}' title='Not sure about these flags; click to load accurate information for ${postFlags.assumeInactiveCommentFlagCount} undefined flags'>load full flag info</a>)`);
}
else
tools.hide();
if (postFlags.commentFlags.length && forceCommentVisibility)
{
let issues = postContainer.find(".js-post-issue"),
moreCommentsLink = $("#comments-link-" + postFlags.postId + " a.js-show-link:last:visible"),
deletedCommentsLink = issues.filter("a[href='/admin/posts/" + postFlags.postId + "/comments']"),
inactiveCommentFlags = !postFlags.commentFlags.every(f => f.active);
// load comments to trigger flag display
if (inactiveCommentFlags && deletedCommentsLink.length)
deletedCommentsLink.click();
else if (moreCommentsLink.length)
moreCommentsLink.click();
else
ShowCommentFlags(postFlags.postId);
}
else if (totalFlags > activeCount-inactiveCount || $("#comments-" + postFlags.postId + " .mod-tools-comment").length)
{
ShowCommentFlags(postFlags.postId);
}
/* diagnostics
if ( postFlags.reviews )
{
let reviews = '';
for (let task of postFlags.reviews.sort((a,b) => b.creationDate-a.CreationDate) )
{
reviews += `
<li>
<span title="${FlagFilter.tools.formatISODate(task.creationDate)}" class="relativetime-clean">${FlagFilter.tools.formatDate(task.creationDate)}</span>
<a href="${task.url}">${task.type}</a>
`;
if ( task.result )
reviews += `<span>ended
<span title="${FlagFilter.tools.formatISODate(task.resultDate)}" class="relativetime-clean">${FlagFilter.tools.formatDate(task.resultDate)}</span>:
${task.result}</span>`;
else
reviews += "<i>pending...</i>";
reviews += "</li>";
}
tools.find("ul.reviews").empty().append(reviews);
}
*/
setTimeout(() => StackExchange.realtime.updateRelativeDates(), 100);
}
function ShowCommentFlags(postId)
{
var commentContainer = $("#comments-" + postId);
var postContainer = commentContainer.closest(".question, .answer");
var tools = postContainer.find(".mod-tools-post");
var postFlags = flagCache[postId];
var commentModToolsContainer = commentContainer.find(".mod-tools-comment");
if (!postFlags || ((!postFlags.commentFlags.length || !commentContainer.length) && !postFlags.assumeInactiveCommentFlagCount) )
{
commentModToolsContainer.remove();
return;
}
if ( !commentModToolsContainer.length)
{
commentModToolsContainer = $(`<li class="comment mod-tools-comment">
<div class="js-comment-actions comment-actions"></div>
<div class="comment-text">
<h3 class="comment-flag-summary"></h3>
</div>
</li>`);
commentContainer
.addClass("mod-tools")
.find(">ul.comments-list").prepend(commentModToolsContainer);
}
commentContainer
.removeClass("dno")
.find(".comment").removeClass("active-flag").end()
.find(".comment-text .flags").remove();
var activeCount = 0;
var inactiveCount = 0;
var flagsShown = 0;
for (let flag of postFlags.commentFlags)
{
let comment = commentContainer.find("#comment-" + flag.commentId);
let container = comment.find(".comment-text .flags");
if (!container.length)
container = $('<div><ul class="flags"></ul></div>')
.appendTo(comment.find(".comment-text"))
.find(".flags");
comment.addClass("mod-tools-comment");
if (flag.active)
{
activeCount += flag.flaggers.length;
comment.addClass("active-flag");
}
else
inactiveCount += flag.flaggers.length;
if ( !comment.length )
continue;
flagsShown += flag.flaggers.length;
let flagItem = RenderFlagItem(flag);
let flagDismiss = flagItem.find(".flag-dismiss").remove();
container.append(flagItem);
if ( !comment.find(".comment-actions .flag-dismiss").length )
flagDismiss
.html("dismiss<br>flags")